2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #include "cl_dyntexture.h"
31 mempool_t *r_main_mempool;
32 rtexturepool_t *r_main_texturepool;
34 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
36 static qboolean r_loadnormalmap;
37 static qboolean r_loadgloss;
39 static qboolean r_loaddds;
40 static qboolean r_savedds;
47 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
48 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
49 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
50 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
51 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
52 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
53 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
54 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
56 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
57 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
58 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
59 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
60 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
62 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
63 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
64 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
65 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
66 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
67 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
68 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
69 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
70 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
71 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
72 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
73 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
74 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
75 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
76 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
77 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
78 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
79 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
80 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
81 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
82 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
83 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
84 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
85 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
86 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
87 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
88 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
89 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
90 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
91 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
92 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
93 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."};
94 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
95 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
96 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
97 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."};
98 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
99 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
100 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
101 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
102 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"};
103 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"};
104 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
105 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
106 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
107 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
108 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"};
110 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
111 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
112 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
113 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
114 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
115 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
116 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
117 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
119 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)"};
120 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"};
122 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
123 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
124 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
125 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
126 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
128 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
129 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
130 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
132 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)"};
133 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
134 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
135 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
136 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
137 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)"};
138 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)"};
139 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)"};
140 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)"};
142 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)"};
143 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
144 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"};
145 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
146 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
148 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
149 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
150 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
151 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
153 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
154 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
155 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
156 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
157 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
158 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
159 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
161 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
162 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
163 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
164 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)"};
166 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"};
168 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"};
170 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
172 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
173 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"};
174 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
175 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
176 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
177 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
178 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)"};
180 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
182 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)"};
184 extern cvar_t v_glslgamma;
186 extern qboolean v_flipped_state;
188 static struct r_bloomstate_s
193 int bloomwidth, bloomheight;
195 int screentexturewidth, screentextureheight;
196 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
198 int bloomtexturewidth, bloomtextureheight;
199 rtexture_t *texture_bloom;
201 // arrays for rendering the screen passes
202 float screentexcoord2f[8];
203 float bloomtexcoord2f[8];
204 float offsettexcoord2f[8];
206 r_viewport_t viewport;
210 r_waterstate_t r_waterstate;
212 /// shadow volume bsp struct with automatically growing nodes buffer
215 rtexture_t *r_texture_blanknormalmap;
216 rtexture_t *r_texture_white;
217 rtexture_t *r_texture_grey128;
218 rtexture_t *r_texture_black;
219 rtexture_t *r_texture_notexture;
220 rtexture_t *r_texture_whitecube;
221 rtexture_t *r_texture_normalizationcube;
222 rtexture_t *r_texture_fogattenuation;
223 rtexture_t *r_texture_fogheighttexture;
224 rtexture_t *r_texture_gammaramps;
225 unsigned int r_texture_gammaramps_serial;
226 //rtexture_t *r_texture_fogintensity;
227 rtexture_t *r_texture_reflectcube;
229 // TODO: hash lookups?
230 typedef struct cubemapinfo_s
237 int r_texture_numcubemaps;
238 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
240 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
241 unsigned int r_numqueries;
242 unsigned int r_maxqueries;
244 typedef struct r_qwskincache_s
246 char name[MAX_QPATH];
247 skinframe_t *skinframe;
251 static r_qwskincache_t *r_qwskincache;
252 static int r_qwskincache_size;
254 /// vertex coordinates for a quad that covers the screen exactly
255 const float r_screenvertex3f[12] =
263 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
266 for (i = 0;i < verts;i++)
277 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
280 for (i = 0;i < verts;i++)
290 // FIXME: move this to client?
293 if (gamemode == GAME_NEHAHRA)
295 Cvar_Set("gl_fogenable", "0");
296 Cvar_Set("gl_fogdensity", "0.2");
297 Cvar_Set("gl_fogred", "0.3");
298 Cvar_Set("gl_foggreen", "0.3");
299 Cvar_Set("gl_fogblue", "0.3");
301 r_refdef.fog_density = 0;
302 r_refdef.fog_red = 0;
303 r_refdef.fog_green = 0;
304 r_refdef.fog_blue = 0;
305 r_refdef.fog_alpha = 1;
306 r_refdef.fog_start = 0;
307 r_refdef.fog_end = 16384;
308 r_refdef.fog_height = 1<<30;
309 r_refdef.fog_fadedepth = 128;
310 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
313 static void R_BuildBlankTextures(void)
315 unsigned char data[4];
316 data[2] = 128; // normal X
317 data[1] = 128; // normal Y
318 data[0] = 255; // normal Z
319 data[3] = 128; // height
320 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
325 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
330 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
335 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
338 static void R_BuildNoTexture(void)
341 unsigned char pix[16][16][4];
342 // this makes a light grey/dark grey checkerboard texture
343 for (y = 0;y < 16;y++)
345 for (x = 0;x < 16;x++)
347 if ((y < 8) ^ (x < 8))
363 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
366 static void R_BuildWhiteCube(void)
368 unsigned char data[6*1*1*4];
369 memset(data, 255, sizeof(data));
370 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
373 static void R_BuildNormalizationCube(void)
377 vec_t s, t, intensity;
380 data = Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
381 for (side = 0;side < 6;side++)
383 for (y = 0;y < NORMSIZE;y++)
385 for (x = 0;x < NORMSIZE;x++)
387 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
388 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
423 intensity = 127.0f / sqrt(DotProduct(v, v));
424 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
425 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
426 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
427 data[((side*64+y)*64+x)*4+3] = 255;
431 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
435 static void R_BuildFogTexture(void)
439 unsigned char data1[FOGWIDTH][4];
440 //unsigned char data2[FOGWIDTH][4];
443 r_refdef.fogmasktable_start = r_refdef.fog_start;
444 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
445 r_refdef.fogmasktable_range = r_refdef.fogrange;
446 r_refdef.fogmasktable_density = r_refdef.fog_density;
448 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
449 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
451 d = (x * r - r_refdef.fogmasktable_start);
452 if(developer_extra.integer)
453 Con_DPrintf("%f ", d);
455 if (r_fog_exp2.integer)
456 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
458 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
459 if(developer_extra.integer)
460 Con_DPrintf(" : %f ", alpha);
461 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
462 if(developer_extra.integer)
463 Con_DPrintf(" = %f\n", alpha);
464 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
467 for (x = 0;x < FOGWIDTH;x++)
469 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
474 //data2[x][0] = 255 - b;
475 //data2[x][1] = 255 - b;
476 //data2[x][2] = 255 - b;
479 if (r_texture_fogattenuation)
481 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
482 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
486 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
487 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
491 static void R_BuildFogHeightTexture(void)
493 unsigned char *inpixels;
501 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
502 if (r_refdef.fogheighttexturename[0])
503 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
506 r_refdef.fog_height_tablesize = 0;
507 if (r_texture_fogheighttexture)
508 R_FreeTexture(r_texture_fogheighttexture);
509 r_texture_fogheighttexture = NULL;
510 if (r_refdef.fog_height_table2d)
511 Mem_Free(r_refdef.fog_height_table2d);
512 r_refdef.fog_height_table2d = NULL;
513 if (r_refdef.fog_height_table1d)
514 Mem_Free(r_refdef.fog_height_table1d);
515 r_refdef.fog_height_table1d = NULL;
519 r_refdef.fog_height_tablesize = size;
520 r_refdef.fog_height_table1d = Mem_Alloc(r_main_mempool, size * 4);
521 r_refdef.fog_height_table2d = Mem_Alloc(r_main_mempool, size * size * 4);
522 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
524 // LordHavoc: now the magic - what is that table2d for? it is a cooked
525 // average fog color table accounting for every fog layer between a point
526 // and the camera. (Note: attenuation is handled separately!)
527 for (y = 0;y < size;y++)
529 for (x = 0;x < size;x++)
535 for (j = x;j <= y;j++)
537 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
543 for (j = x;j >= y;j--)
545 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
550 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
551 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
552 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
553 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
556 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
559 //=======================================================================================================================================================
561 static const char *builtinshaderstring =
562 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
563 "// written by Forest 'LordHavoc' Hale\n"
564 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
566 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
569 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
570 "#define USELIGHTMAP\n"
572 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
573 "#define USEEYEVECTOR\n"
576 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
577 "# extension GL_ARB_texture_rectangle : enable\n"
580 "#ifdef USESHADOWMAP2D\n"
581 "# ifdef GL_EXT_gpu_shader4\n"
582 "# extension GL_EXT_gpu_shader4 : enable\n"
584 "# ifdef GL_ARB_texture_gather\n"
585 "# extension GL_ARB_texture_gather : enable\n"
587 "# ifdef GL_AMD_texture_texture4\n"
588 "# extension GL_AMD_texture_texture4 : enable\n"
593 "#ifdef USESHADOWMAPCUBE\n"
594 "# extension GL_EXT_gpu_shader4 : enable\n"
597 "//#ifdef USESHADOWSAMPLER\n"
598 "//# extension GL_ARB_shadow : enable\n"
601 "//#ifdef __GLSL_CG_DATA_TYPES\n"
602 "//# define myhalf half\n"
603 "//# define myhalf2 half2\n"
604 "//# define myhalf3 half3\n"
605 "//# define myhalf4 half4\n"
607 "# define myhalf float\n"
608 "# define myhalf2 vec2\n"
609 "# define myhalf3 vec3\n"
610 "# define myhalf4 vec4\n"
613 "#ifdef VERTEX_SHADER\n"
614 "uniform mat4 ModelViewProjectionMatrix;\n"
617 "#ifdef MODE_DEPTH_OR_SHADOW\n"
618 "#ifdef VERTEX_SHADER\n"
621 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
624 "#else // !MODE_DEPTH_ORSHADOW\n"
629 "#ifdef MODE_SHOWDEPTH\n"
630 "#ifdef VERTEX_SHADER\n"
633 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
634 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
638 "#ifdef FRAGMENT_SHADER\n"
641 " gl_FragColor = gl_Color;\n"
644 "#else // !MODE_SHOWDEPTH\n"
649 "#ifdef MODE_POSTPROCESS\n"
650 "varying vec2 TexCoord1;\n"
651 "varying vec2 TexCoord2;\n"
653 "#ifdef VERTEX_SHADER\n"
656 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
657 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
659 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
664 "#ifdef FRAGMENT_SHADER\n"
665 "uniform sampler2D Texture_First;\n"
667 "uniform sampler2D Texture_Second;\n"
669 "#ifdef USEGAMMARAMPS\n"
670 "uniform sampler2D Texture_GammaRamps;\n"
672 "#ifdef USESATURATION\n"
673 "uniform float Saturation;\n"
675 "#ifdef USEVIEWTINT\n"
676 "uniform vec4 ViewTintColor;\n"
678 "//uncomment these if you want to use them:\n"
679 "uniform vec4 UserVec1;\n"
680 "uniform vec4 UserVec2;\n"
681 "// uniform vec4 UserVec3;\n"
682 "// uniform vec4 UserVec4;\n"
683 "// uniform float ClientTime;\n"
684 "uniform vec2 PixelSize;\n"
687 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
689 " gl_FragColor += texture2D(Texture_Second, TexCoord2);\n"
691 "#ifdef USEVIEWTINT\n"
692 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
695 "#ifdef USEPOSTPROCESSING\n"
696 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
697 "// 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"
698 " float sobel = 1.0;\n"
699 " // vec2 ts = textureSize(Texture_First, 0);\n"
700 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
701 " vec2 px = PixelSize;\n"
702 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
703 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
704 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
705 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
706 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
707 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
708 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
709 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
710 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
711 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
712 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
713 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
714 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
715 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
716 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
717 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
718 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
719 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
720 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
721 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
722 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
723 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
724 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
725 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
726 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
727 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
728 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
729 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
730 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
731 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
732 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
733 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
736 "#ifdef USESATURATION\n"
737 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
738 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
739 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
740 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
743 "#ifdef USEGAMMARAMPS\n"
744 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
745 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
746 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
750 "#else // !MODE_POSTPROCESS\n"
755 "#ifdef MODE_GENERIC\n"
756 "#ifdef USEDIFFUSE\n"
757 "varying vec2 TexCoord1;\n"
759 "#ifdef USESPECULAR\n"
760 "varying vec2 TexCoord2;\n"
762 "#ifdef VERTEX_SHADER\n"
765 " gl_FrontColor = gl_Color;\n"
766 "#ifdef USEDIFFUSE\n"
767 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
769 "#ifdef USESPECULAR\n"
770 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
772 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
776 "#ifdef FRAGMENT_SHADER\n"
777 "#ifdef USEDIFFUSE\n"
778 "uniform sampler2D Texture_First;\n"
780 "#ifdef USESPECULAR\n"
781 "uniform sampler2D Texture_Second;\n"
786 " gl_FragColor = gl_Color;\n"
787 "#ifdef USEDIFFUSE\n"
788 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
791 "#ifdef USESPECULAR\n"
792 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
793 "# ifdef USECOLORMAPPING\n"
794 " gl_FragColor *= tex2;\n"
797 " gl_FragColor += tex2;\n"
799 "# ifdef USEVERTEXTEXTUREBLEND\n"
800 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
805 "#else // !MODE_GENERIC\n"
810 "#ifdef MODE_BLOOMBLUR\n"
811 "varying TexCoord;\n"
812 "#ifdef VERTEX_SHADER\n"
815 " gl_FrontColor = gl_Color;\n"
816 " TexCoord = gl_MultiTexCoord0.xy;\n"
817 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
821 "#ifdef FRAGMENT_SHADER\n"
822 "uniform sampler2D Texture_First;\n"
823 "uniform vec4 BloomBlur_Parameters;\n"
828 " vec2 tc = TexCoord;\n"
829 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
830 " tc += BloomBlur_Parameters.xy;\n"
831 " for (i = 1;i < SAMPLES;i++)\n"
833 " color += texture2D(Texture_First, tc).rgb;\n"
834 " tc += BloomBlur_Parameters.xy;\n"
836 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
839 "#else // !MODE_BLOOMBLUR\n"
840 "#ifdef MODE_REFRACTION\n"
841 "varying vec2 TexCoord;\n"
842 "varying vec4 ModelViewProjectionPosition;\n"
843 "uniform mat4 TexMatrix;\n"
844 "#ifdef VERTEX_SHADER\n"
848 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
849 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
850 " ModelViewProjectionPosition = gl_Position;\n"
854 "#ifdef FRAGMENT_SHADER\n"
855 "uniform sampler2D Texture_Normal;\n"
856 "uniform sampler2D Texture_Refraction;\n"
857 "uniform sampler2D Texture_Reflection;\n"
859 "uniform vec4 DistortScaleRefractReflect;\n"
860 "uniform vec4 ScreenScaleRefractReflect;\n"
861 "uniform vec4 ScreenCenterRefractReflect;\n"
862 "uniform vec4 RefractColor;\n"
863 "uniform vec4 ReflectColor;\n"
864 "uniform float ReflectFactor;\n"
865 "uniform float ReflectOffset;\n"
869 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
870 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
871 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
872 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
873 " // FIXME temporary hack to detect the case that the reflection\n"
874 " // gets blackened at edges due to leaving the area that contains actual\n"
876 " // Remove this 'ack once we have a better way to stop this thing from\n"
878 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
879 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
880 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
881 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
882 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
883 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
886 "#else // !MODE_REFRACTION\n"
891 "#ifdef MODE_WATER\n"
892 "varying vec2 TexCoord;\n"
893 "varying vec3 EyeVector;\n"
894 "varying vec4 ModelViewProjectionPosition;\n"
895 "#ifdef VERTEX_SHADER\n"
896 "uniform vec3 EyePosition;\n"
897 "uniform mat4 TexMatrix;\n"
901 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
902 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
903 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
904 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
905 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
906 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
907 " ModelViewProjectionPosition = gl_Position;\n"
911 "#ifdef FRAGMENT_SHADER\n"
912 "uniform sampler2D Texture_Normal;\n"
913 "uniform sampler2D Texture_Refraction;\n"
914 "uniform sampler2D Texture_Reflection;\n"
916 "uniform vec4 DistortScaleRefractReflect;\n"
917 "uniform vec4 ScreenScaleRefractReflect;\n"
918 "uniform vec4 ScreenCenterRefractReflect;\n"
919 "uniform vec4 RefractColor;\n"
920 "uniform vec4 ReflectColor;\n"
921 "uniform float ReflectFactor;\n"
922 "uniform float ReflectOffset;\n"
926 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
927 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
928 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
929 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
930 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
931 " // FIXME temporary hack to detect the case that the reflection\n"
932 " // gets blackened at edges due to leaving the area that contains actual\n"
934 " // Remove this 'ack once we have a better way to stop this thing from\n"
936 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
937 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
938 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
939 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
940 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
941 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
942 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
943 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
944 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
945 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
946 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
947 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
950 "#else // !MODE_WATER\n"
955 "// common definitions between vertex shader and fragment shader:\n"
957 "varying vec2 TexCoord;\n"
958 "#ifdef USEVERTEXTEXTUREBLEND\n"
959 "varying vec2 TexCoord2;\n"
961 "#ifdef USELIGHTMAP\n"
962 "varying vec2 TexCoordLightmap;\n"
965 "#ifdef MODE_LIGHTSOURCE\n"
966 "varying vec3 CubeVector;\n"
969 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
970 "varying vec3 LightVector;\n"
973 "#ifdef USEEYEVECTOR\n"
974 "varying vec3 EyeVector;\n"
977 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
980 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
981 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
982 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
983 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
986 "#ifdef USEREFLECTION\n"
987 "varying vec4 ModelViewProjectionPosition;\n"
989 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
990 "uniform vec3 LightPosition;\n"
991 "varying vec4 ModelViewPosition;\n"
994 "#ifdef MODE_LIGHTSOURCE\n"
995 "uniform vec3 LightPosition;\n"
997 "uniform vec3 EyePosition;\n"
998 "#ifdef MODE_LIGHTDIRECTION\n"
999 "uniform vec3 LightDir;\n"
1001 "uniform vec4 FogPlane;\n"
1003 "#ifdef USESHADOWMAPORTHO\n"
1004 "varying vec3 ShadowMapTC;\n"
1011 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
1013 "// fragment shader specific:\n"
1014 "#ifdef FRAGMENT_SHADER\n"
1016 "uniform sampler2D Texture_Normal;\n"
1017 "uniform sampler2D Texture_Color;\n"
1018 "uniform sampler2D Texture_Gloss;\n"
1020 "uniform sampler2D Texture_Glow;\n"
1022 "#ifdef USEVERTEXTEXTUREBLEND\n"
1023 "uniform sampler2D Texture_SecondaryNormal;\n"
1024 "uniform sampler2D Texture_SecondaryColor;\n"
1025 "uniform sampler2D Texture_SecondaryGloss;\n"
1027 "uniform sampler2D Texture_SecondaryGlow;\n"
1030 "#ifdef USECOLORMAPPING\n"
1031 "uniform sampler2D Texture_Pants;\n"
1032 "uniform sampler2D Texture_Shirt;\n"
1035 "#ifdef USEFOGHEIGHTTEXTURE\n"
1036 "uniform sampler2D Texture_FogHeightTexture;\n"
1038 "uniform sampler2D Texture_FogMask;\n"
1040 "#ifdef USELIGHTMAP\n"
1041 "uniform sampler2D Texture_Lightmap;\n"
1043 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1044 "uniform sampler2D Texture_Deluxemap;\n"
1046 "#ifdef USEREFLECTION\n"
1047 "uniform sampler2D Texture_Reflection;\n"
1050 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1051 "uniform sampler2D Texture_ScreenDepth;\n"
1052 "uniform sampler2D Texture_ScreenNormalMap;\n"
1054 "#ifdef USEDEFERREDLIGHTMAP\n"
1055 "uniform sampler2D Texture_ScreenDiffuse;\n"
1056 "uniform sampler2D Texture_ScreenSpecular;\n"
1059 "uniform myhalf3 Color_Pants;\n"
1060 "uniform myhalf3 Color_Shirt;\n"
1061 "uniform myhalf3 FogColor;\n"
1064 "uniform float FogRangeRecip;\n"
1065 "uniform float FogPlaneViewDist;\n"
1066 "uniform float FogHeightFade;\n"
1067 "vec3 FogVertex(vec3 surfacecolor)\n"
1069 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1070 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1072 "#ifdef USEFOGHEIGHTTEXTURE\n"
1073 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1074 " fogfrac = fogheightpixel.a;\n"
1075 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1077 "# ifdef USEFOGOUTSIDE\n"
1078 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1080 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1082 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1087 "#ifdef USEOFFSETMAPPING\n"
1088 "uniform float OffsetMapping_Scale;\n"
1089 "vec2 OffsetMapping(vec2 TexCoord)\n"
1091 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1092 " // 14 sample relief mapping: linear search and then binary search\n"
1093 " // this basically steps forward a small amount repeatedly until it finds\n"
1094 " // itself inside solid, then jitters forward and back using decreasing\n"
1095 " // amounts to find the impact\n"
1096 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1097 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1098 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1099 " vec3 RT = vec3(TexCoord, 1);\n"
1100 " OffsetVector *= 0.1;\n"
1101 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1102 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1103 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1104 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1105 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1106 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1107 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1108 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1109 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1110 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1111 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1112 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1113 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1114 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1117 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1118 " // this basically moves forward the full distance, and then backs up based\n"
1119 " // on height of samples\n"
1120 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1121 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1122 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1123 " TexCoord += OffsetVector;\n"
1124 " OffsetVector *= 0.333;\n"
1125 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1126 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1127 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1128 " return TexCoord;\n"
1131 "#endif // USEOFFSETMAPPING\n"
1133 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1134 "uniform sampler2D Texture_Attenuation;\n"
1135 "uniform samplerCube Texture_Cube;\n"
1138 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1140 "#ifdef USESHADOWMAPRECT\n"
1141 "# ifdef USESHADOWSAMPLER\n"
1142 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1144 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1148 "#ifdef USESHADOWMAP2D\n"
1149 "# ifdef USESHADOWSAMPLER\n"
1150 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1152 "uniform sampler2D Texture_ShadowMap2D;\n"
1156 "#ifdef USESHADOWMAPVSDCT\n"
1157 "uniform samplerCube Texture_CubeProjection;\n"
1160 "#ifdef USESHADOWMAPCUBE\n"
1161 "# ifdef USESHADOWSAMPLER\n"
1162 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1164 "uniform samplerCube Texture_ShadowMapCube;\n"
1168 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1169 "uniform vec2 ShadowMap_TextureScale;\n"
1170 "uniform vec4 ShadowMap_Parameters;\n"
1173 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1174 "# ifdef USESHADOWMAPORTHO\n"
1175 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1177 "# ifdef USESHADOWMAPVSDCT\n"
1178 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1180 " vec3 adir = abs(dir);\n"
1181 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1182 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1183 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1186 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1188 " vec3 adir = abs(dir);\n"
1189 " float ma = adir.z;\n"
1190 " vec4 proj = vec4(dir, 2.5);\n"
1191 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1192 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1193 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1194 " return vec3(proj.xy * aparams.x + vec2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1198 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1200 "#ifdef USESHADOWMAPCUBE\n"
1201 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1203 " vec3 adir = abs(dir);\n"
1204 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1208 "# ifdef USESHADOWMAPRECT\n"
1209 "float ShadowMapCompare(vec3 dir)\n"
1211 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1213 "# ifdef USESHADOWSAMPLER\n"
1215 "# ifdef USESHADOWMAPPCF\n"
1216 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1217 " f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1219 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1224 "# ifdef USESHADOWMAPPCF\n"
1225 "# if USESHADOWMAPPCF > 1\n"
1226 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1227 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1228 " vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1229 " vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
1230 " vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
1231 " vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
1232 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1233 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1235 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1236 " vec2 offset = fract(shadowmaptc.xy);\n"
1237 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1238 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1239 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1240 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1241 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1244 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1248 "# ifdef USESHADOWMAPORTHO\n"
1249 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1256 "# ifdef USESHADOWMAP2D\n"
1257 "float ShadowMapCompare(vec3 dir)\n"
1259 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1262 "# ifdef USESHADOWSAMPLER\n"
1263 "# ifdef USESHADOWMAPPCF\n"
1264 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1265 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1266 " f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1268 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1271 "# ifdef USESHADOWMAPPCF\n"
1272 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1273 "# ifdef GL_ARB_texture_gather\n"
1274 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1276 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1278 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1279 "# if USESHADOWMAPPCF > 1\n"
1280 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1281 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1282 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1283 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1284 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1285 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1286 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1287 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1288 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1289 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1290 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1291 " locols.yz += group2.ab;\n"
1292 " hicols.yz += group8.rg;\n"
1293 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1294 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1295 " mix(locols, hicols, offset.y);\n"
1296 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1297 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1298 " f = dot(cols, vec4(1.0/25.0));\n"
1300 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1301 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1302 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1303 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1304 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1305 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1306 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1309 "# ifdef GL_EXT_gpu_shader4\n"
1310 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1312 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1314 "# if USESHADOWMAPPCF > 1\n"
1315 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1316 " center *= ShadowMap_TextureScale;\n"
1317 " vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1318 " vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
1319 " vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
1320 " vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
1321 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1322 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1324 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1325 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1326 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1327 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1328 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1329 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1333 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1336 "# ifdef USESHADOWMAPORTHO\n"
1337 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1344 "# ifdef USESHADOWMAPCUBE\n"
1345 "float ShadowMapCompare(vec3 dir)\n"
1347 " // apply depth texture cubemap as light filter\n"
1348 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1350 "# ifdef USESHADOWSAMPLER\n"
1351 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1353 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1358 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1359 "#endif // FRAGMENT_SHADER\n"
1364 "#ifdef MODE_DEFERREDGEOMETRY\n"
1365 "#ifdef VERTEX_SHADER\n"
1366 "uniform mat4 TexMatrix;\n"
1367 "#ifdef USEVERTEXTEXTUREBLEND\n"
1368 "uniform mat4 BackgroundTexMatrix;\n"
1370 "uniform mat4 ModelViewMatrix;\n"
1373 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1374 "#ifdef USEVERTEXTEXTUREBLEND\n"
1375 " gl_FrontColor = gl_Color;\n"
1376 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1379 " // transform unnormalized eye direction into tangent space\n"
1380 "#ifdef USEOFFSETMAPPING\n"
1381 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1382 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1383 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1384 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1387 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1388 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1389 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1390 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1392 "#endif // VERTEX_SHADER\n"
1394 "#ifdef FRAGMENT_SHADER\n"
1397 "#ifdef USEOFFSETMAPPING\n"
1398 " // apply offsetmapping\n"
1399 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1400 "#define TexCoord TexCoordOffset\n"
1403 "#ifdef USEALPHAKILL\n"
1404 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1408 "#ifdef USEVERTEXTEXTUREBLEND\n"
1409 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1410 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1411 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1412 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1415 "#ifdef USEVERTEXTEXTUREBLEND\n"
1416 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1417 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1419 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1420 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1423 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1425 "#endif // FRAGMENT_SHADER\n"
1426 "#else // !MODE_DEFERREDGEOMETRY\n"
1431 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1432 "#ifdef VERTEX_SHADER\n"
1433 "uniform mat4 ModelViewMatrix;\n"
1436 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1437 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1439 "#endif // VERTEX_SHADER\n"
1441 "#ifdef FRAGMENT_SHADER\n"
1442 "uniform mat4 ViewToLight;\n"
1443 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1444 "uniform vec2 ScreenToDepth;\n"
1445 "uniform myhalf3 DeferredColor_Ambient;\n"
1446 "uniform myhalf3 DeferredColor_Diffuse;\n"
1447 "#ifdef USESPECULAR\n"
1448 "uniform myhalf3 DeferredColor_Specular;\n"
1449 "uniform myhalf SpecularPower;\n"
1451 "uniform myhalf2 PixelToScreenTexCoord;\n"
1454 " // calculate viewspace pixel position\n"
1455 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1457 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1458 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1459 " // decode viewspace pixel normal\n"
1460 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1461 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1462 " // surfacenormal = pixel normal in viewspace\n"
1463 " // LightVector = pixel to light in viewspace\n"
1464 " // CubeVector = position in lightspace\n"
1465 " // eyevector = pixel to view in viewspace\n"
1466 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1467 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1468 "#ifdef USEDIFFUSE\n"
1469 " // calculate diffuse shading\n"
1470 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1471 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1473 "#ifdef USESPECULAR\n"
1474 " // calculate directional shading\n"
1475 " vec3 eyevector = position * -1.0;\n"
1476 "# ifdef USEEXACTSPECULARMATH\n"
1477 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1479 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1480 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1484 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1485 " fade *= ShadowMapCompare(CubeVector);\n"
1488 "#ifdef USEDIFFUSE\n"
1489 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1491 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1493 "#ifdef USESPECULAR\n"
1494 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1496 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1499 "# ifdef USECUBEFILTER\n"
1500 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1501 " gl_FragData[0].rgb *= cubecolor;\n"
1502 " gl_FragData[1].rgb *= cubecolor;\n"
1505 "#endif // FRAGMENT_SHADER\n"
1506 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1511 "#ifdef VERTEX_SHADER\n"
1512 "uniform mat4 TexMatrix;\n"
1513 "#ifdef USEVERTEXTEXTUREBLEND\n"
1514 "uniform mat4 BackgroundTexMatrix;\n"
1516 "#ifdef MODE_LIGHTSOURCE\n"
1517 "uniform mat4 ModelToLight;\n"
1519 "#ifdef USESHADOWMAPORTHO\n"
1520 "uniform mat4 ShadowMapMatrix;\n"
1524 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1525 " gl_FrontColor = gl_Color;\n"
1527 " // copy the surface texcoord\n"
1528 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1529 "#ifdef USEVERTEXTEXTUREBLEND\n"
1530 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1532 "#ifdef USELIGHTMAP\n"
1533 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1536 "#ifdef MODE_LIGHTSOURCE\n"
1537 " // transform vertex position into light attenuation/cubemap space\n"
1538 " // (-1 to +1 across the light box)\n"
1539 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1541 "# ifdef USEDIFFUSE\n"
1542 " // transform unnormalized light direction into tangent space\n"
1543 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1544 " // normalize it per pixel)\n"
1545 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1546 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1547 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1548 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1552 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1553 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1554 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1555 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1558 " // transform unnormalized eye direction into tangent space\n"
1559 "#ifdef USEEYEVECTOR\n"
1560 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1561 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1562 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1563 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1567 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1568 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1571 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1572 " VectorS = gl_MultiTexCoord1.xyz;\n"
1573 " VectorT = gl_MultiTexCoord2.xyz;\n"
1574 " VectorR = gl_MultiTexCoord3.xyz;\n"
1577 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1578 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1580 "#ifdef USESHADOWMAPORTHO\n"
1581 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1584 "#ifdef USEREFLECTION\n"
1585 " ModelViewProjectionPosition = gl_Position;\n"
1588 "#endif // VERTEX_SHADER\n"
1593 "#ifdef FRAGMENT_SHADER\n"
1594 "#ifdef USEDEFERREDLIGHTMAP\n"
1595 "uniform myhalf2 PixelToScreenTexCoord;\n"
1596 "uniform myhalf3 DeferredMod_Diffuse;\n"
1597 "uniform myhalf3 DeferredMod_Specular;\n"
1599 "uniform myhalf3 Color_Ambient;\n"
1600 "uniform myhalf3 Color_Diffuse;\n"
1601 "uniform myhalf3 Color_Specular;\n"
1602 "uniform myhalf SpecularPower;\n"
1604 "uniform myhalf3 Color_Glow;\n"
1606 "uniform myhalf Alpha;\n"
1607 "#ifdef USEREFLECTION\n"
1608 "uniform vec4 DistortScaleRefractReflect;\n"
1609 "uniform vec4 ScreenScaleRefractReflect;\n"
1610 "uniform vec4 ScreenCenterRefractReflect;\n"
1611 "uniform myhalf4 ReflectColor;\n"
1613 "#ifdef USEREFLECTCUBE\n"
1614 "uniform mat4 ModelToReflectCube;\n"
1615 "uniform sampler2D Texture_ReflectMask;\n"
1616 "uniform samplerCube Texture_ReflectCube;\n"
1618 "#ifdef MODE_LIGHTDIRECTION\n"
1619 "uniform myhalf3 LightColor;\n"
1621 "#ifdef MODE_LIGHTSOURCE\n"
1622 "uniform myhalf3 LightColor;\n"
1626 "#ifdef USEOFFSETMAPPING\n"
1627 " // apply offsetmapping\n"
1628 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1629 "#define TexCoord TexCoordOffset\n"
1632 " // combine the diffuse textures (base, pants, shirt)\n"
1633 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1634 "#ifdef USEALPHAKILL\n"
1635 " if (color.a < 0.5)\n"
1638 " color.a *= Alpha;\n"
1639 "#ifdef USECOLORMAPPING\n"
1640 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1642 "#ifdef USEVERTEXTEXTUREBLEND\n"
1643 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1644 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1645 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1646 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1648 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1651 " // get the surface normal\n"
1652 "#ifdef USEVERTEXTEXTUREBLEND\n"
1653 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1655 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1658 " // get the material colors\n"
1659 " myhalf3 diffusetex = color.rgb;\n"
1660 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1661 "# ifdef USEVERTEXTEXTUREBLEND\n"
1662 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1664 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1668 "#ifdef USEREFLECTCUBE\n"
1669 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1670 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1671 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1672 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1678 "#ifdef MODE_LIGHTSOURCE\n"
1679 " // light source\n"
1680 "#ifdef USEDIFFUSE\n"
1681 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1682 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1683 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1684 "#ifdef USESPECULAR\n"
1685 "#ifdef USEEXACTSPECULARMATH\n"
1686 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1688 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1689 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1691 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1694 " color.rgb = diffusetex * Color_Ambient;\n"
1696 " color.rgb *= LightColor;\n"
1697 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1698 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1699 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1701 "# ifdef USECUBEFILTER\n"
1702 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1704 "#endif // MODE_LIGHTSOURCE\n"
1709 "#ifdef MODE_LIGHTDIRECTION\n"
1711 "#ifdef USEDIFFUSE\n"
1712 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1714 "#define lightcolor LightColor\n"
1715 "#endif // MODE_LIGHTDIRECTION\n"
1716 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1718 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1719 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1720 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1721 " // convert modelspace light vector to tangentspace\n"
1722 " myhalf3 lightnormal;\n"
1723 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1724 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1725 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1726 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1727 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1728 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1729 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1730 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1731 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1732 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1733 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1734 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1735 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1736 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1737 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1739 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1740 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1741 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1747 "#ifdef MODE_LIGHTMAP\n"
1748 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1749 "#endif // MODE_LIGHTMAP\n"
1750 "#ifdef MODE_VERTEXCOLOR\n"
1751 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1752 "#endif // MODE_VERTEXCOLOR\n"
1753 "#ifdef MODE_FLATCOLOR\n"
1754 " color.rgb = diffusetex * Color_Ambient;\n"
1755 "#endif // MODE_FLATCOLOR\n"
1761 "# ifdef USEDIFFUSE\n"
1762 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1763 "# ifdef USESPECULAR\n"
1764 "# ifdef USEEXACTSPECULARMATH\n"
1765 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1767 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1768 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1770 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1772 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1775 " color.rgb = diffusetex * Color_Ambient;\n"
1779 "#ifdef USESHADOWMAPORTHO\n"
1780 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1783 "#ifdef USEDEFERREDLIGHTMAP\n"
1784 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1785 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1786 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1790 "#ifdef USEVERTEXTEXTUREBLEND\n"
1791 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1793 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1798 " color.rgb = FogVertex(color.rgb);\n"
1801 " // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1802 "#ifdef USEREFLECTION\n"
1803 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1804 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1805 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1806 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1807 " // FIXME temporary hack to detect the case that the reflection\n"
1808 " // gets blackened at edges due to leaving the area that contains actual\n"
1810 " // Remove this 'ack once we have a better way to stop this thing from\n"
1812 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1813 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1814 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1815 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1816 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1817 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1820 " gl_FragColor = vec4(color);\n"
1822 "#endif // FRAGMENT_SHADER\n"
1824 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1825 "#endif // !MODE_DEFERREDGEOMETRY\n"
1826 "#endif // !MODE_WATER\n"
1827 "#endif // !MODE_REFRACTION\n"
1828 "#endif // !MODE_BLOOMBLUR\n"
1829 "#endif // !MODE_GENERIC\n"
1830 "#endif // !MODE_POSTPROCESS\n"
1831 "#endif // !MODE_SHOWDEPTH\n"
1832 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1836 =========================================================================================================================================================
1840 =========================================================================================================================================================
1844 =========================================================================================================================================================
1848 =========================================================================================================================================================
1852 =========================================================================================================================================================
1856 =========================================================================================================================================================
1860 =========================================================================================================================================================
1863 const char *builtincgshaderstring =
1864 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1865 "// written by Forest 'LordHavoc' Hale\n"
1866 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1868 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1869 "#if defined(USEREFLECTION)\n"
1870 "#undef USESHADOWMAPORTHO\n"
1873 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1876 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1877 "#define USELIGHTMAP\n"
1879 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1880 "#define USEEYEVECTOR\n"
1883 "#ifdef FRAGMENT_SHADER\n"
1884 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1887 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1888 "#ifdef VERTEX_SHADER\n"
1891 "float4 gl_Vertex : POSITION,\n"
1892 "uniform float4x4 ModelViewProjectionMatrix,\n"
1893 "out float4 gl_Position : POSITION\n"
1896 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1899 "#else // !MODE_DEPTH_ORSHADOW\n"
1904 "#ifdef MODE_SHOWDEPTH\n"
1905 "#ifdef VERTEX_SHADER\n"
1908 "float4 gl_Vertex : POSITION,\n"
1909 "uniform float4x4 ModelViewProjectionMatrix,\n"
1910 "out float4 gl_Position : POSITION,\n"
1911 "out float4 gl_FrontColor : COLOR0\n"
1914 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1915 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1919 "#ifdef FRAGMENT_SHADER\n"
1922 "float4 gl_FrontColor : COLOR0,\n"
1923 "out float4 gl_FragColor : COLOR\n"
1926 " gl_FragColor = gl_FrontColor;\n"
1929 "#else // !MODE_SHOWDEPTH\n"
1934 "#ifdef MODE_POSTPROCESS\n"
1936 "#ifdef VERTEX_SHADER\n"
1939 "float4 gl_Vertex : POSITION,\n"
1940 "uniform float4x4 ModelViewProjectionMatrix,\n"
1941 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1942 "float4 gl_MultiTexCoord1 : TEXCOORD4,\n"
1943 "out float4 gl_Position : POSITION,\n"
1944 "out float2 TexCoord1 : TEXCOORD0,\n"
1945 "out float2 TexCoord2 : TEXCOORD1\n"
1948 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1949 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1951 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
1956 "#ifdef FRAGMENT_SHADER\n"
1959 "float2 TexCoord1 : TEXCOORD0,\n"
1960 "float2 TexCoord2 : TEXCOORD1,\n"
1961 "uniform sampler2D Texture_First,\n"
1963 "uniform sampler2D Texture_Second,\n"
1965 "#ifdef USEGAMMARAMPS\n"
1966 "uniform sampler2D Texture_GammaRamps,\n"
1968 "#ifdef USESATURATION\n"
1969 "uniform float Saturation,\n"
1971 "#ifdef USEVIEWTINT\n"
1972 "uniform float4 ViewTintColor,\n"
1974 "uniform float4 UserVec1,\n"
1975 "uniform float4 UserVec2,\n"
1976 "uniform float4 UserVec3,\n"
1977 "uniform float4 UserVec4,\n"
1978 "uniform float ClientTime,\n"
1979 "uniform float2 PixelSize,\n"
1980 "out float4 gl_FragColor : COLOR\n"
1983 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
1985 " gl_FragColor += tex2D(Texture_Second, TexCoord2);\n"
1987 "#ifdef USEVIEWTINT\n"
1988 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
1991 "#ifdef USEPOSTPROCESSING\n"
1992 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
1993 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
1994 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
1995 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
1996 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
1997 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
1998 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
1999 " gl_FragColor /= (1 + 5 * UserVec1.y);\n"
2002 "#ifdef USESATURATION\n"
2003 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2004 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2005 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2006 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2009 "#ifdef USEGAMMARAMPS\n"
2010 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2011 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2012 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2016 "#else // !MODE_POSTPROCESS\n"
2021 "#ifdef MODE_GENERIC\n"
2022 "#ifdef VERTEX_SHADER\n"
2025 "float4 gl_Vertex : POSITION,\n"
2026 "uniform float4x4 ModelViewProjectionMatrix,\n"
2027 "float4 gl_Color : COLOR0,\n"
2028 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2029 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2030 "out float4 gl_Position : POSITION,\n"
2031 "out float4 gl_FrontColor : COLOR,\n"
2032 "out float2 TexCoord1 : TEXCOORD0,\n"
2033 "out float2 TexCoord2 : TEXCOORD1\n"
2036 " gl_FrontColor = gl_Color;\n"
2037 "#ifdef USEDIFFUSE\n"
2038 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2040 "#ifdef USESPECULAR\n"
2041 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2043 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2047 "#ifdef FRAGMENT_SHADER\n"
2051 "float4 gl_FrontColor : COLOR,\n"
2052 "float2 TexCoord1 : TEXCOORD0,\n"
2053 "float2 TexCoord2 : TEXCOORD1,\n"
2054 "#ifdef USEDIFFUSE\n"
2055 "uniform sampler2D Texture_First,\n"
2057 "#ifdef USESPECULAR\n"
2058 "uniform sampler2D Texture_Second,\n"
2060 "out float4 gl_FragColor : COLOR\n"
2063 " gl_FragColor = gl_FrontColor;\n"
2064 "#ifdef USEDIFFUSE\n"
2065 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2068 "#ifdef USESPECULAR\n"
2069 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2070 "# ifdef USECOLORMAPPING\n"
2071 " gl_FragColor *= tex2;\n"
2074 " gl_FragColor += tex2;\n"
2076 "# ifdef USEVERTEXTEXTUREBLEND\n"
2077 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2082 "#else // !MODE_GENERIC\n"
2087 "#ifdef MODE_BLOOMBLUR\n"
2088 "#ifdef VERTEX_SHADER\n"
2091 "float4 gl_Vertex : POSITION,\n"
2092 "uniform float4x4 ModelViewProjectionMatrix,\n"
2093 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2094 "out float4 gl_Position : POSITION,\n"
2095 "out float2 TexCoord : TEXCOORD0\n"
2098 " TexCoord = gl_MultiTexCoord0.xy;\n"
2099 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2103 "#ifdef FRAGMENT_SHADER\n"
2107 "float2 TexCoord : TEXCOORD0,\n"
2108 "uniform sampler2D Texture_First,\n"
2109 "uniform float4 BloomBlur_Parameters,\n"
2110 "out float4 gl_FragColor : COLOR\n"
2114 " float2 tc = TexCoord;\n"
2115 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2116 " tc += BloomBlur_Parameters.xy;\n"
2117 " for (i = 1;i < SAMPLES;i++)\n"
2119 " color += tex2D(Texture_First, tc).rgb;\n"
2120 " tc += BloomBlur_Parameters.xy;\n"
2122 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2125 "#else // !MODE_BLOOMBLUR\n"
2126 "#ifdef MODE_REFRACTION\n"
2127 "#ifdef VERTEX_SHADER\n"
2130 "float4 gl_Vertex : POSITION,\n"
2131 "uniform float4x4 ModelViewProjectionMatrix,\n"
2132 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2133 "uniform float4x4 TexMatrix,\n"
2134 "uniform float3 EyePosition,\n"
2135 "out float4 gl_Position : POSITION,\n"
2136 "out float2 TexCoord : TEXCOORD0,\n"
2137 "out float3 EyeVector : TEXCOORD1,\n"
2138 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2141 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2142 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2143 " ModelViewProjectionPosition = gl_Position;\n"
2147 "#ifdef FRAGMENT_SHADER\n"
2150 "float2 TexCoord : TEXCOORD0,\n"
2151 "float3 EyeVector : TEXCOORD1,\n"
2152 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2153 "uniform sampler2D Texture_Normal,\n"
2154 "uniform sampler2D Texture_Refraction,\n"
2155 "uniform sampler2D Texture_Reflection,\n"
2156 "uniform float4 DistortScaleRefractReflect,\n"
2157 "uniform float4 ScreenScaleRefractReflect,\n"
2158 "uniform float4 ScreenCenterRefractReflect,\n"
2159 "uniform float4 RefractColor,\n"
2160 "out float4 gl_FragColor : COLOR\n"
2163 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2164 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2165 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2166 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
2167 " // FIXME temporary hack to detect the case that the reflection\n"
2168 " // gets blackened at edges due to leaving the area that contains actual\n"
2170 " // Remove this 'ack once we have a better way to stop this thing from\n"
2172 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2173 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2174 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2175 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2176 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2177 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2180 "#else // !MODE_REFRACTION\n"
2185 "#ifdef MODE_WATER\n"
2186 "#ifdef VERTEX_SHADER\n"
2190 "float4 gl_Vertex : POSITION,\n"
2191 "uniform float4x4 ModelViewProjectionMatrix,\n"
2192 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2193 "uniform float4x4 TexMatrix,\n"
2194 "uniform float3 EyePosition,\n"
2195 "out float4 gl_Position : POSITION,\n"
2196 "out float2 TexCoord : TEXCOORD0,\n"
2197 "out float3 EyeVector : TEXCOORD1,\n"
2198 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2201 " TexCoord = float2(mul(TexMatrix, gl_MultiTexCoord0));\n"
2202 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2203 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2204 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2205 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2206 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2207 " ModelViewProjectionPosition = gl_Position;\n"
2211 "#ifdef FRAGMENT_SHADER\n"
2214 "float2 TexCoord : TEXCOORD0,\n"
2215 "float3 EyeVector : TEXCOORD1,\n"
2216 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2217 "uniform sampler2D Texture_Normal,\n"
2218 "uniform sampler2D Texture_Refraction,\n"
2219 "uniform sampler2D Texture_Reflection,\n"
2220 "uniform float4 DistortScaleRefractReflect,\n"
2221 "uniform float4 ScreenScaleRefractReflect,\n"
2222 "uniform float4 ScreenCenterRefractReflect,\n"
2223 "uniform float4 RefractColor,\n"
2224 "uniform float4 ReflectColor,\n"
2225 "uniform float ReflectFactor,\n"
2226 "uniform float ReflectOffset,\n"
2227 "out float4 gl_FragColor : COLOR\n"
2230 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2231 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2232 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2233 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5))).xyxy * DistortScaleRefractReflect;\n"
2234 " // FIXME temporary hack to detect the case that the reflection\n"
2235 " // gets blackened at edges due to leaving the area that contains actual\n"
2237 " // Remove this 'ack once we have a better way to stop this thing from\n"
2239 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2240 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2241 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2242 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2243 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2244 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2245 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2246 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2247 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2248 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2249 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2250 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2253 "#else // !MODE_WATER\n"
2258 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
2260 "// fragment shader specific:\n"
2261 "#ifdef FRAGMENT_SHADER\n"
2264 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler2D Texture_FogMask, sampler2D Texture_FogHeightTexture)\n"
2267 "#ifdef USEFOGHEIGHTTEXTURE\n"
2268 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2269 " fogfrac = fogheightpixel.a;\n"
2270 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2272 "# ifdef USEFOGOUTSIDE\n"
2273 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2275 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2277 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2282 "#ifdef USEOFFSETMAPPING\n"
2283 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler2D Texture_Normal)\n"
2285 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2286 " // 14 sample relief mapping: linear search and then binary search\n"
2287 " // this basically steps forward a small amount repeatedly until it finds\n"
2288 " // itself inside solid, then jitters forward and back using decreasing\n"
2289 " // amounts to find the impact\n"
2290 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2291 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2292 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2293 " float3 RT = float3(TexCoord, 1);\n"
2294 " OffsetVector *= 0.1;\n"
2295 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2296 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2297 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2298 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2299 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2300 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2301 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2302 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2303 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2304 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2305 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2306 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2307 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2308 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2311 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2312 " // this basically moves forward the full distance, and then backs up based\n"
2313 " // on height of samples\n"
2314 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2315 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2316 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2317 " TexCoord += OffsetVector;\n"
2318 " OffsetVector *= 0.333;\n"
2319 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2320 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2321 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2322 " return TexCoord;\n"
2325 "#endif // USEOFFSETMAPPING\n"
2327 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2328 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2329 "# ifdef USESHADOWMAPORTHO\n"
2330 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2332 "# ifdef USESHADOWMAPVSDCT\n"
2333 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2335 " float3 adir = abs(dir);\n"
2336 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2337 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2338 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2341 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2343 " float3 adir = abs(dir);\n"
2344 " float ma = adir.z;\n"
2345 " float4 proj = float4(dir, 2.5);\n"
2346 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2347 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2348 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2349 " return float3(proj.xy * aparams.x + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2353 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2355 "#ifdef USESHADOWMAPCUBE\n"
2356 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2358 " float3 adir = abs(dir);\n"
2359 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2363 "# ifdef USESHADOWMAPRECT\n"
2364 "#ifdef USESHADOWMAPVSDCT\n"
2365 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2367 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2370 "#ifdef USESHADOWMAPVSDCT\n"
2371 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2373 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2376 "# ifdef USESHADOWSAMPLER\n"
2378 "# ifdef USESHADOWMAPPCF\n"
2379 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2380 " f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2382 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2387 "# ifdef USESHADOWMAPPCF\n"
2388 "# if USESHADOWMAPPCF > 1\n"
2389 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2390 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2391 " float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2392 " float4 row2 = step(shadowmaptc.z, float4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
2393 " float4 row3 = step(shadowmaptc.z, float4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
2394 " float4 row4 = step(shadowmaptc.z, float4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
2395 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2396 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2398 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2399 " float2 offset = frac(shadowmaptc.xy);\n"
2400 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2401 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2402 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2403 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2404 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2407 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2411 "# ifdef USESHADOWMAPORTHO\n"
2412 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2419 "# ifdef USESHADOWMAP2D\n"
2420 "#ifdef USESHADOWMAPVSDCT\n"
2421 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2423 "float ShadowMapCompare(float3 dir, sampler2D Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2426 "#ifdef USESHADOWMAPVSDCT\n"
2427 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2429 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2433 "# ifdef USESHADOWSAMPLER\n"
2434 "# ifdef USESHADOWMAPPCF\n"
2435 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, float3(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
2436 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2437 " f = dot(float4(0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2439 " f = shadow2D(Texture_ShadowMap2D, float3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
2442 "# ifdef USESHADOWMAPPCF\n"
2443 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2444 "# ifdef GL_ARB_texture_gather\n"
2445 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec(x, y))\n"
2447 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x,y)*ShadowMap_TextureScale)\n"
2449 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2450 " center *= ShadowMap_TextureScale;\n"
2451 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2452 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2453 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2454 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2455 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2456 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2457 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2459 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale) \n"
2460 "# if USESHADOWMAPPCF > 1\n"
2461 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2462 " center *= ShadowMap_TextureScale;\n"
2463 " float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2464 " float4 row2 = step(shadowmaptc.z, float4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
2465 " float4 row3 = step(shadowmaptc.z, float4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
2466 " float4 row4 = step(shadowmaptc.z, float4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
2467 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2468 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2470 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2471 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2472 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2473 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2474 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2475 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25));\n"
2479 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2482 "# ifdef USESHADOWMAPORTHO\n"
2483 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2490 "# ifdef USESHADOWMAPCUBE\n"
2491 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2493 " // apply depth texture cubemap as light filter\n"
2494 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2496 "# ifdef USESHADOWSAMPLER\n"
2497 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2499 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2504 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE)\n"
2505 "#endif // FRAGMENT_SHADER\n"
2510 "#ifdef MODE_DEFERREDGEOMETRY\n"
2511 "#ifdef VERTEX_SHADER\n"
2514 "float4 gl_Vertex : POSITION,\n"
2515 "uniform float4x4 ModelViewProjectionMatrix,\n"
2516 "#ifdef USEVERTEXTEXTUREBLEND\n"
2517 "float4 gl_Color : COLOR0,\n"
2519 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2520 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2521 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2522 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2523 "uniform float4x4 TexMatrix,\n"
2524 "#ifdef USEVERTEXTEXTUREBLEND\n"
2525 "uniform float4x4 BackgroundTexMatrix,\n"
2527 "uniform float4x4 ModelViewMatrix,\n"
2528 "#ifdef USEOFFSETMAPPING\n"
2529 "uniform float3 EyePosition,\n"
2531 "out float4 gl_Position : POSITION,\n"
2532 "out float4 gl_FrontColor : COLOR,\n"
2533 "out float4 TexCoordBoth : TEXCOORD0,\n"
2534 "#ifdef USEOFFSETMAPPING\n"
2535 "out float3 EyeVector : TEXCOORD2,\n"
2537 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2538 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2539 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2542 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2543 "#ifdef USEVERTEXTEXTUREBLEND\n"
2544 " gl_FrontColor = gl_Color;\n"
2545 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2548 " // transform unnormalized eye direction into tangent space\n"
2549 "#ifdef USEOFFSETMAPPING\n"
2550 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2551 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2552 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2553 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2556 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2557 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2558 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2559 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2561 "#endif // VERTEX_SHADER\n"
2563 "#ifdef FRAGMENT_SHADER\n"
2566 "float4 TexCoordBoth : TEXCOORD0,\n"
2567 "float3 EyeVector : TEXCOORD2,\n"
2568 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2569 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2570 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2571 "uniform sampler2D Texture_Normal,\n"
2572 "#ifdef USEALPHAKILL\n"
2573 "uniform sampler2D Texture_Color,\n"
2575 "uniform sampler2D Texture_Gloss,\n"
2576 "#ifdef USEVERTEXTEXTUREBLEND\n"
2577 "uniform sampler2D Texture_SecondaryNormal,\n"
2578 "uniform sampler2D Texture_SecondaryGloss,\n"
2580 "#ifdef USEOFFSETMAPPING\n"
2581 "uniform float OffsetMapping_Scale,\n"
2583 "uniform half SpecularPower,\n"
2584 "out float4 gl_FragColor : COLOR\n"
2587 " float2 TexCoord = TexCoordBoth.xy;\n"
2588 "#ifdef USEOFFSETMAPPING\n"
2589 " // apply offsetmapping\n"
2590 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2591 "#define TexCoord TexCoordOffset\n"
2594 "#ifdef USEALPHAKILL\n"
2595 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2599 "#ifdef USEVERTEXTEXTUREBLEND\n"
2600 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2601 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2602 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2603 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2606 "#ifdef USEVERTEXTEXTUREBLEND\n"
2607 " float3 surfacenormal = lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend) - float3(0.5, 0.5, 0.5);\n"
2608 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2610 " float3 surfacenormal = float3(tex2D(Texture_Normal, TexCoord)) - float3(0.5, 0.5, 0.5);\n"
2611 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2614 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), 1);\n"
2616 "#endif // FRAGMENT_SHADER\n"
2617 "#else // !MODE_DEFERREDGEOMETRY\n"
2622 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2623 "#ifdef VERTEX_SHADER\n"
2626 "float4 gl_Vertex : POSITION,\n"
2627 "uniform float4x4 ModelViewProjectionMatrix,\n"
2628 "uniform float4x4 ModelViewMatrix,\n"
2629 "out float4 gl_Position : POSITION,\n"
2630 "out float4 ModelViewPosition : TEXCOORD0\n"
2633 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2634 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2636 "#endif // VERTEX_SHADER\n"
2638 "#ifdef FRAGMENT_SHADER\n"
2641 "float2 Pixel : WPOS,\n"
2642 "float4 ModelViewPosition : TEXCOORD0,\n"
2643 "uniform float4x4 ViewToLight,\n"
2644 "uniform float2 ScreenToDepth, // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2645 "uniform float3 LightPosition,\n"
2646 "uniform half2 PixelToScreenTexCoord,\n"
2647 "uniform half3 DeferredColor_Ambient,\n"
2648 "uniform half3 DeferredColor_Diffuse,\n"
2649 "#ifdef USESPECULAR\n"
2650 "uniform half3 DeferredColor_Specular,\n"
2651 "uniform half SpecularPower,\n"
2653 "uniform sampler2D Texture_Attenuation,\n"
2654 "uniform sampler2D Texture_ScreenDepth,\n"
2655 "uniform sampler2D Texture_ScreenNormalMap,\n"
2657 "#ifdef USECUBEFILTER\n"
2658 "uniform samplerCUBE Texture_Cube,\n"
2661 "#ifdef USESHADOWMAPRECT\n"
2662 "# ifdef USESHADOWSAMPLER\n"
2663 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
2665 "uniform samplerRECT Texture_ShadowMapRect,\n"
2669 "#ifdef USESHADOWMAP2D\n"
2670 "# ifdef USESHADOWSAMPLER\n"
2671 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
2673 "uniform sampler2D Texture_ShadowMap2D,\n"
2677 "#ifdef USESHADOWMAPVSDCT\n"
2678 "uniform samplerCUBE Texture_CubeProjection,\n"
2681 "#ifdef USESHADOWMAPCUBE\n"
2682 "# ifdef USESHADOWSAMPLER\n"
2683 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
2685 "uniform samplerCUBE Texture_ShadowMapCube,\n"
2689 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2690 "uniform float2 ShadowMap_TextureScale,\n"
2691 "uniform float4 ShadowMap_Parameters,\n"
2694 "out float4 gl_FragData0 : COLOR0,\n"
2695 "out float4 gl_FragData1 : COLOR1\n"
2698 " // calculate viewspace pixel position\n"
2699 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2700 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2701 " float3 position;\n"
2702 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2703 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2704 " // decode viewspace pixel normal\n"
2705 " half4 normalmap = tex2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
2706 " half3 surfacenormal = normalize(normalmap.rgb - half3(0.5,0.5,0.5));\n"
2707 " // surfacenormal = pixel normal in viewspace\n"
2708 " // LightVector = pixel to light in viewspace\n"
2709 " // CubeVector = position in lightspace\n"
2710 " // eyevector = pixel to view in viewspace\n"
2711 " float3 CubeVector = float3(mul(ViewToLight, float4(position,1)));\n"
2712 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
2713 "#ifdef USEDIFFUSE\n"
2714 " // calculate diffuse shading\n"
2715 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2716 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2718 "#ifdef USESPECULAR\n"
2719 " // calculate directional shading\n"
2720 " float3 eyevector = position * -1.0;\n"
2721 "# ifdef USEEXACTSPECULARMATH\n"
2722 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2724 " half3 specularnormal = normalize(lightnormal + half3(normalize(eyevector)));\n"
2725 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2729 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2730 " fade *= ShadowMapCompare(CubeVector,\n"
2731 "# if defined(USESHADOWMAP2D)\n"
2732 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2734 "# if defined(USESHADOWMAPRECT)\n"
2735 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2737 "# if defined(USESHADOWMAPCUBE)\n"
2738 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2741 "#ifdef USESHADOWMAPVSDCT\n"
2742 ", Texture_CubeProjection\n"
2747 "#ifdef USEDIFFUSE\n"
2748 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2750 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2752 "#ifdef USESPECULAR\n"
2753 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2755 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2758 "# ifdef USECUBEFILTER\n"
2759 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2760 " gl_FragData0.rgb *= cubecolor;\n"
2761 " gl_FragData1.rgb *= cubecolor;\n"
2764 "#endif // FRAGMENT_SHADER\n"
2765 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2770 "#ifdef VERTEX_SHADER\n"
2773 "float4 gl_Vertex : POSITION,\n"
2774 "uniform float4x4 ModelViewProjectionMatrix,\n"
2775 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2776 "float4 gl_Color : COLOR0,\n"
2778 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2779 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2780 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2781 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2782 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2784 "uniform float3 EyePosition,\n"
2785 "uniform float4x4 TexMatrix,\n"
2786 "#ifdef USEVERTEXTEXTUREBLEND\n"
2787 "uniform float4x4 BackgroundTexMatrix,\n"
2789 "#ifdef MODE_LIGHTSOURCE\n"
2790 "uniform float4x4 ModelToLight,\n"
2792 "#ifdef MODE_LIGHTSOURCE\n"
2793 "uniform float3 LightPosition,\n"
2795 "#ifdef MODE_LIGHTDIRECTION\n"
2796 "uniform float3 LightDir,\n"
2798 "uniform float4 FogPlane,\n"
2799 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2800 "uniform float3 LightPosition,\n"
2802 "#ifdef USESHADOWMAPORTHO\n"
2803 "uniform float4x4 ShadowMapMatrix,\n"
2806 "out float4 gl_FrontColor : COLOR,\n"
2807 "out float4 TexCoordBoth : TEXCOORD0,\n"
2808 "#ifdef USELIGHTMAP\n"
2809 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2811 "#ifdef USEEYEVECTOR\n"
2812 "out float3 EyeVector : TEXCOORD2,\n"
2814 "#ifdef USEREFLECTION\n"
2815 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2818 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2820 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2821 "out float3 LightVector : TEXCOORD1,\n"
2823 "#ifdef MODE_LIGHTSOURCE\n"
2824 "out float3 CubeVector : TEXCOORD3,\n"
2826 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2827 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2828 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2829 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2831 "#ifdef USESHADOWMAPORTHO\n"
2832 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2834 "out float4 gl_Position : POSITION\n"
2837 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2838 " gl_FrontColor = gl_Color;\n"
2840 " // copy the surface texcoord\n"
2841 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2842 "#ifdef USEVERTEXTEXTUREBLEND\n"
2843 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2845 "#ifdef USELIGHTMAP\n"
2846 " TexCoordLightmap = float2(gl_MultiTexCoord4);\n"
2849 "#ifdef MODE_LIGHTSOURCE\n"
2850 " // transform vertex position into light attenuation/cubemap space\n"
2851 " // (-1 to +1 across the light box)\n"
2852 " CubeVector = float3(mul(ModelToLight, gl_Vertex));\n"
2854 "# ifdef USEDIFFUSE\n"
2855 " // transform unnormalized light direction into tangent space\n"
2856 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2857 " // normalize it per pixel)\n"
2858 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2859 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2860 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2861 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2865 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2866 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2867 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2868 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2871 " // transform unnormalized eye direction into tangent space\n"
2872 "#ifdef USEEYEVECTOR\n"
2873 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2874 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2875 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2876 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2880 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2881 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2884 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2885 " VectorS = gl_MultiTexCoord1.xyz;\n"
2886 " VectorT = gl_MultiTexCoord2.xyz;\n"
2887 " VectorR = gl_MultiTexCoord3.xyz;\n"
2890 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2891 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2893 "#ifdef USESHADOWMAPORTHO\n"
2894 " ShadowMapTC = float3(mul(ShadowMapMatrix, gl_Position));\n"
2897 "#ifdef USEREFLECTION\n"
2898 " ModelViewProjectionPosition = gl_Position;\n"
2901 "#endif // VERTEX_SHADER\n"
2906 "#ifdef FRAGMENT_SHADER\n"
2909 "#ifdef USEDEFERREDLIGHTMAP\n"
2910 "float2 Pixel : WPOS,\n"
2912 "float4 gl_FrontColor : COLOR,\n"
2913 "float4 TexCoordBoth : TEXCOORD0,\n"
2914 "#ifdef USELIGHTMAP\n"
2915 "float2 TexCoordLightmap : TEXCOORD1,\n"
2917 "#ifdef USEEYEVECTOR\n"
2918 "float3 EyeVector : TEXCOORD2,\n"
2920 "#ifdef USEREFLECTION\n"
2921 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2924 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2926 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2927 "float3 LightVector : TEXCOORD1,\n"
2929 "#ifdef MODE_LIGHTSOURCE\n"
2930 "float3 CubeVector : TEXCOORD3,\n"
2932 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2933 "float4 ModelViewPosition : TEXCOORD0,\n"
2935 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2936 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2937 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2938 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2940 "#ifdef USESHADOWMAPORTHO\n"
2941 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2944 "uniform sampler2D Texture_Normal,\n"
2945 "uniform sampler2D Texture_Color,\n"
2946 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2947 "uniform sampler2D Texture_Gloss,\n"
2950 "uniform sampler2D Texture_Glow,\n"
2952 "#ifdef USEVERTEXTEXTUREBLEND\n"
2953 "uniform sampler2D Texture_SecondaryNormal,\n"
2954 "uniform sampler2D Texture_SecondaryColor,\n"
2955 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
2956 "uniform sampler2D Texture_SecondaryGloss,\n"
2959 "uniform sampler2D Texture_SecondaryGlow,\n"
2962 "#ifdef USECOLORMAPPING\n"
2963 "uniform sampler2D Texture_Pants,\n"
2964 "uniform sampler2D Texture_Shirt,\n"
2967 "uniform sampler2D Texture_FogHeightTexture,\n"
2968 "uniform sampler2D Texture_FogMask,\n"
2970 "#ifdef USELIGHTMAP\n"
2971 "uniform sampler2D Texture_Lightmap,\n"
2973 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
2974 "uniform sampler2D Texture_Deluxemap,\n"
2976 "#ifdef USEREFLECTION\n"
2977 "uniform sampler2D Texture_Reflection,\n"
2980 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2981 "uniform sampler2D Texture_ScreenDepth,\n"
2982 "uniform sampler2D Texture_ScreenNormalMap,\n"
2984 "#ifdef USEDEFERREDLIGHTMAP\n"
2985 "uniform sampler2D Texture_ScreenDiffuse,\n"
2986 "uniform sampler2D Texture_ScreenSpecular,\n"
2989 "#ifdef USECOLORMAPPING\n"
2990 "uniform half3 Color_Pants,\n"
2991 "uniform half3 Color_Shirt,\n"
2994 "uniform float3 FogColor,\n"
2995 "uniform float FogRangeRecip,\n"
2996 "uniform float FogPlaneViewDist,\n"
2997 "uniform float FogHeightFade,\n"
3000 "#ifdef USEOFFSETMAPPING\n"
3001 "uniform float OffsetMapping_Scale,\n"
3004 "#ifdef USEDEFERREDLIGHTMAP\n"
3005 "uniform half2 PixelToScreenTexCoord,\n"
3006 "uniform half3 DeferredMod_Diffuse,\n"
3007 "uniform half3 DeferredMod_Specular,\n"
3009 "uniform half3 Color_Ambient,\n"
3010 "uniform half3 Color_Diffuse,\n"
3011 "uniform half3 Color_Specular,\n"
3012 "uniform half SpecularPower,\n"
3014 "uniform half3 Color_Glow,\n"
3016 "uniform half Alpha,\n"
3017 "#ifdef USEREFLECTION\n"
3018 "uniform float4 DistortScaleRefractReflect,\n"
3019 "uniform float4 ScreenScaleRefractReflect,\n"
3020 "uniform float4 ScreenCenterRefractReflect,\n"
3021 "uniform half4 ReflectColor,\n"
3023 "#ifdef USEREFLECTCUBE\n"
3024 "uniform float4x4 ModelToReflectCube,\n"
3025 "uniform sampler2D Texture_ReflectMask,\n"
3026 "uniform samplerCUBE Texture_ReflectCube,\n"
3028 "#ifdef MODE_LIGHTDIRECTION\n"
3029 "uniform half3 LightColor,\n"
3031 "#ifdef MODE_LIGHTSOURCE\n"
3032 "uniform half3 LightColor,\n"
3035 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3036 "uniform sampler2D Texture_Attenuation,\n"
3037 "uniform samplerCUBE Texture_Cube,\n"
3040 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3042 "#ifdef USESHADOWMAPRECT\n"
3043 "# ifdef USESHADOWSAMPLER\n"
3044 "uniform samplerRECTShadow Texture_ShadowMapRect,\n"
3046 "uniform samplerRECT Texture_ShadowMapRect,\n"
3050 "#ifdef USESHADOWMAP2D\n"
3051 "# ifdef USESHADOWSAMPLER\n"
3052 "uniform sampler2DShadow Texture_ShadowMap2D,\n"
3054 "uniform sampler2D Texture_ShadowMap2D,\n"
3058 "#ifdef USESHADOWMAPVSDCT\n"
3059 "uniform samplerCUBE Texture_CubeProjection,\n"
3062 "#ifdef USESHADOWMAPCUBE\n"
3063 "# ifdef USESHADOWSAMPLER\n"
3064 "uniform samplerCUBEShadow Texture_ShadowMapCube,\n"
3066 "uniform samplerCUBE Texture_ShadowMapCube,\n"
3070 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3071 "uniform float2 ShadowMap_TextureScale,\n"
3072 "uniform float4 ShadowMap_Parameters,\n"
3074 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3076 "out float4 gl_FragColor : COLOR\n"
3079 " float2 TexCoord = TexCoordBoth.xy;\n"
3080 "#ifdef USEVERTEXTEXTUREBLEND\n"
3081 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3083 "#ifdef USEOFFSETMAPPING\n"
3084 " // apply offsetmapping\n"
3085 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3086 "#define TexCoord TexCoordOffset\n"
3089 " // combine the diffuse textures (base, pants, shirt)\n"
3090 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3091 "#ifdef USEALPHAKILL\n"
3092 " if (color.a < 0.5)\n"
3095 " color.a *= Alpha;\n"
3096 "#ifdef USECOLORMAPPING\n"
3097 " color.rgb += half3(tex2D(Texture_Pants, TexCoord)) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
3099 "#ifdef USEVERTEXTEXTUREBLEND\n"
3100 " float terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3101 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3102 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3103 " color.rgb = half3(lerp(float3(tex2D(Texture_SecondaryColor, TexCoord2)), float3(color.rgb), terrainblend));\n"
3105 " //color = lerp(half4(1, 0, 0, 1), color, terrainblend);\n"
3108 " // get the surface normal\n"
3109 "#ifdef USEVERTEXTEXTUREBLEND\n"
3110 " half3 surfacenormal = normalize(half3(lerp(float3(tex2D(Texture_SecondaryNormal, TexCoord2)), float3(tex2D(Texture_Normal, TexCoord)), terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3112 " half3 surfacenormal = normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5, 0.5, 0.5));\n"
3115 " // get the material colors\n"
3116 " half3 diffusetex = color.rgb;\n"
3117 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3118 "# ifdef USEVERTEXTEXTUREBLEND\n"
3119 " half4 glosstex = half4(lerp(float4(tex2D(Texture_SecondaryGloss, TexCoord2)), float4(tex2D(Texture_Gloss, TexCoord)), terrainblend));\n"
3121 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3125 "#ifdef USEREFLECTCUBE\n"
3126 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3127 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3128 " float3 ReflectCubeTexCoord = float3(mul(ModelToReflectCube, float4(ModelReflectVector, 0)));\n"
3129 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord)) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord));\n"
3135 "#ifdef MODE_LIGHTSOURCE\n"
3136 " // light source\n"
3137 "#ifdef USEDIFFUSE\n"
3138 " half3 lightnormal = half3(normalize(LightVector));\n"
3139 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3140 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3141 "#ifdef USESPECULAR\n"
3142 "#ifdef USEEXACTSPECULARMATH\n"
3143 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3145 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3146 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3148 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3151 " color.rgb = diffusetex * Color_Ambient;\n"
3153 " color.rgb *= LightColor;\n"
3154 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)));\n"
3155 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3156 " color.rgb *= ShadowMapCompare(CubeVector,\n"
3157 "# if defined(USESHADOWMAP2D)\n"
3158 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3160 "# if defined(USESHADOWMAPRECT)\n"
3161 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3163 "# if defined(USESHADOWMAPCUBE)\n"
3164 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3167 "#ifdef USESHADOWMAPVSDCT\n"
3168 ", Texture_CubeProjection\n"
3173 "# ifdef USECUBEFILTER\n"
3174 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector));\n"
3176 "#endif // MODE_LIGHTSOURCE\n"
3181 "#ifdef MODE_LIGHTDIRECTION\n"
3183 "#ifdef USEDIFFUSE\n"
3184 " half3 lightnormal = half3(normalize(LightVector));\n"
3186 "#define lightcolor LightColor\n"
3187 "#endif // MODE_LIGHTDIRECTION\n"
3188 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3190 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3191 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3192 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3193 " // convert modelspace light vector to tangentspace\n"
3194 " half3 lightnormal;\n"
3195 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3196 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3197 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3198 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3199 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3200 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3201 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3202 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3203 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3204 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3205 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3206 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3207 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3208 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3209 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3211 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3212 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3213 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap));\n"
3219 "#ifdef MODE_LIGHTMAP\n"
3220 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
3221 "#endif // MODE_LIGHTMAP\n"
3222 "#ifdef MODE_VERTEXCOLOR\n"
3223 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3224 "#endif // MODE_VERTEXCOLOR\n"
3225 "#ifdef MODE_FLATCOLOR\n"
3226 " color.rgb = diffusetex * Color_Ambient;\n"
3227 "#endif // MODE_FLATCOLOR\n"
3233 "# ifdef USEDIFFUSE\n"
3234 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3235 "# ifdef USESPECULAR\n"
3236 "# ifdef USEEXACTSPECULARMATH\n"
3237 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
3239 " half3 specularnormal = normalize(lightnormal + half3(normalize(EyeVector)));\n"
3240 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
3242 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3244 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3247 " color.rgb = diffusetex * Color_Ambient;\n"
3251 "#ifdef USESHADOWMAPORTHO\n"
3252 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3253 "# if defined(USESHADOWMAP2D)\n"
3254 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3256 "# if defined(USESHADOWMAPRECT)\n"
3257 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3262 "#ifdef USEDEFERREDLIGHTMAP\n"
3263 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3264 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
3265 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
3269 "#ifdef USEVERTEXTEXTUREBLEND\n"
3270 " color.rgb += lerp(half3(tex2D(Texture_SecondaryGlow, TexCoord2)), half3(tex2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
3272 " color.rgb += half3(tex2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
3277 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3280 " // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
3281 "#ifdef USEREFLECTION\n"
3282 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3283 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3284 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3285 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord)) - half3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
3286 " // FIXME temporary hack to detect the case that the reflection\n"
3287 " // gets blackened at edges due to leaving the area that contains actual\n"
3289 " // Remove this 'ack once we have a better way to stop this thing from\n"
3291 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3292 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3293 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3294 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3295 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3296 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
3299 " gl_FragColor = float4(color);\n"
3301 "#endif // FRAGMENT_SHADER\n"
3303 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3304 "#endif // !MODE_DEFERREDGEOMETRY\n"
3305 "#endif // !MODE_WATER\n"
3306 "#endif // !MODE_REFRACTION\n"
3307 "#endif // !MODE_BLOOMBLUR\n"
3308 "#endif // !MODE_GENERIC\n"
3309 "#endif // !MODE_POSTPROCESS\n"
3310 "#endif // !MODE_SHOWDEPTH\n"
3311 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3314 char *glslshaderstring = NULL;
3315 char *cgshaderstring = NULL;
3317 //=======================================================================================================================================================
3319 typedef struct shaderpermutationinfo_s
3321 const char *pretext;
3324 shaderpermutationinfo_t;
3326 typedef struct shadermodeinfo_s
3328 const char *vertexfilename;
3329 const char *geometryfilename;
3330 const char *fragmentfilename;
3331 const char *pretext;
3336 typedef enum shaderpermutation_e
3338 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3339 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3340 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3341 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3342 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3343 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3344 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3345 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3346 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3347 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3348 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3349 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3350 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3351 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3352 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3353 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3354 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3355 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3356 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3357 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3358 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3359 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3360 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3361 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3362 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3363 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3364 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3365 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3366 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3367 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3368 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3370 shaderpermutation_t;
3372 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3373 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3375 {"#define USEDIFFUSE\n", " diffuse"},
3376 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3377 {"#define USEVIEWTINT\n", " viewtint"},
3378 {"#define USECOLORMAPPING\n", " colormapping"},
3379 {"#define USESATURATION\n", " saturation"},
3380 {"#define USEFOGINSIDE\n", " foginside"},
3381 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3382 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3383 {"#define USEGAMMARAMPS\n", " gammaramps"},
3384 {"#define USECUBEFILTER\n", " cubefilter"},
3385 {"#define USEGLOW\n", " glow"},
3386 {"#define USEBLOOM\n", " bloom"},
3387 {"#define USESPECULAR\n", " specular"},
3388 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3389 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3390 {"#define USEREFLECTION\n", " reflection"},
3391 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3392 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3393 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3394 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3395 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3396 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3397 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3398 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3399 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3400 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3401 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3402 {"#define USEALPHAKILL\n", " alphakill"},
3403 {"#define USEREFLECTCUBE\n", " reflectcube"},
3406 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3407 typedef enum shadermode_e
3409 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3410 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3411 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3412 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3413 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3414 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3415 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3416 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3417 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3418 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3419 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3420 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3421 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3422 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3423 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3428 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3429 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3431 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3432 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3433 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3434 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3435 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3436 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3437 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3438 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3439 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3440 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3441 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3442 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3443 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3444 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3445 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3449 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3451 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3452 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3453 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3454 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3455 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3456 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3457 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3458 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3459 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3460 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3461 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3462 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3463 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3464 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3465 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3469 struct r_glsl_permutation_s;
3470 typedef struct r_glsl_permutation_s
3472 /// hash lookup data
3473 struct r_glsl_permutation_s *hashnext;
3475 unsigned int permutation;
3477 /// indicates if we have tried compiling this permutation already
3479 /// 0 if compilation failed
3481 /// locations of detected uniforms in program object, or -1 if not found
3482 int loc_Texture_First;
3483 int loc_Texture_Second;
3484 int loc_Texture_GammaRamps;
3485 int loc_Texture_Normal;
3486 int loc_Texture_Color;
3487 int loc_Texture_Gloss;
3488 int loc_Texture_Glow;
3489 int loc_Texture_SecondaryNormal;
3490 int loc_Texture_SecondaryColor;
3491 int loc_Texture_SecondaryGloss;
3492 int loc_Texture_SecondaryGlow;
3493 int loc_Texture_Pants;
3494 int loc_Texture_Shirt;
3495 int loc_Texture_FogHeightTexture;
3496 int loc_Texture_FogMask;
3497 int loc_Texture_Lightmap;
3498 int loc_Texture_Deluxemap;
3499 int loc_Texture_Attenuation;
3500 int loc_Texture_Cube;
3501 int loc_Texture_Refraction;
3502 int loc_Texture_Reflection;
3503 int loc_Texture_ShadowMapRect;
3504 int loc_Texture_ShadowMapCube;
3505 int loc_Texture_ShadowMap2D;
3506 int loc_Texture_CubeProjection;
3507 int loc_Texture_ScreenDepth;
3508 int loc_Texture_ScreenNormalMap;
3509 int loc_Texture_ScreenDiffuse;
3510 int loc_Texture_ScreenSpecular;
3511 int loc_Texture_ReflectMask;
3512 int loc_Texture_ReflectCube;
3514 int loc_BloomBlur_Parameters;
3516 int loc_Color_Ambient;
3517 int loc_Color_Diffuse;
3518 int loc_Color_Specular;
3520 int loc_Color_Pants;
3521 int loc_Color_Shirt;
3522 int loc_DeferredColor_Ambient;
3523 int loc_DeferredColor_Diffuse;
3524 int loc_DeferredColor_Specular;
3525 int loc_DeferredMod_Diffuse;
3526 int loc_DeferredMod_Specular;
3527 int loc_DistortScaleRefractReflect;
3528 int loc_EyePosition;
3530 int loc_FogHeightFade;
3532 int loc_FogPlaneViewDist;
3533 int loc_FogRangeRecip;
3536 int loc_LightPosition;
3537 int loc_OffsetMapping_Scale;
3539 int loc_ReflectColor;
3540 int loc_ReflectFactor;
3541 int loc_ReflectOffset;
3542 int loc_RefractColor;
3544 int loc_ScreenCenterRefractReflect;
3545 int loc_ScreenScaleRefractReflect;
3546 int loc_ScreenToDepth;
3547 int loc_ShadowMap_Parameters;
3548 int loc_ShadowMap_TextureScale;
3549 int loc_SpecularPower;
3554 int loc_ViewTintColor;
3555 int loc_ViewToLight;
3556 int loc_ModelToLight;
3558 int loc_BackgroundTexMatrix;
3559 int loc_ModelViewProjectionMatrix;
3560 int loc_ModelViewMatrix;
3561 int loc_PixelToScreenTexCoord;
3562 int loc_ModelToReflectCube;
3563 int loc_ShadowMapMatrix;
3565 r_glsl_permutation_t;
3567 #define SHADERPERMUTATION_HASHSIZE 256
3569 /// information about each possible shader permutation
3570 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3571 /// currently selected permutation
3572 r_glsl_permutation_t *r_glsl_permutation;
3573 /// storage for permutations linked in the hash table
3574 memexpandablearray_t r_glsl_permutationarray;
3576 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3578 //unsigned int hashdepth = 0;
3579 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3580 r_glsl_permutation_t *p;
3581 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3583 if (p->mode == mode && p->permutation == permutation)
3585 //if (hashdepth > 10)
3586 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3591 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3593 p->permutation = permutation;
3594 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3595 r_glsl_permutationhash[mode][hashindex] = p;
3596 //if (hashdepth > 10)
3597 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3601 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3604 if (!filename || !filename[0])
3606 if (!strcmp(filename, "glsl/default.glsl"))
3608 if (!glslshaderstring)
3610 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3611 if (glslshaderstring)
3612 Con_DPrintf("Loading shaders from file %s...\n", filename);
3614 glslshaderstring = (char *)builtinshaderstring;
3616 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3617 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3618 return shaderstring;
3620 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3623 if (printfromdisknotice)
3624 Con_DPrintf("from disk %s... ", filename);
3625 return shaderstring;
3627 return shaderstring;
3630 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3633 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3634 int vertstrings_count = 0;
3635 int geomstrings_count = 0;
3636 int fragstrings_count = 0;
3637 char *vertexstring, *geometrystring, *fragmentstring;
3638 const char *vertstrings_list[32+3];
3639 const char *geomstrings_list[32+3];
3640 const char *fragstrings_list[32+3];
3641 char permutationname[256];
3648 permutationname[0] = 0;
3649 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3650 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3651 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3653 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3655 // the first pretext is which type of shader to compile as
3656 // (later these will all be bound together as a program object)
3657 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3658 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3659 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3661 // the second pretext is the mode (for example a light source)
3662 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3663 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3664 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3665 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3667 // now add all the permutation pretexts
3668 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3670 if (permutation & (1<<i))
3672 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3673 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3674 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3675 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3679 // keep line numbers correct
3680 vertstrings_list[vertstrings_count++] = "\n";
3681 geomstrings_list[geomstrings_count++] = "\n";
3682 fragstrings_list[fragstrings_count++] = "\n";
3686 // now append the shader text itself
3687 vertstrings_list[vertstrings_count++] = vertexstring;
3688 geomstrings_list[geomstrings_count++] = geometrystring;
3689 fragstrings_list[fragstrings_count++] = fragmentstring;
3691 // if any sources were NULL, clear the respective list
3693 vertstrings_count = 0;
3694 if (!geometrystring)
3695 geomstrings_count = 0;
3696 if (!fragmentstring)
3697 fragstrings_count = 0;
3699 // compile the shader program
3700 if (vertstrings_count + geomstrings_count + fragstrings_count)
3701 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3705 qglUseProgramObjectARB(p->program);CHECKGLERROR
3706 // look up all the uniform variable names we care about, so we don't
3707 // have to look them up every time we set them
3709 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3710 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3711 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3712 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3713 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3714 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3715 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3716 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3717 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3718 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3719 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3720 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3721 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3722 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3723 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3724 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3725 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3726 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3727 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3728 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3729 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3730 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3731 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3732 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3733 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3734 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3735 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3736 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3737 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3738 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3739 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3740 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3741 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3742 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3743 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3744 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3745 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3746 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3747 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3748 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3749 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3750 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3751 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3752 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3753 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3754 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3755 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3756 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3757 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3758 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3759 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3760 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3761 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3762 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3763 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3764 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3765 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3766 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3767 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3768 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3769 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3770 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3771 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3772 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3773 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3774 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3775 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3776 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3777 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3778 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3779 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3780 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3781 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3782 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3783 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3784 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3785 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3786 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3787 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3788 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3789 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3790 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3791 // initialize the samplers to refer to the texture units we use
3792 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3793 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3794 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3795 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3796 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3797 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3798 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3799 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3800 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3801 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3802 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3803 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3804 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3805 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3806 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3807 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3808 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3809 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3810 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3811 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3812 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3813 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3814 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3815 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3816 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3817 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3818 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3819 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3820 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3821 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3822 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3824 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3827 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3831 Mem_Free(vertexstring);
3833 Mem_Free(geometrystring);
3835 Mem_Free(fragmentstring);
3838 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
3840 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
3841 if (r_glsl_permutation != perm)
3843 r_glsl_permutation = perm;
3844 if (!r_glsl_permutation->program)
3846 if (!r_glsl_permutation->compiled)
3847 R_GLSL_CompilePermutation(perm, mode, permutation);
3848 if (!r_glsl_permutation->program)
3850 // remove features until we find a valid permutation
3852 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3854 // reduce i more quickly whenever it would not remove any bits
3855 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
3856 if (!(permutation & j))
3859 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3860 if (!r_glsl_permutation->compiled)
3861 R_GLSL_CompilePermutation(perm, mode, permutation);
3862 if (r_glsl_permutation->program)
3865 if (i >= SHADERPERMUTATION_COUNT)
3867 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
3868 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
3869 qglUseProgramObjectARB(0);CHECKGLERROR
3870 return; // no bit left to clear, entire mode is broken
3875 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
3877 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
3878 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
3879 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
3883 #include <Cg/cgGL.h>
3884 struct r_cg_permutation_s;
3885 typedef struct r_cg_permutation_s
3887 /// hash lookup data
3888 struct r_cg_permutation_s *hashnext;
3890 unsigned int permutation;
3892 /// indicates if we have tried compiling this permutation already
3894 /// 0 if compilation failed
3897 /// locations of detected parameters in programs, or NULL if not found
3898 CGparameter vp_EyePosition;
3899 CGparameter vp_FogPlane;
3900 CGparameter vp_LightDir;
3901 CGparameter vp_LightPosition;
3902 CGparameter vp_ModelToLight;
3903 CGparameter vp_TexMatrix;
3904 CGparameter vp_BackgroundTexMatrix;
3905 CGparameter vp_ModelViewProjectionMatrix;
3906 CGparameter vp_ModelViewMatrix;
3907 CGparameter vp_ShadowMapMatrix;
3909 CGparameter fp_Texture_First;
3910 CGparameter fp_Texture_Second;
3911 CGparameter fp_Texture_GammaRamps;
3912 CGparameter fp_Texture_Normal;
3913 CGparameter fp_Texture_Color;
3914 CGparameter fp_Texture_Gloss;
3915 CGparameter fp_Texture_Glow;
3916 CGparameter fp_Texture_SecondaryNormal;
3917 CGparameter fp_Texture_SecondaryColor;
3918 CGparameter fp_Texture_SecondaryGloss;
3919 CGparameter fp_Texture_SecondaryGlow;
3920 CGparameter fp_Texture_Pants;
3921 CGparameter fp_Texture_Shirt;
3922 CGparameter fp_Texture_FogHeightTexture;
3923 CGparameter fp_Texture_FogMask;
3924 CGparameter fp_Texture_Lightmap;
3925 CGparameter fp_Texture_Deluxemap;
3926 CGparameter fp_Texture_Attenuation;
3927 CGparameter fp_Texture_Cube;
3928 CGparameter fp_Texture_Refraction;
3929 CGparameter fp_Texture_Reflection;
3930 CGparameter fp_Texture_ShadowMapRect;
3931 CGparameter fp_Texture_ShadowMapCube;
3932 CGparameter fp_Texture_ShadowMap2D;
3933 CGparameter fp_Texture_CubeProjection;
3934 CGparameter fp_Texture_ScreenDepth;
3935 CGparameter fp_Texture_ScreenNormalMap;
3936 CGparameter fp_Texture_ScreenDiffuse;
3937 CGparameter fp_Texture_ScreenSpecular;
3938 CGparameter fp_Texture_ReflectMask;
3939 CGparameter fp_Texture_ReflectCube;
3940 CGparameter fp_Alpha;
3941 CGparameter fp_BloomBlur_Parameters;
3942 CGparameter fp_ClientTime;
3943 CGparameter fp_Color_Ambient;
3944 CGparameter fp_Color_Diffuse;
3945 CGparameter fp_Color_Specular;
3946 CGparameter fp_Color_Glow;
3947 CGparameter fp_Color_Pants;
3948 CGparameter fp_Color_Shirt;
3949 CGparameter fp_DeferredColor_Ambient;
3950 CGparameter fp_DeferredColor_Diffuse;
3951 CGparameter fp_DeferredColor_Specular;
3952 CGparameter fp_DeferredMod_Diffuse;
3953 CGparameter fp_DeferredMod_Specular;
3954 CGparameter fp_DistortScaleRefractReflect;
3955 CGparameter fp_EyePosition;
3956 CGparameter fp_FogColor;
3957 CGparameter fp_FogHeightFade;
3958 CGparameter fp_FogPlane;
3959 CGparameter fp_FogPlaneViewDist;
3960 CGparameter fp_FogRangeRecip;
3961 CGparameter fp_LightColor;
3962 CGparameter fp_LightDir;
3963 CGparameter fp_LightPosition;
3964 CGparameter fp_OffsetMapping_Scale;
3965 CGparameter fp_PixelSize;
3966 CGparameter fp_ReflectColor;
3967 CGparameter fp_ReflectFactor;
3968 CGparameter fp_ReflectOffset;
3969 CGparameter fp_RefractColor;
3970 CGparameter fp_Saturation;
3971 CGparameter fp_ScreenCenterRefractReflect;
3972 CGparameter fp_ScreenScaleRefractReflect;
3973 CGparameter fp_ScreenToDepth;
3974 CGparameter fp_ShadowMap_Parameters;
3975 CGparameter fp_ShadowMap_TextureScale;
3976 CGparameter fp_SpecularPower;
3977 CGparameter fp_UserVec1;
3978 CGparameter fp_UserVec2;
3979 CGparameter fp_UserVec3;
3980 CGparameter fp_UserVec4;
3981 CGparameter fp_ViewTintColor;
3982 CGparameter fp_ViewToLight;
3983 CGparameter fp_PixelToScreenTexCoord;
3984 CGparameter fp_ModelToReflectCube;
3988 /// information about each possible shader permutation
3989 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3990 /// currently selected permutation
3991 r_cg_permutation_t *r_cg_permutation;
3992 /// storage for permutations linked in the hash table
3993 memexpandablearray_t r_cg_permutationarray;
3995 #define CHECKCGERROR {CGerror err = cgGetError(), err2 = err;if (err){Con_Printf("%s:%i CG error %i: %s : %s\n", __FILE__, __LINE__, err, cgGetErrorString(err), cgGetLastErrorString(&err2));if (err == 1) Con_Printf("last listing:\n%s\n", cgGetLastListing(vid.cgcontext));}}
3997 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
3999 //unsigned int hashdepth = 0;
4000 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4001 r_cg_permutation_t *p;
4002 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4004 if (p->mode == mode && p->permutation == permutation)
4006 //if (hashdepth > 10)
4007 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4012 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4014 p->permutation = permutation;
4015 p->hashnext = r_cg_permutationhash[mode][hashindex];
4016 r_cg_permutationhash[mode][hashindex] = p;
4017 //if (hashdepth > 10)
4018 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4022 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4025 if (!filename || !filename[0])
4027 if (!strcmp(filename, "cg/default.cg"))
4029 if (!cgshaderstring)
4031 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4033 Con_DPrintf("Loading shaders from file %s...\n", filename);
4035 cgshaderstring = (char *)builtincgshaderstring;
4037 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4038 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4039 return shaderstring;
4041 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4044 if (printfromdisknotice)
4045 Con_DPrintf("from disk %s... ", filename);
4046 return shaderstring;
4048 return shaderstring;
4051 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4053 // TODO: load or create .fp and .vp shader files
4056 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4059 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4060 int vertstrings_count = 0, vertstring_length = 0;
4061 int geomstrings_count = 0, geomstring_length = 0;
4062 int fragstrings_count = 0, fragstring_length = 0;
4064 char *vertexstring, *geometrystring, *fragmentstring;
4065 char *vertstring, *geomstring, *fragstring;
4066 const char *vertstrings_list[32+3];
4067 const char *geomstrings_list[32+3];
4068 const char *fragstrings_list[32+3];
4069 char permutationname[256];
4070 char cachename[256];
4071 CGprofile vertexProfile;
4072 CGprofile fragmentProfile;
4080 permutationname[0] = 0;
4082 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4083 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4084 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4086 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4087 strlcat(cachename, "cg/", sizeof(cachename));
4089 // the first pretext is which type of shader to compile as
4090 // (later these will all be bound together as a program object)
4091 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4092 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4093 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4095 // the second pretext is the mode (for example a light source)
4096 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4097 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4098 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4099 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4100 strlcat(cachename, modeinfo->name, sizeof(cachename));
4102 // now add all the permutation pretexts
4103 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4105 if (permutation & (1<<i))
4107 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4108 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4109 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4110 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4111 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4115 // keep line numbers correct
4116 vertstrings_list[vertstrings_count++] = "\n";
4117 geomstrings_list[geomstrings_count++] = "\n";
4118 fragstrings_list[fragstrings_count++] = "\n";
4122 // replace spaces in the cachename with _ characters
4123 for (i = 0;cachename[i];i++)
4124 if (cachename[i] == ' ')
4127 // now append the shader text itself
4128 vertstrings_list[vertstrings_count++] = vertexstring;
4129 geomstrings_list[geomstrings_count++] = geometrystring;
4130 fragstrings_list[fragstrings_count++] = fragmentstring;
4132 // if any sources were NULL, clear the respective list
4134 vertstrings_count = 0;
4135 if (!geometrystring)
4136 geomstrings_count = 0;
4137 if (!fragmentstring)
4138 fragstrings_count = 0;
4140 vertstring_length = 0;
4141 for (i = 0;i < vertstrings_count;i++)
4142 vertstring_length += strlen(vertstrings_list[i]);
4143 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4144 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4145 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4147 geomstring_length = 0;
4148 for (i = 0;i < geomstrings_count;i++)
4149 geomstring_length += strlen(geomstrings_list[i]);
4150 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4151 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4152 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4154 fragstring_length = 0;
4155 for (i = 0;i < fragstrings_count;i++)
4156 fragstring_length += strlen(fragstrings_list[i]);
4157 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4158 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4159 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4163 //vertexProfile = CG_PROFILE_ARBVP1;
4164 //fragmentProfile = CG_PROFILE_ARBFP1;
4165 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4166 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4167 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4168 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4169 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4172 // try to load the cached shader, or generate one
4173 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4175 // if caching failed, do a dynamic compile for now
4177 if (vertstring[0] && !p->vprogram)
4178 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4180 if (fragstring[0] && !p->fprogram)
4181 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4184 // look up all the uniform variable names we care about, so we don't
4185 // have to look them up every time we set them
4189 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4190 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4191 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4192 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4193 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4194 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4195 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4196 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4197 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4198 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4199 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4200 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4206 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4207 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4208 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4209 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4210 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4211 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4212 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4213 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4214 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4215 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4216 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4217 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4218 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4219 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4220 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4221 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4222 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4223 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4224 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4225 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4226 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4227 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4228 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4229 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4230 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4231 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4232 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4233 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4234 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4235 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4236 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4237 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4238 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4239 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4240 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4241 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4242 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4243 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4244 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4245 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4246 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4247 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4248 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4249 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4250 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4251 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4252 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4253 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4254 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4255 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4256 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4257 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4258 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4259 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4260 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4261 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4262 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4263 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4264 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4265 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4266 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4267 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4268 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4269 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4270 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4271 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4272 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4273 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4274 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4275 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4276 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4277 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4278 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4279 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4280 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4281 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4282 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4283 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4287 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4288 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4290 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4294 Mem_Free(vertstring);
4296 Mem_Free(geomstring);
4298 Mem_Free(fragstring);
4300 Mem_Free(vertexstring);
4302 Mem_Free(geometrystring);
4304 Mem_Free(fragmentstring);
4307 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4309 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4312 if (r_cg_permutation != perm)
4314 r_cg_permutation = perm;
4315 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4317 if (!r_cg_permutation->compiled)
4318 R_CG_CompilePermutation(perm, mode, permutation);
4319 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4321 // remove features until we find a valid permutation
4323 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4325 // reduce i more quickly whenever it would not remove any bits
4326 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4327 if (!(permutation & j))
4330 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4331 if (!r_cg_permutation->compiled)
4332 R_CG_CompilePermutation(perm, mode, permutation);
4333 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4336 if (i >= SHADERPERMUTATION_COUNT)
4338 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4339 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4340 return; // no bit left to clear, entire mode is broken
4346 if (r_cg_permutation->vprogram)
4348 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4349 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4350 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4354 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4355 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4357 if (r_cg_permutation->fprogram)
4359 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4360 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4361 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4365 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4366 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4370 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4371 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4372 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4375 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4377 cgGLSetTextureParameter(param, R_GetTexture(tex));
4378 cgGLEnableTextureParameter(param);
4382 void R_GLSL_Restart_f(void)
4384 unsigned int i, limit;
4385 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4386 Mem_Free(glslshaderstring);
4387 glslshaderstring = NULL;
4388 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4389 Mem_Free(cgshaderstring);
4390 cgshaderstring = NULL;
4391 switch(vid.renderpath)
4393 case RENDERPATH_GL20:
4395 r_glsl_permutation_t *p;
4396 r_glsl_permutation = NULL;
4397 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4398 for (i = 0;i < limit;i++)
4400 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4402 GL_Backend_FreeProgram(p->program);
4403 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4406 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4409 case RENDERPATH_CGGL:
4412 r_cg_permutation_t *p;
4413 r_cg_permutation = NULL;
4414 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4415 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4416 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4417 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4418 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
4419 for (i = 0;i < limit;i++)
4421 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
4424 cgDestroyProgram(p->vprogram);
4426 cgDestroyProgram(p->fprogram);
4427 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
4430 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
4434 case RENDERPATH_GL13:
4435 case RENDERPATH_GL11:
4440 void R_GLSL_DumpShader_f(void)
4445 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4448 FS_Print(file, "/* The engine may define the following macros:\n");
4449 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4450 for (i = 0;i < SHADERMODE_COUNT;i++)
4451 FS_Print(file, glslshadermodeinfo[i].pretext);
4452 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4453 FS_Print(file, shaderpermutationinfo[i].pretext);
4454 FS_Print(file, "*/\n");
4455 FS_Print(file, builtinshaderstring);
4457 Con_Printf("glsl/default.glsl written\n");
4460 Con_Printf("failed to write to glsl/default.glsl\n");
4463 file = FS_OpenRealFile("cg/default.cg", "w", false);
4466 FS_Print(file, "/* The engine may define the following macros:\n");
4467 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4468 for (i = 0;i < SHADERMODE_COUNT;i++)
4469 FS_Print(file, cgshadermodeinfo[i].pretext);
4470 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4471 FS_Print(file, shaderpermutationinfo[i].pretext);
4472 FS_Print(file, "*/\n");
4473 FS_Print(file, builtincgshaderstring);
4475 Con_Printf("cg/default.cg written\n");
4478 Con_Printf("failed to write to cg/default.cg\n");
4482 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4485 texturemode = GL_MODULATE;
4486 switch (vid.renderpath)
4488 case RENDERPATH_GL20:
4489 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4490 if (r_glsl_permutation->loc_Texture_First ) R_Mesh_TexBind(GL20TU_FIRST , first );
4491 if (r_glsl_permutation->loc_Texture_Second) R_Mesh_TexBind(GL20TU_SECOND, second);
4493 case RENDERPATH_CGGL:
4496 R_SetupShader_SetPermutationCG(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4497 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
4498 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
4501 case RENDERPATH_GL13:
4502 R_Mesh_TexBind(0, first );
4503 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4504 R_Mesh_TexBind(1, second);
4506 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4508 case RENDERPATH_GL11:
4509 R_Mesh_TexBind(0, first );
4514 void R_SetupShader_DepthOrShadow(void)
4516 switch (vid.renderpath)
4518 case RENDERPATH_GL20:
4519 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4521 case RENDERPATH_CGGL:
4523 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
4526 case RENDERPATH_GL13:
4527 R_Mesh_TexBind(0, 0);
4528 R_Mesh_TexBind(1, 0);
4530 case RENDERPATH_GL11:
4531 R_Mesh_TexBind(0, 0);
4536 void R_SetupShader_ShowDepth(void)
4538 switch (vid.renderpath)
4540 case RENDERPATH_GL20:
4541 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4543 case RENDERPATH_CGGL:
4545 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
4548 case RENDERPATH_GL13:
4550 case RENDERPATH_GL11:
4555 extern qboolean r_shadow_usingdeferredprepass;
4556 extern cvar_t r_shadow_deferred_8bitrange;
4557 extern rtexture_t *r_shadow_attenuationgradienttexture;
4558 extern rtexture_t *r_shadow_attenuation2dtexture;
4559 extern rtexture_t *r_shadow_attenuation3dtexture;
4560 extern qboolean r_shadow_usingshadowmaprect;
4561 extern qboolean r_shadow_usingshadowmapcube;
4562 extern qboolean r_shadow_usingshadowmap2d;
4563 extern qboolean r_shadow_usingshadowmaportho;
4564 extern float r_shadow_shadowmap_texturescale[2];
4565 extern float r_shadow_shadowmap_parameters[4];
4566 extern qboolean r_shadow_shadowmapvsdct;
4567 extern qboolean r_shadow_shadowmapsampler;
4568 extern int r_shadow_shadowmappcf;
4569 extern rtexture_t *r_shadow_shadowmaprectangletexture;
4570 extern rtexture_t *r_shadow_shadowmap2dtexture;
4571 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
4572 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4573 extern matrix4x4_t r_shadow_shadowmapmatrix;
4574 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4575 extern int r_shadow_prepass_width;
4576 extern int r_shadow_prepass_height;
4577 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4578 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4579 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4580 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4581 extern cvar_t gl_mesh_separatearrays;
4582 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
4584 // a blendfunc allows colormod if:
4585 // a) it can never keep the destination pixel invariant, or
4586 // b) it can keep the destination pixel invariant, and still can do so if colormodded
4587 // this is to prevent unintended side effects from colormod
4590 // IF there is a (s, sa) for which for all (d, da),
4591 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4592 // THEN, for this (s, sa) and all (colormod, d, da):
4593 // s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
4594 // OBVIOUSLY, this means that
4595 // s*colormod * src(s*colormod, d, sa, da) = 0
4596 // dst(s*colormod, d, sa, da) = 1
4598 // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
4600 // main condition to leave dst color invariant:
4601 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4603 // s * 0 + d * dst(s, d, sa, da) == d
4604 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4605 // => colormod is a problem for GL_SRC_COLOR only
4607 // s + d * dst(s, d, sa, da) == d
4609 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4610 // => colormod is never problematic for these
4611 // src == GL_SRC_COLOR:
4612 // s*s + d * dst(s, d, sa, da) == d
4614 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4615 // => colormod is never problematic for these
4616 // src == GL_ONE_MINUS_SRC_COLOR:
4617 // s*(1-s) + d * dst(s, d, sa, da) == d
4618 // => s == 0 or s == 1
4619 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4620 // => colormod is a problem for GL_SRC_COLOR only
4621 // src == GL_DST_COLOR
4622 // s*d + d * dst(s, d, sa, da) == d
4624 // => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4625 // => colormod is always a problem
4628 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4629 // => colormod is never problematic for these
4630 // => BUT, we do not know s! We must assume it is problematic
4631 // then... except in GL_ONE case, where we know all invariant
4633 // src == GL_ONE_MINUS_DST_COLOR
4634 // s*(1-d) + d * dst(s, d, sa, da) == d
4635 // => s == 0 (1-d is impossible to handle for our desired result)
4636 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4637 // => colormod is never problematic for these
4638 // src == GL_SRC_ALPHA
4639 // s*sa + d * dst(s, d, sa, da) == d
4640 // => s == 0, or sa == 0
4641 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4642 // => colormod breaks in the case GL_SRC_COLOR only
4643 // src == GL_ONE_MINUS_SRC_ALPHA
4644 // s*(1-sa) + d * dst(s, d, sa, da) == d
4645 // => s == 0, or sa == 1
4646 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4647 // => colormod breaks in the case GL_SRC_COLOR only
4648 // src == GL_DST_ALPHA
4649 // s*da + d * dst(s, d, sa, da) == d
4651 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4652 // => colormod is never problematic for these
4657 case GL_ONE_MINUS_SRC_COLOR:
4659 case GL_ONE_MINUS_SRC_ALPHA:
4660 if(dst == GL_SRC_COLOR)
4665 case GL_ONE_MINUS_DST_COLOR:
4667 case GL_ONE_MINUS_DST_ALPHA:
4677 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)
4679 // select a permutation of the lighting shader appropriate to this
4680 // combination of texture, entity, light source, and fogging, only use the
4681 // minimum features necessary to avoid wasting rendering time in the
4682 // fragment shader on features that are not being used
4683 unsigned int permutation = 0;
4684 unsigned int mode = 0;
4685 qboolean allow_colormod;
4686 static float dummy_colormod[3] = {1, 1, 1};
4687 float *colormod = rsurface.colormod;
4689 if (rsurfacepass == RSURFPASS_BACKGROUND)
4691 // distorted background
4692 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4693 mode = SHADERMODE_WATER;
4694 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4695 mode = SHADERMODE_REFRACTION;
4698 mode = SHADERMODE_GENERIC;
4699 permutation |= SHADERPERMUTATION_DIFFUSE;
4701 GL_AlphaTest(false);
4702 GL_BlendFunc(GL_ONE, GL_ZERO);
4703 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4705 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4707 if (r_glsl_offsetmapping.integer)
4709 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4710 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4711 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4712 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4713 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4715 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4716 if (r_glsl_offsetmapping_reliefmapping.integer)
4717 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4720 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4721 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4722 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4723 permutation |= SHADERPERMUTATION_ALPHAKILL;
4724 // normalmap (deferred prepass), may use alpha test on diffuse
4725 mode = SHADERMODE_DEFERREDGEOMETRY;
4726 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4727 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4728 GL_AlphaTest(false);
4729 GL_BlendFunc(GL_ONE, GL_ZERO);
4730 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4732 else if (rsurfacepass == RSURFPASS_RTLIGHT)
4734 if (r_glsl_offsetmapping.integer)
4736 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4737 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4738 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4739 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4740 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4742 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4743 if (r_glsl_offsetmapping_reliefmapping.integer)
4744 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4747 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4748 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4750 mode = SHADERMODE_LIGHTSOURCE;
4751 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4752 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4753 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4754 permutation |= SHADERPERMUTATION_CUBEFILTER;
4755 if (diffusescale > 0)
4756 permutation |= SHADERPERMUTATION_DIFFUSE;
4757 if (specularscale > 0)
4759 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4760 if (r_shadow_glossexact.integer)
4761 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4763 if (r_refdef.fogenabled)
4764 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4765 if (rsurface.texture->colormapping)
4766 permutation |= SHADERPERMUTATION_COLORMAPPING;
4767 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
4769 if (r_shadow_usingshadowmaprect)
4770 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4771 if (r_shadow_usingshadowmap2d)
4772 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4773 if (r_shadow_usingshadowmapcube)
4774 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
4775 else if(r_shadow_shadowmapvsdct)
4776 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
4778 if (r_shadow_shadowmapsampler)
4779 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4780 if (r_shadow_shadowmappcf > 1)
4781 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4782 else if (r_shadow_shadowmappcf)
4783 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4785 if (rsurface.texture->reflectmasktexture)
4786 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4787 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4788 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
4789 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
4791 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
4793 if (r_glsl_offsetmapping.integer)
4795 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4796 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4797 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4798 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4799 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4801 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4802 if (r_glsl_offsetmapping_reliefmapping.integer)
4803 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4806 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4807 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4808 // unshaded geometry (fullbright or ambient model lighting)
4809 mode = SHADERMODE_FLATCOLOR;
4810 ambientscale = diffusescale = specularscale = 0;
4811 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4812 permutation |= SHADERPERMUTATION_GLOW;
4813 if (r_refdef.fogenabled)
4814 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4815 if (rsurface.texture->colormapping)
4816 permutation |= SHADERPERMUTATION_COLORMAPPING;
4817 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4819 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4820 if (r_shadow_usingshadowmaprect)
4821 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4822 if (r_shadow_usingshadowmap2d)
4823 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4825 if (r_shadow_shadowmapsampler)
4826 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4827 if (r_shadow_shadowmappcf > 1)
4828 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4829 else if (r_shadow_shadowmappcf)
4830 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4832 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4833 permutation |= SHADERPERMUTATION_REFLECTION;
4834 if (rsurface.texture->reflectmasktexture)
4835 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4836 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4837 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4838 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4840 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
4842 if (r_glsl_offsetmapping.integer)
4844 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4845 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4846 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4847 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4848 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4850 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4851 if (r_glsl_offsetmapping_reliefmapping.integer)
4852 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4855 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4856 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4857 // directional model lighting
4858 mode = SHADERMODE_LIGHTDIRECTION;
4859 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4860 permutation |= SHADERPERMUTATION_GLOW;
4861 permutation |= SHADERPERMUTATION_DIFFUSE;
4862 if (specularscale > 0)
4864 permutation |= SHADERPERMUTATION_SPECULAR;
4865 if (r_shadow_glossexact.integer)
4866 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
4868 if (r_refdef.fogenabled)
4869 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4870 if (rsurface.texture->colormapping)
4871 permutation |= SHADERPERMUTATION_COLORMAPPING;
4872 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4874 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4875 if (r_shadow_usingshadowmaprect)
4876 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4877 if (r_shadow_usingshadowmap2d)
4878 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4880 if (r_shadow_shadowmapsampler)
4881 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4882 if (r_shadow_shadowmappcf > 1)
4883 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4884 else if (r_shadow_shadowmappcf)
4885 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4887 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4888 permutation |= SHADERPERMUTATION_REFLECTION;
4889 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4890 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4891 if (rsurface.texture->reflectmasktexture)
4892 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4893 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4894 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4895 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4897 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
4899 if (r_glsl_offsetmapping.integer)
4901 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4902 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4903 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4904 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4905 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4907 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4908 if (r_glsl_offsetmapping_reliefmapping.integer)
4909 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4912 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4913 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4914 // ambient model lighting
4915 mode = SHADERMODE_LIGHTDIRECTION;
4916 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4917 permutation |= SHADERPERMUTATION_GLOW;
4918 if (r_refdef.fogenabled)
4919 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4920 if (rsurface.texture->colormapping)
4921 permutation |= SHADERPERMUTATION_COLORMAPPING;
4922 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4924 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4925 if (r_shadow_usingshadowmaprect)
4926 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4927 if (r_shadow_usingshadowmap2d)
4928 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4930 if (r_shadow_shadowmapsampler)
4931 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4932 if (r_shadow_shadowmappcf > 1)
4933 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4934 else if (r_shadow_shadowmappcf)
4935 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4937 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4938 permutation |= SHADERPERMUTATION_REFLECTION;
4939 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4940 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4941 if (rsurface.texture->reflectmasktexture)
4942 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4943 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
4944 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4945 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
4949 if (r_glsl_offsetmapping.integer)
4951 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4952 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4953 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4954 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4955 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4957 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4958 if (r_glsl_offsetmapping_reliefmapping.integer)
4959 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4962 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4963 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4965 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
4966 permutation |= SHADERPERMUTATION_GLOW;
4967 if (r_refdef.fogenabled)
4968 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4969 if (rsurface.texture->colormapping)
4970 permutation |= SHADERPERMUTATION_COLORMAPPING;
4971 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
4973 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
4974 if (r_shadow_usingshadowmaprect)
4975 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
4976 if (r_shadow_usingshadowmap2d)
4977 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
4979 if (r_shadow_shadowmapsampler)
4980 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
4981 if (r_shadow_shadowmappcf > 1)
4982 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
4983 else if (r_shadow_shadowmappcf)
4984 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
4986 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
4987 permutation |= SHADERPERMUTATION_REFLECTION;
4988 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
4989 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
4990 if (rsurface.texture->reflectmasktexture)
4991 permutation |= SHADERPERMUTATION_REFLECTCUBE;
4992 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
4994 // deluxemapping (light direction texture)
4995 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
4996 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
4998 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
4999 permutation |= SHADERPERMUTATION_DIFFUSE;
5000 if (specularscale > 0)
5002 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5003 if (r_shadow_glossexact.integer)
5004 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5007 else if (r_glsl_deluxemapping.integer >= 2)
5009 // fake deluxemapping (uniform light direction in tangentspace)
5010 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5011 permutation |= SHADERPERMUTATION_DIFFUSE;
5012 if (specularscale > 0)
5014 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5015 if (r_shadow_glossexact.integer)
5016 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5019 else if (rsurface.uselightmaptexture)
5021 // ordinary lightmapping (q1bsp, q3bsp)
5022 mode = SHADERMODE_LIGHTMAP;
5026 // ordinary vertex coloring (q3bsp)
5027 mode = SHADERMODE_VERTEXCOLOR;
5029 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5030 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5031 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5034 colormod = dummy_colormod;
5035 switch(vid.renderpath)
5037 case RENDERPATH_GL20:
5038 if (gl_mesh_separatearrays.integer)
5040 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5041 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5042 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5043 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5044 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5045 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5046 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5047 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5051 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5052 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5054 R_SetupShader_SetPermutationGLSL(mode, permutation);
5055 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5056 if (mode == SHADERMODE_LIGHTSOURCE)
5058 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5059 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5060 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5061 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5062 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5063 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);
5065 // additive passes are only darkened by fog, not tinted
5066 if (r_glsl_permutation->loc_FogColor >= 0)
5067 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5068 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5072 if (mode == SHADERMODE_FLATCOLOR)
5074 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5076 else if (mode == SHADERMODE_LIGHTDIRECTION)
5078 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5079 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5080 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);
5081 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5082 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);
5083 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]);
5084 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]);
5088 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5089 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]);
5090 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);
5091 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5092 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);
5094 // additive passes are only darkened by fog, not tinted
5095 if (r_glsl_permutation->loc_FogColor >= 0)
5097 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5098 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5100 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5102 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);
5103 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]);
5104 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]);
5105 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
5106 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
5107 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5108 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5109 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5111 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5112 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5113 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5114 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]);
5115 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]);
5117 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5118 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5119 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5120 if (r_glsl_permutation->loc_Color_Pants >= 0)
5122 if (rsurface.texture->pantstexture)
5123 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5125 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5127 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5129 if (rsurface.texture->shirttexture)
5130 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5132 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5134 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]);
5135 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5136 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5137 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5138 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5139 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]);
5140 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5142 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5143 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5144 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5145 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5146 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5147 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5148 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5149 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5150 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5151 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5152 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5153 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5154 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5155 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5156 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5157 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5158 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5159 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , r_texture_white );
5160 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP , r_texture_blanknormalmap );
5161 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5162 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION , r_texture_white );
5163 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION , r_texture_white );
5164 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5165 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5166 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5167 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5168 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5170 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5171 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5172 if (rsurface.rtlight)
5174 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5175 if (r_shadow_usingshadowmapcube)
5176 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5177 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5182 case RENDERPATH_CGGL:
5184 if (gl_mesh_separatearrays.integer)
5186 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5187 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5188 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5189 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5190 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5191 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5192 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5193 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5197 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5198 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5200 R_SetupShader_SetPermutationCG(mode, permutation);
5201 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5202 if (mode == SHADERMODE_LIGHTSOURCE)
5204 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5205 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5209 if (mode == SHADERMODE_LIGHTDIRECTION)
5211 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
5214 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5215 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5216 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5217 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5218 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
5221 if (mode == SHADERMODE_LIGHTSOURCE)
5223 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5224 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5225 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);CHECKCGERROR
5226 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);CHECKCGERROR
5227 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
5229 // additive passes are only darkened by fog, not tinted
5230 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5231 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5235 if (mode == SHADERMODE_FLATCOLOR)
5237 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, colormod[0], colormod[1], colormod[2]);CHECKCGERROR
5239 else if (mode == SHADERMODE_LIGHTDIRECTION)
5241 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);CHECKCGERROR
5242 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);CHECKCGERROR
5243 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
5244 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5245 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
5246 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
5247 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
5251 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);CHECKCGERROR
5252 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
5253 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
5254 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5255 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
5257 // additive passes are only darkened by fog, not tinted
5258 if (r_cg_permutation->fp_FogColor)
5260 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5261 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5263 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5266 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
5267 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
5268 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
5269 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5270 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5271 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5272 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
5273 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5275 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
5276 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
5277 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
5278 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
5279 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5280 if (r_cg_permutation->fp_Color_Pants)
5282 if (rsurface.texture->pantstexture)
5283 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5285 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
5288 if (r_cg_permutation->fp_Color_Shirt)
5290 if (rsurface.texture->shirttexture)
5291 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5293 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
5296 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
5297 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
5298 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
5299 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
5300 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
5301 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
5302 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5304 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
5305 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
5306 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
5307 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
5308 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
5309 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
5310 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
5311 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
5312 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
5313 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
5314 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
5315 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
5316 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
5317 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
5318 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
5319 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
5320 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
5321 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , r_texture_white );CHECKCGERROR
5322 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , r_texture_blanknormalmap );CHECKCGERROR
5323 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5324 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , r_texture_white );CHECKCGERROR
5325 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , r_texture_white );CHECKCGERROR
5326 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5327 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5328 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
5329 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
5330 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5332 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5333 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5334 if (rsurface.rtlight)
5336 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5337 if (r_shadow_usingshadowmapcube)
5338 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5339 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5346 case RENDERPATH_GL13:
5347 case RENDERPATH_GL11:
5352 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5354 // select a permutation of the lighting shader appropriate to this
5355 // combination of texture, entity, light source, and fogging, only use the
5356 // minimum features necessary to avoid wasting rendering time in the
5357 // fragment shader on features that are not being used
5358 unsigned int permutation = 0;
5359 unsigned int mode = 0;
5360 const float *lightcolorbase = rtlight->currentcolor;
5361 float ambientscale = rtlight->ambientscale;
5362 float diffusescale = rtlight->diffusescale;
5363 float specularscale = rtlight->specularscale;
5364 // this is the location of the light in view space
5365 vec3_t viewlightorigin;
5366 // this transforms from view space (camera) to light space (cubemap)
5367 matrix4x4_t viewtolight;
5368 matrix4x4_t lighttoview;
5369 float viewtolight16f[16];
5370 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5372 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5373 if (rtlight->currentcubemap != r_texture_whitecube)
5374 permutation |= SHADERPERMUTATION_CUBEFILTER;
5375 if (diffusescale > 0)
5376 permutation |= SHADERPERMUTATION_DIFFUSE;
5377 if (specularscale > 0)
5379 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5380 if (r_shadow_glossexact.integer)
5381 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5383 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5385 if (r_shadow_usingshadowmaprect)
5386 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5387 if (r_shadow_usingshadowmap2d)
5388 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5389 if (r_shadow_usingshadowmapcube)
5390 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5391 else if(r_shadow_shadowmapvsdct)
5392 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5394 if (r_shadow_shadowmapsampler)
5395 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5396 if (r_shadow_shadowmappcf > 1)
5397 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5398 else if (r_shadow_shadowmappcf)
5399 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5401 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5402 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5403 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5404 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5405 switch(vid.renderpath)
5407 case RENDERPATH_GL20:
5408 R_SetupShader_SetPermutationGLSL(mode, permutation);
5409 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5410 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
5411 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);
5412 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);
5413 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);
5414 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]);
5415 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]);
5416 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));
5417 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]);
5418 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5420 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5421 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5422 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5423 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5424 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
5425 if (r_shadow_usingshadowmapcube)
5426 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5427 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
5428 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5430 case RENDERPATH_CGGL:
5432 R_SetupShader_SetPermutationCG(mode, permutation);
5433 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
5434 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
5435 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
5436 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
5437 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
5438 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
5439 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
5440 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
5441 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
5442 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
5444 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
5445 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
5446 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
5447 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
5448 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
5449 if (r_shadow_usingshadowmapcube)
5450 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
5451 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
5452 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
5455 case RENDERPATH_GL13:
5456 case RENDERPATH_GL11:
5461 #define SKINFRAME_HASH 1024
5465 int loadsequence; // incremented each level change
5466 memexpandablearray_t array;
5467 skinframe_t *hash[SKINFRAME_HASH];
5470 r_skinframe_t r_skinframe;
5472 void R_SkinFrame_PrepareForPurge(void)
5474 r_skinframe.loadsequence++;
5475 // wrap it without hitting zero
5476 if (r_skinframe.loadsequence >= 200)
5477 r_skinframe.loadsequence = 1;
5480 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5484 // mark the skinframe as used for the purging code
5485 skinframe->loadsequence = r_skinframe.loadsequence;
5488 void R_SkinFrame_Purge(void)
5492 for (i = 0;i < SKINFRAME_HASH;i++)
5494 for (s = r_skinframe.hash[i];s;s = s->next)
5496 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5498 if (s->merged == s->base)
5500 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5501 R_PurgeTexture(s->stain );s->stain = NULL;
5502 R_PurgeTexture(s->merged);s->merged = NULL;
5503 R_PurgeTexture(s->base );s->base = NULL;
5504 R_PurgeTexture(s->pants );s->pants = NULL;
5505 R_PurgeTexture(s->shirt );s->shirt = NULL;
5506 R_PurgeTexture(s->nmap );s->nmap = NULL;
5507 R_PurgeTexture(s->gloss );s->gloss = NULL;
5508 R_PurgeTexture(s->glow );s->glow = NULL;
5509 R_PurgeTexture(s->fog );s->fog = NULL;
5510 R_PurgeTexture(s->reflect);s->reflect = NULL;
5511 s->loadsequence = 0;
5517 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5519 char basename[MAX_QPATH];
5521 Image_StripImageExtension(name, basename, sizeof(basename));
5523 if( last == NULL ) {
5525 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5526 item = r_skinframe.hash[hashindex];
5531 // linearly search through the hash bucket
5532 for( ; item ; item = item->next ) {
5533 if( !strcmp( item->basename, basename ) ) {
5540 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5544 char basename[MAX_QPATH];
5546 Image_StripImageExtension(name, basename, sizeof(basename));
5548 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5549 for (item = r_skinframe.hash[hashindex];item;item = item->next)
5550 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5554 rtexture_t *dyntexture;
5555 // check whether its a dynamic texture
5556 dyntexture = CL_GetDynTexture( basename );
5557 if (!add && !dyntexture)
5559 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5560 memset(item, 0, sizeof(*item));
5561 strlcpy(item->basename, basename, sizeof(item->basename));
5562 item->base = dyntexture; // either NULL or dyntexture handle
5563 item->textureflags = textureflags;
5564 item->comparewidth = comparewidth;
5565 item->compareheight = compareheight;
5566 item->comparecrc = comparecrc;
5567 item->next = r_skinframe.hash[hashindex];
5568 r_skinframe.hash[hashindex] = item;
5570 else if( item->base == NULL )
5572 rtexture_t *dyntexture;
5573 // check whether its a dynamic texture
5574 // 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]
5575 dyntexture = CL_GetDynTexture( basename );
5576 item->base = dyntexture; // either NULL or dyntexture handle
5579 R_SkinFrame_MarkUsed(item);
5583 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5585 unsigned long long avgcolor[5], wsum; \
5593 for(pix = 0; pix < cnt; ++pix) \
5596 for(comp = 0; comp < 3; ++comp) \
5598 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5601 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5603 for(comp = 0; comp < 3; ++comp) \
5604 avgcolor[comp] += getpixel * w; \
5607 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5608 avgcolor[4] += getpixel; \
5610 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
5612 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
5613 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
5614 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
5615 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
5618 extern cvar_t gl_picmip;
5619 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
5622 unsigned char *pixels;
5623 unsigned char *bumppixels;
5624 unsigned char *basepixels = NULL;
5625 int basepixels_width = 0;
5626 int basepixels_height = 0;
5627 skinframe_t *skinframe;
5628 rtexture_t *ddsbase = NULL;
5629 qboolean ddshasalpha = false;
5630 float ddsavgcolor[4];
5631 char basename[MAX_QPATH];
5632 int miplevel = R_PicmipForFlags(textureflags);
5633 int savemiplevel = miplevel;
5636 if (cls.state == ca_dedicated)
5639 // return an existing skinframe if already loaded
5640 // if loading of the first image fails, don't make a new skinframe as it
5641 // would cause all future lookups of this to be missing
5642 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
5643 if (skinframe && skinframe->base)
5646 Image_StripImageExtension(name, basename, sizeof(basename));
5648 // check for DDS texture file first
5649 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
5651 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer, &miplevel);
5652 if (basepixels == NULL)
5656 // FIXME handle miplevel
5658 if (developer_loading.integer)
5659 Con_Printf("loading skin \"%s\"\n", name);
5661 // we've got some pixels to store, so really allocate this new texture now
5663 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
5664 skinframe->stain = NULL;
5665 skinframe->merged = NULL;
5666 skinframe->base = NULL;
5667 skinframe->pants = NULL;
5668 skinframe->shirt = NULL;
5669 skinframe->nmap = NULL;
5670 skinframe->gloss = NULL;
5671 skinframe->glow = NULL;
5672 skinframe->fog = NULL;
5673 skinframe->reflect = NULL;
5674 skinframe->hasalpha = false;
5678 skinframe->base = ddsbase;
5679 skinframe->hasalpha = ddshasalpha;
5680 VectorCopy(ddsavgcolor, skinframe->avgcolor);
5681 if (r_loadfog && skinframe->hasalpha)
5682 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
5683 //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]);
5687 basepixels_width = image_width;
5688 basepixels_height = image_height;
5689 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5690 if (textureflags & TEXF_ALPHA)
5692 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
5694 if (basepixels[j] < 255)
5696 skinframe->hasalpha = true;
5700 if (r_loadfog && skinframe->hasalpha)
5702 // has transparent pixels
5703 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5704 for (j = 0;j < image_width * image_height * 4;j += 4)
5709 pixels[j+3] = basepixels[j+3];
5711 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
5715 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
5716 //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]);
5717 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
5718 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
5719 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
5720 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
5725 mymiplevel = savemiplevel;
5726 if (r_loadnormalmap)
5727 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
5728 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5730 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5731 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5732 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5733 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
5736 // _norm is the name used by tenebrae and has been adopted as standard
5737 if (r_loadnormalmap && skinframe->nmap == NULL)
5739 mymiplevel = savemiplevel;
5740 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5742 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5746 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
5748 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
5749 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
5750 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5752 Mem_Free(bumppixels);
5754 else if (r_shadow_bumpscale_basetexture.value > 0)
5756 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
5757 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
5758 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5761 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
5762 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
5765 // _luma is supported only for tenebrae compatibility
5766 // _glow is the preferred name
5767 mymiplevel = savemiplevel;
5768 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel))))
5770 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5771 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
5772 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
5773 Mem_Free(pixels);pixels = NULL;
5776 mymiplevel = savemiplevel;
5777 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5779 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5780 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
5781 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
5786 mymiplevel = savemiplevel;
5787 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5789 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5790 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
5791 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
5796 mymiplevel = savemiplevel;
5797 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5799 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5800 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
5801 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
5806 mymiplevel = savemiplevel;
5807 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer, &mymiplevel)))
5809 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
5810 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
5811 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
5817 Mem_Free(basepixels);
5822 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
5823 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
5826 unsigned char *temp1, *temp2;
5827 skinframe_t *skinframe;
5829 if (cls.state == ca_dedicated)
5832 // if already loaded just return it, otherwise make a new skinframe
5833 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
5834 if (skinframe && skinframe->base)
5837 skinframe->stain = NULL;
5838 skinframe->merged = NULL;
5839 skinframe->base = NULL;
5840 skinframe->pants = NULL;
5841 skinframe->shirt = NULL;
5842 skinframe->nmap = NULL;
5843 skinframe->gloss = NULL;
5844 skinframe->glow = NULL;
5845 skinframe->fog = NULL;
5846 skinframe->reflect = NULL;
5847 skinframe->hasalpha = false;
5849 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5853 if (developer_loading.integer)
5854 Con_Printf("loading 32bit skin \"%s\"\n", name);
5856 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
5858 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5859 temp2 = temp1 + width * height * 4;
5860 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5861 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
5864 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
5865 if (textureflags & TEXF_ALPHA)
5867 for (i = 3;i < width * height * 4;i += 4)
5869 if (skindata[i] < 255)
5871 skinframe->hasalpha = true;
5875 if (r_loadfog && skinframe->hasalpha)
5877 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
5878 memcpy(fogpixels, skindata, width * height * 4);
5879 for (i = 0;i < width * height * 4;i += 4)
5880 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
5881 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
5882 Mem_Free(fogpixels);
5886 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
5887 //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]);
5892 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
5896 skinframe_t *skinframe;
5898 if (cls.state == ca_dedicated)
5901 // if already loaded just return it, otherwise make a new skinframe
5902 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
5903 if (skinframe && skinframe->base)
5906 skinframe->stain = NULL;
5907 skinframe->merged = NULL;
5908 skinframe->base = NULL;
5909 skinframe->pants = NULL;
5910 skinframe->shirt = NULL;
5911 skinframe->nmap = NULL;
5912 skinframe->gloss = NULL;
5913 skinframe->glow = NULL;
5914 skinframe->fog = NULL;
5915 skinframe->reflect = NULL;
5916 skinframe->hasalpha = false;
5918 // if no data was provided, then clearly the caller wanted to get a blank skinframe
5922 if (developer_loading.integer)
5923 Con_Printf("loading quake skin \"%s\"\n", name);
5925 // 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)
5926 skinframe->qpixels = Mem_Alloc(r_main_mempool, width*height);
5927 memcpy(skinframe->qpixels, skindata, width*height);
5928 skinframe->qwidth = width;
5929 skinframe->qheight = height;
5932 for (i = 0;i < width * height;i++)
5933 featuresmask |= palette_featureflags[skindata[i]];
5935 skinframe->hasalpha = false;
5936 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
5937 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
5938 skinframe->qgeneratemerged = true;
5939 skinframe->qgeneratebase = skinframe->qhascolormapping;
5940 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
5942 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
5943 //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]);
5948 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
5952 unsigned char *skindata;
5954 if (!skinframe->qpixels)
5957 if (!skinframe->qhascolormapping)
5958 colormapped = false;
5962 if (!skinframe->qgeneratebase)
5967 if (!skinframe->qgeneratemerged)
5971 width = skinframe->qwidth;
5972 height = skinframe->qheight;
5973 skindata = skinframe->qpixels;
5975 if (skinframe->qgeneratenmap)
5977 unsigned char *temp1, *temp2;
5978 skinframe->qgeneratenmap = false;
5979 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
5980 temp2 = temp1 + width * height * 4;
5981 // use either a custom palette or the quake palette
5982 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
5983 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
5984 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
5988 if (skinframe->qgenerateglow)
5990 skinframe->qgenerateglow = false;
5991 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
5996 skinframe->qgeneratebase = false;
5997 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);
5998 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
5999 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6003 skinframe->qgeneratemerged = false;
6004 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);
6007 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6009 Mem_Free(skinframe->qpixels);
6010 skinframe->qpixels = NULL;
6014 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)
6017 skinframe_t *skinframe;
6019 if (cls.state == ca_dedicated)
6022 // if already loaded just return it, otherwise make a new skinframe
6023 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6024 if (skinframe && skinframe->base)
6027 skinframe->stain = NULL;
6028 skinframe->merged = NULL;
6029 skinframe->base = NULL;
6030 skinframe->pants = NULL;
6031 skinframe->shirt = NULL;
6032 skinframe->nmap = NULL;
6033 skinframe->gloss = NULL;
6034 skinframe->glow = NULL;
6035 skinframe->fog = NULL;
6036 skinframe->reflect = NULL;
6037 skinframe->hasalpha = false;
6039 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6043 if (developer_loading.integer)
6044 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6046 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6047 if (textureflags & TEXF_ALPHA)
6049 for (i = 0;i < width * height;i++)
6051 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6053 skinframe->hasalpha = true;
6057 if (r_loadfog && skinframe->hasalpha)
6058 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6061 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6062 //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]);
6067 skinframe_t *R_SkinFrame_LoadMissing(void)
6069 skinframe_t *skinframe;
6071 if (cls.state == ca_dedicated)
6074 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6075 skinframe->stain = NULL;
6076 skinframe->merged = NULL;
6077 skinframe->base = NULL;
6078 skinframe->pants = NULL;
6079 skinframe->shirt = NULL;
6080 skinframe->nmap = NULL;
6081 skinframe->gloss = NULL;
6082 skinframe->glow = NULL;
6083 skinframe->fog = NULL;
6084 skinframe->reflect = NULL;
6085 skinframe->hasalpha = false;
6087 skinframe->avgcolor[0] = rand() / RAND_MAX;
6088 skinframe->avgcolor[1] = rand() / RAND_MAX;
6089 skinframe->avgcolor[2] = rand() / RAND_MAX;
6090 skinframe->avgcolor[3] = 1;
6095 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6096 typedef struct suffixinfo_s
6099 qboolean flipx, flipy, flipdiagonal;
6102 static suffixinfo_t suffix[3][6] =
6105 {"px", false, false, false},
6106 {"nx", false, false, false},
6107 {"py", false, false, false},
6108 {"ny", false, false, false},
6109 {"pz", false, false, false},
6110 {"nz", false, false, false}
6113 {"posx", false, false, false},
6114 {"negx", false, false, false},
6115 {"posy", false, false, false},
6116 {"negy", false, false, false},
6117 {"posz", false, false, false},
6118 {"negz", false, false, false}
6121 {"rt", true, false, true},
6122 {"lf", false, true, true},
6123 {"ft", true, true, false},
6124 {"bk", false, false, false},
6125 {"up", true, false, true},
6126 {"dn", true, false, true}
6130 static int componentorder[4] = {0, 1, 2, 3};
6132 rtexture_t *R_LoadCubemap(const char *basename)
6134 int i, j, cubemapsize;
6135 unsigned char *cubemappixels, *image_buffer;
6136 rtexture_t *cubemaptexture;
6138 // must start 0 so the first loadimagepixels has no requested width/height
6140 cubemappixels = NULL;
6141 cubemaptexture = NULL;
6142 // keep trying different suffix groups (posx, px, rt) until one loads
6143 for (j = 0;j < 3 && !cubemappixels;j++)
6145 // load the 6 images in the suffix group
6146 for (i = 0;i < 6;i++)
6148 // generate an image name based on the base and and suffix
6149 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6151 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer, NULL)))
6153 // an image loaded, make sure width and height are equal
6154 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6156 // if this is the first image to load successfully, allocate the cubemap memory
6157 if (!cubemappixels && image_width >= 1)
6159 cubemapsize = image_width;
6160 // note this clears to black, so unavailable sides are black
6161 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6163 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6165 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);
6168 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6170 Mem_Free(image_buffer);
6174 // if a cubemap loaded, upload it
6177 if (developer_loading.integer)
6178 Con_Printf("loading cubemap \"%s\"\n", basename);
6180 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6181 Mem_Free(cubemappixels);
6185 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6186 if (developer_loading.integer)
6188 Con_Printf("(tried tried images ");
6189 for (j = 0;j < 3;j++)
6190 for (i = 0;i < 6;i++)
6191 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6192 Con_Print(" and was unable to find any of them).\n");
6195 return cubemaptexture;
6198 rtexture_t *R_GetCubemap(const char *basename)
6201 for (i = 0;i < r_texture_numcubemaps;i++)
6202 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6203 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6204 if (i >= MAX_CUBEMAPS)
6205 return r_texture_whitecube;
6206 r_texture_numcubemaps++;
6207 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6208 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6209 return r_texture_cubemaps[i].texture;
6212 void R_FreeCubemaps(void)
6215 for (i = 0;i < r_texture_numcubemaps;i++)
6217 if (developer_loading.integer)
6218 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6219 if (r_texture_cubemaps[i].texture)
6220 R_FreeTexture(r_texture_cubemaps[i].texture);
6222 r_texture_numcubemaps = 0;
6225 void R_Main_FreeViewCache(void)
6227 if (r_refdef.viewcache.entityvisible)
6228 Mem_Free(r_refdef.viewcache.entityvisible);
6229 if (r_refdef.viewcache.world_pvsbits)
6230 Mem_Free(r_refdef.viewcache.world_pvsbits);
6231 if (r_refdef.viewcache.world_leafvisible)
6232 Mem_Free(r_refdef.viewcache.world_leafvisible);
6233 if (r_refdef.viewcache.world_surfacevisible)
6234 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6235 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6238 void R_Main_ResizeViewCache(void)
6240 int numentities = r_refdef.scene.numentities;
6241 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6242 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6243 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6244 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6245 if (r_refdef.viewcache.maxentities < numentities)
6247 r_refdef.viewcache.maxentities = numentities;
6248 if (r_refdef.viewcache.entityvisible)
6249 Mem_Free(r_refdef.viewcache.entityvisible);
6250 r_refdef.viewcache.entityvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6252 if (r_refdef.viewcache.world_numclusters != numclusters)
6254 r_refdef.viewcache.world_numclusters = numclusters;
6255 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6256 if (r_refdef.viewcache.world_pvsbits)
6257 Mem_Free(r_refdef.viewcache.world_pvsbits);
6258 r_refdef.viewcache.world_pvsbits = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6260 if (r_refdef.viewcache.world_numleafs != numleafs)
6262 r_refdef.viewcache.world_numleafs = numleafs;
6263 if (r_refdef.viewcache.world_leafvisible)
6264 Mem_Free(r_refdef.viewcache.world_leafvisible);
6265 r_refdef.viewcache.world_leafvisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6267 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6269 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6270 if (r_refdef.viewcache.world_surfacevisible)
6271 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6272 r_refdef.viewcache.world_surfacevisible = Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6276 extern rtexture_t *loadingscreentexture;
6277 void gl_main_start(void)
6279 loadingscreentexture = NULL;
6280 r_texture_blanknormalmap = NULL;
6281 r_texture_white = NULL;
6282 r_texture_grey128 = NULL;
6283 r_texture_black = NULL;
6284 r_texture_whitecube = NULL;
6285 r_texture_normalizationcube = NULL;
6286 r_texture_fogattenuation = NULL;
6287 r_texture_fogheighttexture = NULL;
6288 r_texture_gammaramps = NULL;
6289 r_texture_numcubemaps = 0;
6291 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
6292 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6294 switch(vid.renderpath)
6296 case RENDERPATH_GL20:
6297 case RENDERPATH_CGGL:
6298 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6299 Cvar_SetValueQuick(&gl_combine, 1);
6300 Cvar_SetValueQuick(&r_glsl, 1);
6301 r_loadnormalmap = true;
6305 case RENDERPATH_GL13:
6306 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6307 Cvar_SetValueQuick(&gl_combine, 1);
6308 Cvar_SetValueQuick(&r_glsl, 0);
6309 r_loadnormalmap = false;
6310 r_loadgloss = false;
6313 case RENDERPATH_GL11:
6314 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6315 Cvar_SetValueQuick(&gl_combine, 0);
6316 Cvar_SetValueQuick(&r_glsl, 0);
6317 r_loadnormalmap = false;
6318 r_loadgloss = false;
6324 R_FrameData_Reset();
6328 memset(r_queries, 0, sizeof(r_queries));
6330 r_qwskincache = NULL;
6331 r_qwskincache_size = 0;
6333 // set up r_skinframe loading system for textures
6334 memset(&r_skinframe, 0, sizeof(r_skinframe));
6335 r_skinframe.loadsequence = 1;
6336 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6338 r_main_texturepool = R_AllocTexturePool();
6339 R_BuildBlankTextures();
6341 if (vid.support.arb_texture_cube_map)
6344 R_BuildNormalizationCube();
6346 r_texture_fogattenuation = NULL;
6347 r_texture_fogheighttexture = NULL;
6348 r_texture_gammaramps = NULL;
6349 //r_texture_fogintensity = NULL;
6350 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6351 memset(&r_waterstate, 0, sizeof(r_waterstate));
6352 r_glsl_permutation = NULL;
6353 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6354 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6355 glslshaderstring = NULL;
6357 r_cg_permutation = NULL;
6358 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6359 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
6360 cgshaderstring = NULL;
6362 memset(&r_svbsp, 0, sizeof (r_svbsp));
6364 r_refdef.fogmasktable_density = 0;
6367 void gl_main_shutdown(void)
6370 R_FrameData_Reset();
6372 R_Main_FreeViewCache();
6375 qglDeleteQueriesARB(r_maxqueries, r_queries);
6379 memset(r_queries, 0, sizeof(r_queries));
6381 r_qwskincache = NULL;
6382 r_qwskincache_size = 0;
6384 // clear out the r_skinframe state
6385 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6386 memset(&r_skinframe, 0, sizeof(r_skinframe));
6389 Mem_Free(r_svbsp.nodes);
6390 memset(&r_svbsp, 0, sizeof (r_svbsp));
6391 R_FreeTexturePool(&r_main_texturepool);
6392 loadingscreentexture = NULL;
6393 r_texture_blanknormalmap = NULL;
6394 r_texture_white = NULL;
6395 r_texture_grey128 = NULL;
6396 r_texture_black = NULL;
6397 r_texture_whitecube = NULL;
6398 r_texture_normalizationcube = NULL;
6399 r_texture_fogattenuation = NULL;
6400 r_texture_fogheighttexture = NULL;
6401 r_texture_gammaramps = NULL;
6402 r_texture_numcubemaps = 0;
6403 //r_texture_fogintensity = NULL;
6404 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6405 memset(&r_waterstate, 0, sizeof(r_waterstate));
6406 r_glsl_permutation = NULL;
6407 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6408 glslshaderstring = NULL;
6410 r_cg_permutation = NULL;
6411 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
6412 cgshaderstring = NULL;
6417 extern void CL_ParseEntityLump(char *entitystring);
6418 void gl_main_newmap(void)
6420 // FIXME: move this code to client
6421 char *entities, entname[MAX_QPATH];
6423 Mem_Free(r_qwskincache);
6424 r_qwskincache = NULL;
6425 r_qwskincache_size = 0;
6428 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
6429 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6431 CL_ParseEntityLump(entities);
6435 if (cl.worldmodel->brush.entities)
6436 CL_ParseEntityLump(cl.worldmodel->brush.entities);
6438 R_Main_FreeViewCache();
6440 R_FrameData_Reset();
6443 void GL_Main_Init(void)
6445 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6447 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6448 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6449 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6450 if (gamemode == GAME_NEHAHRA)
6452 Cvar_RegisterVariable (&gl_fogenable);
6453 Cvar_RegisterVariable (&gl_fogdensity);
6454 Cvar_RegisterVariable (&gl_fogred);
6455 Cvar_RegisterVariable (&gl_foggreen);
6456 Cvar_RegisterVariable (&gl_fogblue);
6457 Cvar_RegisterVariable (&gl_fogstart);
6458 Cvar_RegisterVariable (&gl_fogend);
6459 Cvar_RegisterVariable (&gl_skyclip);
6461 Cvar_RegisterVariable(&r_motionblur);
6462 Cvar_RegisterVariable(&r_motionblur_maxblur);
6463 Cvar_RegisterVariable(&r_motionblur_bmin);
6464 Cvar_RegisterVariable(&r_motionblur_vmin);
6465 Cvar_RegisterVariable(&r_motionblur_vmax);
6466 Cvar_RegisterVariable(&r_motionblur_vcoeff);
6467 Cvar_RegisterVariable(&r_motionblur_randomize);
6468 Cvar_RegisterVariable(&r_damageblur);
6469 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6470 Cvar_RegisterVariable(&r_equalize_entities_minambient);
6471 Cvar_RegisterVariable(&r_equalize_entities_by);
6472 Cvar_RegisterVariable(&r_equalize_entities_to);
6473 Cvar_RegisterVariable(&r_depthfirst);
6474 Cvar_RegisterVariable(&r_useinfinitefarclip);
6475 Cvar_RegisterVariable(&r_farclip_base);
6476 Cvar_RegisterVariable(&r_farclip_world);
6477 Cvar_RegisterVariable(&r_nearclip);
6478 Cvar_RegisterVariable(&r_showbboxes);
6479 Cvar_RegisterVariable(&r_showsurfaces);
6480 Cvar_RegisterVariable(&r_showtris);
6481 Cvar_RegisterVariable(&r_shownormals);
6482 Cvar_RegisterVariable(&r_showlighting);
6483 Cvar_RegisterVariable(&r_showshadowvolumes);
6484 Cvar_RegisterVariable(&r_showcollisionbrushes);
6485 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6486 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6487 Cvar_RegisterVariable(&r_showdisabledepthtest);
6488 Cvar_RegisterVariable(&r_drawportals);
6489 Cvar_RegisterVariable(&r_drawentities);
6490 Cvar_RegisterVariable(&r_draw2d);
6491 Cvar_RegisterVariable(&r_drawworld);
6492 Cvar_RegisterVariable(&r_cullentities_trace);
6493 Cvar_RegisterVariable(&r_cullentities_trace_samples);
6494 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6495 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6496 Cvar_RegisterVariable(&r_cullentities_trace_delay);
6497 Cvar_RegisterVariable(&r_drawviewmodel);
6498 Cvar_RegisterVariable(&r_drawexteriormodel);
6499 Cvar_RegisterVariable(&r_speeds);
6500 Cvar_RegisterVariable(&r_fullbrights);
6501 Cvar_RegisterVariable(&r_wateralpha);
6502 Cvar_RegisterVariable(&r_dynamic);
6503 Cvar_RegisterVariable(&r_fullbright);
6504 Cvar_RegisterVariable(&r_shadows);
6505 Cvar_RegisterVariable(&r_shadows_darken);
6506 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6507 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6508 Cvar_RegisterVariable(&r_shadows_throwdistance);
6509 Cvar_RegisterVariable(&r_shadows_throwdirection);
6510 Cvar_RegisterVariable(&r_shadows_focus);
6511 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6512 Cvar_RegisterVariable(&r_q1bsp_skymasking);
6513 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6514 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6515 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6516 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6517 Cvar_RegisterVariable(&r_fog_exp2);
6518 Cvar_RegisterVariable(&r_drawfog);
6519 Cvar_RegisterVariable(&r_transparentdepthmasking);
6520 Cvar_RegisterVariable(&r_texture_dds_load);
6521 Cvar_RegisterVariable(&r_texture_dds_save);
6522 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6523 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6524 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6525 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6526 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6527 Cvar_RegisterVariable(&r_textureunits);
6528 Cvar_RegisterVariable(&gl_combine);
6529 Cvar_RegisterVariable(&r_glsl);
6530 Cvar_RegisterVariable(&r_glsl_deluxemapping);
6531 Cvar_RegisterVariable(&r_glsl_offsetmapping);
6532 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6533 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6534 Cvar_RegisterVariable(&r_glsl_postprocess);
6535 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6536 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6537 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6538 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6539 Cvar_RegisterVariable(&r_water);
6540 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6541 Cvar_RegisterVariable(&r_water_clippingplanebias);
6542 Cvar_RegisterVariable(&r_water_refractdistort);
6543 Cvar_RegisterVariable(&r_water_reflectdistort);
6544 Cvar_RegisterVariable(&r_lerpsprites);
6545 Cvar_RegisterVariable(&r_lerpmodels);
6546 Cvar_RegisterVariable(&r_lerplightstyles);
6547 Cvar_RegisterVariable(&r_waterscroll);
6548 Cvar_RegisterVariable(&r_bloom);
6549 Cvar_RegisterVariable(&r_bloom_colorscale);
6550 Cvar_RegisterVariable(&r_bloom_brighten);
6551 Cvar_RegisterVariable(&r_bloom_blur);
6552 Cvar_RegisterVariable(&r_bloom_resolution);
6553 Cvar_RegisterVariable(&r_bloom_colorexponent);
6554 Cvar_RegisterVariable(&r_bloom_colorsubtract);
6555 Cvar_RegisterVariable(&r_hdr);
6556 Cvar_RegisterVariable(&r_hdr_scenebrightness);
6557 Cvar_RegisterVariable(&r_hdr_glowintensity);
6558 Cvar_RegisterVariable(&r_hdr_range);
6559 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6560 Cvar_RegisterVariable(&developer_texturelogging);
6561 Cvar_RegisterVariable(&gl_lightmaps);
6562 Cvar_RegisterVariable(&r_test);
6563 Cvar_RegisterVariable(&r_glsl_saturation);
6564 Cvar_RegisterVariable(&r_framedatasize);
6565 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
6566 Cvar_SetValue("r_fullbrights", 0);
6567 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
6569 Cvar_RegisterVariable(&r_track_sprites);
6570 Cvar_RegisterVariable(&r_track_sprites_flags);
6571 Cvar_RegisterVariable(&r_track_sprites_scalew);
6572 Cvar_RegisterVariable(&r_track_sprites_scaleh);
6573 Cvar_RegisterVariable(&r_overheadsprites_perspective);
6574 Cvar_RegisterVariable(&r_overheadsprites_pushback);
6577 extern void R_Textures_Init(void);
6578 extern void GL_Draw_Init(void);
6579 extern void GL_Main_Init(void);
6580 extern void R_Shadow_Init(void);
6581 extern void R_Sky_Init(void);
6582 extern void GL_Surf_Init(void);
6583 extern void R_Particles_Init(void);
6584 extern void R_Explosion_Init(void);
6585 extern void gl_backend_init(void);
6586 extern void Sbar_Init(void);
6587 extern void R_LightningBeams_Init(void);
6588 extern void Mod_RenderInit(void);
6589 extern void Font_Init(void);
6591 void Render_Init(void)
6604 R_LightningBeams_Init();
6613 extern char *ENGINE_EXTENSIONS;
6616 gl_renderer = (const char *)qglGetString(GL_RENDERER);
6617 gl_vendor = (const char *)qglGetString(GL_VENDOR);
6618 gl_version = (const char *)qglGetString(GL_VERSION);
6619 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
6623 if (!gl_platformextensions)
6624 gl_platformextensions = "";
6626 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
6627 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
6628 Con_Printf("GL_VERSION: %s\n", gl_version);
6629 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
6630 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
6632 VID_CheckExtensions();
6634 // LordHavoc: report supported extensions
6635 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
6637 // clear to black (loading plaque will be seen over this)
6639 qglClearColor(0,0,0,1);CHECKGLERROR
6640 qglClear(GL_COLOR_BUFFER_BIT);CHECKGLERROR
6643 int R_CullBox(const vec3_t mins, const vec3_t maxs)
6647 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
6649 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
6652 p = r_refdef.view.frustum + i;
6657 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6661 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6665 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6669 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6673 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6677 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6681 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6685 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6693 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
6697 for (i = 0;i < numplanes;i++)
6704 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6708 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
6712 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6716 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
6720 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6724 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
6728 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6732 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
6740 //==================================================================================
6742 // LordHavoc: this stores temporary data used within the same frame
6744 qboolean r_framedata_failed;
6745 static size_t r_framedata_size;
6746 static size_t r_framedata_current;
6747 static void *r_framedata_base;
6749 void R_FrameData_Reset(void)
6751 if (r_framedata_base)
6752 Mem_Free(r_framedata_base);
6753 r_framedata_base = NULL;
6754 r_framedata_size = 0;
6755 r_framedata_current = 0;
6756 r_framedata_failed = false;
6759 void R_FrameData_NewFrame(void)
6762 if (r_framedata_failed)
6763 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
6764 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
6765 wantedsize = bound(65536, wantedsize, 128*1024*1024);
6766 if (r_framedata_size != wantedsize)
6768 r_framedata_size = wantedsize;
6769 if (r_framedata_base)
6770 Mem_Free(r_framedata_base);
6771 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
6773 r_framedata_current = 0;
6774 r_framedata_failed = false;
6777 void *R_FrameData_Alloc(size_t size)
6781 // align to 16 byte boundary
6782 size = (size + 15) & ~15;
6783 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
6784 r_framedata_current += size;
6787 if (r_framedata_current > r_framedata_size)
6788 r_framedata_failed = true;
6790 // return NULL on everything after a failure
6791 if (r_framedata_failed)
6797 void *R_FrameData_Store(size_t size, void *data)
6799 void *d = R_FrameData_Alloc(size);
6801 memcpy(d, data, size);
6805 //==================================================================================
6807 // LordHavoc: animcache originally written by Echon, rewritten since then
6810 * Animation cache prevents re-generating mesh data for an animated model
6811 * multiple times in one frame for lighting, shadowing, reflections, etc.
6814 void R_AnimCache_Free(void)
6818 void R_AnimCache_ClearCache(void)
6821 entity_render_t *ent;
6823 for (i = 0;i < r_refdef.scene.numentities;i++)
6825 ent = r_refdef.scene.entities[i];
6826 ent->animcache_vertex3f = NULL;
6827 ent->animcache_normal3f = NULL;
6828 ent->animcache_svector3f = NULL;
6829 ent->animcache_tvector3f = NULL;
6830 ent->animcache_vertexposition = NULL;
6831 ent->animcache_vertexmesh = NULL;
6832 ent->animcache_vertexpositionbuffer = NULL;
6833 ent->animcache_vertexmeshbuffer = NULL;
6837 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
6840 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
6841 ent->animcache_vertexmesh = R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
6842 if (!ent->animcache_vertexposition)
6843 ent->animcache_vertexposition = R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
6844 if (ent->animcache_vertexposition)
6846 for (i = 0;i < numvertices;i++)
6847 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
6848 // TODO: upload vertex buffer?
6850 if (ent->animcache_vertexmesh)
6852 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
6853 for (i = 0;i < numvertices;i++)
6854 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
6855 if (ent->animcache_svector3f)
6856 for (i = 0;i < numvertices;i++)
6857 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
6858 if (ent->animcache_tvector3f)
6859 for (i = 0;i < numvertices;i++)
6860 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
6861 if (ent->animcache_normal3f)
6862 for (i = 0;i < numvertices;i++)
6863 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
6864 // TODO: upload vertex buffer?
6868 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
6870 dp_model_t *model = ent->model;
6872 // see if it's already cached this frame
6873 if (ent->animcache_vertex3f)
6875 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
6876 if (wantnormals || wanttangents)
6878 if (ent->animcache_normal3f)
6879 wantnormals = false;
6880 if (ent->animcache_svector3f)
6881 wanttangents = false;
6882 if (wantnormals || wanttangents)
6884 numvertices = model->surfmesh.num_vertices;
6886 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6889 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6890 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6892 if (!r_framedata_failed)
6894 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
6895 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6902 // see if this ent is worth caching
6903 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
6905 // get some memory for this entity and generate mesh data
6906 numvertices = model->surfmesh.num_vertices;
6907 ent->animcache_vertex3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6909 ent->animcache_normal3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6912 ent->animcache_svector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6913 ent->animcache_tvector3f = R_FrameData_Alloc(sizeof(float[3])*numvertices);
6915 if (!r_framedata_failed)
6917 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
6918 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
6921 return !r_framedata_failed;
6924 void R_AnimCache_CacheVisibleEntities(void)
6927 qboolean wantnormals = true;
6928 qboolean wanttangents = !r_showsurfaces.integer;
6930 switch(vid.renderpath)
6932 case RENDERPATH_GL20:
6933 case RENDERPATH_CGGL:
6935 case RENDERPATH_GL13:
6936 case RENDERPATH_GL11:
6937 wanttangents = false;
6941 if (r_shownormals.integer)
6942 wanttangents = wantnormals = true;
6944 // TODO: thread this
6945 // NOTE: R_PrepareRTLights() also caches entities
6947 for (i = 0;i < r_refdef.scene.numentities;i++)
6948 if (r_refdef.viewcache.entityvisible[i])
6949 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
6952 //==================================================================================
6954 static void R_View_UpdateEntityLighting (void)
6957 entity_render_t *ent;
6958 vec3_t tempdiffusenormal, avg;
6959 vec_t f, fa, fd, fdd;
6960 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
6962 for (i = 0;i < r_refdef.scene.numentities;i++)
6964 ent = r_refdef.scene.entities[i];
6966 // skip unseen models
6967 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
6971 if (ent->model && ent->model->brush.num_leafs)
6973 // TODO: use modellight for r_ambient settings on world?
6974 VectorSet(ent->modellight_ambient, 0, 0, 0);
6975 VectorSet(ent->modellight_diffuse, 0, 0, 0);
6976 VectorSet(ent->modellight_lightdir, 0, 0, 1);
6980 // fetch the lighting from the worldmodel data
6981 VectorClear(ent->modellight_ambient);
6982 VectorClear(ent->modellight_diffuse);
6983 VectorClear(tempdiffusenormal);
6984 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
6987 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
6988 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
6989 if(ent->flags & RENDER_EQUALIZE)
6991 // first fix up ambient lighting...
6992 if(r_equalize_entities_minambient.value > 0)
6994 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
6997 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
6998 if(fa < r_equalize_entities_minambient.value * fd)
7001 // fa'/fd' = minambient
7002 // fa'+0.25*fd' = fa+0.25*fd
7004 // fa' = fd' * minambient
7005 // fd'*(0.25+minambient) = fa+0.25*fd
7007 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7008 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7010 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7011 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
7012 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7013 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7018 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7020 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7021 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7024 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7025 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7026 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7032 VectorSet(ent->modellight_ambient, 1, 1, 1);
7034 // move the light direction into modelspace coordinates for lighting code
7035 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7036 if(VectorLength2(ent->modellight_lightdir) == 0)
7037 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7038 VectorNormalize(ent->modellight_lightdir);
7042 #define MAX_LINEOFSIGHTTRACES 64
7044 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7047 vec3_t boxmins, boxmaxs;
7050 dp_model_t *model = r_refdef.scene.worldmodel;
7052 if (!model || !model->brush.TraceLineOfSight)
7055 // expand the box a little
7056 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7057 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7058 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7059 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7060 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7061 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7063 // return true if eye is inside enlarged box
7064 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7068 VectorCopy(eye, start);
7069 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7070 if (model->brush.TraceLineOfSight(model, start, end))
7073 // try various random positions
7074 for (i = 0;i < numsamples;i++)
7076 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7077 if (model->brush.TraceLineOfSight(model, start, end))
7085 static void R_View_UpdateEntityVisible (void)
7090 entity_render_t *ent;
7092 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7093 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7094 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
7095 : RENDER_EXTERIORMODEL;
7096 if (!r_drawviewmodel.integer)
7097 renderimask |= RENDER_VIEWMODEL;
7098 if (!r_drawexteriormodel.integer)
7099 renderimask |= RENDER_EXTERIORMODEL;
7100 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7102 // worldmodel can check visibility
7103 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7104 for (i = 0;i < r_refdef.scene.numentities;i++)
7106 ent = r_refdef.scene.entities[i];
7107 if (!(ent->flags & renderimask))
7108 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7109 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))
7110 r_refdef.viewcache.entityvisible[i] = true;
7112 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7113 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7115 for (i = 0;i < r_refdef.scene.numentities;i++)
7117 ent = r_refdef.scene.entities[i];
7118 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7120 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7122 continue; // temp entities do pvs only
7123 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7124 ent->last_trace_visibility = realtime;
7125 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7126 r_refdef.viewcache.entityvisible[i] = 0;
7133 // no worldmodel or it can't check visibility
7134 for (i = 0;i < r_refdef.scene.numentities;i++)
7136 ent = r_refdef.scene.entities[i];
7137 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));
7142 /// only used if skyrendermasked, and normally returns false
7143 int R_DrawBrushModelsSky (void)
7146 entity_render_t *ent;
7149 for (i = 0;i < r_refdef.scene.numentities;i++)
7151 if (!r_refdef.viewcache.entityvisible[i])
7153 ent = r_refdef.scene.entities[i];
7154 if (!ent->model || !ent->model->DrawSky)
7156 ent->model->DrawSky(ent);
7162 static void R_DrawNoModel(entity_render_t *ent);
7163 static void R_DrawModels(void)
7166 entity_render_t *ent;
7168 for (i = 0;i < r_refdef.scene.numentities;i++)
7170 if (!r_refdef.viewcache.entityvisible[i])
7172 ent = r_refdef.scene.entities[i];
7173 r_refdef.stats.entities++;
7174 if (ent->model && ent->model->Draw != NULL)
7175 ent->model->Draw(ent);
7181 static void R_DrawModelsDepth(void)
7184 entity_render_t *ent;
7186 for (i = 0;i < r_refdef.scene.numentities;i++)
7188 if (!r_refdef.viewcache.entityvisible[i])
7190 ent = r_refdef.scene.entities[i];
7191 if (ent->model && ent->model->DrawDepth != NULL)
7192 ent->model->DrawDepth(ent);
7196 static void R_DrawModelsDebug(void)
7199 entity_render_t *ent;
7201 for (i = 0;i < r_refdef.scene.numentities;i++)
7203 if (!r_refdef.viewcache.entityvisible[i])
7205 ent = r_refdef.scene.entities[i];
7206 if (ent->model && ent->model->DrawDebug != NULL)
7207 ent->model->DrawDebug(ent);
7211 static void R_DrawModelsAddWaterPlanes(void)
7214 entity_render_t *ent;
7216 for (i = 0;i < r_refdef.scene.numentities;i++)
7218 if (!r_refdef.viewcache.entityvisible[i])
7220 ent = r_refdef.scene.entities[i];
7221 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7222 ent->model->DrawAddWaterPlanes(ent);
7226 static void R_View_SetFrustum(void)
7229 double slopex, slopey;
7230 vec3_t forward, left, up, origin;
7232 // we can't trust r_refdef.view.forward and friends in reflected scenes
7233 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7236 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7237 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7238 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7239 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7240 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7241 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7242 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7243 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7244 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7245 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7246 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7247 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7251 zNear = r_refdef.nearclip;
7252 nudge = 1.0 - 1.0 / (1<<23);
7253 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7254 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7255 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7256 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7257 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7258 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7259 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7260 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7266 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7267 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7268 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7269 r_refdef.view.frustum[0].dist = m[15] - m[12];
7271 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7272 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7273 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7274 r_refdef.view.frustum[1].dist = m[15] + m[12];
7276 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7277 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7278 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7279 r_refdef.view.frustum[2].dist = m[15] - m[13];
7281 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7282 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7283 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7284 r_refdef.view.frustum[3].dist = m[15] + m[13];
7286 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7287 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7288 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7289 r_refdef.view.frustum[4].dist = m[15] - m[14];
7291 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7292 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7293 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7294 r_refdef.view.frustum[5].dist = m[15] + m[14];
7297 if (r_refdef.view.useperspective)
7299 slopex = 1.0 / r_refdef.view.frustum_x;
7300 slopey = 1.0 / r_refdef.view.frustum_y;
7301 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
7302 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
7303 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
7304 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
7305 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7307 // Leaving those out was a mistake, those were in the old code, and they
7308 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7309 // I couldn't reproduce it after adding those normalizations. --blub
7310 VectorNormalize(r_refdef.view.frustum[0].normal);
7311 VectorNormalize(r_refdef.view.frustum[1].normal);
7312 VectorNormalize(r_refdef.view.frustum[2].normal);
7313 VectorNormalize(r_refdef.view.frustum[3].normal);
7315 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7316 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]);
7317 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]);
7318 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]);
7319 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]);
7321 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7322 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7323 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7324 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7325 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7329 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7330 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7331 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7332 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7333 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7334 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7335 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7336 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7337 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7338 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7340 r_refdef.view.numfrustumplanes = 5;
7342 if (r_refdef.view.useclipplane)
7344 r_refdef.view.numfrustumplanes = 6;
7345 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7348 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7349 PlaneClassify(r_refdef.view.frustum + i);
7351 // LordHavoc: note to all quake engine coders, Quake had a special case
7352 // for 90 degrees which assumed a square view (wrong), so I removed it,
7353 // Quake2 has it disabled as well.
7355 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7356 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7357 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7358 //PlaneClassify(&frustum[0]);
7360 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7361 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7362 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7363 //PlaneClassify(&frustum[1]);
7365 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7366 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7367 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7368 //PlaneClassify(&frustum[2]);
7370 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7371 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7372 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7373 //PlaneClassify(&frustum[3]);
7376 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7377 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7378 //PlaneClassify(&frustum[4]);
7381 void R_View_Update(void)
7383 R_Main_ResizeViewCache();
7384 R_View_SetFrustum();
7385 R_View_WorldVisibility(r_refdef.view.useclipplane);
7386 R_View_UpdateEntityVisible();
7387 R_View_UpdateEntityLighting();
7390 void R_SetupView(qboolean allowwaterclippingplane)
7392 const float *customclipplane = NULL;
7394 if (r_refdef.view.useclipplane && allowwaterclippingplane)
7396 // LordHavoc: couldn't figure out how to make this approach the
7397 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7398 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7399 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7400 dist = r_refdef.view.clipplane.dist;
7401 plane[0] = r_refdef.view.clipplane.normal[0];
7402 plane[1] = r_refdef.view.clipplane.normal[1];
7403 plane[2] = r_refdef.view.clipplane.normal[2];
7405 customclipplane = plane;
7408 if (!r_refdef.view.useperspective)
7409 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);
7410 else if (vid.stencil && r_useinfinitefarclip.integer)
7411 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);
7413 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);
7414 R_SetViewport(&r_refdef.view.viewport);
7417 void R_EntityMatrix(const matrix4x4_t *matrix)
7419 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7421 gl_modelmatrixchanged = false;
7422 gl_modelmatrix = *matrix;
7423 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
7424 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
7425 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
7426 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
7428 switch(vid.renderpath)
7430 case RENDERPATH_GL20:
7431 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
7432 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
7433 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7435 case RENDERPATH_CGGL:
7438 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
7439 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
7440 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7443 case RENDERPATH_GL13:
7444 case RENDERPATH_GL11:
7445 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
7451 void R_ResetViewRendering2D(void)
7453 r_viewport_t viewport;
7456 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
7457 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);
7458 R_SetViewport(&viewport);
7459 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
7460 GL_Color(1, 1, 1, 1);
7461 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7462 GL_BlendFunc(GL_ONE, GL_ZERO);
7463 GL_AlphaTest(false);
7464 GL_ScissorTest(false);
7465 GL_DepthMask(false);
7466 GL_DepthRange(0, 1);
7467 GL_DepthTest(false);
7468 R_EntityMatrix(&identitymatrix);
7469 R_Mesh_ResetTextureState();
7470 GL_PolygonOffset(0, 0);
7471 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7472 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7473 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7474 qglStencilMask(~0);CHECKGLERROR
7475 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7476 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7477 GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
7480 void R_ResetViewRendering3D(void)
7485 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
7486 GL_Color(1, 1, 1, 1);
7487 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
7488 GL_BlendFunc(GL_ONE, GL_ZERO);
7489 GL_AlphaTest(false);
7490 GL_ScissorTest(true);
7492 GL_DepthRange(0, 1);
7494 R_EntityMatrix(&identitymatrix);
7495 R_Mesh_ResetTextureState();
7496 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
7497 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
7498 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
7499 qglDisable(GL_STENCIL_TEST);CHECKGLERROR
7500 qglStencilMask(~0);CHECKGLERROR
7501 qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR
7502 qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR
7503 GL_CullFace(r_refdef.view.cullface_back);
7508 R_RenderView_UpdateViewVectors
7511 static void R_RenderView_UpdateViewVectors(void)
7513 // break apart the view matrix into vectors for various purposes
7514 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
7515 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
7516 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
7517 VectorNegate(r_refdef.view.left, r_refdef.view.right);
7518 // make an inverted copy of the view matrix for tracking sprites
7519 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
7522 void R_RenderScene(void);
7523 void R_RenderWaterPlanes(void);
7525 static void R_Water_StartFrame(void)
7528 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
7529 r_waterstate_waterplane_t *p;
7531 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
7534 switch(vid.renderpath)
7536 case RENDERPATH_GL20:
7537 case RENDERPATH_CGGL:
7539 case RENDERPATH_GL13:
7540 case RENDERPATH_GL11:
7544 // set waterwidth and waterheight to the water resolution that will be
7545 // used (often less than the screen resolution for faster rendering)
7546 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
7547 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
7549 // calculate desired texture sizes
7550 // can't use water if the card does not support the texture size
7551 if (!r_water.integer || r_showsurfaces.integer)
7552 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
7553 else if (vid.support.arb_texture_non_power_of_two)
7555 texturewidth = waterwidth;
7556 textureheight = waterheight;
7557 camerawidth = waterwidth;
7558 cameraheight = waterheight;
7562 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
7563 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
7564 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
7565 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
7568 // allocate textures as needed
7569 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
7571 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7572 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
7574 if (p->texture_refraction)
7575 R_FreeTexture(p->texture_refraction);
7576 p->texture_refraction = NULL;
7577 if (p->texture_reflection)
7578 R_FreeTexture(p->texture_reflection);
7579 p->texture_reflection = NULL;
7580 if (p->texture_camera)
7581 R_FreeTexture(p->texture_camera);
7582 p->texture_camera = NULL;
7584 memset(&r_waterstate, 0, sizeof(r_waterstate));
7585 r_waterstate.texturewidth = texturewidth;
7586 r_waterstate.textureheight = textureheight;
7587 r_waterstate.camerawidth = camerawidth;
7588 r_waterstate.cameraheight = cameraheight;
7591 if (r_waterstate.texturewidth)
7593 r_waterstate.enabled = true;
7595 // when doing a reduced render (HDR) we want to use a smaller area
7596 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
7597 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
7599 // set up variables that will be used in shader setup
7600 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7601 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7602 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
7603 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
7606 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
7607 r_waterstate.numwaterplanes = 0;
7610 void R_Water_AddWaterPlane(msurface_t *surface)
7612 int triangleindex, planeindex;
7619 r_waterstate_waterplane_t *p;
7620 texture_t *t = R_GetCurrentTexture(surface->texture);
7621 cam_ent = t->camera_entity;
7622 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
7625 // just use the first triangle with a valid normal for any decisions
7626 VectorClear(normal);
7627 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7629 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
7630 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
7631 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
7632 TriangleNormal(vert[0], vert[1], vert[2], normal);
7633 if (VectorLength2(normal) >= 0.001)
7637 VectorCopy(normal, plane.normal);
7638 VectorNormalize(plane.normal);
7639 plane.dist = DotProduct(vert[0], plane.normal);
7640 PlaneClassify(&plane);
7641 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
7643 // skip backfaces (except if nocullface is set)
7644 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
7646 VectorNegate(plane.normal, plane.normal);
7648 PlaneClassify(&plane);
7652 // find a matching plane if there is one
7653 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7654 if(p->camera_entity == t->camera_entity)
7655 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
7657 if (planeindex >= r_waterstate.maxwaterplanes)
7658 return; // nothing we can do, out of planes
7660 // if this triangle does not fit any known plane rendered this frame, add one
7661 if (planeindex >= r_waterstate.numwaterplanes)
7663 // store the new plane
7664 r_waterstate.numwaterplanes++;
7666 // clear materialflags and pvs
7667 p->materialflags = 0;
7668 p->pvsvalid = false;
7669 p->camera_entity = t->camera_entity;
7671 // merge this surface's materialflags into the waterplane
7672 p->materialflags |= t->currentmaterialflags;
7673 if(!(p->materialflags & MATERIALFLAG_CAMERA))
7675 // merge this surface's PVS into the waterplane
7676 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
7677 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
7678 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
7680 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
7686 static void R_Water_ProcessPlanes(void)
7688 r_refdef_view_t originalview;
7689 r_refdef_view_t myview;
7691 r_waterstate_waterplane_t *p;
7694 originalview = r_refdef.view;
7696 // make sure enough textures are allocated
7697 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7699 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7701 if (!p->texture_refraction)
7702 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7703 if (!p->texture_refraction)
7706 else if (p->materialflags & MATERIALFLAG_CAMERA)
7708 if (!p->texture_camera)
7709 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR, -1, NULL);
7710 if (!p->texture_camera)
7714 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7716 if (!p->texture_reflection)
7717 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7718 if (!p->texture_reflection)
7724 r_refdef.view = originalview;
7725 r_refdef.view.showdebug = false;
7726 r_refdef.view.width = r_waterstate.waterwidth;
7727 r_refdef.view.height = r_waterstate.waterheight;
7728 r_refdef.view.useclipplane = true;
7729 myview = r_refdef.view;
7730 r_waterstate.renderingscene = true;
7731 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
7733 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
7735 r_refdef.view = myview;
7736 // render reflected scene and copy into texture
7737 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
7738 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
7739 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
7740 r_refdef.view.clipplane = p->plane;
7741 // reverse the cullface settings for this render
7742 r_refdef.view.cullface_front = GL_FRONT;
7743 r_refdef.view.cullface_back = GL_BACK;
7744 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
7746 r_refdef.view.usecustompvs = true;
7748 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7750 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
7753 R_ResetViewRendering3D();
7754 R_ClearScreen(r_refdef.fogenabled);
7758 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);
7761 // render the normal view scene and copy into texture
7762 // (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)
7763 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
7765 r_waterstate.renderingrefraction = true;
7766 r_refdef.view = myview;
7768 r_refdef.view.clipplane = p->plane;
7769 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7770 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7772 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
7774 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7775 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
7776 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7777 R_RenderView_UpdateViewVectors();
7778 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7780 r_refdef.view.usecustompvs = true;
7781 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);
7785 PlaneClassify(&r_refdef.view.clipplane);
7787 R_ResetViewRendering3D();
7788 R_ClearScreen(r_refdef.fogenabled);
7792 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);
7793 r_waterstate.renderingrefraction = false;
7795 else if (p->materialflags & MATERIALFLAG_CAMERA)
7797 r_refdef.view = myview;
7799 r_refdef.view.clipplane = p->plane;
7800 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
7801 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
7803 r_refdef.view.width = r_waterstate.camerawidth;
7804 r_refdef.view.height = r_waterstate.cameraheight;
7805 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
7806 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
7808 if(p->camera_entity)
7810 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
7811 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
7814 // reverse the cullface settings for this render
7815 r_refdef.view.cullface_front = GL_FRONT;
7816 r_refdef.view.cullface_back = GL_BACK;
7817 // also reverse the view matrix
7818 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
7819 R_RenderView_UpdateViewVectors();
7820 if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
7822 r_refdef.view.usecustompvs = true;
7823 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);
7826 // camera needs no clipplane
7827 r_refdef.view.useclipplane = false;
7829 PlaneClassify(&r_refdef.view.clipplane);
7831 R_ResetViewRendering3D();
7832 R_ClearScreen(r_refdef.fogenabled);
7836 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);
7837 r_waterstate.renderingrefraction = false;
7841 r_waterstate.renderingscene = false;
7842 r_refdef.view = originalview;
7843 R_ResetViewRendering3D();
7844 R_ClearScreen(r_refdef.fogenabled);
7848 r_refdef.view = originalview;
7849 r_waterstate.renderingscene = false;
7850 Cvar_SetValueQuick(&r_water, 0);
7851 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
7855 void R_Bloom_StartFrame(void)
7857 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
7859 switch(vid.renderpath)
7861 case RENDERPATH_GL20:
7862 case RENDERPATH_CGGL:
7864 case RENDERPATH_GL13:
7865 case RENDERPATH_GL11:
7869 // set bloomwidth and bloomheight to the bloom resolution that will be
7870 // used (often less than the screen resolution for faster rendering)
7871 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
7872 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
7873 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
7874 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
7875 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
7877 // calculate desired texture sizes
7878 if (vid.support.arb_texture_non_power_of_two)
7880 screentexturewidth = r_refdef.view.width;
7881 screentextureheight = r_refdef.view.height;
7882 bloomtexturewidth = r_bloomstate.bloomwidth;
7883 bloomtextureheight = r_bloomstate.bloomheight;
7887 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
7888 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
7889 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
7890 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
7893 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))
7895 Cvar_SetValueQuick(&r_hdr, 0);
7896 Cvar_SetValueQuick(&r_bloom, 0);
7897 Cvar_SetValueQuick(&r_motionblur, 0);
7898 Cvar_SetValueQuick(&r_damageblur, 0);
7901 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)))
7902 screentexturewidth = screentextureheight = 0;
7903 if (!r_hdr.integer && !r_bloom.integer)
7904 bloomtexturewidth = bloomtextureheight = 0;
7906 // allocate textures as needed
7907 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
7909 if (r_bloomstate.texture_screen)
7910 R_FreeTexture(r_bloomstate.texture_screen);
7911 r_bloomstate.texture_screen = NULL;
7912 r_bloomstate.screentexturewidth = screentexturewidth;
7913 r_bloomstate.screentextureheight = screentextureheight;
7914 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
7915 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
7917 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
7919 if (r_bloomstate.texture_bloom)
7920 R_FreeTexture(r_bloomstate.texture_bloom);
7921 r_bloomstate.texture_bloom = NULL;
7922 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
7923 r_bloomstate.bloomtextureheight = bloomtextureheight;
7924 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
7925 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
7928 // when doing a reduced render (HDR) we want to use a smaller area
7929 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
7930 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
7931 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
7932 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
7933 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
7935 // set up a texcoord array for the full resolution screen image
7936 // (we have to keep this around to copy back during final render)
7937 r_bloomstate.screentexcoord2f[0] = 0;
7938 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7939 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7940 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
7941 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
7942 r_bloomstate.screentexcoord2f[5] = 0;
7943 r_bloomstate.screentexcoord2f[6] = 0;
7944 r_bloomstate.screentexcoord2f[7] = 0;
7946 // set up a texcoord array for the reduced resolution bloom image
7947 // (which will be additive blended over the screen image)
7948 r_bloomstate.bloomtexcoord2f[0] = 0;
7949 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7950 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7951 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
7952 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
7953 r_bloomstate.bloomtexcoord2f[5] = 0;
7954 r_bloomstate.bloomtexcoord2f[6] = 0;
7955 r_bloomstate.bloomtexcoord2f[7] = 0;
7957 if (r_hdr.integer || r_bloom.integer)
7959 r_bloomstate.enabled = true;
7960 r_bloomstate.hdr = r_hdr.integer != 0;
7963 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);
7966 void R_Bloom_CopyBloomTexture(float colorscale)
7968 r_refdef.stats.bloom++;
7970 // scale down screen texture to the bloom texture size
7972 R_SetViewport(&r_bloomstate.viewport);
7973 GL_BlendFunc(GL_ONE, GL_ZERO);
7974 GL_Color(colorscale, colorscale, colorscale, 1);
7975 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
7976 // TODO: do boxfilter scale-down in shader?
7977 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
7978 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
7979 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
7981 // we now have a bloom image in the framebuffer
7982 // copy it into the bloom image texture for later processing
7983 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);
7984 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
7987 void R_Bloom_CopyHDRTexture(void)
7989 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);
7990 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
7993 void R_Bloom_MakeTexture(void)
7996 float xoffset, yoffset, r, brighten;
7998 r_refdef.stats.bloom++;
8000 R_ResetViewRendering2D();
8002 // we have a bloom image in the framebuffer
8004 R_SetViewport(&r_bloomstate.viewport);
8006 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8009 r = bound(0, r_bloom_colorexponent.value / x, 1);
8010 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8012 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8013 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8014 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8015 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8017 // copy the vertically blurred bloom view to a texture
8018 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);
8019 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8022 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8023 brighten = r_bloom_brighten.value;
8025 brighten *= r_hdr_range.value;
8026 brighten = sqrt(brighten);
8028 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8029 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8031 for (dir = 0;dir < 2;dir++)
8033 // blend on at multiple vertical offsets to achieve a vertical blur
8034 // TODO: do offset blends using GLSL
8035 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8036 GL_BlendFunc(GL_ONE, GL_ZERO);
8037 for (x = -range;x <= range;x++)
8039 if (!dir){xoffset = 0;yoffset = x;}
8040 else {xoffset = x;yoffset = 0;}
8041 xoffset /= (float)r_bloomstate.bloomtexturewidth;
8042 yoffset /= (float)r_bloomstate.bloomtextureheight;
8043 // compute a texcoord array with the specified x and y offset
8044 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8045 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8046 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8047 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8048 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8049 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8050 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8051 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8052 // this r value looks like a 'dot' particle, fading sharply to
8053 // black at the edges
8054 // (probably not realistic but looks good enough)
8055 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8056 //r = brighten/(range*2+1);
8057 r = brighten / (range * 2 + 1);
8059 r *= (1 - x*x/(float)(range*range));
8060 GL_Color(r, r, r, 1);
8061 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8062 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8063 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8064 GL_BlendFunc(GL_ONE, GL_ONE);
8067 // copy the vertically blurred bloom view to a texture
8068 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);
8069 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8072 // apply subtract last
8073 // (just like it would be in a GLSL shader)
8074 if (r_bloom_colorsubtract.value > 0 && vid.support.ext_blend_subtract)
8076 GL_BlendFunc(GL_ONE, GL_ZERO);
8078 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8079 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8080 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8081 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8083 GL_BlendFunc(GL_ONE, GL_ONE);
8084 qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT);
8085 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8086 GL_Color(r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 1);
8087 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8088 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8089 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8090 qglBlendEquationEXT(GL_FUNC_ADD_EXT);
8092 // copy the darkened bloom view to a texture
8093 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);
8094 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8098 void R_HDR_RenderBloomTexture(void)
8100 int oldwidth, oldheight;
8101 float oldcolorscale;
8103 oldcolorscale = r_refdef.view.colorscale;
8104 oldwidth = r_refdef.view.width;
8105 oldheight = r_refdef.view.height;
8106 r_refdef.view.width = r_bloomstate.bloomwidth;
8107 r_refdef.view.height = r_bloomstate.bloomheight;
8109 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
8110 // TODO: add exposure compensation features
8111 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8113 r_refdef.view.showdebug = false;
8114 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8116 R_ResetViewRendering3D();
8118 R_ClearScreen(r_refdef.fogenabled);
8119 if (r_timereport_active)
8120 R_TimeReport("HDRclear");
8123 if (r_timereport_active)
8124 R_TimeReport("visibility");
8126 // only do secondary renders with HDR if r_hdr is 2 or higher
8127 r_waterstate.numwaterplanes = 0;
8128 if (r_waterstate.enabled && r_hdr.integer >= 2)
8129 R_RenderWaterPlanes();
8131 r_refdef.view.showdebug = true;
8133 r_waterstate.numwaterplanes = 0;
8135 R_ResetViewRendering2D();
8137 R_Bloom_CopyHDRTexture();
8138 R_Bloom_MakeTexture();
8140 // restore the view settings
8141 r_refdef.view.width = oldwidth;
8142 r_refdef.view.height = oldheight;
8143 r_refdef.view.colorscale = oldcolorscale;
8145 R_ResetViewRendering3D();
8147 R_ClearScreen(r_refdef.fogenabled);
8148 if (r_timereport_active)
8149 R_TimeReport("viewclear");
8152 static void R_BlendView(void)
8154 unsigned int permutation;
8155 float uservecs[4][4];
8157 switch (vid.renderpath)
8159 case RENDERPATH_GL20:
8160 case RENDERPATH_CGGL:
8162 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8163 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8164 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8165 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8166 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8168 if (r_bloomstate.texture_screen)
8170 // make sure the buffer is available
8171 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8173 R_ResetViewRendering2D();
8175 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8177 // declare variables
8179 static float avgspeed;
8181 speed = VectorLength(cl.movement_velocity);
8183 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8184 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8186 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8187 speed = bound(0, speed, 1);
8188 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8190 // calculate values into a standard alpha
8191 cl.motionbluralpha = 1 - exp(-
8193 (r_motionblur.value * speed / 80)
8195 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8198 max(0.0001, cl.time - cl.oldtime) // fps independent
8201 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8202 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8204 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8206 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8207 GL_Color(1, 1, 1, cl.motionbluralpha);
8208 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8209 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8210 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8211 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8215 // copy view into the screen texture
8216 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);
8217 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8219 else if (!r_bloomstate.texture_bloom)
8221 // we may still have to do view tint...
8222 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8224 // apply a color tint to the whole view
8225 R_ResetViewRendering2D();
8226 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8227 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8228 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8229 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8230 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8232 break; // no screen processing, no bloom, skip it
8235 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8237 // render simple bloom effect
8238 // copy the screen and shrink it and darken it for the bloom process
8239 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8240 // make the bloom texture
8241 R_Bloom_MakeTexture();
8244 #if _MSC_VER >= 1400
8245 #define sscanf sscanf_s
8247 memset(uservecs, 0, sizeof(uservecs));
8248 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8249 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8250 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8251 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8253 R_ResetViewRendering2D();
8254 GL_Color(1, 1, 1, 1);
8255 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8256 GL_BlendFunc(GL_ONE, GL_ZERO);
8258 switch(vid.renderpath)
8260 case RENDERPATH_GL20:
8261 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8262 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8263 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8264 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8265 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]);
8266 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8267 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]);
8268 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]);
8269 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]);
8270 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]);
8271 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8272 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8274 case RENDERPATH_CGGL:
8276 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
8277 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
8278 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
8279 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
8280 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
8281 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
8282 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
8283 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
8284 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
8285 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
8286 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
8287 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
8293 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8294 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8296 case RENDERPATH_GL13:
8297 case RENDERPATH_GL11:
8298 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8300 // apply a color tint to the whole view
8301 R_ResetViewRendering2D();
8302 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8303 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8304 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8305 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8306 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8312 matrix4x4_t r_waterscrollmatrix;
8314 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
8316 if (r_refdef.fog_density)
8318 r_refdef.fogcolor[0] = r_refdef.fog_red;
8319 r_refdef.fogcolor[1] = r_refdef.fog_green;
8320 r_refdef.fogcolor[2] = r_refdef.fog_blue;
8322 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
8323 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
8324 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
8325 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
8329 VectorCopy(r_refdef.fogcolor, fogvec);
8330 // color.rgb *= ContrastBoost * SceneBrightness;
8331 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
8332 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
8333 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
8334 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
8339 void R_UpdateVariables(void)
8343 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
8345 r_refdef.farclip = r_farclip_base.value;
8346 if (r_refdef.scene.worldmodel)
8347 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
8348 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
8350 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
8351 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
8352 r_refdef.polygonfactor = 0;
8353 r_refdef.polygonoffset = 0;
8354 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8355 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
8357 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
8358 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
8359 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
8360 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
8361 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
8362 if (r_showsurfaces.integer)
8364 r_refdef.scene.rtworld = false;
8365 r_refdef.scene.rtworldshadows = false;
8366 r_refdef.scene.rtdlight = false;
8367 r_refdef.scene.rtdlightshadows = false;
8368 r_refdef.lightmapintensity = 0;
8371 if (gamemode == GAME_NEHAHRA)
8373 if (gl_fogenable.integer)
8375 r_refdef.oldgl_fogenable = true;
8376 r_refdef.fog_density = gl_fogdensity.value;
8377 r_refdef.fog_red = gl_fogred.value;
8378 r_refdef.fog_green = gl_foggreen.value;
8379 r_refdef.fog_blue = gl_fogblue.value;
8380 r_refdef.fog_alpha = 1;
8381 r_refdef.fog_start = 0;
8382 r_refdef.fog_end = gl_skyclip.value;
8383 r_refdef.fog_height = 1<<30;
8384 r_refdef.fog_fadedepth = 128;
8386 else if (r_refdef.oldgl_fogenable)
8388 r_refdef.oldgl_fogenable = false;
8389 r_refdef.fog_density = 0;
8390 r_refdef.fog_red = 0;
8391 r_refdef.fog_green = 0;
8392 r_refdef.fog_blue = 0;
8393 r_refdef.fog_alpha = 0;
8394 r_refdef.fog_start = 0;
8395 r_refdef.fog_end = 0;
8396 r_refdef.fog_height = 1<<30;
8397 r_refdef.fog_fadedepth = 128;
8401 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
8402 r_refdef.fog_start = max(0, r_refdef.fog_start);
8403 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
8405 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
8407 if (r_refdef.fog_density && r_drawfog.integer)
8409 r_refdef.fogenabled = true;
8410 // this is the point where the fog reaches 0.9986 alpha, which we
8411 // consider a good enough cutoff point for the texture
8412 // (0.9986 * 256 == 255.6)
8413 if (r_fog_exp2.integer)
8414 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
8416 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
8417 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
8418 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
8419 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
8420 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
8421 R_BuildFogHeightTexture();
8422 // fog color was already set
8423 // update the fog texture
8424 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)
8425 R_BuildFogTexture();
8426 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
8427 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
8430 r_refdef.fogenabled = false;
8432 switch(vid.renderpath)
8434 case RENDERPATH_GL20:
8435 case RENDERPATH_CGGL:
8436 if(v_glslgamma.integer && !vid_gammatables_trivial)
8438 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
8440 // build GLSL gamma texture
8441 #define RAMPWIDTH 256
8442 unsigned short ramp[RAMPWIDTH * 3];
8443 unsigned char rampbgr[RAMPWIDTH][4];
8446 r_texture_gammaramps_serial = vid_gammatables_serial;
8448 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
8449 for(i = 0; i < RAMPWIDTH; ++i)
8451 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8452 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
8453 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
8456 if (r_texture_gammaramps)
8458 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
8462 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
8468 // remove GLSL gamma texture
8471 case RENDERPATH_GL13:
8472 case RENDERPATH_GL11:
8477 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
8478 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
8484 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
8485 if( scenetype != r_currentscenetype ) {
8486 // store the old scenetype
8487 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
8488 r_currentscenetype = scenetype;
8489 // move in the new scene
8490 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
8499 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
8501 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
8502 if( scenetype == r_currentscenetype ) {
8503 return &r_refdef.scene;
8505 return &r_scenes_store[ scenetype ];
8514 void R_RenderView(void)
8516 if (r_timereport_active)
8517 R_TimeReport("start");
8518 r_textureframe++; // used only by R_GetCurrentTexture
8519 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
8521 if (!r_drawentities.integer)
8522 r_refdef.scene.numentities = 0;
8524 R_AnimCache_ClearCache();
8525 R_FrameData_NewFrame();
8527 if (r_refdef.view.isoverlay)
8529 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
8530 GL_Clear( GL_DEPTH_BUFFER_BIT );
8531 R_TimeReport("depthclear");
8533 r_refdef.view.showdebug = false;
8535 r_waterstate.enabled = false;
8536 r_waterstate.numwaterplanes = 0;
8544 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
8545 return; //Host_Error ("R_RenderView: NULL worldmodel");
8547 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
8549 R_RenderView_UpdateViewVectors();
8551 R_Shadow_UpdateWorldLightSelection();
8553 R_Bloom_StartFrame();
8554 R_Water_StartFrame();
8557 if (r_timereport_active)
8558 R_TimeReport("viewsetup");
8560 R_ResetViewRendering3D();
8562 if (r_refdef.view.clear || r_refdef.fogenabled)
8564 R_ClearScreen(r_refdef.fogenabled);
8565 if (r_timereport_active)
8566 R_TimeReport("viewclear");
8568 r_refdef.view.clear = true;
8570 // this produces a bloom texture to be used in R_BlendView() later
8571 if (r_hdr.integer && r_bloomstate.bloomwidth)
8573 R_HDR_RenderBloomTexture();
8574 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
8575 r_textureframe++; // used only by R_GetCurrentTexture
8578 r_refdef.view.showdebug = true;
8581 if (r_timereport_active)
8582 R_TimeReport("visibility");
8584 r_waterstate.numwaterplanes = 0;
8585 if (r_waterstate.enabled)
8586 R_RenderWaterPlanes();
8589 r_waterstate.numwaterplanes = 0;
8592 if (r_timereport_active)
8593 R_TimeReport("blendview");
8595 GL_Scissor(0, 0, vid.width, vid.height);
8596 GL_ScissorTest(false);
8600 void R_RenderWaterPlanes(void)
8602 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
8604 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
8605 if (r_timereport_active)
8606 R_TimeReport("waterworld");
8609 // don't let sound skip if going slow
8610 if (r_refdef.scene.extraupdate)
8613 R_DrawModelsAddWaterPlanes();
8614 if (r_timereport_active)
8615 R_TimeReport("watermodels");
8617 if (r_waterstate.numwaterplanes)
8619 R_Water_ProcessPlanes();
8620 if (r_timereport_active)
8621 R_TimeReport("waterscenes");
8625 extern void R_DrawLightningBeams (void);
8626 extern void VM_CL_AddPolygonsToMeshQueue (void);
8627 extern void R_DrawPortals (void);
8628 extern cvar_t cl_locs_show;
8629 static void R_DrawLocs(void);
8630 static void R_DrawEntityBBoxes(void);
8631 static void R_DrawModelDecals(void);
8632 extern void R_DrawModelShadows(void);
8633 extern void R_DrawModelShadowMaps(void);
8634 extern cvar_t cl_decals_newsystem;
8635 extern qboolean r_shadow_usingdeferredprepass;
8636 void R_RenderScene(void)
8638 qboolean shadowmapping = false;
8640 if (r_timereport_active)
8641 R_TimeReport("beginscene");
8643 r_refdef.stats.renders++;
8647 // don't let sound skip if going slow
8648 if (r_refdef.scene.extraupdate)
8651 R_MeshQueue_BeginScene();
8655 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);
8657 if (r_timereport_active)
8658 R_TimeReport("skystartframe");
8660 if (cl.csqc_vidvars.drawworld)
8662 // don't let sound skip if going slow
8663 if (r_refdef.scene.extraupdate)
8666 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
8668 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
8669 if (r_timereport_active)
8670 R_TimeReport("worldsky");
8673 if (R_DrawBrushModelsSky() && r_timereport_active)
8674 R_TimeReport("bmodelsky");
8676 if (skyrendermasked && skyrenderlater)
8678 // we have to force off the water clipping plane while rendering sky
8682 if (r_timereport_active)
8683 R_TimeReport("sky");
8687 R_AnimCache_CacheVisibleEntities();
8688 if (r_timereport_active)
8689 R_TimeReport("animation");
8691 R_Shadow_PrepareLights();
8692 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
8693 R_Shadow_PrepareModelShadows();
8694 if (r_timereport_active)
8695 R_TimeReport("preparelights");
8697 if (R_Shadow_ShadowMappingEnabled())
8698 shadowmapping = true;
8700 if (r_shadow_usingdeferredprepass)
8701 R_Shadow_DrawPrepass();
8703 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
8705 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
8706 if (r_timereport_active)
8707 R_TimeReport("worlddepth");
8709 if (r_depthfirst.integer >= 2)
8711 R_DrawModelsDepth();
8712 if (r_timereport_active)
8713 R_TimeReport("modeldepth");
8716 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
8718 R_DrawModelShadowMaps();
8719 R_ResetViewRendering3D();
8720 // don't let sound skip if going slow
8721 if (r_refdef.scene.extraupdate)
8725 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
8727 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
8728 if (r_timereport_active)
8729 R_TimeReport("world");
8732 // don't let sound skip if going slow
8733 if (r_refdef.scene.extraupdate)
8737 if (r_timereport_active)
8738 R_TimeReport("models");
8740 // don't let sound skip if going slow
8741 if (r_refdef.scene.extraupdate)
8744 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8746 R_DrawModelShadows();
8747 R_ResetViewRendering3D();
8748 // don't let sound skip if going slow
8749 if (r_refdef.scene.extraupdate)
8753 if (!r_shadow_usingdeferredprepass)
8755 R_Shadow_DrawLights();
8756 if (r_timereport_active)
8757 R_TimeReport("rtlights");
8760 // don't let sound skip if going slow
8761 if (r_refdef.scene.extraupdate)
8764 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
8766 R_DrawModelShadows();
8767 R_ResetViewRendering3D();
8768 // don't let sound skip if going slow
8769 if (r_refdef.scene.extraupdate)
8773 if (cl.csqc_vidvars.drawworld)
8775 if (cl_decals_newsystem.integer)
8777 R_DrawModelDecals();
8778 if (r_timereport_active)
8779 R_TimeReport("modeldecals");
8784 if (r_timereport_active)
8785 R_TimeReport("decals");
8789 if (r_timereport_active)
8790 R_TimeReport("particles");
8793 if (r_timereport_active)
8794 R_TimeReport("explosions");
8796 R_DrawLightningBeams();
8797 if (r_timereport_active)
8798 R_TimeReport("lightning");
8801 VM_CL_AddPolygonsToMeshQueue();
8803 if (r_refdef.view.showdebug)
8805 if (cl_locs_show.integer)
8808 if (r_timereport_active)
8809 R_TimeReport("showlocs");
8812 if (r_drawportals.integer)
8815 if (r_timereport_active)
8816 R_TimeReport("portals");
8819 if (r_showbboxes.value > 0)
8821 R_DrawEntityBBoxes();
8822 if (r_timereport_active)
8823 R_TimeReport("bboxes");
8827 R_MeshQueue_RenderTransparent();
8828 if (r_timereport_active)
8829 R_TimeReport("drawtrans");
8831 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))
8833 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
8834 if (r_timereport_active)
8835 R_TimeReport("worlddebug");
8836 R_DrawModelsDebug();
8837 if (r_timereport_active)
8838 R_TimeReport("modeldebug");
8841 if (cl.csqc_vidvars.drawworld)
8843 R_Shadow_DrawCoronas();
8844 if (r_timereport_active)
8845 R_TimeReport("coronas");
8848 // don't let sound skip if going slow
8849 if (r_refdef.scene.extraupdate)
8852 R_ResetViewRendering2D();
8855 static const unsigned short bboxelements[36] =
8865 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
8868 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
8870 RSurf_ActiveWorldEntity();
8872 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8873 GL_DepthMask(false);
8874 GL_DepthRange(0, 1);
8875 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8876 R_Mesh_ResetTextureState();
8878 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
8879 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
8880 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
8881 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
8882 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
8883 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
8884 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
8885 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
8886 R_FillColors(color4f, 8, cr, cg, cb, ca);
8887 if (r_refdef.fogenabled)
8889 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
8891 f1 = RSurf_FogVertex(v);
8893 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
8894 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
8895 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
8898 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
8899 R_Mesh_ResetTextureState();
8900 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8901 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
8904 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
8908 prvm_edict_t *edict;
8909 prvm_prog_t *prog_save = prog;
8911 // this function draws bounding boxes of server entities
8915 GL_CullFace(GL_NONE);
8916 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8920 for (i = 0;i < numsurfaces;i++)
8922 edict = PRVM_EDICT_NUM(surfacelist[i]);
8923 switch ((int)edict->fields.server->solid)
8925 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
8926 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
8927 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
8928 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
8929 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
8930 default: Vector4Set(color, 0, 0, 0, 0.50);break;
8932 color[3] *= r_showbboxes.value;
8933 color[3] = bound(0, color[3], 1);
8934 GL_DepthTest(!r_showdisabledepthtest.integer);
8935 GL_CullFace(r_refdef.view.cullface_front);
8936 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
8942 static void R_DrawEntityBBoxes(void)
8945 prvm_edict_t *edict;
8947 prvm_prog_t *prog_save = prog;
8949 // this function draws bounding boxes of server entities
8955 for (i = 0;i < prog->num_edicts;i++)
8957 edict = PRVM_EDICT_NUM(i);
8958 if (edict->priv.server->free)
8960 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
8961 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
8963 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
8965 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
8966 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
8972 static const int nomodelelement3i[24] =
8984 static const unsigned short nomodelelement3s[24] =
8996 static const float nomodelvertex3f[6*3] =
9006 static const float nomodelcolor4f[6*4] =
9008 0.0f, 0.0f, 0.5f, 1.0f,
9009 0.0f, 0.0f, 0.5f, 1.0f,
9010 0.0f, 0.5f, 0.0f, 1.0f,
9011 0.0f, 0.5f, 0.0f, 1.0f,
9012 0.5f, 0.0f, 0.0f, 1.0f,
9013 0.5f, 0.0f, 0.0f, 1.0f
9016 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9022 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);
9024 // this is only called once per entity so numsurfaces is always 1, and
9025 // surfacelist is always {0}, so this code does not handle batches
9027 if (rsurface.ent_flags & RENDER_ADDITIVE)
9029 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9030 GL_DepthMask(false);
9032 else if (rsurface.colormod[3] < 1)
9034 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9035 GL_DepthMask(false);
9039 GL_BlendFunc(GL_ONE, GL_ZERO);
9042 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9043 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9044 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9045 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9046 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9047 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9048 for (i = 0, c = color4f;i < 6;i++, c += 4)
9050 c[0] *= rsurface.colormod[0];
9051 c[1] *= rsurface.colormod[1];
9052 c[2] *= rsurface.colormod[2];
9053 c[3] *= rsurface.colormod[3];
9055 if (r_refdef.fogenabled)
9057 for (i = 0, c = color4f;i < 6;i++, c += 4)
9059 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9061 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9062 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9063 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9066 R_Mesh_ResetTextureState();
9067 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9068 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9071 void R_DrawNoModel(entity_render_t *ent)
9074 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9075 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9076 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9078 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9081 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9083 vec3_t right1, right2, diff, normal;
9085 VectorSubtract (org2, org1, normal);
9087 // calculate 'right' vector for start
9088 VectorSubtract (r_refdef.view.origin, org1, diff);
9089 CrossProduct (normal, diff, right1);
9090 VectorNormalize (right1);
9092 // calculate 'right' vector for end
9093 VectorSubtract (r_refdef.view.origin, org2, diff);
9094 CrossProduct (normal, diff, right2);
9095 VectorNormalize (right2);
9097 vert[ 0] = org1[0] + width * right1[0];
9098 vert[ 1] = org1[1] + width * right1[1];
9099 vert[ 2] = org1[2] + width * right1[2];
9100 vert[ 3] = org1[0] - width * right1[0];
9101 vert[ 4] = org1[1] - width * right1[1];
9102 vert[ 5] = org1[2] - width * right1[2];
9103 vert[ 6] = org2[0] - width * right2[0];
9104 vert[ 7] = org2[1] - width * right2[1];
9105 vert[ 8] = org2[2] - width * right2[2];
9106 vert[ 9] = org2[0] + width * right2[0];
9107 vert[10] = org2[1] + width * right2[1];
9108 vert[11] = org2[2] + width * right2[2];
9111 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)
9113 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9114 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9115 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9116 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9117 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9118 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9119 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9120 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9121 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9122 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9123 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9124 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9127 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9132 VectorSet(v, x, y, z);
9133 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9134 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9136 if (i == mesh->numvertices)
9138 if (mesh->numvertices < mesh->maxvertices)
9140 VectorCopy(v, vertex3f);
9141 mesh->numvertices++;
9143 return mesh->numvertices;
9149 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9153 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9154 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9155 e = mesh->element3i + mesh->numtriangles * 3;
9156 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9158 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9159 if (mesh->numtriangles < mesh->maxtriangles)
9164 mesh->numtriangles++;
9166 element[1] = element[2];
9170 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9174 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9175 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9176 e = mesh->element3i + mesh->numtriangles * 3;
9177 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9179 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9180 if (mesh->numtriangles < mesh->maxtriangles)
9185 mesh->numtriangles++;
9187 element[1] = element[2];
9191 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9192 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9194 int planenum, planenum2;
9197 mplane_t *plane, *plane2;
9199 double temppoints[2][256*3];
9200 // figure out how large a bounding box we need to properly compute this brush
9202 for (w = 0;w < numplanes;w++)
9203 maxdist = max(maxdist, fabs(planes[w].dist));
9204 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9205 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9206 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9210 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9211 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9213 if (planenum2 == planenum)
9215 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);
9218 if (tempnumpoints < 3)
9220 // generate elements forming a triangle fan for this polygon
9221 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9225 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)
9227 texturelayer_t *layer;
9228 layer = t->currentlayers + t->currentnumlayers++;
9230 layer->depthmask = depthmask;
9231 layer->blendfunc1 = blendfunc1;
9232 layer->blendfunc2 = blendfunc2;
9233 layer->texture = texture;
9234 layer->texmatrix = *matrix;
9235 layer->color[0] = r;
9236 layer->color[1] = g;
9237 layer->color[2] = b;
9238 layer->color[3] = a;
9241 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
9243 if(parms[0] == 0 && parms[1] == 0)
9245 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9246 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
9251 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
9254 index = parms[2] + r_refdef.scene.time * parms[3];
9255 index -= floor(index);
9256 switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
9259 case Q3WAVEFUNC_NONE:
9260 case Q3WAVEFUNC_NOISE:
9261 case Q3WAVEFUNC_COUNT:
9264 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
9265 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
9266 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
9267 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
9268 case Q3WAVEFUNC_TRIANGLE:
9270 f = index - floor(index);
9281 f = parms[0] + parms[1] * f;
9282 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
9283 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
9287 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
9292 matrix4x4_t matrix, temp;
9293 switch(tcmod->tcmod)
9297 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9298 matrix = r_waterscrollmatrix;
9300 matrix = identitymatrix;
9302 case Q3TCMOD_ENTITYTRANSLATE:
9303 // this is used in Q3 to allow the gamecode to control texcoord
9304 // scrolling on the entity, which is not supported in darkplaces yet.
9305 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
9307 case Q3TCMOD_ROTATE:
9308 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
9309 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
9310 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
9313 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
9315 case Q3TCMOD_SCROLL:
9316 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
9318 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
9319 w = (int) tcmod->parms[0];
9320 h = (int) tcmod->parms[1];
9321 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
9323 idx = (int) floor(f * w * h);
9324 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
9326 case Q3TCMOD_STRETCH:
9327 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
9328 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
9330 case Q3TCMOD_TRANSFORM:
9331 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
9332 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
9333 VectorSet(tcmat + 6, 0 , 0 , 1);
9334 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
9335 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
9337 case Q3TCMOD_TURBULENT:
9338 // this is handled in the RSurf_PrepareVertices function
9339 matrix = identitymatrix;
9343 Matrix4x4_Concat(texmatrix, &matrix, &temp);
9346 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
9348 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
9349 char name[MAX_QPATH];
9350 skinframe_t *skinframe;
9351 unsigned char pixels[296*194];
9352 strlcpy(cache->name, skinname, sizeof(cache->name));
9353 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
9354 if (developer_loading.integer)
9355 Con_Printf("loading %s\n", name);
9356 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
9357 if (!skinframe || !skinframe->base)
9360 fs_offset_t filesize;
9362 f = FS_LoadFile(name, tempmempool, true, &filesize);
9365 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
9366 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
9370 cache->skinframe = skinframe;
9373 texture_t *R_GetCurrentTexture(texture_t *t)
9376 const entity_render_t *ent = rsurface.entity;
9377 dp_model_t *model = ent->model;
9378 q3shaderinfo_layer_tcmod_t *tcmod;
9380 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
9381 return t->currentframe;
9382 t->update_lastrenderframe = r_textureframe;
9383 t->update_lastrenderentity = (void *)ent;
9385 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
9386 t->camera_entity = ent->entitynumber;
9388 t->camera_entity = 0;
9390 // switch to an alternate material if this is a q1bsp animated material
9392 texture_t *texture = t;
9393 int s = rsurface.ent_skinnum;
9394 if ((unsigned int)s >= (unsigned int)model->numskins)
9396 if (model->skinscenes)
9398 if (model->skinscenes[s].framecount > 1)
9399 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
9401 s = model->skinscenes[s].firstframe;
9404 t = t + s * model->num_surfaces;
9407 // use an alternate animation if the entity's frame is not 0,
9408 // and only if the texture has an alternate animation
9409 if (rsurface.ent_alttextures && t->anim_total[1])
9410 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
9412 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
9414 texture->currentframe = t;
9417 // update currentskinframe to be a qw skin or animation frame
9418 if (rsurface.ent_qwskin >= 0)
9420 i = rsurface.ent_qwskin;
9421 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
9423 r_qwskincache_size = cl.maxclients;
9425 Mem_Free(r_qwskincache);
9426 r_qwskincache = Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
9428 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
9429 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
9430 t->currentskinframe = r_qwskincache[i].skinframe;
9431 if (t->currentskinframe == NULL)
9432 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9434 else if (t->numskinframes >= 2)
9435 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
9436 if (t->backgroundnumskinframes >= 2)
9437 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
9439 t->currentmaterialflags = t->basematerialflags;
9440 t->currentalpha = rsurface.colormod[3];
9441 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
9442 t->currentalpha *= r_wateralpha.value;
9443 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
9444 t->currentalpha *= t->r_water_wateralpha;
9445 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
9446 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
9447 if (!(rsurface.ent_flags & RENDER_LIGHT))
9448 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
9449 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
9451 // pick a model lighting mode
9452 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
9453 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
9455 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
9457 if (rsurface.ent_flags & RENDER_ADDITIVE)
9458 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9459 else if (t->currentalpha < 1)
9460 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
9461 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
9462 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
9463 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
9464 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
9465 if (t->backgroundnumskinframes)
9466 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
9467 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
9469 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
9470 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
9473 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
9474 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
9475 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
9477 // there is no tcmod
9478 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
9480 t->currenttexmatrix = r_waterscrollmatrix;
9481 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
9483 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
9485 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
9486 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
9489 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9490 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
9491 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
9492 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
9494 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
9495 if (t->currentskinframe->qpixels)
9496 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
9497 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
9498 if (!t->basetexture)
9499 t->basetexture = r_texture_notexture;
9500 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
9501 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
9502 t->nmaptexture = t->currentskinframe->nmap;
9503 if (!t->nmaptexture)
9504 t->nmaptexture = r_texture_blanknormalmap;
9505 t->glosstexture = r_texture_black;
9506 t->glowtexture = t->currentskinframe->glow;
9507 t->fogtexture = t->currentskinframe->fog;
9508 t->reflectmasktexture = t->currentskinframe->reflect;
9509 if (t->backgroundnumskinframes)
9511 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
9512 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
9513 t->backgroundglosstexture = r_texture_black;
9514 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
9515 if (!t->backgroundnmaptexture)
9516 t->backgroundnmaptexture = r_texture_blanknormalmap;
9520 t->backgroundbasetexture = r_texture_white;
9521 t->backgroundnmaptexture = r_texture_blanknormalmap;
9522 t->backgroundglosstexture = r_texture_black;
9523 t->backgroundglowtexture = NULL;
9525 t->specularpower = r_shadow_glossexponent.value;
9526 // TODO: store reference values for these in the texture?
9527 t->specularscale = 0;
9528 if (r_shadow_gloss.integer > 0)
9530 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
9532 if (r_shadow_glossintensity.value > 0)
9534 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
9535 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
9536 t->specularscale = r_shadow_glossintensity.value;
9539 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
9541 t->glosstexture = r_texture_white;
9542 t->backgroundglosstexture = r_texture_white;
9543 t->specularscale = r_shadow_gloss2intensity.value;
9544 t->specularpower = r_shadow_gloss2exponent.value;
9547 t->specularscale *= t->specularscalemod;
9548 t->specularpower *= t->specularpowermod;
9550 // lightmaps mode looks bad with dlights using actual texturing, so turn
9551 // off the colormap and glossmap, but leave the normalmap on as it still
9552 // accurately represents the shading involved
9553 if (gl_lightmaps.integer)
9555 t->basetexture = r_texture_grey128;
9556 t->pantstexture = r_texture_black;
9557 t->shirttexture = r_texture_black;
9558 t->nmaptexture = r_texture_blanknormalmap;
9559 t->glosstexture = r_texture_black;
9560 t->glowtexture = NULL;
9561 t->fogtexture = NULL;
9562 t->reflectmasktexture = NULL;
9563 t->backgroundbasetexture = NULL;
9564 t->backgroundnmaptexture = r_texture_blanknormalmap;
9565 t->backgroundglosstexture = r_texture_black;
9566 t->backgroundglowtexture = NULL;
9567 t->specularscale = 0;
9568 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
9571 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
9572 VectorClear(t->dlightcolor);
9573 t->currentnumlayers = 0;
9574 if (t->currentmaterialflags & MATERIALFLAG_WALL)
9576 int blendfunc1, blendfunc2;
9578 if (t->currentmaterialflags & MATERIALFLAG_ADD)
9580 blendfunc1 = GL_SRC_ALPHA;
9581 blendfunc2 = GL_ONE;
9583 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
9585 blendfunc1 = GL_SRC_ALPHA;
9586 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
9588 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
9590 blendfunc1 = t->customblendfunc[0];
9591 blendfunc2 = t->customblendfunc[1];
9595 blendfunc1 = GL_ONE;
9596 blendfunc2 = GL_ZERO;
9598 // don't colormod evilblend textures
9599 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
9600 VectorSet(t->lightmapcolor, 1, 1, 1);
9601 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
9602 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
9604 // fullbright is not affected by r_refdef.lightmapintensity
9605 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]);
9606 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9607 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]);
9608 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9609 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]);
9613 vec3_t ambientcolor;
9615 // set the color tint used for lights affecting this surface
9616 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
9618 // q3bsp has no lightmap updates, so the lightstylevalue that
9619 // would normally be baked into the lightmap must be
9620 // applied to the color
9621 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
9622 if (model->type == mod_brushq3)
9623 colorscale *= r_refdef.scene.rtlightstylevalue[0];
9624 colorscale *= r_refdef.lightmapintensity;
9625 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
9626 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
9627 // basic lit geometry
9628 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]);
9629 // add pants/shirt if needed
9630 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9631 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]);
9632 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9633 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]);
9634 // now add ambient passes if needed
9635 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
9637 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]);
9638 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
9639 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]);
9640 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
9641 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]);
9644 if (t->glowtexture != NULL && !gl_lightmaps.integer)
9645 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]);
9646 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
9648 // if this is opaque use alpha blend which will darken the earlier
9651 // if this is an alpha blended material, all the earlier passes
9652 // were darkened by fog already, so we only need to add the fog
9653 // color ontop through the fog mask texture
9655 // if this is an additive blended material, all the earlier passes
9656 // were darkened by fog already, and we should not add fog color
9657 // (because the background was not darkened, there is no fog color
9658 // that was lost behind it).
9659 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]);
9663 return t->currentframe;
9666 rsurfacestate_t rsurface;
9668 void R_Mesh_ResizeArrays(int newvertices)
9670 unsigned char *base;
9672 if (rsurface.array_size >= newvertices)
9674 if (rsurface.array_base)
9675 Mem_Free(rsurface.array_base);
9676 rsurface.array_size = (newvertices + 1023) & ~1023;
9678 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9679 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9680 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9681 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9682 size += rsurface.array_size * sizeof(float[3]);
9683 size += rsurface.array_size * sizeof(float[3]);
9684 size += rsurface.array_size * sizeof(float[3]);
9685 size += rsurface.array_size * sizeof(float[3]);
9686 size += rsurface.array_size * sizeof(float[3]);
9687 size += rsurface.array_size * sizeof(float[3]);
9688 size += rsurface.array_size * sizeof(float[3]);
9689 size += rsurface.array_size * sizeof(float[3]);
9690 size += rsurface.array_size * sizeof(float[4]);
9691 size += rsurface.array_size * sizeof(float[2]);
9692 size += rsurface.array_size * sizeof(float[2]);
9693 size += rsurface.array_size * sizeof(float[4]);
9694 size += rsurface.array_size * sizeof(int[3]);
9695 size += rsurface.array_size * sizeof(unsigned short[3]);
9696 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
9697 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
9698 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
9699 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
9700 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
9701 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9702 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9703 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9704 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9705 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9706 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9707 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9708 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
9709 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9710 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9711 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
9712 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
9713 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
9714 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
9717 void RSurf_ActiveWorldEntity(void)
9719 dp_model_t *model = r_refdef.scene.worldmodel;
9720 //if (rsurface.entity == r_refdef.scene.worldentity)
9722 rsurface.entity = r_refdef.scene.worldentity;
9723 rsurface.skeleton = NULL;
9724 memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
9725 rsurface.ent_skinnum = 0;
9726 rsurface.ent_qwskin = -1;
9727 rsurface.ent_shadertime = 0;
9728 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
9729 if (rsurface.array_size < model->surfmesh.num_vertices)
9730 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9731 rsurface.matrix = identitymatrix;
9732 rsurface.inversematrix = identitymatrix;
9733 rsurface.matrixscale = 1;
9734 rsurface.inversematrixscale = 1;
9735 R_EntityMatrix(&identitymatrix);
9736 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
9737 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
9738 rsurface.fograngerecip = r_refdef.fograngerecip;
9739 rsurface.fogheightfade = r_refdef.fogheightfade;
9740 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
9741 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9742 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
9743 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
9744 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
9745 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
9746 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
9747 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
9748 rsurface.colormod[3] = 1;
9749 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);
9750 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
9751 rsurface.frameblend[0].lerp = 1;
9752 rsurface.ent_alttextures = false;
9753 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9754 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9755 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9756 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9757 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9758 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9759 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9760 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9761 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9762 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9763 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9764 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9765 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9766 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9767 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9768 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9769 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9770 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9771 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9772 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9773 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9774 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9775 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9776 rsurface.modelelement3i = model->surfmesh.data_element3i;
9777 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9778 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9779 rsurface.modelelement3s = model->surfmesh.data_element3s;
9780 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9781 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9782 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9783 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9784 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9785 rsurface.modelsurfaces = model->data_surfaces;
9786 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9787 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9788 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9789 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9790 rsurface.modelgeneratedvertex = false;
9791 rsurface.batchgeneratedvertex = false;
9792 rsurface.batchfirstvertex = 0;
9793 rsurface.batchnumvertices = 0;
9794 rsurface.batchfirsttriangle = 0;
9795 rsurface.batchnumtriangles = 0;
9796 rsurface.batchvertex3f = NULL;
9797 rsurface.batchvertex3f_vertexbuffer = NULL;
9798 rsurface.batchvertex3f_bufferoffset = 0;
9799 rsurface.batchsvector3f = NULL;
9800 rsurface.batchsvector3f_vertexbuffer = NULL;
9801 rsurface.batchsvector3f_bufferoffset = 0;
9802 rsurface.batchtvector3f = NULL;
9803 rsurface.batchtvector3f_vertexbuffer = NULL;
9804 rsurface.batchtvector3f_bufferoffset = 0;
9805 rsurface.batchnormal3f = NULL;
9806 rsurface.batchnormal3f_vertexbuffer = NULL;
9807 rsurface.batchnormal3f_bufferoffset = 0;
9808 rsurface.batchlightmapcolor4f = NULL;
9809 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9810 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9811 rsurface.batchtexcoordtexture2f = NULL;
9812 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9813 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9814 rsurface.batchtexcoordlightmap2f = NULL;
9815 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9816 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9817 rsurface.batchvertexmesh = NULL;
9818 rsurface.batchvertexmeshbuffer = NULL;
9819 rsurface.batchvertexposition = NULL;
9820 rsurface.batchvertexpositionbuffer = NULL;
9821 rsurface.batchelement3i = NULL;
9822 rsurface.batchelement3i_indexbuffer = NULL;
9823 rsurface.batchelement3i_bufferoffset = 0;
9824 rsurface.batchelement3s = NULL;
9825 rsurface.batchelement3s_indexbuffer = NULL;
9826 rsurface.batchelement3s_bufferoffset = 0;
9827 rsurface.passcolor4f = NULL;
9828 rsurface.passcolor4f_vertexbuffer = NULL;
9829 rsurface.passcolor4f_bufferoffset = 0;
9832 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
9834 dp_model_t *model = ent->model;
9835 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
9837 rsurface.entity = (entity_render_t *)ent;
9838 rsurface.skeleton = ent->skeleton;
9839 memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
9840 rsurface.ent_skinnum = ent->skinnum;
9841 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;
9842 rsurface.ent_shadertime = ent->shadertime;
9843 rsurface.ent_flags = ent->flags;
9844 if (rsurface.array_size < model->surfmesh.num_vertices)
9845 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
9846 rsurface.matrix = ent->matrix;
9847 rsurface.inversematrix = ent->inversematrix;
9848 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
9849 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
9850 R_EntityMatrix(&rsurface.matrix);
9851 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
9852 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
9853 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
9854 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
9855 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
9856 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
9857 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
9858 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
9859 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
9860 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
9861 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
9862 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
9863 rsurface.colormod[3] = ent->alpha;
9864 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
9865 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
9866 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
9867 rsurface.basepolygonfactor = r_refdef.polygonfactor;
9868 rsurface.basepolygonoffset = r_refdef.polygonoffset;
9869 if (ent->model->brush.submodel && !prepass)
9871 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
9872 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
9874 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
9876 if (ent->animcache_vertex3f && !r_framedata_failed)
9878 rsurface.modelvertex3f = ent->animcache_vertex3f;
9879 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
9880 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
9881 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
9882 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
9883 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
9884 rsurface.modelvertexposition = ent->animcache_vertexposition;
9885 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
9887 else if (wanttangents)
9889 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9890 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
9891 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
9892 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9893 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
9894 rsurface.modelvertexmesh = NULL;
9895 rsurface.modelvertexmeshbuffer = NULL;
9896 rsurface.modelvertexposition = NULL;
9897 rsurface.modelvertexpositionbuffer = NULL;
9899 else if (wantnormals)
9901 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9902 rsurface.modelsvector3f = NULL;
9903 rsurface.modeltvector3f = NULL;
9904 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
9905 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
9906 rsurface.modelvertexmesh = NULL;
9907 rsurface.modelvertexmeshbuffer = NULL;
9908 rsurface.modelvertexposition = NULL;
9909 rsurface.modelvertexpositionbuffer = NULL;
9913 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
9914 rsurface.modelsvector3f = NULL;
9915 rsurface.modeltvector3f = NULL;
9916 rsurface.modelnormal3f = NULL;
9917 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
9918 rsurface.modelvertexmesh = NULL;
9919 rsurface.modelvertexmeshbuffer = NULL;
9920 rsurface.modelvertexposition = NULL;
9921 rsurface.modelvertexpositionbuffer = NULL;
9923 rsurface.modelvertex3f_vertexbuffer = 0;
9924 rsurface.modelvertex3f_bufferoffset = 0;
9925 rsurface.modelsvector3f_vertexbuffer = 0;
9926 rsurface.modelsvector3f_bufferoffset = 0;
9927 rsurface.modeltvector3f_vertexbuffer = 0;
9928 rsurface.modeltvector3f_bufferoffset = 0;
9929 rsurface.modelnormal3f_vertexbuffer = 0;
9930 rsurface.modelnormal3f_bufferoffset = 0;
9931 rsurface.modelgeneratedvertex = true;
9935 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
9936 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9937 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
9938 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
9939 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9940 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
9941 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
9942 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9943 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
9944 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
9945 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9946 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
9947 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
9948 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
9949 rsurface.modelvertexposition = model->surfmesh.vertexposition;
9950 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
9951 rsurface.modelgeneratedvertex = false;
9953 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
9954 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9955 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
9956 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
9957 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9958 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
9959 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
9960 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
9961 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
9962 rsurface.modelelement3i = model->surfmesh.data_element3i;
9963 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
9964 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
9965 rsurface.modelelement3s = model->surfmesh.data_element3s;
9966 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
9967 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
9968 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
9969 rsurface.modelnumvertices = model->surfmesh.num_vertices;
9970 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
9971 rsurface.modelsurfaces = model->data_surfaces;
9972 rsurface.batchgeneratedvertex = false;
9973 rsurface.batchfirstvertex = 0;
9974 rsurface.batchnumvertices = 0;
9975 rsurface.batchfirsttriangle = 0;
9976 rsurface.batchnumtriangles = 0;
9977 rsurface.batchvertex3f = NULL;
9978 rsurface.batchvertex3f_vertexbuffer = NULL;
9979 rsurface.batchvertex3f_bufferoffset = 0;
9980 rsurface.batchsvector3f = NULL;
9981 rsurface.batchsvector3f_vertexbuffer = NULL;
9982 rsurface.batchsvector3f_bufferoffset = 0;
9983 rsurface.batchtvector3f = NULL;
9984 rsurface.batchtvector3f_vertexbuffer = NULL;
9985 rsurface.batchtvector3f_bufferoffset = 0;
9986 rsurface.batchnormal3f = NULL;
9987 rsurface.batchnormal3f_vertexbuffer = NULL;
9988 rsurface.batchnormal3f_bufferoffset = 0;
9989 rsurface.batchlightmapcolor4f = NULL;
9990 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
9991 rsurface.batchlightmapcolor4f_bufferoffset = 0;
9992 rsurface.batchtexcoordtexture2f = NULL;
9993 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
9994 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
9995 rsurface.batchtexcoordlightmap2f = NULL;
9996 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
9997 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
9998 rsurface.batchvertexmesh = NULL;
9999 rsurface.batchvertexmeshbuffer = NULL;
10000 rsurface.batchvertexposition = NULL;
10001 rsurface.batchvertexpositionbuffer = NULL;
10002 rsurface.batchelement3i = NULL;
10003 rsurface.batchelement3i_indexbuffer = NULL;
10004 rsurface.batchelement3i_bufferoffset = 0;
10005 rsurface.batchelement3s = NULL;
10006 rsurface.batchelement3s_indexbuffer = NULL;
10007 rsurface.batchelement3s_bufferoffset = 0;
10008 rsurface.passcolor4f = NULL;
10009 rsurface.passcolor4f_vertexbuffer = NULL;
10010 rsurface.passcolor4f_bufferoffset = 0;
10013 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)
10017 rsurface.entity = r_refdef.scene.worldentity;
10018 rsurface.skeleton = NULL;
10019 rsurface.ent_skinnum = 0;
10020 rsurface.ent_qwskin = -1;
10021 rsurface.ent_shadertime = shadertime;
10022 rsurface.ent_flags = entflags;
10023 rsurface.modelnumvertices = numvertices;
10024 rsurface.modelnumtriangles = numtriangles;
10025 if (rsurface.array_size < rsurface.modelnumvertices)
10026 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
10027 rsurface.matrix = *matrix;
10028 rsurface.inversematrix = *inversematrix;
10029 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10030 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10031 R_EntityMatrix(&rsurface.matrix);
10032 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10033 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10034 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10035 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10036 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10037 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10038 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10039 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10040 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10041 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10042 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10043 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10044 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);
10045 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10046 rsurface.frameblend[0].lerp = 1;
10047 rsurface.ent_alttextures = false;
10048 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10049 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10052 rsurface.modelvertex3f = vertex3f;
10053 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10054 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10055 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10057 else if (wantnormals)
10059 rsurface.modelvertex3f = vertex3f;
10060 rsurface.modelsvector3f = NULL;
10061 rsurface.modeltvector3f = NULL;
10062 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10066 rsurface.modelvertex3f = vertex3f;
10067 rsurface.modelsvector3f = NULL;
10068 rsurface.modeltvector3f = NULL;
10069 rsurface.modelnormal3f = NULL;
10071 rsurface.modelvertexmesh = NULL;
10072 rsurface.modelvertexmeshbuffer = NULL;
10073 rsurface.modelvertexposition = NULL;
10074 rsurface.modelvertexpositionbuffer = NULL;
10075 rsurface.modelvertex3f_vertexbuffer = 0;
10076 rsurface.modelvertex3f_bufferoffset = 0;
10077 rsurface.modelsvector3f_vertexbuffer = 0;
10078 rsurface.modelsvector3f_bufferoffset = 0;
10079 rsurface.modeltvector3f_vertexbuffer = 0;
10080 rsurface.modeltvector3f_bufferoffset = 0;
10081 rsurface.modelnormal3f_vertexbuffer = 0;
10082 rsurface.modelnormal3f_bufferoffset = 0;
10083 rsurface.modelgeneratedvertex = true;
10084 rsurface.modellightmapcolor4f = color4f;
10085 rsurface.modellightmapcolor4f_vertexbuffer = 0;
10086 rsurface.modellightmapcolor4f_bufferoffset = 0;
10087 rsurface.modeltexcoordtexture2f = texcoord2f;
10088 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10089 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10090 rsurface.modeltexcoordlightmap2f = NULL;
10091 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10092 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10093 rsurface.modelelement3i = element3i;
10094 rsurface.modelelement3i_indexbuffer = NULL;
10095 rsurface.modelelement3i_bufferoffset = 0;
10096 rsurface.modelelement3s = element3s;
10097 rsurface.modelelement3s_indexbuffer = NULL;
10098 rsurface.modelelement3s_bufferoffset = 0;
10099 rsurface.modellightmapoffsets = NULL;
10100 rsurface.modelsurfaces = NULL;
10101 rsurface.batchgeneratedvertex = false;
10102 rsurface.batchfirstvertex = 0;
10103 rsurface.batchnumvertices = 0;
10104 rsurface.batchfirsttriangle = 0;
10105 rsurface.batchnumtriangles = 0;
10106 rsurface.batchvertex3f = NULL;
10107 rsurface.batchvertex3f_vertexbuffer = NULL;
10108 rsurface.batchvertex3f_bufferoffset = 0;
10109 rsurface.batchsvector3f = NULL;
10110 rsurface.batchsvector3f_vertexbuffer = NULL;
10111 rsurface.batchsvector3f_bufferoffset = 0;
10112 rsurface.batchtvector3f = NULL;
10113 rsurface.batchtvector3f_vertexbuffer = NULL;
10114 rsurface.batchtvector3f_bufferoffset = 0;
10115 rsurface.batchnormal3f = NULL;
10116 rsurface.batchnormal3f_vertexbuffer = NULL;
10117 rsurface.batchnormal3f_bufferoffset = 0;
10118 rsurface.batchlightmapcolor4f = NULL;
10119 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10120 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10121 rsurface.batchtexcoordtexture2f = NULL;
10122 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10123 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10124 rsurface.batchtexcoordlightmap2f = NULL;
10125 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10126 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10127 rsurface.batchvertexmesh = NULL;
10128 rsurface.batchvertexmeshbuffer = NULL;
10129 rsurface.batchvertexposition = NULL;
10130 rsurface.batchvertexpositionbuffer = NULL;
10131 rsurface.batchelement3i = NULL;
10132 rsurface.batchelement3i_indexbuffer = NULL;
10133 rsurface.batchelement3i_bufferoffset = 0;
10134 rsurface.batchelement3s = NULL;
10135 rsurface.batchelement3s_indexbuffer = NULL;
10136 rsurface.batchelement3s_bufferoffset = 0;
10137 rsurface.passcolor4f = NULL;
10138 rsurface.passcolor4f_vertexbuffer = NULL;
10139 rsurface.passcolor4f_bufferoffset = 0;
10141 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10143 if ((wantnormals || wanttangents) && !normal3f)
10145 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10146 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10148 if (wanttangents && !svector3f)
10150 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);
10151 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10152 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10156 // now convert arrays into vertexmesh structs
10157 for (i = 0;i < numvertices;i++)
10159 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
10160 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
10161 if (rsurface.modelsvector3f)
10162 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
10163 if (rsurface.modeltvector3f)
10164 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
10165 if (rsurface.modelnormal3f)
10166 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
10167 if (rsurface.modellightmapcolor4f)
10168 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
10169 if (rsurface.modeltexcoordtexture2f)
10170 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
10171 if (rsurface.modeltexcoordlightmap2f)
10172 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
10176 float RSurf_FogPoint(const float *v)
10178 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10179 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10180 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10181 float FogHeightFade = r_refdef.fogheightfade;
10183 unsigned int fogmasktableindex;
10184 if (r_refdef.fogplaneviewabove)
10185 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10187 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10188 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10189 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10192 float RSurf_FogVertex(const float *v)
10194 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10195 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10196 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10197 float FogHeightFade = rsurface.fogheightfade;
10199 unsigned int fogmasktableindex;
10200 if (r_refdef.fogplaneviewabove)
10201 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10203 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10204 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10205 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10208 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10211 for (i = 0;i < numelements;i++)
10212 outelement3i[i] = inelement3i[i] + adjust;
10215 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10216 extern cvar_t gl_vbo;
10217 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10225 int surfacefirsttriangle;
10226 int surfacenumtriangles;
10227 int surfacefirstvertex;
10228 int surfaceendvertex;
10229 int surfacenumvertices;
10230 int surfaceadjustvertex;
10234 qboolean dynamicvertex;
10238 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10239 float waveparms[4];
10240 q3shaderinfo_deform_t *deform;
10241 const msurface_t *surface, *firstsurface;
10242 r_vertexposition_t *vertexposition;
10243 r_vertexmesh_t *vertexmesh;
10244 if (!texturenumsurfaces)
10246 // find vertex range of this surface batch
10248 firstsurface = texturesurfacelist[0];
10249 firsttriangle = firstsurface->num_firsttriangle;
10251 firstvertex = endvertex = firstsurface->num_firstvertex;
10252 for (i = 0;i < texturenumsurfaces;i++)
10254 surface = texturesurfacelist[i];
10255 if (surface != firstsurface + i)
10257 surfacefirstvertex = surface->num_firstvertex;
10258 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10259 surfacenumtriangles = surface->num_triangles;
10260 if (firstvertex > surfacefirstvertex)
10261 firstvertex = surfacefirstvertex;
10262 if (endvertex < surfaceendvertex)
10263 endvertex = surfaceendvertex;
10264 numtriangles += surfacenumtriangles;
10269 // we now know the vertex range used, and if there are any gaps in it
10270 rsurface.batchfirstvertex = firstvertex;
10271 rsurface.batchnumvertices = endvertex - firstvertex;
10272 rsurface.batchfirsttriangle = firsttriangle;
10273 rsurface.batchnumtriangles = numtriangles;
10275 // this variable holds flags for which properties have been updated that
10276 // may require regenerating vertexmesh or vertexposition arrays...
10279 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10280 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
10281 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10283 switch (deform->deform)
10286 case Q3DEFORM_PROJECTIONSHADOW:
10287 case Q3DEFORM_TEXT0:
10288 case Q3DEFORM_TEXT1:
10289 case Q3DEFORM_TEXT2:
10290 case Q3DEFORM_TEXT3:
10291 case Q3DEFORM_TEXT4:
10292 case Q3DEFORM_TEXT5:
10293 case Q3DEFORM_TEXT6:
10294 case Q3DEFORM_TEXT7:
10295 case Q3DEFORM_NONE:
10297 case Q3DEFORM_AUTOSPRITE:
10298 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10299 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10301 case Q3DEFORM_AUTOSPRITE2:
10302 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10303 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10305 case Q3DEFORM_NORMAL:
10306 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10307 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10309 case Q3DEFORM_WAVE:
10310 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10311 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10313 case Q3DEFORM_BULGE:
10314 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10315 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
10317 case Q3DEFORM_MOVE:
10318 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10319 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
10323 switch(rsurface.texture->tcgen.tcgen)
10326 case Q3TCGEN_TEXTURE:
10328 case Q3TCGEN_LIGHTMAP:
10329 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
10330 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
10332 case Q3TCGEN_VECTOR:
10333 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10334 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10336 case Q3TCGEN_ENVIRONMENT:
10337 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
10338 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10341 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10343 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10344 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
10347 // check if any dynamic vertex processing must occur
10348 dynamicvertex = false;
10350 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10352 dynamicvertex = true;
10353 batchneed |= BATCHNEED_NOGAPS;
10354 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
10357 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
10359 dynamicvertex = true;
10360 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
10361 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
10364 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
10366 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
10367 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
10368 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
10369 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
10370 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
10371 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
10372 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
10375 // when the model data has no vertex buffer (dynamic mesh), we need to
10377 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
10378 batchneed |= BATCHNEED_NOGAPS;
10380 // if needsupdate, we have to do a dynamic vertex batch for sure
10381 if (needsupdate & batchneed)
10382 dynamicvertex = true;
10384 // see if we need to build vertexmesh from arrays
10385 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
10386 dynamicvertex = true;
10388 // see if we need to build vertexposition from arrays
10389 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
10390 dynamicvertex = true;
10392 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
10393 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
10394 dynamicvertex = true;
10396 // if there is a chance of animated vertex colors, it's a dynamic batch
10397 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10398 dynamicvertex = true;
10400 rsurface.batchvertex3f = rsurface.modelvertex3f;
10401 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
10402 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
10403 rsurface.batchsvector3f = rsurface.modelsvector3f;
10404 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
10405 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
10406 rsurface.batchtvector3f = rsurface.modeltvector3f;
10407 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
10408 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
10409 rsurface.batchnormal3f = rsurface.modelnormal3f;
10410 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
10411 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
10412 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
10413 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
10414 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
10415 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
10416 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
10417 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
10418 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
10419 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
10420 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
10421 rsurface.batchvertexposition = rsurface.modelvertexposition;
10422 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
10423 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
10424 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
10425 rsurface.batchelement3i = rsurface.modelelement3i;
10426 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
10427 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
10428 rsurface.batchelement3s = rsurface.modelelement3s;
10429 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
10430 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
10432 // if any dynamic vertex processing has to occur in software, we copy the
10433 // entire surface list together before processing to rebase the vertices
10434 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
10436 // if any gaps exist and we do not have a static vertex buffer, we have to
10437 // copy the surface list together to avoid wasting upload bandwidth on the
10438 // vertices in the gaps.
10440 // if gaps exist and we have a static vertex buffer, we still have to
10441 // combine the index buffer ranges into one dynamic index buffer.
10443 // in all cases we end up with data that can be drawn in one call.
10445 if (!dynamicvertex)
10447 // static vertex data, just set pointers...
10448 rsurface.batchgeneratedvertex = false;
10449 // if there are gaps, we want to build a combined index buffer,
10450 // otherwise use the original static buffer with an appropriate offset
10455 for (i = 0;i < texturenumsurfaces;i++)
10457 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10458 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10459 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
10460 numtriangles += surfacenumtriangles;
10462 rsurface.batchelement3i = rsurface.array_batchelement3i;
10463 rsurface.batchelement3i_indexbuffer = NULL;
10464 rsurface.batchelement3i_bufferoffset = 0;
10465 rsurface.batchelement3s = NULL;
10466 rsurface.batchelement3s_indexbuffer = NULL;
10467 rsurface.batchelement3s_bufferoffset = 0;
10468 if (endvertex <= 65536)
10470 rsurface.batchelement3s = rsurface.array_batchelement3s;
10471 for (i = 0;i < numtriangles*3;i++)
10472 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10474 rsurface.batchfirsttriangle = firsttriangle;
10475 rsurface.batchnumtriangles = numtriangles;
10480 // something needs software processing, do it for real...
10481 // we only directly handle interleaved array data in this case...
10482 rsurface.batchgeneratedvertex = true;
10484 // now copy the vertex data into a combined array and make an index array
10485 // (this is what Quake3 does all the time)
10486 //if (gaps || rsurface.batchfirstvertex)
10488 rsurface.batchvertexposition = NULL;
10489 rsurface.batchvertexpositionbuffer = NULL;
10490 rsurface.batchvertexmesh = NULL;
10491 rsurface.batchvertexmeshbuffer = NULL;
10492 rsurface.batchvertex3f = NULL;
10493 rsurface.batchvertex3f_vertexbuffer = NULL;
10494 rsurface.batchvertex3f_bufferoffset = 0;
10495 rsurface.batchsvector3f = NULL;
10496 rsurface.batchsvector3f_vertexbuffer = NULL;
10497 rsurface.batchsvector3f_bufferoffset = 0;
10498 rsurface.batchtvector3f = NULL;
10499 rsurface.batchtvector3f_vertexbuffer = NULL;
10500 rsurface.batchtvector3f_bufferoffset = 0;
10501 rsurface.batchnormal3f = NULL;
10502 rsurface.batchnormal3f_vertexbuffer = NULL;
10503 rsurface.batchnormal3f_bufferoffset = 0;
10504 rsurface.batchlightmapcolor4f = NULL;
10505 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10506 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10507 rsurface.batchtexcoordtexture2f = NULL;
10508 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10509 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10510 rsurface.batchtexcoordlightmap2f = NULL;
10511 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10512 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10513 rsurface.batchelement3i = rsurface.array_batchelement3i;
10514 rsurface.batchelement3i_indexbuffer = NULL;
10515 rsurface.batchelement3i_bufferoffset = 0;
10516 rsurface.batchelement3s = NULL;
10517 rsurface.batchelement3s_indexbuffer = NULL;
10518 rsurface.batchelement3s_bufferoffset = 0;
10519 // we'll only be setting up certain arrays as needed
10520 if (batchneed & BATCHNEED_VERTEXPOSITION)
10521 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
10522 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10523 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10524 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10525 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10526 if (batchneed & BATCHNEED_ARRAY_NORMAL)
10527 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10528 if (batchneed & BATCHNEED_ARRAY_VECTOR)
10530 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10531 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10533 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
10534 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10535 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
10536 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10537 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
10538 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
10541 for (i = 0;i < texturenumsurfaces;i++)
10543 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
10544 surfacenumvertices = texturesurfacelist[i]->num_vertices;
10545 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
10546 surfaceadjustvertex = numvertices - surfacefirstvertex;
10547 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
10548 // copy only the data requested
10549 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
10550 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
10551 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
10552 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
10553 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
10555 if (batchneed & BATCHNEED_ARRAY_VERTEX)
10556 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10557 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
10558 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10559 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
10561 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10562 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
10564 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
10565 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
10566 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
10567 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10568 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
10569 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
10571 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
10572 numvertices += surfacenumvertices;
10573 numtriangles += surfacenumtriangles;
10576 // generate a 16bit index array as well if possible
10577 // (in general, dynamic batches fit)
10578 if (numvertices <= 65536)
10580 rsurface.batchelement3s = rsurface.array_batchelement3s;
10581 for (i = 0;i < numtriangles*3;i++)
10582 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
10585 // since we've copied everything, the batch now starts at 0
10586 rsurface.batchfirstvertex = 0;
10587 rsurface.batchnumvertices = numvertices;
10588 rsurface.batchfirsttriangle = 0;
10589 rsurface.batchnumtriangles = numtriangles;
10592 // q1bsp surfaces rendered in vertex color mode have to have colors
10593 // calculated based on lightstyles
10594 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10596 // generate color arrays for the surfaces in this list
10600 const int *offsets;
10601 const unsigned char *lm;
10603 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
10604 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10605 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10606 for (i = 0;i < texturenumsurfaces;i++)
10608 surface = texturesurfacelist[i];
10609 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
10610 surfacenumvertices = surface->num_vertices;
10611 if (surface->lightmapinfo->samples)
10613 for (j = 0;j < surfacenumvertices;j++)
10615 lm = surface->lightmapinfo->samples + offsets[j];
10616 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
10617 VectorScale(lm, scale, c);
10618 if (surface->lightmapinfo->styles[1] != 255)
10620 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
10622 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
10623 VectorMA(c, scale, lm, c);
10624 if (surface->lightmapinfo->styles[2] != 255)
10627 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
10628 VectorMA(c, scale, lm, c);
10629 if (surface->lightmapinfo->styles[3] != 255)
10632 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
10633 VectorMA(c, scale, lm, c);
10640 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);
10646 for (j = 0;j < surfacenumvertices;j++)
10648 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
10655 // if vertices are deformed (sprite flares and things in maps, possibly
10656 // water waves, bulges and other deformations), modify the copied vertices
10658 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10660 switch (deform->deform)
10663 case Q3DEFORM_PROJECTIONSHADOW:
10664 case Q3DEFORM_TEXT0:
10665 case Q3DEFORM_TEXT1:
10666 case Q3DEFORM_TEXT2:
10667 case Q3DEFORM_TEXT3:
10668 case Q3DEFORM_TEXT4:
10669 case Q3DEFORM_TEXT5:
10670 case Q3DEFORM_TEXT6:
10671 case Q3DEFORM_TEXT7:
10672 case Q3DEFORM_NONE:
10674 case Q3DEFORM_AUTOSPRITE:
10675 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10676 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10677 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10678 VectorNormalize(newforward);
10679 VectorNormalize(newright);
10680 VectorNormalize(newup);
10681 // a single autosprite surface can contain multiple sprites...
10682 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10684 VectorClear(center);
10685 for (i = 0;i < 4;i++)
10686 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10687 VectorScale(center, 0.25f, center);
10688 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
10689 VectorCopy(rsurface.batchsvector3f + 3*j, right);
10690 VectorCopy(rsurface.batchtvector3f + 3*j, up);
10691 for (i = 0;i < 4;i++)
10693 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
10694 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
10697 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10698 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);
10699 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10700 rsurface.batchvertex3f_vertexbuffer = NULL;
10701 rsurface.batchvertex3f_bufferoffset = 0;
10702 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10703 rsurface.batchsvector3f_vertexbuffer = NULL;
10704 rsurface.batchsvector3f_bufferoffset = 0;
10705 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10706 rsurface.batchtvector3f_vertexbuffer = NULL;
10707 rsurface.batchtvector3f_bufferoffset = 0;
10708 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10709 rsurface.batchnormal3f_vertexbuffer = NULL;
10710 rsurface.batchnormal3f_bufferoffset = 0;
10712 case Q3DEFORM_AUTOSPRITE2:
10713 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
10714 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
10715 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
10716 VectorNormalize(newforward);
10717 VectorNormalize(newright);
10718 VectorNormalize(newup);
10720 const float *v1, *v2;
10730 memset(shortest, 0, sizeof(shortest));
10731 // a single autosprite surface can contain multiple sprites...
10732 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
10734 VectorClear(center);
10735 for (i = 0;i < 4;i++)
10736 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
10737 VectorScale(center, 0.25f, center);
10738 // find the two shortest edges, then use them to define the
10739 // axis vectors for rotating around the central axis
10740 for (i = 0;i < 6;i++)
10742 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
10743 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
10744 l = VectorDistance2(v1, v2);
10745 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
10746 if (v1[2] != v2[2])
10747 l += (1.0f / 1024.0f);
10748 if (shortest[0].length2 > l || i == 0)
10750 shortest[1] = shortest[0];
10751 shortest[0].length2 = l;
10752 shortest[0].v1 = v1;
10753 shortest[0].v2 = v2;
10755 else if (shortest[1].length2 > l || i == 1)
10757 shortest[1].length2 = l;
10758 shortest[1].v1 = v1;
10759 shortest[1].v2 = v2;
10762 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
10763 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
10764 // this calculates the right vector from the shortest edge
10765 // and the up vector from the edge midpoints
10766 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
10767 VectorNormalize(right);
10768 VectorSubtract(end, start, up);
10769 VectorNormalize(up);
10770 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
10771 VectorSubtract(rsurface.localvieworigin, center, forward);
10772 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
10773 VectorNegate(forward, forward);
10774 VectorReflect(forward, 0, up, forward);
10775 VectorNormalize(forward);
10776 CrossProduct(up, forward, newright);
10777 VectorNormalize(newright);
10778 // rotate the quad around the up axis vector, this is made
10779 // especially easy by the fact we know the quad is flat,
10780 // so we only have to subtract the center position and
10781 // measure distance along the right vector, and then
10782 // multiply that by the newright vector and add back the
10784 // we also need to subtract the old position to undo the
10785 // displacement from the center, which we do with a
10786 // DotProduct, the subtraction/addition of center is also
10787 // optimized into DotProducts here
10788 l = DotProduct(right, center);
10789 for (i = 0;i < 4;i++)
10791 v1 = rsurface.batchvertex3f + 3*(j+i);
10792 f = DotProduct(right, v1) - l;
10793 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
10797 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10798 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);
10799 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10800 rsurface.batchvertex3f_vertexbuffer = NULL;
10801 rsurface.batchvertex3f_bufferoffset = 0;
10802 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10803 rsurface.batchsvector3f_vertexbuffer = NULL;
10804 rsurface.batchsvector3f_bufferoffset = 0;
10805 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10806 rsurface.batchtvector3f_vertexbuffer = NULL;
10807 rsurface.batchtvector3f_bufferoffset = 0;
10808 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10809 rsurface.batchnormal3f_vertexbuffer = NULL;
10810 rsurface.batchnormal3f_bufferoffset = 0;
10812 case Q3DEFORM_NORMAL:
10813 // deform the normals to make reflections wavey
10814 for (j = 0;j < rsurface.batchnumvertices;j++)
10817 float *normal = rsurface.array_batchnormal3f + 3*j;
10818 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
10819 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
10820 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]);
10821 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]);
10822 VectorNormalize(normal);
10824 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);
10825 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10826 rsurface.batchsvector3f_vertexbuffer = NULL;
10827 rsurface.batchsvector3f_bufferoffset = 0;
10828 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10829 rsurface.batchtvector3f_vertexbuffer = NULL;
10830 rsurface.batchtvector3f_bufferoffset = 0;
10831 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10832 rsurface.batchnormal3f_vertexbuffer = NULL;
10833 rsurface.batchnormal3f_bufferoffset = 0;
10835 case Q3DEFORM_WAVE:
10836 // deform vertex array to make wavey water and flags and such
10837 waveparms[0] = deform->waveparms[0];
10838 waveparms[1] = deform->waveparms[1];
10839 waveparms[2] = deform->waveparms[2];
10840 waveparms[3] = deform->waveparms[3];
10841 if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
10842 break; // if wavefunc is a nop, don't make a dynamic vertex array
10843 // this is how a divisor of vertex influence on deformation
10844 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
10845 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10846 for (j = 0;j < rsurface.batchnumvertices;j++)
10848 // if the wavefunc depends on time, evaluate it per-vertex
10851 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
10852 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
10854 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10856 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10857 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);
10858 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10859 rsurface.batchvertex3f_vertexbuffer = NULL;
10860 rsurface.batchvertex3f_bufferoffset = 0;
10861 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10862 rsurface.batchsvector3f_vertexbuffer = NULL;
10863 rsurface.batchsvector3f_bufferoffset = 0;
10864 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10865 rsurface.batchtvector3f_vertexbuffer = NULL;
10866 rsurface.batchtvector3f_bufferoffset = 0;
10867 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10868 rsurface.batchnormal3f_vertexbuffer = NULL;
10869 rsurface.batchnormal3f_bufferoffset = 0;
10871 case Q3DEFORM_BULGE:
10872 // deform vertex array to make the surface have moving bulges
10873 for (j = 0;j < rsurface.batchnumvertices;j++)
10875 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
10876 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
10878 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
10879 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);
10880 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10881 rsurface.batchvertex3f_vertexbuffer = NULL;
10882 rsurface.batchvertex3f_bufferoffset = 0;
10883 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
10884 rsurface.batchsvector3f_vertexbuffer = NULL;
10885 rsurface.batchsvector3f_bufferoffset = 0;
10886 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
10887 rsurface.batchtvector3f_vertexbuffer = NULL;
10888 rsurface.batchtvector3f_bufferoffset = 0;
10889 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
10890 rsurface.batchnormal3f_vertexbuffer = NULL;
10891 rsurface.batchnormal3f_bufferoffset = 0;
10893 case Q3DEFORM_MOVE:
10894 // deform vertex array
10895 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
10896 break; // if wavefunc is a nop, don't make a dynamic vertex array
10897 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
10898 VectorScale(deform->parms, scale, waveparms);
10899 for (j = 0;j < rsurface.batchnumvertices;j++)
10900 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
10901 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
10902 rsurface.batchvertex3f_vertexbuffer = NULL;
10903 rsurface.batchvertex3f_bufferoffset = 0;
10908 // generate texcoords based on the chosen texcoord source
10909 switch(rsurface.texture->tcgen.tcgen)
10912 case Q3TCGEN_TEXTURE:
10914 case Q3TCGEN_LIGHTMAP:
10915 if (rsurface.batchtexcoordlightmap2f)
10916 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
10917 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10918 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10919 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10921 case Q3TCGEN_VECTOR:
10922 for (j = 0;j < rsurface.batchnumvertices;j++)
10924 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
10925 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
10927 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10928 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10929 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10931 case Q3TCGEN_ENVIRONMENT:
10932 // make environment reflections using a spheremap
10933 for (j = 0;j < rsurface.batchnumvertices;j++)
10935 // identical to Q3A's method, but executed in worldspace so
10936 // carried models can be shiny too
10938 float viewer[3], d, reflected[3], worldreflected[3];
10940 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
10941 // VectorNormalize(viewer);
10943 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
10945 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
10946 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
10947 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
10948 // note: this is proportinal to viewer, so we can normalize later
10950 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
10951 VectorNormalize(worldreflected);
10953 // note: this sphere map only uses world x and z!
10954 // so positive and negative y will LOOK THE SAME.
10955 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
10956 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
10958 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10959 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10960 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10963 // the only tcmod that needs software vertex processing is turbulent, so
10964 // check for it here and apply the changes if needed
10965 // and we only support that as the first one
10966 // (handling a mixture of turbulent and other tcmods would be problematic
10967 // without punting it entirely to a software path)
10968 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
10970 amplitude = rsurface.texture->tcmods[0].parms[1];
10971 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
10972 for (j = 0;j < rsurface.batchnumvertices;j++)
10974 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);
10975 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
10977 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
10978 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10979 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10982 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
10984 // convert the modified arrays to vertex structs
10985 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
10986 rsurface.batchvertexmeshbuffer = NULL;
10987 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
10988 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10989 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
10990 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
10991 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10992 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
10993 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
10995 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
10997 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
10998 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11001 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11002 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11003 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11004 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11005 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11006 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11007 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11008 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11009 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11012 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11014 // convert the modified arrays to vertex structs
11015 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11016 rsurface.batchvertexpositionbuffer = NULL;
11017 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
11018 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
11020 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
11021 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
11025 void RSurf_DrawBatch(void)
11027 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);
11030 static void RSurf_BindLightmapForBatch(void)
11032 switch(vid.renderpath)
11034 case RENDERPATH_CGGL:
11036 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture );CHECKCGERROR
11037 if (r_cg_permutation->fp_Texture_Deluxemap) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap, rsurface.deluxemaptexture);CHECKCGERROR
11040 case RENDERPATH_GL20:
11041 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture );
11042 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP, rsurface.deluxemaptexture);
11044 case RENDERPATH_GL13:
11045 case RENDERPATH_GL11:
11046 R_Mesh_TexBind(0, rsurface.lightmaptexture);
11051 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11053 // pick the closest matching water plane
11054 int planeindex, vertexindex, bestplaneindex = -1;
11058 r_waterstate_waterplane_t *p;
11060 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11062 if(p->camera_entity != rsurface.texture->camera_entity)
11065 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
11066 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11068 Matrix4x4_Transform(&rsurface.matrix, v, vert);
11069 d += fabs(PlaneDiff(vert, &p->plane));
11071 if (bestd > d || bestplaneindex < 0)
11074 bestplaneindex = planeindex;
11077 return bestplaneindex;
11080 static void RSurf_BindReflectionForBatch(int planeindex)
11082 // pick the closest matching water plane and bind textures
11083 r_waterstate_waterplane_t *bestp = planeindex >= 0 ? r_waterstate.waterplanes + planeindex : NULL;
11084 switch(vid.renderpath)
11086 case RENDERPATH_CGGL:
11088 if (r_cg_permutation->fp_Texture_Refraction) {CG_BindTexture(r_cg_permutation->fp_Texture_Refraction, bestp ? bestp->texture_refraction : r_texture_black);CHECKCGERROR}
11089 else if (r_cg_permutation->fp_Texture_First) {CG_BindTexture(r_cg_permutation->fp_Texture_First, bestp ? bestp->texture_camera : r_texture_black);CHECKCGERROR}
11090 if (r_cg_permutation->fp_Texture_Reflection) {CG_BindTexture(r_cg_permutation->fp_Texture_Reflection, bestp ? bestp->texture_reflection : r_texture_black);CHECKCGERROR}
11093 case RENDERPATH_GL20:
11094 if (r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION, bestp ? bestp->texture_refraction : r_texture_black);
11095 else if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST, bestp ? bestp->texture_camera : r_texture_black);
11096 if (r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION, bestp ? bestp->texture_reflection : r_texture_black);
11098 case RENDERPATH_GL13:
11099 case RENDERPATH_GL11:
11104 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11107 for (i = 0;i < rsurface.batchnumvertices;i++)
11108 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11109 rsurface.passcolor4f = rsurface.array_passcolor4f;
11110 rsurface.passcolor4f_vertexbuffer = 0;
11111 rsurface.passcolor4f_bufferoffset = 0;
11114 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11121 if (rsurface.passcolor4f)
11123 // generate color arrays
11124 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)
11126 f = RSurf_FogVertex(v);
11135 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11137 f = RSurf_FogVertex(v);
11144 rsurface.passcolor4f = rsurface.array_passcolor4f;
11145 rsurface.passcolor4f_vertexbuffer = 0;
11146 rsurface.passcolor4f_bufferoffset = 0;
11149 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11156 if (!rsurface.passcolor4f)
11158 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)
11160 f = RSurf_FogVertex(v);
11161 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11162 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11163 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11166 rsurface.passcolor4f = rsurface.array_passcolor4f;
11167 rsurface.passcolor4f_vertexbuffer = 0;
11168 rsurface.passcolor4f_bufferoffset = 0;
11171 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11176 if (!rsurface.passcolor4f)
11178 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11185 rsurface.passcolor4f = rsurface.array_passcolor4f;
11186 rsurface.passcolor4f_vertexbuffer = 0;
11187 rsurface.passcolor4f_bufferoffset = 0;
11190 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11195 if (!rsurface.passcolor4f)
11197 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11199 c2[0] = c[0] + r_refdef.scene.ambient;
11200 c2[1] = c[1] + r_refdef.scene.ambient;
11201 c2[2] = c[2] + r_refdef.scene.ambient;
11204 rsurface.passcolor4f = rsurface.array_passcolor4f;
11205 rsurface.passcolor4f_vertexbuffer = 0;
11206 rsurface.passcolor4f_bufferoffset = 0;
11209 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11212 rsurface.passcolor4f = NULL;
11213 rsurface.passcolor4f_vertexbuffer = 0;
11214 rsurface.passcolor4f_bufferoffset = 0;
11215 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11216 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11217 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11218 GL_Color(r, g, b, a);
11219 RSurf_BindLightmapForBatch();
11223 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11225 // TODO: optimize applyfog && applycolor case
11226 // just apply fog if necessary, and tint the fog color array if necessary
11227 rsurface.passcolor4f = NULL;
11228 rsurface.passcolor4f_vertexbuffer = 0;
11229 rsurface.passcolor4f_bufferoffset = 0;
11230 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11231 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11232 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11233 GL_Color(r, g, b, a);
11237 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11240 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11241 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11242 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11243 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11244 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11245 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11246 GL_Color(r, g, b, a);
11250 static void RSurf_DrawBatch_GL11_ClampColor(void)
11255 if (!rsurface.passcolor4f)
11257 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11259 c2[0] = bound(0.0f, c1[0], 1.0f);
11260 c2[1] = bound(0.0f, c1[1], 1.0f);
11261 c2[2] = bound(0.0f, c1[2], 1.0f);
11262 c2[3] = bound(0.0f, c1[3], 1.0f);
11266 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
11274 vec3_t ambientcolor;
11275 vec3_t diffusecolor;
11279 VectorCopy(rsurface.modellight_lightdir, lightdir);
11280 f = 0.5f * r_refdef.lightmapintensity;
11281 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
11282 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
11283 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
11284 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
11285 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
11286 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
11288 if (VectorLength2(diffusecolor) > 0)
11290 // q3-style directional shading
11291 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)
11293 if ((f = DotProduct(n, lightdir)) > 0)
11294 VectorMA(ambientcolor, f, diffusecolor, c);
11296 VectorCopy(ambientcolor, c);
11303 rsurface.passcolor4f = rsurface.array_passcolor4f;
11304 rsurface.passcolor4f_vertexbuffer = 0;
11305 rsurface.passcolor4f_bufferoffset = 0;
11306 *applycolor = false;
11310 *r = ambientcolor[0];
11311 *g = ambientcolor[1];
11312 *b = ambientcolor[2];
11313 rsurface.passcolor4f = NULL;
11314 rsurface.passcolor4f_vertexbuffer = 0;
11315 rsurface.passcolor4f_bufferoffset = 0;
11319 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11321 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
11322 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11323 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11324 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11325 GL_Color(r, g, b, a);
11329 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
11335 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
11337 f = 1 - RSurf_FogVertex(v);
11345 void RSurf_SetupDepthAndCulling(void)
11347 // submodels are biased to avoid z-fighting with world surfaces that they
11348 // may be exactly overlapping (avoids z-fighting artifacts on certain
11349 // doors and things in Quake maps)
11350 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
11351 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
11352 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
11353 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
11356 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
11358 // transparent sky would be ridiculous
11359 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
11361 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11362 skyrenderlater = true;
11363 RSurf_SetupDepthAndCulling();
11364 GL_DepthMask(true);
11365 // LordHavoc: HalfLife maps have freaky skypolys so don't use
11366 // skymasking on them, and Quake3 never did sky masking (unlike
11367 // software Quake and software Quake2), so disable the sky masking
11368 // in Quake3 maps as it causes problems with q3map2 sky tricks,
11369 // and skymasking also looks very bad when noclipping outside the
11370 // level, so don't use it then either.
11371 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
11373 R_Mesh_ResetTextureState();
11374 if (skyrendermasked)
11376 R_SetupShader_DepthOrShadow();
11377 // depth-only (masking)
11378 GL_ColorMask(0,0,0,0);
11379 // just to make sure that braindead drivers don't draw
11380 // anything despite that colormask...
11381 GL_BlendFunc(GL_ZERO, GL_ONE);
11382 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11383 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11387 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11389 GL_BlendFunc(GL_ONE, GL_ZERO);
11390 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
11391 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
11392 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
11395 if (skyrendermasked)
11396 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11398 R_Mesh_ResetTextureState();
11399 GL_Color(1, 1, 1, 1);
11402 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
11403 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
11404 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11406 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
11410 // render screenspace normalmap to texture
11411 GL_DepthMask(true);
11412 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist);
11417 // bind lightmap texture
11419 // water/refraction/reflection/camera surfaces have to be handled specially
11420 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
11422 int start, end, startplaneindex;
11423 for (start = 0;start < texturenumsurfaces;start = end)
11425 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
11426 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
11428 // now that we have a batch using the same planeindex, render it
11429 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
11431 // render water or distortion background
11432 GL_DepthMask(true);
11433 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start);
11434 RSurf_BindReflectionForBatch(startplaneindex);
11435 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11436 RSurf_BindLightmapForBatch();
11438 // blend surface on top
11439 GL_DepthMask(false);
11440 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11443 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
11445 // render surface with reflection texture as input
11446 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11447 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start);
11448 RSurf_BindReflectionForBatch(startplaneindex);
11449 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11450 RSurf_BindLightmapForBatch();
11457 // render surface batch normally
11458 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
11459 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist);
11460 if (rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
11461 RSurf_BindLightmapForBatch();
11465 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11467 // OpenGL 1.3 path - anything not completely ancient
11468 qboolean applycolor;
11471 const texturelayer_t *layer;
11472 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);
11473 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11475 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11478 int layertexrgbscale;
11479 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11481 if (layerindex == 0)
11482 GL_AlphaTest(true);
11485 GL_AlphaTest(false);
11486 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11489 GL_DepthMask(layer->depthmask && writedepth);
11490 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11491 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
11493 layertexrgbscale = 4;
11494 VectorScale(layer->color, 0.25f, layercolor);
11496 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
11498 layertexrgbscale = 2;
11499 VectorScale(layer->color, 0.5f, layercolor);
11503 layertexrgbscale = 1;
11504 VectorScale(layer->color, 1.0f, layercolor);
11506 layercolor[3] = layer->color[3];
11507 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
11508 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11509 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11510 switch (layer->type)
11512 case TEXTURELAYERTYPE_LITTEXTURE:
11513 // single-pass lightmapped texture with 2x rgbscale
11514 R_Mesh_TexBind(0, r_texture_white);
11515 R_Mesh_TexMatrix(0, NULL);
11516 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11517 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11518 R_Mesh_TexBind(1, layer->texture);
11519 R_Mesh_TexMatrix(1, &layer->texmatrix);
11520 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11521 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11522 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11523 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11524 else if (rsurface.uselightmaptexture)
11525 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11527 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11529 case TEXTURELAYERTYPE_TEXTURE:
11530 // singletexture unlit texture with transparency support
11531 R_Mesh_TexBind(0, layer->texture);
11532 R_Mesh_TexMatrix(0, &layer->texmatrix);
11533 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11534 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11535 R_Mesh_TexBind(1, 0);
11536 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11537 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
11539 case TEXTURELAYERTYPE_FOG:
11540 // singletexture fogging
11541 if (layer->texture)
11543 R_Mesh_TexBind(0, layer->texture);
11544 R_Mesh_TexMatrix(0, &layer->texmatrix);
11545 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
11546 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11550 R_Mesh_TexBind(0, 0);
11551 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11553 R_Mesh_TexBind(1, 0);
11554 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11555 // generate a color array for the fog pass
11556 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11557 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
11561 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11565 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11567 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11568 GL_AlphaTest(false);
11572 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11574 // OpenGL 1.1 - crusty old voodoo path
11577 const texturelayer_t *layer;
11578 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);
11579 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
11581 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
11583 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11585 if (layerindex == 0)
11586 GL_AlphaTest(true);
11589 GL_AlphaTest(false);
11590 qglDepthFunc(GL_EQUAL);CHECKGLERROR
11593 GL_DepthMask(layer->depthmask && writedepth);
11594 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
11595 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
11596 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
11597 switch (layer->type)
11599 case TEXTURELAYERTYPE_LITTEXTURE:
11600 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
11602 // two-pass lit texture with 2x rgbscale
11603 // first the lightmap pass
11604 R_Mesh_TexBind(0, r_texture_white);
11605 R_Mesh_TexMatrix(0, NULL);
11606 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11607 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
11608 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11609 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
11610 else if (rsurface.uselightmaptexture)
11611 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
11613 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
11614 // then apply the texture to it
11615 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
11616 R_Mesh_TexBind(0, layer->texture);
11617 R_Mesh_TexMatrix(0, &layer->texmatrix);
11618 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11619 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11620 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);
11624 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
11625 R_Mesh_TexBind(0, layer->texture);
11626 R_Mesh_TexMatrix(0, &layer->texmatrix);
11627 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11628 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11629 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11630 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);
11632 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);
11635 case TEXTURELAYERTYPE_TEXTURE:
11636 // singletexture unlit texture with transparency support
11637 R_Mesh_TexBind(0, layer->texture);
11638 R_Mesh_TexMatrix(0, &layer->texmatrix);
11639 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11640 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11641 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);
11643 case TEXTURELAYERTYPE_FOG:
11644 // singletexture fogging
11645 if (layer->texture)
11647 R_Mesh_TexBind(0, layer->texture);
11648 R_Mesh_TexMatrix(0, &layer->texmatrix);
11649 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
11650 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
11654 R_Mesh_TexBind(0, 0);
11655 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
11657 // generate a color array for the fog pass
11658 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
11659 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
11663 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
11667 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11669 qglDepthFunc(GL_LEQUAL);CHECKGLERROR
11670 GL_AlphaTest(false);
11674 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
11678 r_vertexgeneric_t *batchvertex;
11681 GL_AlphaTest(false);
11682 R_Mesh_ResetTextureState();
11683 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11685 if(rsurface.texture && rsurface.texture->currentskinframe)
11687 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
11688 c[3] *= rsurface.texture->currentalpha;
11698 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
11700 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
11701 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
11702 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
11705 // brighten it up (as texture value 127 means "unlit")
11706 c[0] *= 2 * r_refdef.view.colorscale;
11707 c[1] *= 2 * r_refdef.view.colorscale;
11708 c[2] *= 2 * r_refdef.view.colorscale;
11710 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
11711 c[3] *= r_wateralpha.value;
11713 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
11715 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
11716 GL_DepthMask(false);
11718 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
11720 GL_BlendFunc(GL_ONE, GL_ONE);
11721 GL_DepthMask(false);
11723 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
11725 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
11726 GL_DepthMask(false);
11728 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
11730 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
11731 GL_DepthMask(false);
11735 GL_BlendFunc(GL_ONE, GL_ZERO);
11736 GL_DepthMask(writedepth);
11739 if (r_showsurfaces.integer == 3)
11741 rsurface.passcolor4f = NULL;
11743 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
11745 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11747 rsurface.passcolor4f = NULL;
11748 rsurface.passcolor4f_vertexbuffer = 0;
11749 rsurface.passcolor4f_bufferoffset = 0;
11751 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
11753 qboolean applycolor = true;
11756 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11758 r_refdef.lightmapintensity = 1;
11759 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
11760 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
11764 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11766 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11767 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11768 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11771 if(!rsurface.passcolor4f)
11772 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
11774 RSurf_DrawBatch_GL11_ApplyAmbient();
11775 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
11776 if(r_refdef.fogenabled)
11777 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
11778 RSurf_DrawBatch_GL11_ClampColor();
11780 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
11781 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
11784 else if (!r_refdef.view.showdebug)
11786 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11787 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11788 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11790 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11791 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
11793 R_Mesh_PrepareVertices_Generic_Unlock();
11796 else if (r_showsurfaces.integer == 4)
11798 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11799 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
11800 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
11802 unsigned char c = vi << 3;
11803 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11804 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
11806 R_Mesh_PrepareVertices_Generic_Unlock();
11809 else if (r_showsurfaces.integer == 2)
11812 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11813 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
11814 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
11816 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
11817 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
11818 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
11819 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
11820 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
11821 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
11822 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
11824 R_Mesh_PrepareVertices_Generic_Unlock();
11825 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
11829 int texturesurfaceindex;
11831 const msurface_t *surface;
11832 unsigned char surfacecolor4ub[4];
11833 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
11834 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
11836 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
11838 surface = texturesurfacelist[texturesurfaceindex];
11839 k = (int)(((size_t)surface) / sizeof(msurface_t));
11840 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
11841 for (j = 0;j < surface->num_vertices;j++)
11843 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
11844 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
11848 R_Mesh_PrepareVertices_Generic_Unlock();
11853 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11856 RSurf_SetupDepthAndCulling();
11857 if (r_showsurfaces.integer)
11859 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11862 switch (vid.renderpath)
11864 case RENDERPATH_GL20:
11865 case RENDERPATH_CGGL:
11866 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11868 case RENDERPATH_GL13:
11869 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11871 case RENDERPATH_GL11:
11872 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11878 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
11881 RSurf_SetupDepthAndCulling();
11882 if (r_showsurfaces.integer)
11884 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
11887 switch (vid.renderpath)
11889 case RENDERPATH_GL20:
11890 case RENDERPATH_CGGL:
11891 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
11893 case RENDERPATH_GL13:
11894 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
11896 case RENDERPATH_GL11:
11897 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
11903 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
11906 int texturenumsurfaces, endsurface;
11907 texture_t *texture;
11908 const msurface_t *surface;
11909 #define MAXBATCH_TRANSPARENTSURFACES 256
11910 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
11912 // if the model is static it doesn't matter what value we give for
11913 // wantnormals and wanttangents, so this logic uses only rules applicable
11914 // to a model, knowing that they are meaningless otherwise
11915 if (ent == r_refdef.scene.worldentity)
11916 RSurf_ActiveWorldEntity();
11917 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
11918 RSurf_ActiveModelEntity(ent, false, false, false);
11921 switch (vid.renderpath)
11923 case RENDERPATH_GL20:
11924 case RENDERPATH_CGGL:
11925 RSurf_ActiveModelEntity(ent, true, true, false);
11927 case RENDERPATH_GL13:
11928 case RENDERPATH_GL11:
11929 RSurf_ActiveModelEntity(ent, true, false, false);
11934 if (r_transparentdepthmasking.integer)
11936 qboolean setup = false;
11937 for (i = 0;i < numsurfaces;i = j)
11940 surface = rsurface.modelsurfaces + surfacelist[i];
11941 texture = surface->texture;
11942 rsurface.texture = R_GetCurrentTexture(texture);
11943 rsurface.lightmaptexture = NULL;
11944 rsurface.deluxemaptexture = NULL;
11945 rsurface.uselightmaptexture = false;
11946 // scan ahead until we find a different texture
11947 endsurface = min(i + 1024, numsurfaces);
11948 texturenumsurfaces = 0;
11949 texturesurfacelist[texturenumsurfaces++] = surface;
11950 for (;j < endsurface;j++)
11952 surface = rsurface.modelsurfaces + surfacelist[j];
11953 if (texture != surface->texture)
11955 texturesurfacelist[texturenumsurfaces++] = surface;
11957 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
11959 // render the range of surfaces as depth
11963 GL_ColorMask(0,0,0,0);
11965 GL_DepthTest(true);
11966 GL_BlendFunc(GL_ONE, GL_ZERO);
11967 GL_DepthMask(true);
11968 GL_AlphaTest(false);
11969 R_Mesh_ResetTextureState();
11970 R_SetupShader_DepthOrShadow();
11972 RSurf_SetupDepthAndCulling();
11973 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
11974 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
11978 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
11981 for (i = 0;i < numsurfaces;i = j)
11984 surface = rsurface.modelsurfaces + surfacelist[i];
11985 texture = surface->texture;
11986 rsurface.texture = R_GetCurrentTexture(texture);
11987 rsurface.lightmaptexture = surface->lightmaptexture;
11988 rsurface.deluxemaptexture = surface->deluxemaptexture;
11989 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
11990 // scan ahead until we find a different texture
11991 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
11992 texturenumsurfaces = 0;
11993 texturesurfacelist[texturenumsurfaces++] = surface;
11994 for (;j < endsurface;j++)
11996 surface = rsurface.modelsurfaces + surfacelist[j];
11997 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
11999 texturesurfacelist[texturenumsurfaces++] = surface;
12001 // render the range of surfaces
12002 if (ent == r_refdef.scene.worldentity)
12003 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12005 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12007 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12008 GL_AlphaTest(false);
12011 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12013 // transparent surfaces get pushed off into the transparent queue
12014 int surfacelistindex;
12015 const msurface_t *surface;
12016 vec3_t tempcenter, center;
12017 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12019 surface = texturesurfacelist[surfacelistindex];
12020 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12021 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12022 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12023 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12024 if (queueentity->transparent_offset) // transparent offset
12026 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12027 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12028 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12030 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12034 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12036 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12038 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12040 RSurf_SetupDepthAndCulling();
12041 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12042 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12046 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12048 const entity_render_t *queueentity = r_refdef.scene.worldentity;
12051 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12054 if (!rsurface.texture->currentnumlayers)
12056 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12057 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12059 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12061 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12062 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12063 else if (!rsurface.texture->currentnumlayers)
12065 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12067 // in the deferred case, transparent surfaces were queued during prepass
12068 if (!r_shadow_usingdeferredprepass)
12069 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12073 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12074 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12079 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12082 texture_t *texture;
12083 // break the surface list down into batches by texture and use of lightmapping
12084 for (i = 0;i < numsurfaces;i = j)
12087 // texture is the base texture pointer, rsurface.texture is the
12088 // current frame/skin the texture is directing us to use (for example
12089 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12090 // use skin 1 instead)
12091 texture = surfacelist[i]->texture;
12092 rsurface.texture = R_GetCurrentTexture(texture);
12093 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12094 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12095 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12096 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12098 // if this texture is not the kind we want, skip ahead to the next one
12099 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12103 // simply scan ahead until we find a different texture or lightmap state
12104 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12106 // render the range of surfaces
12107 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12111 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12115 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12118 if (!rsurface.texture->currentnumlayers)
12120 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12121 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12123 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12125 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12126 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12127 else if (!rsurface.texture->currentnumlayers)
12129 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12131 // in the deferred case, transparent surfaces were queued during prepass
12132 if (!r_shadow_usingdeferredprepass)
12133 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12137 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12138 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12143 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12146 texture_t *texture;
12147 // break the surface list down into batches by texture and use of lightmapping
12148 for (i = 0;i < numsurfaces;i = j)
12151 // texture is the base texture pointer, rsurface.texture is the
12152 // current frame/skin the texture is directing us to use (for example
12153 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12154 // use skin 1 instead)
12155 texture = surfacelist[i]->texture;
12156 rsurface.texture = R_GetCurrentTexture(texture);
12157 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12158 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12159 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12160 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12162 // if this texture is not the kind we want, skip ahead to the next one
12163 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12167 // simply scan ahead until we find a different texture or lightmap state
12168 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12170 // render the range of surfaces
12171 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12175 float locboxvertex3f[6*4*3] =
12177 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12178 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12179 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12180 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12181 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12182 1,0,0, 0,0,0, 0,1,0, 1,1,0
12185 unsigned short locboxelements[6*2*3] =
12190 12,13,14, 12,14,15,
12191 16,17,18, 16,18,19,
12195 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12198 cl_locnode_t *loc = (cl_locnode_t *)ent;
12200 float vertex3f[6*4*3];
12202 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12203 GL_DepthMask(false);
12204 GL_DepthRange(0, 1);
12205 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12206 GL_DepthTest(true);
12207 GL_CullFace(GL_NONE);
12208 R_EntityMatrix(&identitymatrix);
12210 R_Mesh_ResetTextureState();
12212 i = surfacelist[0];
12213 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12214 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12215 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
12216 surfacelist[0] < 0 ? 0.5f : 0.125f);
12218 if (VectorCompare(loc->mins, loc->maxs))
12220 VectorSet(size, 2, 2, 2);
12221 VectorMA(loc->mins, -0.5f, size, mins);
12225 VectorCopy(loc->mins, mins);
12226 VectorSubtract(loc->maxs, loc->mins, size);
12229 for (i = 0;i < 6*4*3;)
12230 for (j = 0;j < 3;j++, i++)
12231 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
12233 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
12234 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12235 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
12238 void R_DrawLocs(void)
12241 cl_locnode_t *loc, *nearestloc;
12243 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
12244 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
12246 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
12247 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
12251 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
12253 if (decalsystem->decals)
12254 Mem_Free(decalsystem->decals);
12255 memset(decalsystem, 0, sizeof(*decalsystem));
12258 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)
12261 tridecal_t *decals;
12264 // expand or initialize the system
12265 if (decalsystem->maxdecals <= decalsystem->numdecals)
12267 decalsystem_t old = *decalsystem;
12268 qboolean useshortelements;
12269 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
12270 useshortelements = decalsystem->maxdecals * 3 <= 65536;
12271 decalsystem->decals = Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
12272 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
12273 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
12274 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
12275 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
12276 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
12277 if (decalsystem->numdecals)
12278 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
12280 Mem_Free(old.decals);
12281 for (i = 0;i < decalsystem->maxdecals*3;i++)
12282 decalsystem->element3i[i] = i;
12283 if (useshortelements)
12284 for (i = 0;i < decalsystem->maxdecals*3;i++)
12285 decalsystem->element3s[i] = i;
12288 // grab a decal and search for another free slot for the next one
12289 decals = decalsystem->decals;
12290 decal = decalsystem->decals + (i = decalsystem->freedecal++);
12291 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
12293 decalsystem->freedecal = i;
12294 if (decalsystem->numdecals <= i)
12295 decalsystem->numdecals = i + 1;
12297 // initialize the decal
12299 decal->triangleindex = triangleindex;
12300 decal->surfaceindex = surfaceindex;
12301 decal->decalsequence = decalsequence;
12302 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
12303 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
12304 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
12305 decal->color4ub[0][3] = 255;
12306 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
12307 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
12308 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
12309 decal->color4ub[1][3] = 255;
12310 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
12311 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
12312 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
12313 decal->color4ub[2][3] = 255;
12314 decal->vertex3f[0][0] = v0[0];
12315 decal->vertex3f[0][1] = v0[1];
12316 decal->vertex3f[0][2] = v0[2];
12317 decal->vertex3f[1][0] = v1[0];
12318 decal->vertex3f[1][1] = v1[1];
12319 decal->vertex3f[1][2] = v1[2];
12320 decal->vertex3f[2][0] = v2[0];
12321 decal->vertex3f[2][1] = v2[1];
12322 decal->vertex3f[2][2] = v2[2];
12323 decal->texcoord2f[0][0] = t0[0];
12324 decal->texcoord2f[0][1] = t0[1];
12325 decal->texcoord2f[1][0] = t1[0];
12326 decal->texcoord2f[1][1] = t1[1];
12327 decal->texcoord2f[2][0] = t2[0];
12328 decal->texcoord2f[2][1] = t2[1];
12331 extern cvar_t cl_decals_bias;
12332 extern cvar_t cl_decals_models;
12333 extern cvar_t cl_decals_newsystem_intensitymultiplier;
12334 // baseparms, parms, temps
12335 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)
12340 const float *vertex3f;
12342 float points[2][9][3];
12349 e = rsurface.modelelement3i + 3*triangleindex;
12351 vertex3f = rsurface.modelvertex3f;
12353 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12355 index = 3*e[cornerindex];
12356 VectorCopy(vertex3f + index, v[cornerindex]);
12359 //TriangleNormal(v[0], v[1], v[2], normal);
12360 //if (DotProduct(normal, localnormal) < 0.0f)
12362 // clip by each of the box planes formed from the projection matrix
12363 // if anything survives, we emit the decal
12364 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]);
12367 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]);
12370 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]);
12373 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]);
12376 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]);
12379 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]);
12382 // some part of the triangle survived, so we have to accept it...
12385 // dynamic always uses the original triangle
12387 for (cornerindex = 0;cornerindex < 3;cornerindex++)
12389 index = 3*e[cornerindex];
12390 VectorCopy(vertex3f + index, v[cornerindex]);
12393 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
12395 // convert vertex positions to texcoords
12396 Matrix4x4_Transform(projection, v[cornerindex], temp);
12397 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
12398 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
12399 // calculate distance fade from the projection origin
12400 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
12401 f = bound(0.0f, f, 1.0f);
12402 c[cornerindex][0] = r * f;
12403 c[cornerindex][1] = g * f;
12404 c[cornerindex][2] = b * f;
12405 c[cornerindex][3] = 1.0f;
12406 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
12409 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
12411 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
12412 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
12414 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12416 matrix4x4_t projection;
12417 decalsystem_t *decalsystem;
12420 const msurface_t *surface;
12421 const msurface_t *surfaces;
12422 const int *surfacelist;
12423 const texture_t *texture;
12425 int numsurfacelist;
12426 int surfacelistindex;
12429 float localorigin[3];
12430 float localnormal[3];
12431 float localmins[3];
12432 float localmaxs[3];
12435 float planes[6][4];
12438 int bih_triangles_count;
12439 int bih_triangles[256];
12440 int bih_surfaces[256];
12442 decalsystem = &ent->decalsystem;
12443 model = ent->model;
12444 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
12446 R_DecalSystem_Reset(&ent->decalsystem);
12450 if (!model->brush.data_nodes && !cl_decals_models.integer)
12452 if (decalsystem->model)
12453 R_DecalSystem_Reset(decalsystem);
12457 if (decalsystem->model != model)
12458 R_DecalSystem_Reset(decalsystem);
12459 decalsystem->model = model;
12461 RSurf_ActiveModelEntity(ent, false, false, false);
12463 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
12464 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
12465 VectorNormalize(localnormal);
12466 localsize = worldsize*rsurface.inversematrixscale;
12467 localmins[0] = localorigin[0] - localsize;
12468 localmins[1] = localorigin[1] - localsize;
12469 localmins[2] = localorigin[2] - localsize;
12470 localmaxs[0] = localorigin[0] + localsize;
12471 localmaxs[1] = localorigin[1] + localsize;
12472 localmaxs[2] = localorigin[2] + localsize;
12474 //VectorCopy(localnormal, planes[4]);
12475 //VectorVectors(planes[4], planes[2], planes[0]);
12476 AnglesFromVectors(angles, localnormal, NULL, false);
12477 AngleVectors(angles, planes[0], planes[2], planes[4]);
12478 VectorNegate(planes[0], planes[1]);
12479 VectorNegate(planes[2], planes[3]);
12480 VectorNegate(planes[4], planes[5]);
12481 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
12482 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
12483 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
12484 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
12485 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
12486 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
12491 matrix4x4_t forwardprojection;
12492 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
12493 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
12498 float projectionvector[4][3];
12499 VectorScale(planes[0], ilocalsize, projectionvector[0]);
12500 VectorScale(planes[2], ilocalsize, projectionvector[1]);
12501 VectorScale(planes[4], ilocalsize, projectionvector[2]);
12502 projectionvector[0][0] = planes[0][0] * ilocalsize;
12503 projectionvector[0][1] = planes[1][0] * ilocalsize;
12504 projectionvector[0][2] = planes[2][0] * ilocalsize;
12505 projectionvector[1][0] = planes[0][1] * ilocalsize;
12506 projectionvector[1][1] = planes[1][1] * ilocalsize;
12507 projectionvector[1][2] = planes[2][1] * ilocalsize;
12508 projectionvector[2][0] = planes[0][2] * ilocalsize;
12509 projectionvector[2][1] = planes[1][2] * ilocalsize;
12510 projectionvector[2][2] = planes[2][2] * ilocalsize;
12511 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
12512 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
12513 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
12514 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
12518 dynamic = model->surfmesh.isanimated;
12519 numsurfacelist = model->nummodelsurfaces;
12520 surfacelist = model->sortedmodelsurfaces;
12521 surfaces = model->data_surfaces;
12524 bih_triangles_count = -1;
12527 if(model->render_bih.numleafs)
12528 bih = &model->render_bih;
12529 else if(model->collision_bih.numleafs)
12530 bih = &model->collision_bih;
12533 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
12534 if(bih_triangles_count == 0)
12536 if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
12538 if(bih_triangles_count > 0)
12540 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
12542 surfaceindex = bih_surfaces[triangleindex];
12543 surface = surfaces + surfaceindex;
12544 texture = surface->texture;
12545 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12547 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12549 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
12554 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
12556 surfaceindex = surfacelist[surfacelistindex];
12557 surface = surfaces + surfaceindex;
12558 // check cull box first because it rejects more than any other check
12559 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
12561 // skip transparent surfaces
12562 texture = surface->texture;
12563 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
12565 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
12567 numtriangles = surface->num_triangles;
12568 for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
12569 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
12574 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
12575 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
12577 int renderentityindex;
12578 float worldmins[3];
12579 float worldmaxs[3];
12580 entity_render_t *ent;
12582 if (!cl_decals_newsystem.integer)
12585 worldmins[0] = worldorigin[0] - worldsize;
12586 worldmins[1] = worldorigin[1] - worldsize;
12587 worldmins[2] = worldorigin[2] - worldsize;
12588 worldmaxs[0] = worldorigin[0] + worldsize;
12589 worldmaxs[1] = worldorigin[1] + worldsize;
12590 worldmaxs[2] = worldorigin[2] + worldsize;
12592 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12594 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
12596 ent = r_refdef.scene.entities[renderentityindex];
12597 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
12600 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
12604 typedef struct r_decalsystem_splatqueue_s
12606 vec3_t worldorigin;
12607 vec3_t worldnormal;
12613 r_decalsystem_splatqueue_t;
12615 int r_decalsystem_numqueued = 0;
12616 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
12618 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
12620 r_decalsystem_splatqueue_t *queue;
12622 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
12625 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
12626 VectorCopy(worldorigin, queue->worldorigin);
12627 VectorCopy(worldnormal, queue->worldnormal);
12628 Vector4Set(queue->color, r, g, b, a);
12629 Vector4Set(queue->tcrange, s1, t1, s2, t2);
12630 queue->worldsize = worldsize;
12631 queue->decalsequence = cl.decalsequence++;
12634 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
12637 r_decalsystem_splatqueue_t *queue;
12639 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
12640 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);
12641 r_decalsystem_numqueued = 0;
12644 extern cvar_t cl_decals_max;
12645 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
12648 decalsystem_t *decalsystem = &ent->decalsystem;
12655 if (!decalsystem->numdecals)
12658 if (r_showsurfaces.integer)
12661 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12663 R_DecalSystem_Reset(decalsystem);
12667 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
12668 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
12670 if (decalsystem->lastupdatetime)
12671 frametime = (cl.time - decalsystem->lastupdatetime);
12674 decalsystem->lastupdatetime = cl.time;
12675 decal = decalsystem->decals;
12676 numdecals = decalsystem->numdecals;
12678 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12680 if (decal->color4ub[0][3])
12682 decal->lived += frametime;
12683 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
12685 memset(decal, 0, sizeof(*decal));
12686 if (decalsystem->freedecal > i)
12687 decalsystem->freedecal = i;
12691 decal = decalsystem->decals;
12692 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
12695 // collapse the array by shuffling the tail decals into the gaps
12698 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
12699 decalsystem->freedecal++;
12700 if (decalsystem->freedecal == numdecals)
12702 decal[decalsystem->freedecal] = decal[--numdecals];
12705 decalsystem->numdecals = numdecals;
12707 if (numdecals <= 0)
12709 // if there are no decals left, reset decalsystem
12710 R_DecalSystem_Reset(decalsystem);
12714 extern skinframe_t *decalskinframe;
12715 static void R_DrawModelDecals_Entity(entity_render_t *ent)
12718 decalsystem_t *decalsystem = &ent->decalsystem;
12727 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
12730 numdecals = decalsystem->numdecals;
12734 if (r_showsurfaces.integer)
12737 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
12739 R_DecalSystem_Reset(decalsystem);
12743 // if the model is static it doesn't matter what value we give for
12744 // wantnormals and wanttangents, so this logic uses only rules applicable
12745 // to a model, knowing that they are meaningless otherwise
12746 if (ent == r_refdef.scene.worldentity)
12747 RSurf_ActiveWorldEntity();
12749 RSurf_ActiveModelEntity(ent, false, false, false);
12751 decalsystem->lastupdatetime = cl.time;
12752 decal = decalsystem->decals;
12754 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
12756 // update vertex positions for animated models
12757 v3f = decalsystem->vertex3f;
12758 c4f = decalsystem->color4f;
12759 t2f = decalsystem->texcoord2f;
12760 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
12762 if (!decal->color4ub[0][3])
12765 if (surfacevisible && !surfacevisible[decal->surfaceindex])
12768 // update color values for fading decals
12769 if (decal->lived >= cl_decals_time.value)
12771 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
12772 alpha *= (1.0f/255.0f);
12775 alpha = 1.0f/255.0f;
12777 c4f[ 0] = decal->color4ub[0][0] * alpha;
12778 c4f[ 1] = decal->color4ub[0][1] * alpha;
12779 c4f[ 2] = decal->color4ub[0][2] * alpha;
12781 c4f[ 4] = decal->color4ub[1][0] * alpha;
12782 c4f[ 5] = decal->color4ub[1][1] * alpha;
12783 c4f[ 6] = decal->color4ub[1][2] * alpha;
12785 c4f[ 8] = decal->color4ub[2][0] * alpha;
12786 c4f[ 9] = decal->color4ub[2][1] * alpha;
12787 c4f[10] = decal->color4ub[2][2] * alpha;
12790 t2f[0] = decal->texcoord2f[0][0];
12791 t2f[1] = decal->texcoord2f[0][1];
12792 t2f[2] = decal->texcoord2f[1][0];
12793 t2f[3] = decal->texcoord2f[1][1];
12794 t2f[4] = decal->texcoord2f[2][0];
12795 t2f[5] = decal->texcoord2f[2][1];
12797 // update vertex positions for animated models
12798 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
12800 e = rsurface.modelelement3i + 3*decal->triangleindex;
12801 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
12802 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
12803 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
12807 VectorCopy(decal->vertex3f[0], v3f);
12808 VectorCopy(decal->vertex3f[1], v3f + 3);
12809 VectorCopy(decal->vertex3f[2], v3f + 6);
12812 if (r_refdef.fogenabled)
12814 alpha = RSurf_FogVertex(v3f);
12815 VectorScale(c4f, alpha, c4f);
12816 alpha = RSurf_FogVertex(v3f + 3);
12817 VectorScale(c4f + 4, alpha, c4f + 4);
12818 alpha = RSurf_FogVertex(v3f + 6);
12819 VectorScale(c4f + 8, alpha, c4f + 8);
12830 r_refdef.stats.drawndecals += numtris;
12832 // now render the decals all at once
12833 // (this assumes they all use one particle font texture!)
12834 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);
12835 R_Mesh_ResetTextureState();
12836 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
12837 GL_DepthMask(false);
12838 GL_DepthRange(0, 1);
12839 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
12840 GL_DepthTest(true);
12841 GL_CullFace(GL_NONE);
12842 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
12843 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
12844 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
12848 static void R_DrawModelDecals(void)
12852 // fade faster when there are too many decals
12853 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12854 for (i = 0;i < r_refdef.scene.numentities;i++)
12855 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12857 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
12858 for (i = 0;i < r_refdef.scene.numentities;i++)
12859 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12860 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
12862 R_DecalSystem_ApplySplatEntitiesQueue();
12864 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
12865 for (i = 0;i < r_refdef.scene.numentities;i++)
12866 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
12868 r_refdef.stats.totaldecals += numdecals;
12870 if (r_showsurfaces.integer)
12873 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
12875 for (i = 0;i < r_refdef.scene.numentities;i++)
12877 if (!r_refdef.viewcache.entityvisible[i])
12879 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
12880 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
12884 extern cvar_t mod_collision_bih;
12885 void R_DrawDebugModel(void)
12887 entity_render_t *ent = rsurface.entity;
12888 int i, j, k, l, flagsmask;
12889 const msurface_t *surface;
12890 dp_model_t *model = ent->model;
12893 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
12895 R_Mesh_ResetTextureState();
12896 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12897 GL_DepthRange(0, 1);
12898 GL_DepthTest(!r_showdisabledepthtest.integer);
12899 GL_DepthMask(false);
12900 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12902 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
12906 qboolean cullbox = ent == r_refdef.scene.worldentity;
12907 const q3mbrush_t *brush;
12908 const bih_t *bih = &model->collision_bih;
12909 const bih_leaf_t *bihleaf;
12910 float vertex3f[3][3];
12911 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
12913 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
12915 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
12917 switch (bihleaf->type)
12920 brush = model->brush.data_brushes + bihleaf->itemindex;
12921 if (brush->colbrushf && brush->colbrushf->numtriangles)
12923 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);
12924 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
12925 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
12928 case BIH_COLLISIONTRIANGLE:
12929 triangleindex = bihleaf->itemindex;
12930 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
12931 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
12932 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
12933 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);
12934 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12935 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12937 case BIH_RENDERTRIANGLE:
12938 triangleindex = bihleaf->itemindex;
12939 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
12940 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
12941 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
12942 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);
12943 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
12944 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
12950 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
12952 if (r_showtris.integer || r_shownormals.integer)
12954 if (r_showdisabledepthtest.integer)
12956 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12957 GL_DepthMask(false);
12961 GL_BlendFunc(GL_ONE, GL_ZERO);
12962 GL_DepthMask(true);
12964 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
12966 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
12968 rsurface.texture = R_GetCurrentTexture(surface->texture);
12969 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
12971 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
12972 if (r_showtris.value > 0)
12974 if (!rsurface.texture->currentlayers->depthmask)
12975 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
12976 else if (ent == r_refdef.scene.worldentity)
12977 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
12979 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
12980 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12981 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
12983 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
12986 if (r_shownormals.value < 0)
12988 qglBegin(GL_LINES);
12989 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
12991 VectorCopy(rsurface.batchvertex3f + l * 3, v);
12992 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
12993 qglVertex3f(v[0], v[1], v[2]);
12994 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
12995 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
12996 qglVertex3f(v[0], v[1], v[2]);
13001 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13003 qglBegin(GL_LINES);
13004 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13006 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13007 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13008 qglVertex3f(v[0], v[1], v[2]);
13009 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13010 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13011 qglVertex3f(v[0], v[1], v[2]);
13015 qglBegin(GL_LINES);
13016 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13018 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13019 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13020 qglVertex3f(v[0], v[1], v[2]);
13021 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13022 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13023 qglVertex3f(v[0], v[1], v[2]);
13027 qglBegin(GL_LINES);
13028 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13030 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13031 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13032 qglVertex3f(v[0], v[1], v[2]);
13033 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13034 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13035 qglVertex3f(v[0], v[1], v[2]);
13042 rsurface.texture = NULL;
13046 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13047 int r_maxsurfacelist = 0;
13048 const msurface_t **r_surfacelist = NULL;
13049 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13051 int i, j, endj, flagsmask;
13052 dp_model_t *model = r_refdef.scene.worldmodel;
13053 msurface_t *surfaces;
13054 unsigned char *update;
13055 int numsurfacelist = 0;
13059 if (r_maxsurfacelist < model->num_surfaces)
13061 r_maxsurfacelist = model->num_surfaces;
13063 Mem_Free((msurface_t**)r_surfacelist);
13064 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13067 RSurf_ActiveWorldEntity();
13069 surfaces = model->data_surfaces;
13070 update = model->brushq1.lightmapupdateflags;
13072 // update light styles on this submodel
13073 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13075 model_brush_lightstyleinfo_t *style;
13076 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13078 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13080 int *list = style->surfacelist;
13081 style->value = r_refdef.scene.lightstylevalue[style->style];
13082 for (j = 0;j < style->numsurfaces;j++)
13083 update[list[j]] = true;
13088 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13092 R_DrawDebugModel();
13093 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13097 rsurface.lightmaptexture = NULL;
13098 rsurface.deluxemaptexture = NULL;
13099 rsurface.uselightmaptexture = false;
13100 rsurface.texture = NULL;
13101 rsurface.rtlight = NULL;
13102 numsurfacelist = 0;
13103 // add visible surfaces to draw list
13104 for (i = 0;i < model->nummodelsurfaces;i++)
13106 j = model->sortedmodelsurfaces[i];
13107 if (r_refdef.viewcache.world_surfacevisible[j])
13108 r_surfacelist[numsurfacelist++] = surfaces + j;
13110 // update lightmaps if needed
13111 if (model->brushq1.firstrender)
13113 model->brushq1.firstrender = false;
13114 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13116 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13120 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13121 if (r_refdef.viewcache.world_surfacevisible[j])
13123 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13125 // don't do anything if there were no surfaces
13126 if (!numsurfacelist)
13128 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13131 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13132 GL_AlphaTest(false);
13134 // add to stats if desired
13135 if (r_speeds.integer && !skysurfaces && !depthonly)
13137 r_refdef.stats.world_surfaces += numsurfacelist;
13138 for (j = 0;j < numsurfacelist;j++)
13139 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13142 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13145 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13147 int i, j, endj, flagsmask;
13148 dp_model_t *model = ent->model;
13149 msurface_t *surfaces;
13150 unsigned char *update;
13151 int numsurfacelist = 0;
13155 if (r_maxsurfacelist < model->num_surfaces)
13157 r_maxsurfacelist = model->num_surfaces;
13159 Mem_Free((msurface_t **)r_surfacelist);
13160 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13163 // if the model is static it doesn't matter what value we give for
13164 // wantnormals and wanttangents, so this logic uses only rules applicable
13165 // to a model, knowing that they are meaningless otherwise
13166 if (ent == r_refdef.scene.worldentity)
13167 RSurf_ActiveWorldEntity();
13168 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13169 RSurf_ActiveModelEntity(ent, false, false, false);
13171 RSurf_ActiveModelEntity(ent, true, true, true);
13172 else if (depthonly)
13174 switch (vid.renderpath)
13176 case RENDERPATH_GL20:
13177 case RENDERPATH_CGGL:
13178 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
13180 case RENDERPATH_GL13:
13181 case RENDERPATH_GL11:
13182 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
13188 switch (vid.renderpath)
13190 case RENDERPATH_GL20:
13191 case RENDERPATH_CGGL:
13192 RSurf_ActiveModelEntity(ent, true, true, false);
13194 case RENDERPATH_GL13:
13195 case RENDERPATH_GL11:
13196 RSurf_ActiveModelEntity(ent, true, false, false);
13201 surfaces = model->data_surfaces;
13202 update = model->brushq1.lightmapupdateflags;
13204 // update light styles
13205 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13207 model_brush_lightstyleinfo_t *style;
13208 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13210 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13212 int *list = style->surfacelist;
13213 style->value = r_refdef.scene.lightstylevalue[style->style];
13214 for (j = 0;j < style->numsurfaces;j++)
13215 update[list[j]] = true;
13220 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13224 R_DrawDebugModel();
13225 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13229 rsurface.lightmaptexture = NULL;
13230 rsurface.deluxemaptexture = NULL;
13231 rsurface.uselightmaptexture = false;
13232 rsurface.texture = NULL;
13233 rsurface.rtlight = NULL;
13234 numsurfacelist = 0;
13235 // add visible surfaces to draw list
13236 for (i = 0;i < model->nummodelsurfaces;i++)
13237 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
13238 // don't do anything if there were no surfaces
13239 if (!numsurfacelist)
13241 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13244 // update lightmaps if needed
13248 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13253 R_BuildLightMap(ent, surfaces + j);
13258 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13260 R_BuildLightMap(ent, surfaces + j);
13261 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13262 GL_AlphaTest(false);
13264 // add to stats if desired
13265 if (r_speeds.integer && !skysurfaces && !depthonly)
13267 r_refdef.stats.entities_surfaces += numsurfacelist;
13268 for (j = 0;j < numsurfacelist;j++)
13269 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
13272 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13275 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13277 static texture_t texture;
13278 static msurface_t surface;
13279 const msurface_t *surfacelist = &surface;
13281 // fake enough texture and surface state to render this geometry
13283 texture.update_lastrenderframe = -1; // regenerate this texture
13284 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
13285 texture.currentskinframe = skinframe;
13286 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
13287 texture.offsetmapping = OFFSETMAPPING_OFF;
13288 texture.offsetscale = 1;
13289 texture.specularscalemod = 1;
13290 texture.specularpowermod = 1;
13292 surface.texture = &texture;
13293 surface.num_triangles = numtriangles;
13294 surface.num_firsttriangle = firsttriangle;
13295 surface.num_vertices = numvertices;
13296 surface.num_firstvertex = firstvertex;
13299 rsurface.texture = R_GetCurrentTexture(surface.texture);
13300 rsurface.lightmaptexture = NULL;
13301 rsurface.deluxemaptexture = NULL;
13302 rsurface.uselightmaptexture = false;
13303 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
13306 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
13308 static msurface_t surface;
13309 const msurface_t *surfacelist = &surface;
13311 // fake enough texture and surface state to render this geometry
13313 surface.texture = texture;
13314 surface.num_triangles = numtriangles;
13315 surface.num_firsttriangle = firsttriangle;
13316 surface.num_vertices = numvertices;
13317 surface.num_firstvertex = firstvertex;
13320 rsurface.texture = R_GetCurrentTexture(surface.texture);
13321 rsurface.lightmaptexture = NULL;
13322 rsurface.deluxemaptexture = NULL;
13323 rsurface.uselightmaptexture = false;
13324 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);