2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 #include "cl_dyntexture.h"
33 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
36 mempool_t *r_main_mempool;
37 rtexturepool_t *r_main_texturepool;
39 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
41 static qboolean r_loadnormalmap;
42 static qboolean r_loadgloss;
44 static qboolean r_loaddds;
45 static qboolean r_savedds;
52 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
53 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
54 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
55 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
56 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
57 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
58 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
59 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
61 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
62 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
63 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
64 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
65 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
67 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
68 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
69 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
70 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
71 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
72 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
73 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
74 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
75 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
76 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
77 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
78 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
79 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
80 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
81 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
82 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
83 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
84 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
85 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
86 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
87 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
88 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
89 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
90 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
91 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
92 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
93 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
94 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
95 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
96 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
97 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
98 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
99 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
100 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
101 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
102 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
103 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
104 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
105 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
106 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
107 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
108 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
109 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
110 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
111 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
112 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
113 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
115 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
116 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
117 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
118 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
119 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
120 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
121 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
122 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
124 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
125 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
127 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
128 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
129 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
130 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
131 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
133 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
134 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
135 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
137 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
138 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
139 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
140 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
141 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
142 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
143 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
144 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
145 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
147 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
148 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
149 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
150 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
151 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
153 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
154 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
155 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
156 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
158 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
159 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
160 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
161 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
162 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
163 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exagerated the glow is"};
164 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
166 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
167 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
168 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
169 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivilant to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
171 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
173 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
175 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
177 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
178 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
179 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accodringly, 2: Make it a continuous rotation"};
180 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
181 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
182 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "0.15", "fake perspective effect for SPR_OVERHEAD sprites"};
183 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "16", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
185 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
187 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "1", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
189 extern cvar_t v_glslgamma;
191 extern qboolean v_flipped_state;
193 static struct r_bloomstate_s
198 int bloomwidth, bloomheight;
200 int screentexturewidth, screentextureheight;
201 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
203 int bloomtexturewidth, bloomtextureheight;
204 rtexture_t *texture_bloom;
206 // arrays for rendering the screen passes
207 float screentexcoord2f[8];
208 float bloomtexcoord2f[8];
209 float offsettexcoord2f[8];
211 r_viewport_t viewport;
215 r_waterstate_t r_waterstate;
217 /// shadow volume bsp struct with automatically growing nodes buffer
220 rtexture_t *r_texture_blanknormalmap;
221 rtexture_t *r_texture_white;
222 rtexture_t *r_texture_grey128;
223 rtexture_t *r_texture_black;
224 rtexture_t *r_texture_notexture;
225 rtexture_t *r_texture_whitecube;
226 rtexture_t *r_texture_normalizationcube;
227 rtexture_t *r_texture_fogattenuation;
228 rtexture_t *r_texture_fogheighttexture;
229 rtexture_t *r_texture_gammaramps;
230 unsigned int r_texture_gammaramps_serial;
231 //rtexture_t *r_texture_fogintensity;
232 rtexture_t *r_texture_reflectcube;
234 // TODO: hash lookups?
235 typedef struct cubemapinfo_s
242 int r_texture_numcubemaps;
243 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
245 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
246 unsigned int r_numqueries;
247 unsigned int r_maxqueries;
249 typedef struct r_qwskincache_s
251 char name[MAX_QPATH];
252 skinframe_t *skinframe;
256 static r_qwskincache_t *r_qwskincache;
257 static int r_qwskincache_size;
259 /// vertex coordinates for a quad that covers the screen exactly
260 extern const float r_screenvertex3f[12];
261 extern const float r_d3dscreenvertex3f[12];
262 const float r_screenvertex3f[12] =
269 const float r_d3dscreenvertex3f[12] =
277 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
280 for (i = 0;i < verts;i++)
291 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
294 for (i = 0;i < verts;i++)
304 // FIXME: move this to client?
307 if (gamemode == GAME_NEHAHRA)
309 Cvar_Set("gl_fogenable", "0");
310 Cvar_Set("gl_fogdensity", "0.2");
311 Cvar_Set("gl_fogred", "0.3");
312 Cvar_Set("gl_foggreen", "0.3");
313 Cvar_Set("gl_fogblue", "0.3");
315 r_refdef.fog_density = 0;
316 r_refdef.fog_red = 0;
317 r_refdef.fog_green = 0;
318 r_refdef.fog_blue = 0;
319 r_refdef.fog_alpha = 1;
320 r_refdef.fog_start = 0;
321 r_refdef.fog_end = 16384;
322 r_refdef.fog_height = 1<<30;
323 r_refdef.fog_fadedepth = 128;
324 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
327 static void R_BuildBlankTextures(void)
329 unsigned char data[4];
330 data[2] = 128; // normal X
331 data[1] = 128; // normal Y
332 data[0] = 255; // normal Z
333 data[3] = 128; // height
334 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
339 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
344 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
349 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
352 static void R_BuildNoTexture(void)
355 unsigned char pix[16][16][4];
356 // this makes a light grey/dark grey checkerboard texture
357 for (y = 0;y < 16;y++)
359 for (x = 0;x < 16;x++)
361 if ((y < 8) ^ (x < 8))
377 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
380 static void R_BuildWhiteCube(void)
382 unsigned char data[6*1*1*4];
383 memset(data, 255, sizeof(data));
384 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
387 static void R_BuildNormalizationCube(void)
391 vec_t s, t, intensity;
394 data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
395 for (side = 0;side < 6;side++)
397 for (y = 0;y < NORMSIZE;y++)
399 for (x = 0;x < NORMSIZE;x++)
401 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
402 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
437 intensity = 127.0f / sqrt(DotProduct(v, v));
438 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
439 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
440 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
441 data[((side*64+y)*64+x)*4+3] = 255;
445 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
449 static void R_BuildFogTexture(void)
453 unsigned char data1[FOGWIDTH][4];
454 //unsigned char data2[FOGWIDTH][4];
457 r_refdef.fogmasktable_start = r_refdef.fog_start;
458 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
459 r_refdef.fogmasktable_range = r_refdef.fogrange;
460 r_refdef.fogmasktable_density = r_refdef.fog_density;
462 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
463 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
465 d = (x * r - r_refdef.fogmasktable_start);
466 if(developer_extra.integer)
467 Con_DPrintf("%f ", d);
469 if (r_fog_exp2.integer)
470 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
472 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
473 if(developer_extra.integer)
474 Con_DPrintf(" : %f ", alpha);
475 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
476 if(developer_extra.integer)
477 Con_DPrintf(" = %f\n", alpha);
478 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
481 for (x = 0;x < FOGWIDTH;x++)
483 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
488 //data2[x][0] = 255 - b;
489 //data2[x][1] = 255 - b;
490 //data2[x][2] = 255 - b;
493 if (r_texture_fogattenuation)
495 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, FOGWIDTH, 1);
496 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, FOGWIDTH, 1);
500 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, -1, NULL);
501 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_ALLOWUPDATES, NULL);
505 static void R_BuildFogHeightTexture(void)
507 unsigned char *inpixels;
515 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
516 if (r_refdef.fogheighttexturename[0])
517 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
520 r_refdef.fog_height_tablesize = 0;
521 if (r_texture_fogheighttexture)
522 R_FreeTexture(r_texture_fogheighttexture);
523 r_texture_fogheighttexture = NULL;
524 if (r_refdef.fog_height_table2d)
525 Mem_Free(r_refdef.fog_height_table2d);
526 r_refdef.fog_height_table2d = NULL;
527 if (r_refdef.fog_height_table1d)
528 Mem_Free(r_refdef.fog_height_table1d);
529 r_refdef.fog_height_table1d = NULL;
533 r_refdef.fog_height_tablesize = size;
534 r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
535 r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
536 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
538 // LordHavoc: now the magic - what is that table2d for? it is a cooked
539 // average fog color table accounting for every fog layer between a point
540 // and the camera. (Note: attenuation is handled separately!)
541 for (y = 0;y < size;y++)
543 for (x = 0;x < size;x++)
549 for (j = x;j <= y;j++)
551 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
557 for (j = x;j >= y;j--)
559 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
564 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
565 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
566 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
567 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
570 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
573 //=======================================================================================================================================================
575 static const char *builtinshaderstring =
576 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
577 "// written by Forest 'LordHavoc' Hale\n"
578 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
580 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
583 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
584 "#define USELIGHTMAP\n"
586 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
587 "#define USEEYEVECTOR\n"
590 "#if defined(USESHADOWMAPRECT) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USEDEFERREDLIGHTMAP)\n"
591 "# extension GL_ARB_texture_rectangle : enable\n"
594 "#ifdef USESHADOWMAP2D\n"
595 "# ifdef GL_EXT_gpu_shader4\n"
596 "# extension GL_EXT_gpu_shader4 : enable\n"
598 "# ifdef GL_ARB_texture_gather\n"
599 "# extension GL_ARB_texture_gather : enable\n"
601 "# ifdef GL_AMD_texture_texture4\n"
602 "# extension GL_AMD_texture_texture4 : enable\n"
607 "#ifdef USESHADOWMAPCUBE\n"
608 "# extension GL_EXT_gpu_shader4 : enable\n"
611 "//#ifdef USESHADOWSAMPLER\n"
612 "//# extension GL_ARB_shadow : enable\n"
615 "//#ifdef __GLSL_CG_DATA_TYPES\n"
616 "//# define myhalf half\n"
617 "//# define myhalf2 half2\n"
618 "//# define myhalf3 half3\n"
619 "//# define myhalf4 half4\n"
621 "# define myhalf float\n"
622 "# define myhalf2 vec2\n"
623 "# define myhalf3 vec3\n"
624 "# define myhalf4 vec4\n"
627 "#ifdef VERTEX_SHADER\n"
628 "uniform mat4 ModelViewProjectionMatrix;\n"
631 "#ifdef MODE_DEPTH_OR_SHADOW\n"
632 "#ifdef VERTEX_SHADER\n"
635 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
638 "#else // !MODE_DEPTH_ORSHADOW\n"
643 "#ifdef MODE_SHOWDEPTH\n"
644 "#ifdef VERTEX_SHADER\n"
647 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
648 " gl_FrontColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
652 "#ifdef FRAGMENT_SHADER\n"
655 " gl_FragColor = gl_Color;\n"
658 "#else // !MODE_SHOWDEPTH\n"
663 "#ifdef MODE_POSTPROCESS\n"
664 "varying vec2 TexCoord1;\n"
665 "varying vec2 TexCoord2;\n"
667 "#ifdef VERTEX_SHADER\n"
670 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
671 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
673 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
678 "#ifdef FRAGMENT_SHADER\n"
679 "uniform sampler2D Texture_First;\n"
681 "uniform sampler2D Texture_Second;\n"
682 "uniform vec4 BloomColorSubtract;\n"
684 "#ifdef USEGAMMARAMPS\n"
685 "uniform sampler2D Texture_GammaRamps;\n"
687 "#ifdef USESATURATION\n"
688 "uniform float Saturation;\n"
690 "#ifdef USEVIEWTINT\n"
691 "uniform vec4 ViewTintColor;\n"
693 "//uncomment these if you want to use them:\n"
694 "uniform vec4 UserVec1;\n"
695 "uniform vec4 UserVec2;\n"
696 "// uniform vec4 UserVec3;\n"
697 "// uniform vec4 UserVec4;\n"
698 "// uniform float ClientTime;\n"
699 "uniform vec2 PixelSize;\n"
702 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
704 " gl_FragColor += max(vec4(0,0,0,0), texture2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
706 "#ifdef USEVIEWTINT\n"
707 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
710 "#ifdef USEPOSTPROCESSING\n"
711 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
712 "// 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"
713 " float sobel = 1.0;\n"
714 " // vec2 ts = textureSize(Texture_First, 0);\n"
715 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
716 " vec2 px = PixelSize;\n"
717 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
718 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
719 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
720 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
721 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
722 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
723 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
724 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
725 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
726 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
727 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
728 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
729 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
730 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
731 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
732 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
733 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
734 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
735 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
736 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
737 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
738 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
739 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
740 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
741 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
742 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
743 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
744 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
745 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
746 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
747 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
748 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
751 "#ifdef USESATURATION\n"
752 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
753 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
754 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
755 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
758 "#ifdef USEGAMMARAMPS\n"
759 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
760 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
761 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
765 "#else // !MODE_POSTPROCESS\n"
770 "#ifdef MODE_GENERIC\n"
771 "#ifdef USEDIFFUSE\n"
772 "varying vec2 TexCoord1;\n"
774 "#ifdef USESPECULAR\n"
775 "varying vec2 TexCoord2;\n"
777 "#ifdef VERTEX_SHADER\n"
780 " gl_FrontColor = gl_Color;\n"
781 "#ifdef USEDIFFUSE\n"
782 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
784 "#ifdef USESPECULAR\n"
785 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
787 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
791 "#ifdef FRAGMENT_SHADER\n"
792 "#ifdef USEDIFFUSE\n"
793 "uniform sampler2D Texture_First;\n"
795 "#ifdef USESPECULAR\n"
796 "uniform sampler2D Texture_Second;\n"
801 " gl_FragColor = gl_Color;\n"
802 "#ifdef USEDIFFUSE\n"
803 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
806 "#ifdef USESPECULAR\n"
807 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
808 "# ifdef USECOLORMAPPING\n"
809 " gl_FragColor *= tex2;\n"
812 " gl_FragColor += tex2;\n"
814 "# ifdef USEVERTEXTEXTUREBLEND\n"
815 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
820 "#else // !MODE_GENERIC\n"
825 "#ifdef MODE_BLOOMBLUR\n"
826 "varying TexCoord;\n"
827 "#ifdef VERTEX_SHADER\n"
830 " gl_FrontColor = gl_Color;\n"
831 " TexCoord = gl_MultiTexCoord0.xy;\n"
832 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
836 "#ifdef FRAGMENT_SHADER\n"
837 "uniform sampler2D Texture_First;\n"
838 "uniform vec4 BloomBlur_Parameters;\n"
843 " vec2 tc = TexCoord;\n"
844 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
845 " tc += BloomBlur_Parameters.xy;\n"
846 " for (i = 1;i < SAMPLES;i++)\n"
848 " color += texture2D(Texture_First, tc).rgb;\n"
849 " tc += BloomBlur_Parameters.xy;\n"
851 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
854 "#else // !MODE_BLOOMBLUR\n"
855 "#ifdef MODE_REFRACTION\n"
856 "varying vec2 TexCoord;\n"
857 "varying vec4 ModelViewProjectionPosition;\n"
858 "uniform mat4 TexMatrix;\n"
859 "#ifdef VERTEX_SHADER\n"
863 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
864 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
865 " ModelViewProjectionPosition = gl_Position;\n"
869 "#ifdef FRAGMENT_SHADER\n"
870 "uniform sampler2D Texture_Normal;\n"
871 "uniform sampler2D Texture_Refraction;\n"
872 "uniform sampler2D Texture_Reflection;\n"
874 "uniform vec4 DistortScaleRefractReflect;\n"
875 "uniform vec4 ScreenScaleRefractReflect;\n"
876 "uniform vec4 ScreenCenterRefractReflect;\n"
877 "uniform vec4 RefractColor;\n"
878 "uniform vec4 ReflectColor;\n"
879 "uniform float ReflectFactor;\n"
880 "uniform float ReflectOffset;\n"
884 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
885 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
886 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
887 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
888 " // FIXME temporary hack to detect the case that the reflection\n"
889 " // gets blackened at edges due to leaving the area that contains actual\n"
891 " // Remove this 'ack once we have a better way to stop this thing from\n"
893 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
894 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
895 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
896 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
897 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
898 " gl_FragColor = texture2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
901 "#else // !MODE_REFRACTION\n"
906 "#ifdef MODE_WATER\n"
907 "varying vec2 TexCoord;\n"
908 "varying vec3 EyeVector;\n"
909 "varying vec4 ModelViewProjectionPosition;\n"
910 "#ifdef VERTEX_SHADER\n"
911 "uniform vec3 EyePosition;\n"
912 "uniform mat4 TexMatrix;\n"
916 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
917 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
918 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
919 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
920 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
921 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
922 " ModelViewProjectionPosition = gl_Position;\n"
926 "#ifdef FRAGMENT_SHADER\n"
927 "uniform sampler2D Texture_Normal;\n"
928 "uniform sampler2D Texture_Refraction;\n"
929 "uniform sampler2D Texture_Reflection;\n"
931 "uniform vec4 DistortScaleRefractReflect;\n"
932 "uniform vec4 ScreenScaleRefractReflect;\n"
933 "uniform vec4 ScreenCenterRefractReflect;\n"
934 "uniform vec4 RefractColor;\n"
935 "uniform vec4 ReflectColor;\n"
936 "uniform float ReflectFactor;\n"
937 "uniform float ReflectOffset;\n"
941 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
942 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
943 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
944 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
945 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
946 " // FIXME temporary hack to detect the case that the reflection\n"
947 " // gets blackened at edges due to leaving the area that contains actual\n"
949 " // Remove this 'ack once we have a better way to stop this thing from\n"
951 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, 0.01)).rgb) / 0.05);\n"
952 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.01, -0.01)).rgb) / 0.05);\n"
953 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
954 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
955 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
956 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, 0.01)).rgb) / 0.05);\n"
957 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.01, -0.01)).rgb) / 0.05);\n"
958 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
959 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
960 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
961 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
962 " gl_FragColor = mix(texture2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, texture2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
965 "#else // !MODE_WATER\n"
970 "// common definitions between vertex shader and fragment shader:\n"
972 "varying vec2 TexCoord;\n"
973 "#ifdef USEVERTEXTEXTUREBLEND\n"
974 "varying vec2 TexCoord2;\n"
976 "#ifdef USELIGHTMAP\n"
977 "varying vec2 TexCoordLightmap;\n"
980 "#ifdef MODE_LIGHTSOURCE\n"
981 "varying vec3 CubeVector;\n"
984 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
985 "varying vec3 LightVector;\n"
988 "#ifdef USEEYEVECTOR\n"
989 "varying vec3 EyeVector;\n"
992 "varying vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
995 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
996 "varying vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
997 "varying vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
998 "varying vec3 VectorR; // direction of R texcoord (surface normal)\n"
1001 "#ifdef USEREFLECTION\n"
1002 "varying vec4 ModelViewProjectionPosition;\n"
1004 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1005 "uniform vec3 LightPosition;\n"
1006 "varying vec4 ModelViewPosition;\n"
1009 "#ifdef MODE_LIGHTSOURCE\n"
1010 "uniform vec3 LightPosition;\n"
1012 "uniform vec3 EyePosition;\n"
1013 "#ifdef MODE_LIGHTDIRECTION\n"
1014 "uniform vec3 LightDir;\n"
1016 "uniform vec4 FogPlane;\n"
1018 "#ifdef USESHADOWMAPORTHO\n"
1019 "varying vec3 ShadowMapTC;\n"
1026 "// 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"
1028 "// fragment shader specific:\n"
1029 "#ifdef FRAGMENT_SHADER\n"
1031 "uniform sampler2D Texture_Normal;\n"
1032 "uniform sampler2D Texture_Color;\n"
1033 "uniform sampler2D Texture_Gloss;\n"
1035 "uniform sampler2D Texture_Glow;\n"
1037 "#ifdef USEVERTEXTEXTUREBLEND\n"
1038 "uniform sampler2D Texture_SecondaryNormal;\n"
1039 "uniform sampler2D Texture_SecondaryColor;\n"
1040 "uniform sampler2D Texture_SecondaryGloss;\n"
1042 "uniform sampler2D Texture_SecondaryGlow;\n"
1045 "#ifdef USECOLORMAPPING\n"
1046 "uniform sampler2D Texture_Pants;\n"
1047 "uniform sampler2D Texture_Shirt;\n"
1050 "#ifdef USEFOGHEIGHTTEXTURE\n"
1051 "uniform sampler2D Texture_FogHeightTexture;\n"
1053 "uniform sampler2D Texture_FogMask;\n"
1055 "#ifdef USELIGHTMAP\n"
1056 "uniform sampler2D Texture_Lightmap;\n"
1058 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1059 "uniform sampler2D Texture_Deluxemap;\n"
1061 "#ifdef USEREFLECTION\n"
1062 "uniform sampler2D Texture_Reflection;\n"
1065 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1066 "uniform sampler2D Texture_ScreenDepth;\n"
1067 "uniform sampler2D Texture_ScreenNormalMap;\n"
1069 "#ifdef USEDEFERREDLIGHTMAP\n"
1070 "uniform sampler2D Texture_ScreenDiffuse;\n"
1071 "uniform sampler2D Texture_ScreenSpecular;\n"
1074 "uniform myhalf3 Color_Pants;\n"
1075 "uniform myhalf3 Color_Shirt;\n"
1076 "uniform myhalf3 FogColor;\n"
1079 "uniform float FogRangeRecip;\n"
1080 "uniform float FogPlaneViewDist;\n"
1081 "uniform float FogHeightFade;\n"
1082 "vec3 FogVertex(vec3 surfacecolor)\n"
1084 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1085 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1087 "#ifdef USEFOGHEIGHTTEXTURE\n"
1088 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1089 " fogfrac = fogheightpixel.a;\n"
1090 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1092 "# ifdef USEFOGOUTSIDE\n"
1093 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1095 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1097 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1102 "#ifdef USEOFFSETMAPPING\n"
1103 "uniform float OffsetMapping_Scale;\n"
1104 "vec2 OffsetMapping(vec2 TexCoord)\n"
1106 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1107 " // 14 sample relief mapping: linear search and then binary search\n"
1108 " // this basically steps forward a small amount repeatedly until it finds\n"
1109 " // itself inside solid, then jitters forward and back using decreasing\n"
1110 " // amounts to find the impact\n"
1111 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1112 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1113 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1114 " vec3 RT = vec3(TexCoord, 1);\n"
1115 " OffsetVector *= 0.1;\n"
1116 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1117 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1118 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1119 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1120 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1121 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1122 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1123 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1124 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1125 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1126 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1127 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1128 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1129 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1132 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1133 " // this basically moves forward the full distance, and then backs up based\n"
1134 " // on height of samples\n"
1135 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1136 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1137 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1138 " TexCoord += OffsetVector;\n"
1139 " OffsetVector *= 0.333;\n"
1140 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1141 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1142 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1143 " return TexCoord;\n"
1146 "#endif // USEOFFSETMAPPING\n"
1148 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1149 "uniform sampler2D Texture_Attenuation;\n"
1150 "uniform samplerCube Texture_Cube;\n"
1153 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1155 "#ifdef USESHADOWMAPRECT\n"
1156 "# ifdef USESHADOWSAMPLER\n"
1157 "uniform sampler2DRectShadow Texture_ShadowMapRect;\n"
1159 "uniform sampler2DRect Texture_ShadowMapRect;\n"
1163 "#ifdef USESHADOWMAP2D\n"
1164 "# ifdef USESHADOWSAMPLER\n"
1165 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1167 "uniform sampler2D Texture_ShadowMap2D;\n"
1171 "#ifdef USESHADOWMAPVSDCT\n"
1172 "uniform samplerCube Texture_CubeProjection;\n"
1175 "#ifdef USESHADOWMAPCUBE\n"
1176 "# ifdef USESHADOWSAMPLER\n"
1177 "uniform samplerCubeShadow Texture_ShadowMapCube;\n"
1179 "uniform samplerCube Texture_ShadowMapCube;\n"
1183 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
1184 "uniform vec2 ShadowMap_TextureScale;\n"
1185 "uniform vec4 ShadowMap_Parameters;\n"
1188 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1189 "# ifdef USESHADOWMAPORTHO\n"
1190 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1192 "# ifdef USESHADOWMAPVSDCT\n"
1193 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1195 " vec3 adir = abs(dir);\n"
1196 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1197 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1198 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1201 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1203 " vec3 adir = abs(dir);\n"
1204 " float ma = adir.z;\n"
1205 " vec4 proj = vec4(dir, 2.5);\n"
1206 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1207 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1208 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1209 " 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"
1213 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
1215 "#ifdef USESHADOWMAPCUBE\n"
1216 "vec4 GetShadowMapTCCube(vec3 dir)\n"
1218 " vec3 adir = abs(dir);\n"
1219 " return vec4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
1223 "# ifdef USESHADOWMAPRECT\n"
1224 "float ShadowMapCompare(vec3 dir)\n"
1226 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1228 "# ifdef USESHADOWSAMPLER\n"
1230 "# ifdef USESHADOWMAPPCF\n"
1231 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + vec3(x, y, 0.0)).r\n"
1232 " 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"
1234 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
1239 "# ifdef USESHADOWMAPPCF\n"
1240 "# if USESHADOWMAPPCF > 1\n"
1241 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, center + vec2(x, y)).r\n"
1242 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1243 " 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"
1244 " 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"
1245 " 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"
1246 " 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"
1247 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1248 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1250 "# define texval(x, y) texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy + vec2(x, y)).r\n"
1251 " vec2 offset = fract(shadowmaptc.xy);\n"
1252 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1253 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1254 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1255 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1256 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1259 " f = step(shadowmaptc.z, texture2DRect(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
1263 "# ifdef USESHADOWMAPORTHO\n"
1264 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1271 "# ifdef USESHADOWMAP2D\n"
1272 "float ShadowMapCompare(vec3 dir)\n"
1274 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1277 "# ifdef USESHADOWSAMPLER\n"
1278 "# ifdef USESHADOWMAPPCF\n"
1279 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1280 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1281 " 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"
1283 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1286 "# ifdef USESHADOWMAPPCF\n"
1287 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1288 "# ifdef GL_ARB_texture_gather\n"
1289 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1291 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1293 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1294 "# if USESHADOWMAPPCF > 1\n"
1295 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1296 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1297 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1298 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1299 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1300 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1301 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1302 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1303 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1304 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1305 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1306 " locols.yz += group2.ab;\n"
1307 " hicols.yz += group8.rg;\n"
1308 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1309 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1310 " mix(locols, hicols, offset.y);\n"
1311 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1312 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1313 " f = dot(cols, vec4(1.0/25.0));\n"
1315 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1316 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1317 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1318 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1319 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1320 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1321 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1324 "# ifdef GL_EXT_gpu_shader4\n"
1325 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1327 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1329 "# if USESHADOWMAPPCF > 1\n"
1330 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1331 " center *= ShadowMap_TextureScale;\n"
1332 " 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"
1333 " 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"
1334 " 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"
1335 " 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"
1336 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1337 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1339 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1340 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1341 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1342 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1343 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1344 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1348 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1351 "# ifdef USESHADOWMAPORTHO\n"
1352 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1359 "# ifdef USESHADOWMAPCUBE\n"
1360 "float ShadowMapCompare(vec3 dir)\n"
1362 " // apply depth texture cubemap as light filter\n"
1363 " vec4 shadowmaptc = GetShadowMapTCCube(dir);\n"
1365 "# ifdef USESHADOWSAMPLER\n"
1366 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
1368 " f = step(shadowmaptc.w, textureCube(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
1373 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1374 "#endif // FRAGMENT_SHADER\n"
1379 "#ifdef MODE_DEFERREDGEOMETRY\n"
1380 "#ifdef VERTEX_SHADER\n"
1381 "uniform mat4 TexMatrix;\n"
1382 "#ifdef USEVERTEXTEXTUREBLEND\n"
1383 "uniform mat4 BackgroundTexMatrix;\n"
1385 "uniform mat4 ModelViewMatrix;\n"
1388 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1389 "#ifdef USEVERTEXTEXTUREBLEND\n"
1390 " gl_FrontColor = gl_Color;\n"
1391 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1394 " // transform unnormalized eye direction into tangent space\n"
1395 "#ifdef USEOFFSETMAPPING\n"
1396 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1397 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1398 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1399 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1402 " VectorS = (ModelViewMatrix * vec4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
1403 " VectorT = (ModelViewMatrix * vec4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
1404 " VectorR = (ModelViewMatrix * vec4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
1405 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1407 "#endif // VERTEX_SHADER\n"
1409 "#ifdef FRAGMENT_SHADER\n"
1412 "#ifdef USEOFFSETMAPPING\n"
1413 " // apply offsetmapping\n"
1414 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1415 "#define TexCoord TexCoordOffset\n"
1418 "#ifdef USEALPHAKILL\n"
1419 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1423 "#ifdef USEVERTEXTEXTUREBLEND\n"
1424 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1425 " float terrainblend = clamp(float(gl_Color.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1426 " //float terrainblend = min(float(gl_Color.a) * alpha * 2.0, float(1.0));\n"
1427 " //float terrainblend = float(gl_Color.a) * alpha > 0.5;\n"
1430 "#ifdef USEVERTEXTEXTUREBLEND\n"
1431 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1432 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1434 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1435 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1438 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1440 "#endif // FRAGMENT_SHADER\n"
1441 "#else // !MODE_DEFERREDGEOMETRY\n"
1446 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1447 "#ifdef VERTEX_SHADER\n"
1448 "uniform mat4 ModelViewMatrix;\n"
1451 " ModelViewPosition = ModelViewMatrix * gl_Vertex;\n"
1452 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1454 "#endif // VERTEX_SHADER\n"
1456 "#ifdef FRAGMENT_SHADER\n"
1457 "uniform mat4 ViewToLight;\n"
1458 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1459 "uniform vec2 ScreenToDepth;\n"
1460 "uniform myhalf3 DeferredColor_Ambient;\n"
1461 "uniform myhalf3 DeferredColor_Diffuse;\n"
1462 "#ifdef USESPECULAR\n"
1463 "uniform myhalf3 DeferredColor_Specular;\n"
1464 "uniform myhalf SpecularPower;\n"
1466 "uniform myhalf2 PixelToScreenTexCoord;\n"
1469 " // calculate viewspace pixel position\n"
1470 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1472 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1473 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1474 " // decode viewspace pixel normal\n"
1475 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1476 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1477 " // surfacenormal = pixel normal in viewspace\n"
1478 " // LightVector = pixel to light in viewspace\n"
1479 " // CubeVector = position in lightspace\n"
1480 " // eyevector = pixel to view in viewspace\n"
1481 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1482 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1483 "#ifdef USEDIFFUSE\n"
1484 " // calculate diffuse shading\n"
1485 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1486 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1488 "#ifdef USESPECULAR\n"
1489 " // calculate directional shading\n"
1490 " vec3 eyevector = position * -1.0;\n"
1491 "# ifdef USEEXACTSPECULARMATH\n"
1492 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1494 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1495 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1499 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1500 " fade *= ShadowMapCompare(CubeVector);\n"
1503 "#ifdef USEDIFFUSE\n"
1504 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1506 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1508 "#ifdef USESPECULAR\n"
1509 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1511 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1514 "# ifdef USECUBEFILTER\n"
1515 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1516 " gl_FragData[0].rgb *= cubecolor;\n"
1517 " gl_FragData[1].rgb *= cubecolor;\n"
1520 "#endif // FRAGMENT_SHADER\n"
1521 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1526 "#ifdef VERTEX_SHADER\n"
1527 "uniform mat4 TexMatrix;\n"
1528 "#ifdef USEVERTEXTEXTUREBLEND\n"
1529 "uniform mat4 BackgroundTexMatrix;\n"
1531 "#ifdef MODE_LIGHTSOURCE\n"
1532 "uniform mat4 ModelToLight;\n"
1534 "#ifdef USESHADOWMAPORTHO\n"
1535 "uniform mat4 ShadowMapMatrix;\n"
1539 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1540 " gl_FrontColor = gl_Color;\n"
1542 " // copy the surface texcoord\n"
1543 " TexCoord = vec2(TexMatrix * gl_MultiTexCoord0);\n"
1544 "#ifdef USEVERTEXTEXTUREBLEND\n"
1545 " TexCoord2 = vec2(BackgroundTexMatrix * gl_MultiTexCoord0);\n"
1547 "#ifdef USELIGHTMAP\n"
1548 " TexCoordLightmap = vec2(gl_MultiTexCoord4);\n"
1551 "#ifdef MODE_LIGHTSOURCE\n"
1552 " // transform vertex position into light attenuation/cubemap space\n"
1553 " // (-1 to +1 across the light box)\n"
1554 " CubeVector = vec3(ModelToLight * gl_Vertex);\n"
1556 "# ifdef USEDIFFUSE\n"
1557 " // transform unnormalized light direction into tangent space\n"
1558 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1559 " // normalize it per pixel)\n"
1560 " vec3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
1561 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
1562 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
1563 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
1567 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1568 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
1569 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
1570 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
1573 " // transform unnormalized eye direction into tangent space\n"
1574 "#ifdef USEEYEVECTOR\n"
1575 " vec3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
1576 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
1577 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
1578 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
1582 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
1583 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
1586 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1587 " VectorS = gl_MultiTexCoord1.xyz;\n"
1588 " VectorT = gl_MultiTexCoord2.xyz;\n"
1589 " VectorR = gl_MultiTexCoord3.xyz;\n"
1592 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1593 " gl_Position = ModelViewProjectionMatrix * gl_Vertex;\n"
1595 "#ifdef USESHADOWMAPORTHO\n"
1596 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1599 "#ifdef USEREFLECTION\n"
1600 " ModelViewProjectionPosition = gl_Position;\n"
1603 "#endif // VERTEX_SHADER\n"
1608 "#ifdef FRAGMENT_SHADER\n"
1609 "#ifdef USEDEFERREDLIGHTMAP\n"
1610 "uniform myhalf2 PixelToScreenTexCoord;\n"
1611 "uniform myhalf3 DeferredMod_Diffuse;\n"
1612 "uniform myhalf3 DeferredMod_Specular;\n"
1614 "uniform myhalf3 Color_Ambient;\n"
1615 "uniform myhalf3 Color_Diffuse;\n"
1616 "uniform myhalf3 Color_Specular;\n"
1617 "uniform myhalf SpecularPower;\n"
1619 "uniform myhalf3 Color_Glow;\n"
1621 "uniform myhalf Alpha;\n"
1622 "#ifdef USEREFLECTION\n"
1623 "uniform vec4 DistortScaleRefractReflect;\n"
1624 "uniform vec4 ScreenScaleRefractReflect;\n"
1625 "uniform vec4 ScreenCenterRefractReflect;\n"
1626 "uniform myhalf4 ReflectColor;\n"
1628 "#ifdef USEREFLECTCUBE\n"
1629 "uniform mat4 ModelToReflectCube;\n"
1630 "uniform sampler2D Texture_ReflectMask;\n"
1631 "uniform samplerCube Texture_ReflectCube;\n"
1633 "#ifdef MODE_LIGHTDIRECTION\n"
1634 "uniform myhalf3 LightColor;\n"
1636 "#ifdef MODE_LIGHTSOURCE\n"
1637 "uniform myhalf3 LightColor;\n"
1641 "#ifdef USEOFFSETMAPPING\n"
1642 " // apply offsetmapping\n"
1643 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1644 "#define TexCoord TexCoordOffset\n"
1647 " // combine the diffuse textures (base, pants, shirt)\n"
1648 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1649 "#ifdef USEALPHAKILL\n"
1650 " if (color.a < 0.5)\n"
1653 " color.a *= Alpha;\n"
1654 "#ifdef USECOLORMAPPING\n"
1655 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1657 "#ifdef USEVERTEXTEXTUREBLEND\n"
1658 " myhalf terrainblend = clamp(myhalf(gl_Color.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1659 " //myhalf terrainblend = min(myhalf(gl_Color.a) * color.a * 2.0, myhalf(1.0));\n"
1660 " //myhalf terrainblend = myhalf(gl_Color.a) * color.a > 0.5;\n"
1661 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1663 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1666 " // get the surface normal\n"
1667 "#ifdef USEVERTEXTEXTUREBLEND\n"
1668 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1670 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1673 " // get the material colors\n"
1674 " myhalf3 diffusetex = color.rgb;\n"
1675 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1676 "# ifdef USEVERTEXTEXTUREBLEND\n"
1677 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1679 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1683 "#ifdef USEREFLECTCUBE\n"
1684 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1685 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1686 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1687 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1693 "#ifdef MODE_LIGHTSOURCE\n"
1694 " // light source\n"
1695 "#ifdef USEDIFFUSE\n"
1696 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1697 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1698 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1699 "#ifdef USESPECULAR\n"
1700 "#ifdef USEEXACTSPECULARMATH\n"
1701 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1703 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1704 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1706 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1709 " color.rgb = diffusetex * Color_Ambient;\n"
1711 " color.rgb *= LightColor;\n"
1712 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1713 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
1714 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1716 "# ifdef USECUBEFILTER\n"
1717 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1719 "#endif // MODE_LIGHTSOURCE\n"
1724 "#ifdef MODE_LIGHTDIRECTION\n"
1726 "#ifdef USEDIFFUSE\n"
1727 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1729 "#define lightcolor LightColor\n"
1730 "#endif // MODE_LIGHTDIRECTION\n"
1731 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1733 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1734 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1735 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1736 " // convert modelspace light vector to tangentspace\n"
1737 " myhalf3 lightnormal;\n"
1738 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1739 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1740 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1741 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1742 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1743 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1744 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1745 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1746 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1747 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1748 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1749 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1750 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1751 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1752 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1754 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1755 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1756 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1762 "#ifdef MODE_LIGHTMAP\n"
1763 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1764 "#endif // MODE_LIGHTMAP\n"
1765 "#ifdef MODE_VERTEXCOLOR\n"
1766 " color.rgb = diffusetex * (Color_Ambient + myhalf3(gl_Color.rgb) * Color_Diffuse);\n"
1767 "#endif // MODE_VERTEXCOLOR\n"
1768 "#ifdef MODE_FLATCOLOR\n"
1769 " color.rgb = diffusetex * Color_Ambient;\n"
1770 "#endif // MODE_FLATCOLOR\n"
1776 "# ifdef USEDIFFUSE\n"
1777 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1778 "# ifdef USESPECULAR\n"
1779 "# ifdef USEEXACTSPECULARMATH\n"
1780 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1782 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1783 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1785 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1787 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1790 " color.rgb = diffusetex * Color_Ambient;\n"
1794 "#ifdef USESHADOWMAPORTHO\n"
1795 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1798 "#ifdef USEDEFERREDLIGHTMAP\n"
1799 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1800 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1801 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1805 "#ifdef USEVERTEXTEXTUREBLEND\n"
1806 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1808 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1813 " color.rgb = FogVertex(color.rgb);\n"
1816 " // 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"
1817 "#ifdef USEREFLECTION\n"
1818 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1819 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1820 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1821 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1822 " // FIXME temporary hack to detect the case that the reflection\n"
1823 " // gets blackened at edges due to leaving the area that contains actual\n"
1825 " // Remove this 'ack once we have a better way to stop this thing from\n"
1827 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1828 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1829 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1830 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1831 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1832 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1835 " gl_FragColor = vec4(color);\n"
1837 "#endif // FRAGMENT_SHADER\n"
1839 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1840 "#endif // !MODE_DEFERREDGEOMETRY\n"
1841 "#endif // !MODE_WATER\n"
1842 "#endif // !MODE_REFRACTION\n"
1843 "#endif // !MODE_BLOOMBLUR\n"
1844 "#endif // !MODE_GENERIC\n"
1845 "#endif // !MODE_POSTPROCESS\n"
1846 "#endif // !MODE_SHOWDEPTH\n"
1847 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1851 =========================================================================================================================================================
1855 =========================================================================================================================================================
1859 =========================================================================================================================================================
1863 =========================================================================================================================================================
1867 =========================================================================================================================================================
1871 =========================================================================================================================================================
1875 =========================================================================================================================================================
1878 const char *builtincgshaderstring =
1879 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1880 "// written by Forest 'LordHavoc' Hale\n"
1881 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1883 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1884 "#if defined(USEREFLECTION)\n"
1885 "#undef USESHADOWMAPORTHO\n"
1888 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1891 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1892 "#define USELIGHTMAP\n"
1894 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE)\n"
1895 "#define USEEYEVECTOR\n"
1898 "#ifdef FRAGMENT_SHADER\n"
1900 "//#undef USESHADOWMAPPCF\n"
1901 "//#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1902 "#define texDepth2D(tex,texcoord) dot(tex2D(tex,texcoord).rgb, float3(1.0, 255.0/65536.0, 255.0/16777216.0))\n"
1904 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1908 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1909 "#ifdef VERTEX_SHADER\n"
1912 "float4 gl_Vertex : POSITION,\n"
1913 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1914 "out float4 gl_Position : POSITION,\n"
1915 "out float Depth : TEXCOORD0\n"
1918 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1919 " Depth = gl_Position.z;\n"
1923 "#ifdef FRAGMENT_SHADER\n"
1926 "float Depth : TEXCOORD0,\n"
1927 "out float4 gl_FragColor : COLOR\n"
1930 "// float3 temp = float3(Depth,Depth*(65536.0/255.0),Depth*(16777216.0/255.0));\n"
1931 " float3 temp = float3(Depth,Depth*256.0,Depth*65536.0);\n"
1932 " temp.yz -= floor(temp.yz);\n"
1933 " gl_FragColor = float4(temp,0);\n"
1934 "// gl_FragColor = float4(Depth,0,0,0);\n"
1937 "#else // !MODE_DEPTH_ORSHADOW\n"
1942 "#ifdef MODE_SHOWDEPTH\n"
1943 "#ifdef VERTEX_SHADER\n"
1946 "float4 gl_Vertex : POSITION,\n"
1947 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1948 "out float4 gl_Position : POSITION,\n"
1949 "out float4 gl_FrontColor : COLOR0\n"
1952 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1953 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1957 "#ifdef FRAGMENT_SHADER\n"
1960 "float4 gl_FrontColor : COLOR0,\n"
1961 "out float4 gl_FragColor : COLOR\n"
1964 " gl_FragColor = gl_FrontColor;\n"
1967 "#else // !MODE_SHOWDEPTH\n"
1972 "#ifdef MODE_POSTPROCESS\n"
1974 "#ifdef VERTEX_SHADER\n"
1977 "float4 gl_Vertex : POSITION,\n"
1978 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1979 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
1980 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
1981 "out float4 gl_Position : POSITION,\n"
1982 "out float2 TexCoord1 : TEXCOORD0,\n"
1983 "out float2 TexCoord2 : TEXCOORD1\n"
1986 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1987 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
1989 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
1994 "#ifdef FRAGMENT_SHADER\n"
1997 "float2 TexCoord1 : TEXCOORD0,\n"
1998 "float2 TexCoord2 : TEXCOORD1,\n"
1999 "uniform sampler Texture_First : register(s0),\n"
2001 "uniform sampler Texture_Second : register(s1),\n"
2003 "#ifdef USEGAMMARAMPS\n"
2004 "uniform sampler Texture_GammaRamps : register(s2),\n"
2006 "#ifdef USESATURATION\n"
2007 "uniform float Saturation : register(c30),\n"
2009 "#ifdef USEVIEWTINT\n"
2010 "uniform float4 ViewTintColor : register(c41),\n"
2012 "uniform float4 UserVec1 : register(c37),\n"
2013 "uniform float4 UserVec2 : register(c38),\n"
2014 "uniform float4 UserVec3 : register(c39),\n"
2015 "uniform float4 UserVec4 : register(c40),\n"
2016 "uniform float ClientTime : register(c2),\n"
2017 "uniform float2 PixelSize : register(c25),\n"
2018 "uniform float4 BloomColorSubtract : register(c43),\n"
2019 "out float4 gl_FragColor : COLOR\n"
2022 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
2024 " gl_FragColor += max(float4(0,0,0,0), tex2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
2026 "#ifdef USEVIEWTINT\n"
2027 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
2030 "#ifdef USEPOSTPROCESSING\n"
2031 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
2032 "// 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"
2033 " float sobel = 1.0;\n"
2034 " // float2 ts = textureSize(Texture_First, 0);\n"
2035 " // float2 px = float2(1/ts.x, 1/ts.y);\n"
2036 " float2 px = PixelSize;\n"
2037 " float3 x1 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2038 " float3 x2 = tex2D(Texture_First, TexCoord1 + float2(-px.x, 0.0)).rgb;\n"
2039 " float3 x3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2040 " float3 x4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2041 " float3 x5 = tex2D(Texture_First, TexCoord1 + float2( px.x, 0.0)).rgb;\n"
2042 " float3 x6 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2043 " float3 y1 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2044 " float3 y2 = tex2D(Texture_First, TexCoord1 + float2( 0.0,-px.y)).rgb;\n"
2045 " float3 y3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2046 " float3 y4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2047 " float3 y5 = tex2D(Texture_First, TexCoord1 + float2( 0.0, px.y)).rgb;\n"
2048 " float3 y6 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2049 " float px1 = -1.0 * dot(float3(0.3, 0.59, 0.11), x1);\n"
2050 " float px2 = -2.0 * dot(float3(0.3, 0.59, 0.11), x2);\n"
2051 " float px3 = -1.0 * dot(float3(0.3, 0.59, 0.11), x3);\n"
2052 " float px4 = 1.0 * dot(float3(0.3, 0.59, 0.11), x4);\n"
2053 " float px5 = 2.0 * dot(float3(0.3, 0.59, 0.11), x5);\n"
2054 " float px6 = 1.0 * dot(float3(0.3, 0.59, 0.11), x6);\n"
2055 " float py1 = -1.0 * dot(float3(0.3, 0.59, 0.11), y1);\n"
2056 " float py2 = -2.0 * dot(float3(0.3, 0.59, 0.11), y2);\n"
2057 " float py3 = -1.0 * dot(float3(0.3, 0.59, 0.11), y3);\n"
2058 " float py4 = 1.0 * dot(float3(0.3, 0.59, 0.11), y4);\n"
2059 " float py5 = 2.0 * dot(float3(0.3, 0.59, 0.11), y5);\n"
2060 " float py6 = 1.0 * dot(float3(0.3, 0.59, 0.11), y6);\n"
2061 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
2062 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
2063 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
2064 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
2065 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
2066 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
2067 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
2068 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + float3(1,1,1)*max(0.0, sobel - UserVec2.z)*UserVec2.y;\n"
2071 "#ifdef USESATURATION\n"
2072 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2073 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2074 " //gl_FragColor = float3(y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2075 " gl_FragColor.rgb = lerp(float3(y), gl_FragColor.rgb, Saturation);\n"
2078 "#ifdef USEGAMMARAMPS\n"
2079 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2080 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2081 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2085 "#else // !MODE_POSTPROCESS\n"
2090 "#ifdef MODE_GENERIC\n"
2091 "#ifdef VERTEX_SHADER\n"
2094 "float4 gl_Vertex : POSITION,\n"
2095 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2096 "float4 gl_Color : COLOR0,\n"
2097 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2098 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2099 "out float4 gl_Position : POSITION,\n"
2100 "out float4 gl_FrontColor : COLOR,\n"
2101 "out float2 TexCoord1 : TEXCOORD0,\n"
2102 "out float2 TexCoord2 : TEXCOORD1\n"
2106 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2108 " gl_FrontColor = gl_Color; // Cg is forward\n"
2110 "#ifdef USEDIFFUSE\n"
2111 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2113 "#ifdef USESPECULAR\n"
2114 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2116 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2120 "#ifdef FRAGMENT_SHADER\n"
2124 "float4 gl_FrontColor : COLOR0,\n"
2125 "float2 TexCoord1 : TEXCOORD0,\n"
2126 "float2 TexCoord2 : TEXCOORD1,\n"
2127 "#ifdef USEDIFFUSE\n"
2128 "uniform sampler Texture_First : register(s0),\n"
2130 "#ifdef USESPECULAR\n"
2131 "uniform sampler Texture_Second : register(s1),\n"
2133 "out float4 gl_FragColor : COLOR\n"
2136 " gl_FragColor = gl_FrontColor;\n"
2137 "#ifdef USEDIFFUSE\n"
2138 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2141 "#ifdef USESPECULAR\n"
2142 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2143 "# ifdef USECOLORMAPPING\n"
2144 " gl_FragColor *= tex2;\n"
2147 " gl_FragColor += tex2;\n"
2149 "# ifdef USEVERTEXTEXTUREBLEND\n"
2150 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2155 "#else // !MODE_GENERIC\n"
2160 "#ifdef MODE_BLOOMBLUR\n"
2161 "#ifdef VERTEX_SHADER\n"
2164 "float4 gl_Vertex : POSITION,\n"
2165 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2166 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2167 "out float4 gl_Position : POSITION,\n"
2168 "out float2 TexCoord : TEXCOORD0\n"
2171 " TexCoord = gl_MultiTexCoord0.xy;\n"
2172 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2176 "#ifdef FRAGMENT_SHADER\n"
2180 "float2 TexCoord : TEXCOORD0,\n"
2181 "uniform sampler Texture_First : register(s0),\n"
2182 "uniform float4 BloomBlur_Parameters : register(c1),\n"
2183 "out float4 gl_FragColor : COLOR\n"
2187 " float2 tc = TexCoord;\n"
2188 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2189 " tc += BloomBlur_Parameters.xy;\n"
2190 " for (i = 1;i < SAMPLES;i++)\n"
2192 " color += tex2D(Texture_First, tc).rgb;\n"
2193 " tc += BloomBlur_Parameters.xy;\n"
2195 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2198 "#else // !MODE_BLOOMBLUR\n"
2199 "#ifdef MODE_REFRACTION\n"
2200 "#ifdef VERTEX_SHADER\n"
2203 "float4 gl_Vertex : POSITION,\n"
2204 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2205 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2206 "uniform float4x4 TexMatrix : register(c0),\n"
2207 "uniform float3 EyePosition : register(c24),\n"
2208 "out float4 gl_Position : POSITION,\n"
2209 "out float2 TexCoord : TEXCOORD0,\n"
2210 "out float3 EyeVector : TEXCOORD1,\n"
2211 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2214 " TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2215 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2216 " ModelViewProjectionPosition = gl_Position;\n"
2220 "#ifdef FRAGMENT_SHADER\n"
2223 "float2 TexCoord : TEXCOORD0,\n"
2224 "float3 EyeVector : TEXCOORD1,\n"
2225 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2226 "uniform sampler Texture_Normal : register(s0),\n"
2227 "uniform sampler Texture_Refraction : register(s3),\n"
2228 "uniform sampler Texture_Reflection : register(s7),\n"
2229 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2230 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2231 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2232 "uniform float4 RefractColor : register(c29),\n"
2233 "out float4 gl_FragColor : COLOR\n"
2236 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2237 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2238 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2239 " float2 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.xy;\n"
2240 " // FIXME temporary hack to detect the case that the reflection\n"
2241 " // gets blackened at edges due to leaving the area that contains actual\n"
2243 " // Remove this 'ack once we have a better way to stop this thing from\n"
2245 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2246 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2247 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2248 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2249 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2250 " gl_FragColor = tex2D(Texture_Refraction, ScreenTexCoord) * RefractColor;\n"
2253 "#else // !MODE_REFRACTION\n"
2258 "#ifdef MODE_WATER\n"
2259 "#ifdef VERTEX_SHADER\n"
2263 "float4 gl_Vertex : POSITION,\n"
2264 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2265 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2266 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2267 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2268 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2269 "uniform float4x4 TexMatrix : register(c0),\n"
2270 "uniform float3 EyePosition : register(c24),\n"
2271 "out float4 gl_Position : POSITION,\n"
2272 "out float2 TexCoord : TEXCOORD0,\n"
2273 "out float3 EyeVector : TEXCOORD1,\n"
2274 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2277 " TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2278 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2279 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2280 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2281 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2282 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2283 " ModelViewProjectionPosition = gl_Position;\n"
2287 "#ifdef FRAGMENT_SHADER\n"
2290 "float2 TexCoord : TEXCOORD0,\n"
2291 "float3 EyeVector : TEXCOORD1,\n"
2292 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2293 "uniform sampler Texture_Normal : register(s0),\n"
2294 "uniform sampler Texture_Refraction : register(s3),\n"
2295 "uniform sampler Texture_Reflection : register(s7),\n"
2296 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2297 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2298 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2299 "uniform float4 RefractColor : register(c29),\n"
2300 "uniform float4 ReflectColor : register(c26),\n"
2301 "uniform float ReflectFactor : register(c27),\n"
2302 "uniform float ReflectOffset : register(c28),\n"
2303 "out float4 gl_FragColor : COLOR\n"
2306 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2307 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2308 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2309 " //SafeScreenTexCoord = gl_FragCoord.xyxy * float4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
2310 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5))).xyxy * DistortScaleRefractReflect;\n"
2311 " // FIXME temporary hack to detect the case that the reflection\n"
2312 " // gets blackened at edges due to leaving the area that contains actual\n"
2314 " // Remove this 'ack once we have a better way to stop this thing from\n"
2316 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2317 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2318 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2319 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2320 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2321 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2322 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2323 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2324 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2325 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2326 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2327 " gl_FragColor = lerp(tex2D(Texture_Refraction, ScreenTexCoord.xy) * RefractColor, tex2D(Texture_Reflection, ScreenTexCoord.zw) * ReflectColor, Fresnel);\n"
2330 "#else // !MODE_WATER\n"
2335 "// 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"
2337 "// fragment shader specific:\n"
2338 "#ifdef FRAGMENT_SHADER\n"
2341 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler Texture_FogMask, sampler Texture_FogHeightTexture)\n"
2344 "#ifdef USEFOGHEIGHTTEXTURE\n"
2345 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2346 " fogfrac = fogheightpixel.a;\n"
2347 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2349 "# ifdef USEFOGOUTSIDE\n"
2350 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2352 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2354 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2359 "#ifdef USEOFFSETMAPPING\n"
2360 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler Texture_Normal)\n"
2362 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2363 " // 14 sample relief mapping: linear search and then binary search\n"
2364 " // this basically steps forward a small amount repeatedly until it finds\n"
2365 " // itself inside solid, then jitters forward and back using decreasing\n"
2366 " // amounts to find the impact\n"
2367 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2368 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2369 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2370 " float3 RT = float3(TexCoord, 1);\n"
2371 " OffsetVector *= 0.1;\n"
2372 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2373 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2374 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2375 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2376 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2377 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2378 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2379 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2380 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2381 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2382 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2383 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2384 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2385 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2388 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2389 " // this basically moves forward the full distance, and then backs up based\n"
2390 " // on height of samples\n"
2391 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2392 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2393 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2394 " TexCoord += OffsetVector;\n"
2395 " OffsetVector *= 0.333;\n"
2396 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2397 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2398 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2399 " return TexCoord;\n"
2402 "#endif // USEOFFSETMAPPING\n"
2404 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2405 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2406 "# ifdef USESHADOWMAPORTHO\n"
2407 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2409 "# ifdef USESHADOWMAPVSDCT\n"
2410 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2412 " float3 adir = abs(dir);\n"
2413 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2414 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2415 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2418 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2420 " float3 adir = abs(dir);\n"
2421 " float ma = adir.z;\n"
2422 " float4 proj = float4(dir, 2.5);\n"
2423 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2424 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2426 " return float3(proj.xy * ShadowMap_Parameters.x / ma + float2(0.5,0.5) + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, ma + 64 * ShadowMap_Parameters.w);\n"
2428 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2429 " 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"
2434 "#endif // defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D)\n"
2436 "#ifdef USESHADOWMAPCUBE\n"
2437 "float4 GetShadowMapTCCube(float3 dir, float4 ShadowMap_Parameters)\n"
2439 " float3 adir = abs(dir);\n"
2440 " return float4(dir, ShadowMap_Parameters.w + ShadowMap_Parameters.y / max(max(adir.x, adir.y), adir.z));\n"
2444 "# ifdef USESHADOWMAPRECT\n"
2445 "#ifdef USESHADOWMAPVSDCT\n"
2446 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2448 "float ShadowMapCompare(float3 dir, samplerRECT Texture_ShadowMapRect, float4 ShadowMap_Parameters)\n"
2451 "#ifdef USESHADOWMAPVSDCT\n"
2452 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2454 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2457 "# ifdef USESHADOWSAMPLER\n"
2459 "# ifdef USESHADOWMAPPCF\n"
2460 "# define texval(x, y) shadow2DRect(Texture_ShadowMapRect, shadowmaptc + float3(x, y, 0.0)).r\n"
2461 " f = dot(float4(0.25,0.25,0.25,0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2463 " f = shadow2DRect(Texture_ShadowMapRect, shadowmaptc).r;\n"
2468 "# ifdef USESHADOWMAPPCF\n"
2469 "# if USESHADOWMAPPCF > 1\n"
2470 "# define texval(x, y) texRECT(Texture_ShadowMapRect, center + float2(x, y)).r\n"
2471 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2472 " 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"
2473 " 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"
2474 " 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"
2475 " 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"
2476 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2477 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2479 "# define texval(x, y) texRECT(Texture_ShadowMapRect, shadowmaptc.xy + float2(x, y)).r\n"
2480 " float2 offset = frac(shadowmaptc.xy);\n"
2481 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2482 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2483 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2484 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2485 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25,0.25));\n"
2488 " f = step(shadowmaptc.z, texRECT(Texture_ShadowMapRect, shadowmaptc.xy).r);\n"
2492 "# ifdef USESHADOWMAPORTHO\n"
2493 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2500 "# ifdef USESHADOWMAP2D\n"
2501 "#ifdef USESHADOWMAPVSDCT\n"
2502 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2504 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2507 "#ifdef USESHADOWMAPVSDCT\n"
2508 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2510 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2514 "# ifdef USESHADOWSAMPLER\n"
2515 "# ifdef USESHADOWMAPPCF\n"
2516 "# define texval(x, y) tex2Dproj(Texture_ShadowMap2D, float4(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r \n"
2517 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2518 " f = dot(float4(0.25,0.25,0.25,0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2520 " f = tex2Dproj(Texture_ShadowMap2D, float4(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r;\n"
2523 "# ifdef USESHADOWMAPPCF\n"
2524 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2525 "# ifdef GL_ARB_texture_gather\n"
2526 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, int2(x, y))\n"
2528 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)\n"
2530 " float2 offset = frac(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
2531 "# if USESHADOWMAPPCF > 1\n"
2532 " float4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
2533 " float4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
2534 " float4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
2535 " float4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
2536 " float4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
2537 " float4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
2538 " float4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
2539 " float4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
2540 " float4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
2541 " float4 locols = float4(group1.ab, group3.ab);\n"
2542 " float4 hicols = float4(group7.rg, group9.rg);\n"
2543 " locols.yz += group2.ab;\n"
2544 " hicols.yz += group8.rg;\n"
2545 " float4 midcols = float4(group1.rg, group3.rg) + float4(group7.ab, group9.ab) +\n"
2546 " float4(group4.rg, group6.rg) + float4(group4.ab, group6.ab) +\n"
2547 " lerp(locols, hicols, offset.y);\n"
2548 " float4 cols = group5 + float4(group2.rg, group8.ab);\n"
2549 " cols.xyz += lerp(midcols.xyz, midcols.yzw, offset.x);\n"
2550 " f = dot(cols, float4(1.0/25.0));\n"
2552 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2553 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2554 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2555 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2556 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2557 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2558 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2561 "# ifdef GL_EXT_gpu_shader4\n"
2562 "# define texval(x, y) tex2DOffset(Texture_ShadowMap2D, center, int2(x, y)).r\n"
2564 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale).r \n"
2566 "# if USESHADOWMAPPCF > 1\n"
2567 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2568 " center *= ShadowMap_TextureScale;\n"
2569 " 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"
2570 " 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"
2571 " 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"
2572 " 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"
2573 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2574 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2576 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2577 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2578 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2579 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2580 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2581 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25,0.25));\n"
2585 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2588 "# ifdef USESHADOWMAPORTHO\n"
2589 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2596 "# ifdef USESHADOWMAPCUBE\n"
2597 "float ShadowMapCompare(float3 dir, samplerCUBE Texture_ShadowMapCube, float4 ShadowMap_Parameters)\n"
2599 " // apply depth texture cubemap as light filter\n"
2600 " float4 shadowmaptc = GetShadowMapTCCube(dir, ShadowMap_Parameters);\n"
2602 "# ifdef USESHADOWSAMPLER\n"
2603 " f = shadowCube(Texture_ShadowMapCube, shadowmaptc).r;\n"
2605 " f = step(shadowmaptc.w, texCUBE(Texture_ShadowMapCube, shadowmaptc.xyz).r);\n"
2610 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
2611 "#endif // FRAGMENT_SHADER\n"
2616 "#ifdef MODE_DEFERREDGEOMETRY\n"
2617 "#ifdef VERTEX_SHADER\n"
2620 "float4 gl_Vertex : POSITION,\n"
2621 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2622 "#ifdef USEVERTEXTEXTUREBLEND\n"
2623 "float4 gl_Color : COLOR0,\n"
2625 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2626 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2627 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2628 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2629 "uniform float4x4 TexMatrix : register(c0),\n"
2630 "#ifdef USEVERTEXTEXTUREBLEND\n"
2631 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2633 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2634 "#ifdef USEOFFSETMAPPING\n"
2635 "uniform float3 EyePosition : register(c24),\n"
2637 "out float4 gl_Position : POSITION,\n"
2638 "out float4 gl_FrontColor : COLOR,\n"
2639 "out float4 TexCoordBoth : TEXCOORD0,\n"
2640 "#ifdef USEOFFSETMAPPING\n"
2641 "out float3 EyeVector : TEXCOORD2,\n"
2643 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2644 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2645 "out float3 VectorR : TEXCOORD7 // direction of R texcoord (surface normal)\n"
2648 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2649 "#ifdef USEVERTEXTEXTUREBLEND\n"
2651 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2653 " gl_FrontColor = gl_Color; // Cg is forward\n"
2655 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2658 " // transform unnormalized eye direction into tangent space\n"
2659 "#ifdef USEOFFSETMAPPING\n"
2660 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2661 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2662 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2663 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2666 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2667 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2668 " VectorR = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2669 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2671 "#endif // VERTEX_SHADER\n"
2673 "#ifdef FRAGMENT_SHADER\n"
2676 "float4 TexCoordBoth : TEXCOORD0,\n"
2677 "float3 EyeVector : TEXCOORD2,\n"
2678 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2679 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2680 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2681 "uniform sampler Texture_Normal : register(s0),\n"
2682 "#ifdef USEALPHAKILL\n"
2683 "uniform sampler Texture_Color : register(s1),\n"
2685 "uniform sampler Texture_Gloss : register(s2),\n"
2686 "#ifdef USEVERTEXTEXTUREBLEND\n"
2687 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
2688 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
2690 "#ifdef USEOFFSETMAPPING\n"
2691 "uniform float OffsetMapping_Scale : register(c24),\n"
2693 "uniform half SpecularPower : register(c36),\n"
2694 "out float4 gl_FragColor : COLOR\n"
2697 " float2 TexCoord = TexCoordBoth.xy;\n"
2698 "#ifdef USEOFFSETMAPPING\n"
2699 " // apply offsetmapping\n"
2700 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2701 "#define TexCoord TexCoordOffset\n"
2704 "#ifdef USEALPHAKILL\n"
2705 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2709 "#ifdef USEVERTEXTEXTUREBLEND\n"
2710 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2711 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2712 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2713 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2716 "#ifdef USEVERTEXTEXTUREBLEND\n"
2717 " float3 surfacenormal = lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend) - float3(0.5, 0.5, 0.5);\n"
2718 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2).a, tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2720 " float3 surfacenormal = tex2D(Texture_Normal, TexCoord).rgb - float3(0.5, 0.5, 0.5);\n"
2721 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2724 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2726 "#endif // FRAGMENT_SHADER\n"
2727 "#else // !MODE_DEFERREDGEOMETRY\n"
2732 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2733 "#ifdef VERTEX_SHADER\n"
2736 "float4 gl_Vertex : POSITION,\n"
2737 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2738 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2739 "out float4 gl_Position : POSITION,\n"
2740 "out float4 ModelViewPosition : TEXCOORD0\n"
2743 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2744 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2746 "#endif // VERTEX_SHADER\n"
2748 "#ifdef FRAGMENT_SHADER\n"
2752 "float2 Pixel : VPOS,\n"
2754 "float2 Pixel : WPOS,\n"
2756 "float4 ModelViewPosition : TEXCOORD0,\n"
2757 "uniform float4x4 ViewToLight : register(c44),\n"
2758 "uniform float2 ScreenToDepth : register(c33), // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2759 "uniform float3 LightPosition : register(c23),\n"
2760 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
2761 "uniform half3 DeferredColor_Ambient : register(c9),\n"
2762 "uniform half3 DeferredColor_Diffuse : register(c10),\n"
2763 "#ifdef USESPECULAR\n"
2764 "uniform half3 DeferredColor_Specular : register(c11),\n"
2765 "uniform half SpecularPower : register(c36),\n"
2767 "uniform sampler Texture_Attenuation : register(s9),\n"
2768 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2769 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2771 "#ifdef USECUBEFILTER\n"
2772 "uniform samplerCUBE Texture_Cube : register(s10),\n"
2775 "#ifdef USESHADOWMAPRECT\n"
2776 "# ifdef USESHADOWSAMPLER\n"
2777 "uniform samplerRECTShadow Texture_ShadowMapRect : register(s11),\n"
2779 "uniform samplerRECT Texture_ShadowMapRect : register(s11),\n"
2783 "#ifdef USESHADOWMAP2D\n"
2784 "# ifdef USESHADOWSAMPLER\n"
2785 "uniform sampler Texture_ShadowMap2D : register(s11),\n"
2787 "uniform sampler Texture_ShadowMap2D : register(s11),\n"
2791 "#ifdef USESHADOWMAPVSDCT\n"
2792 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
2795 "#ifdef USESHADOWMAPCUBE\n"
2796 "# ifdef USESHADOWSAMPLER\n"
2797 "uniform samplerCUBEShadow Texture_ShadowMapCube : register(s11),\n"
2799 "uniform samplerCUBE Texture_ShadowMapCube : register(s11),\n"
2803 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
2804 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
2805 "uniform float4 ShadowMap_Parameters : register(c34),\n"
2808 "out float4 gl_FragData0 : COLOR0,\n"
2809 "out float4 gl_FragData1 : COLOR1\n"
2812 " // calculate viewspace pixel position\n"
2813 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2814 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2815 " float3 position;\n"
2816 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2817 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2818 " // decode viewspace pixel normal\n"
2819 " half4 normalmap = half4(tex2D(Texture_ScreenNormalMap, ScreenTexCoord));\n"
2820 " half3 surfacenormal = half3(normalize(normalmap.rgb - half3(0.5,0.5,0.5)));\n"
2821 " // surfacenormal = pixel normal in viewspace\n"
2822 " // LightVector = pixel to light in viewspace\n"
2823 " // CubeVector = position in lightspace\n"
2824 " // eyevector = pixel to view in viewspace\n"
2825 " float3 CubeVector = mul(ViewToLight, float4(position,1)).xyz;\n"
2826 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
2827 "#ifdef USEDIFFUSE\n"
2828 " // calculate diffuse shading\n"
2829 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2830 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2832 "#ifdef USESPECULAR\n"
2833 " // calculate directional shading\n"
2834 " float3 eyevector = position * -1.0;\n"
2835 "# ifdef USEEXACTSPECULARMATH\n"
2836 " half specular = pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
2838 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(eyevector))));\n"
2839 " half specular = pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
2843 "#if defined(USESHADOWMAP2D) || defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE)\n"
2844 " fade *= ShadowMapCompare(CubeVector,\n"
2845 "# if defined(USESHADOWMAP2D)\n"
2846 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2848 "# if defined(USESHADOWMAPRECT)\n"
2849 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
2851 "# if defined(USESHADOWMAPCUBE)\n"
2852 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
2855 "#ifdef USESHADOWMAPVSDCT\n"
2856 ", Texture_CubeProjection\n"
2861 "#ifdef USEDIFFUSE\n"
2862 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2864 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2866 "#ifdef USESPECULAR\n"
2867 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2869 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2872 "# ifdef USECUBEFILTER\n"
2873 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2874 " gl_FragData0.rgb *= cubecolor;\n"
2875 " gl_FragData1.rgb *= cubecolor;\n"
2878 "#endif // FRAGMENT_SHADER\n"
2879 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2884 "#ifdef VERTEX_SHADER\n"
2887 "float4 gl_Vertex : POSITION,\n"
2888 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2889 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2890 "float4 gl_Color : COLOR0,\n"
2892 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2893 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2894 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2895 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2896 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2898 "uniform float3 EyePosition : register(c24),\n"
2899 "uniform float4x4 TexMatrix : register(c0),\n"
2900 "#ifdef USEVERTEXTEXTUREBLEND\n"
2901 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2903 "#ifdef MODE_LIGHTSOURCE\n"
2904 "uniform float4x4 ModelToLight : register(c20),\n"
2906 "#ifdef MODE_LIGHTSOURCE\n"
2907 "uniform float3 LightPosition : register(c27),\n"
2909 "#ifdef MODE_LIGHTDIRECTION\n"
2910 "uniform float3 LightDir : register(c26),\n"
2912 "uniform float4 FogPlane : register(c25),\n"
2913 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2914 "uniform float3 LightPosition : register(c27),\n"
2916 "#ifdef USESHADOWMAPORTHO\n"
2917 "uniform float4x4 ShadowMapMatrix : register(c16),\n"
2920 "out float4 gl_FrontColor : COLOR,\n"
2921 "out float4 TexCoordBoth : TEXCOORD0,\n"
2922 "#ifdef USELIGHTMAP\n"
2923 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2925 "#ifdef USEEYEVECTOR\n"
2926 "out float3 EyeVector : TEXCOORD2,\n"
2928 "#ifdef USEREFLECTION\n"
2929 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2932 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2934 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
2935 "out float3 LightVector : TEXCOORD1,\n"
2937 "#ifdef MODE_LIGHTSOURCE\n"
2938 "out float3 CubeVector : TEXCOORD3,\n"
2940 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2941 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2942 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2943 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2945 "#ifdef USESHADOWMAPORTHO\n"
2946 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2948 "out float4 gl_Position : POSITION\n"
2951 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2953 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2955 " gl_FrontColor = gl_Color; // Cg is forward\n"
2958 " // copy the surface texcoord\n"
2959 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2960 "#ifdef USEVERTEXTEXTUREBLEND\n"
2961 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2963 "#ifdef USELIGHTMAP\n"
2964 " TexCoordLightmap = gl_MultiTexCoord4.xy;\n"
2967 "#ifdef MODE_LIGHTSOURCE\n"
2968 " // transform vertex position into light attenuation/cubemap space\n"
2969 " // (-1 to +1 across the light box)\n"
2970 " CubeVector = mul(ModelToLight, gl_Vertex).xyz;\n"
2972 "# ifdef USEDIFFUSE\n"
2973 " // transform unnormalized light direction into tangent space\n"
2974 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2975 " // normalize it per pixel)\n"
2976 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2977 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2978 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2979 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2983 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2984 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2985 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2986 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2989 " // transform unnormalized eye direction into tangent space\n"
2990 "#ifdef USEEYEVECTOR\n"
2991 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2992 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2993 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2994 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2998 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2999 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
3002 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3003 " VectorS = gl_MultiTexCoord1.xyz;\n"
3004 " VectorT = gl_MultiTexCoord2.xyz;\n"
3005 " VectorR = gl_MultiTexCoord3.xyz;\n"
3008 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
3009 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
3011 "#ifdef USESHADOWMAPORTHO\n"
3012 " ShadowMapTC = mul(ShadowMapMatrix, gl_Position).xyz;\n"
3015 "#ifdef USEREFLECTION\n"
3016 " ModelViewProjectionPosition = gl_Position;\n"
3019 "#endif // VERTEX_SHADER\n"
3024 "#ifdef FRAGMENT_SHADER\n"
3027 "#ifdef USEDEFERREDLIGHTMAP\n"
3029 "float2 Pixel : VPOS,\n"
3031 "float2 Pixel : WPOS,\n"
3034 "float4 gl_FrontColor : COLOR,\n"
3035 "float4 TexCoordBoth : TEXCOORD0,\n"
3036 "#ifdef USELIGHTMAP\n"
3037 "float2 TexCoordLightmap : TEXCOORD1,\n"
3039 "#ifdef USEEYEVECTOR\n"
3040 "float3 EyeVector : TEXCOORD2,\n"
3042 "#ifdef USEREFLECTION\n"
3043 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
3046 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
3048 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
3049 "float3 LightVector : TEXCOORD1,\n"
3051 "#ifdef MODE_LIGHTSOURCE\n"
3052 "float3 CubeVector : TEXCOORD3,\n"
3054 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3055 "float4 ModelViewPosition : TEXCOORD0,\n"
3057 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
3058 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
3059 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
3060 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
3062 "#ifdef USESHADOWMAPORTHO\n"
3063 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
3066 "uniform sampler Texture_Normal : register(s0),\n"
3067 "uniform sampler Texture_Color : register(s1),\n"
3068 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3069 "uniform sampler Texture_Gloss : register(s2),\n"
3072 "uniform sampler Texture_Glow : register(s3),\n"
3074 "#ifdef USEVERTEXTEXTUREBLEND\n"
3075 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
3076 "uniform sampler Texture_SecondaryColor : register(s5),\n"
3077 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3078 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
3081 "uniform sampler Texture_SecondaryGlow : register(s7),\n"
3084 "#ifdef USECOLORMAPPING\n"
3085 "uniform sampler Texture_Pants : register(s4),\n"
3086 "uniform sampler Texture_Shirt : register(s7),\n"
3089 "uniform sampler Texture_FogHeightTexture : register(s14),\n"
3090 "uniform sampler Texture_FogMask : register(s8),\n"
3092 "#ifdef USELIGHTMAP\n"
3093 "uniform sampler Texture_Lightmap : register(s9),\n"
3095 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
3096 "uniform sampler Texture_Deluxemap : register(s10),\n"
3098 "#ifdef USEREFLECTION\n"
3099 "uniform sampler Texture_Reflection : register(s7),\n"
3102 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3103 "uniform sampler Texture_ScreenDepth : register(s13),\n"
3104 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
3106 "#ifdef USEDEFERREDLIGHTMAP\n"
3107 "uniform sampler Texture_ScreenDiffuse : register(s11),\n"
3108 "uniform sampler Texture_ScreenSpecular : register(s12),\n"
3111 "#ifdef USECOLORMAPPING\n"
3112 "uniform half3 Color_Pants : register(c7),\n"
3113 "uniform half3 Color_Shirt : register(c8),\n"
3116 "uniform float3 FogColor : register(c16),\n"
3117 "uniform float FogRangeRecip : register(c20),\n"
3118 "uniform float FogPlaneViewDist : register(c19),\n"
3119 "uniform float FogHeightFade : register(c17),\n"
3122 "#ifdef USEOFFSETMAPPING\n"
3123 "uniform float OffsetMapping_Scale : register(c24),\n"
3126 "#ifdef USEDEFERREDLIGHTMAP\n"
3127 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
3128 "uniform half3 DeferredMod_Diffuse : register(c12),\n"
3129 "uniform half3 DeferredMod_Specular : register(c13),\n"
3131 "uniform half3 Color_Ambient : register(c3),\n"
3132 "uniform half3 Color_Diffuse : register(c4),\n"
3133 "uniform half3 Color_Specular : register(c5),\n"
3134 "uniform half SpecularPower : register(c36),\n"
3136 "uniform half3 Color_Glow : register(c6),\n"
3138 "uniform half Alpha : register(c0),\n"
3139 "#ifdef USEREFLECTION\n"
3140 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
3141 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
3142 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
3143 "uniform half4 ReflectColor : register(c26),\n"
3145 "#ifdef USEREFLECTCUBE\n"
3146 "uniform float4x4 ModelToReflectCube : register(c48),\n"
3147 "uniform sampler Texture_ReflectMask : register(s5),\n"
3148 "uniform samplerCUBE Texture_ReflectCube : register(s6),\n"
3150 "#ifdef MODE_LIGHTDIRECTION\n"
3151 "uniform half3 LightColor : register(c21),\n"
3153 "#ifdef MODE_LIGHTSOURCE\n"
3154 "uniform half3 LightColor : register(c21),\n"
3157 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3158 "uniform sampler Texture_Attenuation : register(s9),\n"
3159 "uniform samplerCUBE Texture_Cube : register(s10),\n"
3162 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3164 "#ifdef USESHADOWMAPRECT\n"
3165 "# ifdef USESHADOWSAMPLER\n"
3166 "uniform samplerRECTShadow Texture_ShadowMapRect : register(s11),\n"
3168 "uniform samplerRECT Texture_ShadowMapRect : register(s11),\n"
3172 "#ifdef USESHADOWMAP2D\n"
3173 "# ifdef USESHADOWSAMPLER\n"
3174 "uniform sampler Texture_ShadowMap2D : register(s11),\n"
3176 "uniform sampler Texture_ShadowMap2D : register(s11),\n"
3180 "#ifdef USESHADOWMAPVSDCT\n"
3181 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
3184 "#ifdef USESHADOWMAPCUBE\n"
3185 "# ifdef USESHADOWSAMPLER\n"
3186 "uniform samplerCUBEShadow Texture_ShadowMapCube : register(s11),\n"
3188 "uniform samplerCUBE Texture_ShadowMapCube : register(s11),\n"
3192 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAP2D) || defined(USESHADOWMAPCUBE)\n"
3193 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
3194 "uniform float4 ShadowMap_Parameters : register(c34),\n"
3196 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3198 "out float4 gl_FragColor : COLOR\n"
3201 " float2 TexCoord = TexCoordBoth.xy;\n"
3202 "#ifdef USEVERTEXTEXTUREBLEND\n"
3203 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3205 "#ifdef USEOFFSETMAPPING\n"
3206 " // apply offsetmapping\n"
3207 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3208 "#define TexCoord TexCoordOffset\n"
3211 " // combine the diffuse textures (base, pants, shirt)\n"
3212 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3213 "#ifdef USEALPHAKILL\n"
3214 " if (color.a < 0.5)\n"
3217 " color.a *= Alpha;\n"
3218 "#ifdef USECOLORMAPPING\n"
3219 " color.rgb += half3(tex2D(Texture_Pants, TexCoord).rgb) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord).rgb) * Color_Shirt;\n"
3221 "#ifdef USEVERTEXTEXTUREBLEND\n"
3222 " half terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3223 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3224 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3225 " color.rgb = half3(lerp(tex2D(Texture_SecondaryColor, TexCoord2).rgb, float3(color.rgb), terrainblend));\n"
3227 " //color = half4(lerp(float4(1, 0, 0, 1), color, terrainblend));\n"
3230 " // get the surface normal\n"
3231 "#ifdef USEVERTEXTEXTUREBLEND\n"
3232 " half3 surfacenormal = normalize(half3(lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3234 " half3 surfacenormal = half3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5, 0.5, 0.5)));\n"
3237 " // get the material colors\n"
3238 " half3 diffusetex = color.rgb;\n"
3239 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3240 "# ifdef USEVERTEXTEXTUREBLEND\n"
3241 " half4 glosstex = half4(lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord), terrainblend));\n"
3243 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3247 "#ifdef USEREFLECTCUBE\n"
3248 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3249 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3250 " float3 ReflectCubeTexCoord = mul(ModelToReflectCube, float4(ModelReflectVector, 0)).xyz;\n"
3251 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord).rgb) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord).rgb);\n"
3257 "#ifdef MODE_LIGHTSOURCE\n"
3258 " // light source\n"
3259 "#ifdef USEDIFFUSE\n"
3260 " half3 lightnormal = half3(normalize(LightVector));\n"
3261 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3262 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3263 "#ifdef USESPECULAR\n"
3264 "#ifdef USEEXACTSPECULARMATH\n"
3265 " half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3267 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3268 " half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3270 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3273 " color.rgb = diffusetex * Color_Ambient;\n"
3275 " color.rgb *= LightColor;\n"
3276 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
3277 "#if defined(USESHADOWMAPRECT) || defined(USESHADOWMAPCUBE) || defined(USESHADOWMAP2D)\n"
3278 " color.rgb *= half(ShadowMapCompare(CubeVector,\n"
3279 "# if defined(USESHADOWMAP2D)\n"
3280 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3282 "# if defined(USESHADOWMAPRECT)\n"
3283 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3285 "# if defined(USESHADOWMAPCUBE)\n"
3286 "Texture_ShadowMapCube, ShadowMap_Parameters\n"
3289 "#ifdef USESHADOWMAPVSDCT\n"
3290 ", Texture_CubeProjection\n"
3295 "# ifdef USECUBEFILTER\n"
3296 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector).rgb);\n"
3299 "#ifdef USESHADOWMAP2D\n"
3300 "#ifdef USESHADOWMAPVSDCT\n"
3301 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3302 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection).xy * ShadowMap_TextureScale).rgb);\n"
3303 "// color.rgb = half3(GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection).xyz * float3(ShadowMap_TextureScale,1.0));\n"
3304 "// color.r = half(texDepth2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection).xy * ShadowMap_TextureScale));\n"
3306 "// float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters);\n"
3307 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3308 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector, ShadowMap_Parameters).xy * ShadowMap_TextureScale).rgb);\n"
3309 "// color.rgb = half3(GetShadowMapTC2D(CubeVector, ShadowMap_Parameters).xyz * float3(ShadowMap_TextureScale,1.0));\n"
3310 "// color.r = half(texDepth2D(Texture_ShadowMap2D, GetShadowMapTC2D(CubeVector, ShadowMap_Parameters).xy * ShadowMap_TextureScale));\n"
3311 "// color.r = half(shadowmaptc.z - texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3312 "// color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3313 "// color.r = half(shadowmaptc.z);\n"
3317 "// color.rgb = half3(1,1,1);\n"
3318 "#endif // MODE_LIGHTSOURCE\n"
3323 "#ifdef MODE_LIGHTDIRECTION\n"
3325 "#ifdef USEDIFFUSE\n"
3326 " half3 lightnormal = half3(normalize(LightVector));\n"
3328 "#define lightcolor LightColor\n"
3329 "#endif // MODE_LIGHTDIRECTION\n"
3330 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3332 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3333 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3334 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3335 " // convert modelspace light vector to tangentspace\n"
3336 " half3 lightnormal;\n"
3337 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3338 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3339 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3340 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3341 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3342 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3343 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3344 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3345 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3346 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3347 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3348 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3349 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3350 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3351 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3353 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3354 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3355 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3361 "#ifdef MODE_LIGHTMAP\n"
3362 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb) * Color_Diffuse);\n"
3363 "#endif // MODE_LIGHTMAP\n"
3364 "#ifdef MODE_VERTEXCOLOR\n"
3365 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3366 "#endif // MODE_VERTEXCOLOR\n"
3367 "#ifdef MODE_FLATCOLOR\n"
3368 " color.rgb = diffusetex * Color_Ambient;\n"
3369 "#endif // MODE_FLATCOLOR\n"
3375 "# ifdef USEDIFFUSE\n"
3376 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3377 "# ifdef USESPECULAR\n"
3378 "# ifdef USEEXACTSPECULARMATH\n"
3379 " half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3381 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3382 " half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3384 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3386 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3389 " color.rgb = diffusetex * Color_Ambient;\n"
3393 "#ifdef USESHADOWMAPORTHO\n"
3394 " color.rgb *= ShadowMapCompare(ShadowMapTC,\n"
3395 "# if defined(USESHADOWMAP2D)\n"
3396 "Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3398 "# if defined(USESHADOWMAPRECT)\n"
3399 "Texture_ShadowMapRect, ShadowMap_Parameters\n"
3404 "#ifdef USEDEFERREDLIGHTMAP\n"
3405 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3406 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord).rgb) * DeferredMod_Diffuse;\n"
3407 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord).rgb) * DeferredMod_Specular;\n"
3411 "#ifdef USEVERTEXTEXTUREBLEND\n"
3412 " color.rgb += half3(lerp(tex2D(Texture_SecondaryGlow, TexCoord2).rgb, tex2D(Texture_Glow, TexCoord).rgb, terrainblend)) * Color_Glow;\n"
3414 " color.rgb += half3(tex2D(Texture_Glow, TexCoord).rgb) * Color_Glow;\n"
3419 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3422 " // 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"
3423 "#ifdef USEREFLECTION\n"
3424 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3425 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3426 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3427 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.zw;\n"
3428 " // FIXME temporary hack to detect the case that the reflection\n"
3429 " // gets blackened at edges due to leaving the area that contains actual\n"
3431 " // Remove this 'ack once we have a better way to stop this thing from\n"
3433 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3434 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3435 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3436 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3437 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3438 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord).rgb) * ReflectColor.rgb, ReflectColor.a);\n"
3441 " gl_FragColor = float4(color);\n"
3443 "#endif // FRAGMENT_SHADER\n"
3445 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3446 "#endif // !MODE_DEFERREDGEOMETRY\n"
3447 "#endif // !MODE_WATER\n"
3448 "#endif // !MODE_REFRACTION\n"
3449 "#endif // !MODE_BLOOMBLUR\n"
3450 "#endif // !MODE_GENERIC\n"
3451 "#endif // !MODE_POSTPROCESS\n"
3452 "#endif // !MODE_SHOWDEPTH\n"
3453 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3456 char *glslshaderstring = NULL;
3457 char *cgshaderstring = NULL;
3458 char *hlslshaderstring = NULL;
3460 //=======================================================================================================================================================
3462 typedef struct shaderpermutationinfo_s
3464 const char *pretext;
3467 shaderpermutationinfo_t;
3469 typedef struct shadermodeinfo_s
3471 const char *vertexfilename;
3472 const char *geometryfilename;
3473 const char *fragmentfilename;
3474 const char *pretext;
3479 typedef enum shaderpermutation_e
3481 SHADERPERMUTATION_DIFFUSE = 1<<0, ///< (lightsource) whether to use directional shading
3482 SHADERPERMUTATION_VERTEXTEXTUREBLEND = 1<<1, ///< indicates this is a two-layer material blend based on vertex alpha (q3bsp)
3483 SHADERPERMUTATION_VIEWTINT = 1<<2, ///< view tint (postprocessing only)
3484 SHADERPERMUTATION_COLORMAPPING = 1<<3, ///< indicates this is a colormapped skin
3485 SHADERPERMUTATION_SATURATION = 1<<4, ///< saturation (postprocessing only)
3486 SHADERPERMUTATION_FOGINSIDE = 1<<5, ///< tint the color by fog color or black if using additive blend mode
3487 SHADERPERMUTATION_FOGOUTSIDE = 1<<6, ///< tint the color by fog color or black if using additive blend mode
3488 SHADERPERMUTATION_FOGHEIGHTTEXTURE = 1<<7, ///< fog color and density determined by texture mapped on vertical axis
3489 SHADERPERMUTATION_GAMMARAMPS = 1<<8, ///< gamma (postprocessing only)
3490 SHADERPERMUTATION_CUBEFILTER = 1<<9, ///< (lightsource) use cubemap light filter
3491 SHADERPERMUTATION_GLOW = 1<<10, ///< (lightmap) blend in an additive glow texture
3492 SHADERPERMUTATION_BLOOM = 1<<11, ///< bloom (postprocessing only)
3493 SHADERPERMUTATION_SPECULAR = 1<<12, ///< (lightsource or deluxemapping) render specular effects
3494 SHADERPERMUTATION_POSTPROCESSING = 1<<13, ///< user defined postprocessing (postprocessing only)
3495 SHADERPERMUTATION_EXACTSPECULARMATH = 1<<14, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3496 SHADERPERMUTATION_REFLECTION = 1<<15, ///< normalmap-perturbed reflection of the scene infront of the surface, preformed as an overlay on the surface
3497 SHADERPERMUTATION_OFFSETMAPPING = 1<<16, ///< adjust texcoords to roughly simulate a displacement mapped surface
3498 SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING = 1<<17, ///< adjust texcoords to accurately simulate a displacement mapped surface (requires OFFSETMAPPING to also be set!)
3499 SHADERPERMUTATION_SHADOWMAPRECT = 1<<18, ///< (lightsource) use shadowmap rectangle texture as light filter
3500 SHADERPERMUTATION_SHADOWMAPCUBE = 1<<19, ///< (lightsource) use shadowmap cubemap texture as light filter
3501 SHADERPERMUTATION_SHADOWMAP2D = 1<<20, ///< (lightsource) use shadowmap rectangle texture as light filter
3502 SHADERPERMUTATION_SHADOWMAPPCF = 1<<21, ///< (lightsource) use percentage closer filtering on shadowmap test results
3503 SHADERPERMUTATION_SHADOWMAPPCF2 = 1<<22, ///< (lightsource) use higher quality percentage closer filtering on shadowmap test results
3504 SHADERPERMUTATION_SHADOWSAMPLER = 1<<23, ///< (lightsource) use hardware shadowmap test
3505 SHADERPERMUTATION_SHADOWMAPVSDCT = 1<<24, ///< (lightsource) use virtual shadow depth cube texture for shadowmap indexing
3506 SHADERPERMUTATION_SHADOWMAPORTHO = 1<<25, //< (lightsource) use orthographic shadowmap projection
3507 SHADERPERMUTATION_DEFERREDLIGHTMAP = 1<<26, ///< (lightmap) read Texture_ScreenDiffuse/Specular textures and add them on top of lightmapping
3508 SHADERPERMUTATION_ALPHAKILL = 1<<27, ///< (deferredgeometry) discard pixel if diffuse texture alpha below 0.5
3509 SHADERPERMUTATION_REFLECTCUBE = 1<<28, ///< fake reflections using global cubemap (not HDRI light probe)
3510 SHADERPERMUTATION_LIMIT = 1<<29, ///< size of permutations array
3511 SHADERPERMUTATION_COUNT = 29 ///< size of shaderpermutationinfo array
3513 shaderpermutation_t;
3515 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3516 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3518 {"#define USEDIFFUSE\n", " diffuse"},
3519 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3520 {"#define USEVIEWTINT\n", " viewtint"},
3521 {"#define USECOLORMAPPING\n", " colormapping"},
3522 {"#define USESATURATION\n", " saturation"},
3523 {"#define USEFOGINSIDE\n", " foginside"},
3524 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3525 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3526 {"#define USEGAMMARAMPS\n", " gammaramps"},
3527 {"#define USECUBEFILTER\n", " cubefilter"},
3528 {"#define USEGLOW\n", " glow"},
3529 {"#define USEBLOOM\n", " bloom"},
3530 {"#define USESPECULAR\n", " specular"},
3531 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3532 {"#define USEEXACTSPECULARMATH\n", " exactspecularmath"},
3533 {"#define USEREFLECTION\n", " reflection"},
3534 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3535 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3536 {"#define USESHADOWMAPRECT\n", " shadowmaprect"},
3537 {"#define USESHADOWMAPCUBE\n", " shadowmapcube"},
3538 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3539 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3540 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3541 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3542 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3543 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3544 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3545 {"#define USEALPHAKILL\n", " alphakill"},
3546 {"#define USEREFLECTCUBE\n", " reflectcube"},
3549 /// this enum is multiplied by SHADERPERMUTATION_MODEBASE
3550 typedef enum shadermode_e
3552 SHADERMODE_GENERIC, ///< (particles/HUD/etc) vertex color, optionally multiplied by one texture
3553 SHADERMODE_POSTPROCESS, ///< postprocessing shader (r_glsl_postprocess)
3554 SHADERMODE_DEPTH_OR_SHADOW, ///< (depthfirst/shadows) vertex shader only
3555 SHADERMODE_FLATCOLOR, ///< (lightmap) modulate texture by uniform color (q1bsp, q3bsp)
3556 SHADERMODE_VERTEXCOLOR, ///< (lightmap) modulate texture by vertex colors (q3bsp)
3557 SHADERMODE_LIGHTMAP, ///< (lightmap) modulate texture by lightmap texture (q1bsp, q3bsp)
3558 SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE, ///< (lightmap) use directional pixel shading from texture containing modelspace light directions (q3bsp deluxemap)
3559 SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE, ///< (lightmap) use directional pixel shading from texture containing tangentspace light directions (q1bsp deluxemap)
3560 SHADERMODE_LIGHTDIRECTION, ///< (lightmap) use directional pixel shading from fixed light direction (q3bsp)
3561 SHADERMODE_LIGHTSOURCE, ///< (lightsource) use directional pixel shading from light source (rtlight)
3562 SHADERMODE_REFRACTION, ///< refract background (the material is rendered normally after this pass)
3563 SHADERMODE_WATER, ///< refract background and reflection (the material is rendered normally after this pass)
3564 SHADERMODE_SHOWDEPTH, ///< (debugging) renders depth as color
3565 SHADERMODE_DEFERREDGEOMETRY, ///< (deferred) render material properties to screenspace geometry buffers
3566 SHADERMODE_DEFERREDLIGHTSOURCE, ///< (deferred) use directional pixel shading from light source (rtlight) on screenspace geometry buffers
3571 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3572 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3574 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3575 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3576 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3577 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3578 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3579 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3580 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3581 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3582 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3583 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3584 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3585 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3586 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3587 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3588 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3592 shadermodeinfo_t cgshadermodeinfo[SHADERMODE_COUNT] =
3594 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_GENERIC\n", " generic"},
3595 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_POSTPROCESS\n", " postprocess"},
3596 {"cg/default.cg", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3597 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_FLATCOLOR\n", " flatcolor"},
3598 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3599 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTMAP\n", " lightmap"},
3600 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3601 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3602 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3603 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3604 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_REFRACTION\n", " refraction"},
3605 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_WATER\n", " water"},
3606 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_SHOWDEPTH\n", " showdepth"},
3607 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3608 {"cg/default.cg", NULL, "cg/default.cg", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3613 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
3615 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
3616 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3617 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth"},
3618 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3619 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3620 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3621 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3622 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3623 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3624 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3625 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
3626 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
3627 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3628 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3629 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3633 struct r_glsl_permutation_s;
3634 typedef struct r_glsl_permutation_s
3636 /// hash lookup data
3637 struct r_glsl_permutation_s *hashnext;
3639 unsigned int permutation;
3641 /// indicates if we have tried compiling this permutation already
3643 /// 0 if compilation failed
3645 /// locations of detected uniforms in program object, or -1 if not found
3646 int loc_Texture_First;
3647 int loc_Texture_Second;
3648 int loc_Texture_GammaRamps;
3649 int loc_Texture_Normal;
3650 int loc_Texture_Color;
3651 int loc_Texture_Gloss;
3652 int loc_Texture_Glow;
3653 int loc_Texture_SecondaryNormal;
3654 int loc_Texture_SecondaryColor;
3655 int loc_Texture_SecondaryGloss;
3656 int loc_Texture_SecondaryGlow;
3657 int loc_Texture_Pants;
3658 int loc_Texture_Shirt;
3659 int loc_Texture_FogHeightTexture;
3660 int loc_Texture_FogMask;
3661 int loc_Texture_Lightmap;
3662 int loc_Texture_Deluxemap;
3663 int loc_Texture_Attenuation;
3664 int loc_Texture_Cube;
3665 int loc_Texture_Refraction;
3666 int loc_Texture_Reflection;
3667 int loc_Texture_ShadowMapRect;
3668 int loc_Texture_ShadowMapCube;
3669 int loc_Texture_ShadowMap2D;
3670 int loc_Texture_CubeProjection;
3671 int loc_Texture_ScreenDepth;
3672 int loc_Texture_ScreenNormalMap;
3673 int loc_Texture_ScreenDiffuse;
3674 int loc_Texture_ScreenSpecular;
3675 int loc_Texture_ReflectMask;
3676 int loc_Texture_ReflectCube;
3678 int loc_BloomBlur_Parameters;
3680 int loc_Color_Ambient;
3681 int loc_Color_Diffuse;
3682 int loc_Color_Specular;
3684 int loc_Color_Pants;
3685 int loc_Color_Shirt;
3686 int loc_DeferredColor_Ambient;
3687 int loc_DeferredColor_Diffuse;
3688 int loc_DeferredColor_Specular;
3689 int loc_DeferredMod_Diffuse;
3690 int loc_DeferredMod_Specular;
3691 int loc_DistortScaleRefractReflect;
3692 int loc_EyePosition;
3694 int loc_FogHeightFade;
3696 int loc_FogPlaneViewDist;
3697 int loc_FogRangeRecip;
3700 int loc_LightPosition;
3701 int loc_OffsetMapping_Scale;
3703 int loc_ReflectColor;
3704 int loc_ReflectFactor;
3705 int loc_ReflectOffset;
3706 int loc_RefractColor;
3708 int loc_ScreenCenterRefractReflect;
3709 int loc_ScreenScaleRefractReflect;
3710 int loc_ScreenToDepth;
3711 int loc_ShadowMap_Parameters;
3712 int loc_ShadowMap_TextureScale;
3713 int loc_SpecularPower;
3718 int loc_ViewTintColor;
3719 int loc_ViewToLight;
3720 int loc_ModelToLight;
3722 int loc_BackgroundTexMatrix;
3723 int loc_ModelViewProjectionMatrix;
3724 int loc_ModelViewMatrix;
3725 int loc_PixelToScreenTexCoord;
3726 int loc_ModelToReflectCube;
3727 int loc_ShadowMapMatrix;
3728 int loc_BloomColorSubtract;
3730 r_glsl_permutation_t;
3732 #define SHADERPERMUTATION_HASHSIZE 256
3734 /// information about each possible shader permutation
3735 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3736 /// currently selected permutation
3737 r_glsl_permutation_t *r_glsl_permutation;
3738 /// storage for permutations linked in the hash table
3739 memexpandablearray_t r_glsl_permutationarray;
3741 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3743 //unsigned int hashdepth = 0;
3744 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3745 r_glsl_permutation_t *p;
3746 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3748 if (p->mode == mode && p->permutation == permutation)
3750 //if (hashdepth > 10)
3751 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3756 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3758 p->permutation = permutation;
3759 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3760 r_glsl_permutationhash[mode][hashindex] = p;
3761 //if (hashdepth > 10)
3762 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3766 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3769 if (!filename || !filename[0])
3771 if (!strcmp(filename, "glsl/default.glsl"))
3773 if (!glslshaderstring)
3775 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3776 if (glslshaderstring)
3777 Con_DPrintf("Loading shaders from file %s...\n", filename);
3779 glslshaderstring = (char *)builtinshaderstring;
3781 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3782 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3783 return shaderstring;
3785 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3788 if (printfromdisknotice)
3789 Con_DPrintf("from disk %s... ", filename);
3790 return shaderstring;
3792 return shaderstring;
3795 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3798 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3799 int vertstrings_count = 0;
3800 int geomstrings_count = 0;
3801 int fragstrings_count = 0;
3802 char *vertexstring, *geometrystring, *fragmentstring;
3803 const char *vertstrings_list[32+3];
3804 const char *geomstrings_list[32+3];
3805 const char *fragstrings_list[32+3];
3806 char permutationname[256];
3813 permutationname[0] = 0;
3814 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3815 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3816 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3818 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3820 // the first pretext is which type of shader to compile as
3821 // (later these will all be bound together as a program object)
3822 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3823 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3824 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3826 // the second pretext is the mode (for example a light source)
3827 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3828 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3829 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3830 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3832 // now add all the permutation pretexts
3833 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3835 if (permutation & (1<<i))
3837 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3838 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3839 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3840 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3844 // keep line numbers correct
3845 vertstrings_list[vertstrings_count++] = "\n";
3846 geomstrings_list[geomstrings_count++] = "\n";
3847 fragstrings_list[fragstrings_count++] = "\n";
3851 // now append the shader text itself
3852 vertstrings_list[vertstrings_count++] = vertexstring;
3853 geomstrings_list[geomstrings_count++] = geometrystring;
3854 fragstrings_list[fragstrings_count++] = fragmentstring;
3856 // if any sources were NULL, clear the respective list
3858 vertstrings_count = 0;
3859 if (!geometrystring)
3860 geomstrings_count = 0;
3861 if (!fragmentstring)
3862 fragstrings_count = 0;
3864 // compile the shader program
3865 if (vertstrings_count + geomstrings_count + fragstrings_count)
3866 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3870 qglUseProgramObjectARB(p->program);CHECKGLERROR
3871 // look up all the uniform variable names we care about, so we don't
3872 // have to look them up every time we set them
3874 p->loc_Texture_First = qglGetUniformLocationARB(p->program, "Texture_First");
3875 p->loc_Texture_Second = qglGetUniformLocationARB(p->program, "Texture_Second");
3876 p->loc_Texture_GammaRamps = qglGetUniformLocationARB(p->program, "Texture_GammaRamps");
3877 p->loc_Texture_Normal = qglGetUniformLocationARB(p->program, "Texture_Normal");
3878 p->loc_Texture_Color = qglGetUniformLocationARB(p->program, "Texture_Color");
3879 p->loc_Texture_Gloss = qglGetUniformLocationARB(p->program, "Texture_Gloss");
3880 p->loc_Texture_Glow = qglGetUniformLocationARB(p->program, "Texture_Glow");
3881 p->loc_Texture_SecondaryNormal = qglGetUniformLocationARB(p->program, "Texture_SecondaryNormal");
3882 p->loc_Texture_SecondaryColor = qglGetUniformLocationARB(p->program, "Texture_SecondaryColor");
3883 p->loc_Texture_SecondaryGloss = qglGetUniformLocationARB(p->program, "Texture_SecondaryGloss");
3884 p->loc_Texture_SecondaryGlow = qglGetUniformLocationARB(p->program, "Texture_SecondaryGlow");
3885 p->loc_Texture_Pants = qglGetUniformLocationARB(p->program, "Texture_Pants");
3886 p->loc_Texture_Shirt = qglGetUniformLocationARB(p->program, "Texture_Shirt");
3887 p->loc_Texture_FogHeightTexture = qglGetUniformLocationARB(p->program, "Texture_FogHeightTexture");
3888 p->loc_Texture_FogMask = qglGetUniformLocationARB(p->program, "Texture_FogMask");
3889 p->loc_Texture_Lightmap = qglGetUniformLocationARB(p->program, "Texture_Lightmap");
3890 p->loc_Texture_Deluxemap = qglGetUniformLocationARB(p->program, "Texture_Deluxemap");
3891 p->loc_Texture_Attenuation = qglGetUniformLocationARB(p->program, "Texture_Attenuation");
3892 p->loc_Texture_Cube = qglGetUniformLocationARB(p->program, "Texture_Cube");
3893 p->loc_Texture_Refraction = qglGetUniformLocationARB(p->program, "Texture_Refraction");
3894 p->loc_Texture_Reflection = qglGetUniformLocationARB(p->program, "Texture_Reflection");
3895 p->loc_Texture_ShadowMapRect = qglGetUniformLocationARB(p->program, "Texture_ShadowMapRect");
3896 p->loc_Texture_ShadowMapCube = qglGetUniformLocationARB(p->program, "Texture_ShadowMapCube");
3897 p->loc_Texture_ShadowMap2D = qglGetUniformLocationARB(p->program, "Texture_ShadowMap2D");
3898 p->loc_Texture_CubeProjection = qglGetUniformLocationARB(p->program, "Texture_CubeProjection");
3899 p->loc_Texture_ScreenDepth = qglGetUniformLocationARB(p->program, "Texture_ScreenDepth");
3900 p->loc_Texture_ScreenNormalMap = qglGetUniformLocationARB(p->program, "Texture_ScreenNormalMap");
3901 p->loc_Texture_ScreenDiffuse = qglGetUniformLocationARB(p->program, "Texture_ScreenDiffuse");
3902 p->loc_Texture_ScreenSpecular = qglGetUniformLocationARB(p->program, "Texture_ScreenSpecular");
3903 p->loc_Texture_ReflectMask = qglGetUniformLocationARB(p->program, "Texture_ReflectMask");
3904 p->loc_Texture_ReflectCube = qglGetUniformLocationARB(p->program, "Texture_ReflectCube");
3905 p->loc_Alpha = qglGetUniformLocationARB(p->program, "Alpha");
3906 p->loc_BloomBlur_Parameters = qglGetUniformLocationARB(p->program, "BloomBlur_Parameters");
3907 p->loc_ClientTime = qglGetUniformLocationARB(p->program, "ClientTime");
3908 p->loc_Color_Ambient = qglGetUniformLocationARB(p->program, "Color_Ambient");
3909 p->loc_Color_Diffuse = qglGetUniformLocationARB(p->program, "Color_Diffuse");
3910 p->loc_Color_Specular = qglGetUniformLocationARB(p->program, "Color_Specular");
3911 p->loc_Color_Glow = qglGetUniformLocationARB(p->program, "Color_Glow");
3912 p->loc_Color_Pants = qglGetUniformLocationARB(p->program, "Color_Pants");
3913 p->loc_Color_Shirt = qglGetUniformLocationARB(p->program, "Color_Shirt");
3914 p->loc_DeferredColor_Ambient = qglGetUniformLocationARB(p->program, "DeferredColor_Ambient");
3915 p->loc_DeferredColor_Diffuse = qglGetUniformLocationARB(p->program, "DeferredColor_Diffuse");
3916 p->loc_DeferredColor_Specular = qglGetUniformLocationARB(p->program, "DeferredColor_Specular");
3917 p->loc_DeferredMod_Diffuse = qglGetUniformLocationARB(p->program, "DeferredMod_Diffuse");
3918 p->loc_DeferredMod_Specular = qglGetUniformLocationARB(p->program, "DeferredMod_Specular");
3919 p->loc_DistortScaleRefractReflect = qglGetUniformLocationARB(p->program, "DistortScaleRefractReflect");
3920 p->loc_EyePosition = qglGetUniformLocationARB(p->program, "EyePosition");
3921 p->loc_FogColor = qglGetUniformLocationARB(p->program, "FogColor");
3922 p->loc_FogHeightFade = qglGetUniformLocationARB(p->program, "FogHeightFade");
3923 p->loc_FogPlane = qglGetUniformLocationARB(p->program, "FogPlane");
3924 p->loc_FogPlaneViewDist = qglGetUniformLocationARB(p->program, "FogPlaneViewDist");
3925 p->loc_FogRangeRecip = qglGetUniformLocationARB(p->program, "FogRangeRecip");
3926 p->loc_LightColor = qglGetUniformLocationARB(p->program, "LightColor");
3927 p->loc_LightDir = qglGetUniformLocationARB(p->program, "LightDir");
3928 p->loc_LightPosition = qglGetUniformLocationARB(p->program, "LightPosition");
3929 p->loc_OffsetMapping_Scale = qglGetUniformLocationARB(p->program, "OffsetMapping_Scale");
3930 p->loc_PixelSize = qglGetUniformLocationARB(p->program, "PixelSize");
3931 p->loc_ReflectColor = qglGetUniformLocationARB(p->program, "ReflectColor");
3932 p->loc_ReflectFactor = qglGetUniformLocationARB(p->program, "ReflectFactor");
3933 p->loc_ReflectOffset = qglGetUniformLocationARB(p->program, "ReflectOffset");
3934 p->loc_RefractColor = qglGetUniformLocationARB(p->program, "RefractColor");
3935 p->loc_Saturation = qglGetUniformLocationARB(p->program, "Saturation");
3936 p->loc_ScreenCenterRefractReflect = qglGetUniformLocationARB(p->program, "ScreenCenterRefractReflect");
3937 p->loc_ScreenScaleRefractReflect = qglGetUniformLocationARB(p->program, "ScreenScaleRefractReflect");
3938 p->loc_ScreenToDepth = qglGetUniformLocationARB(p->program, "ScreenToDepth");
3939 p->loc_ShadowMap_Parameters = qglGetUniformLocationARB(p->program, "ShadowMap_Parameters");
3940 p->loc_ShadowMap_TextureScale = qglGetUniformLocationARB(p->program, "ShadowMap_TextureScale");
3941 p->loc_SpecularPower = qglGetUniformLocationARB(p->program, "SpecularPower");
3942 p->loc_UserVec1 = qglGetUniformLocationARB(p->program, "UserVec1");
3943 p->loc_UserVec2 = qglGetUniformLocationARB(p->program, "UserVec2");
3944 p->loc_UserVec3 = qglGetUniformLocationARB(p->program, "UserVec3");
3945 p->loc_UserVec4 = qglGetUniformLocationARB(p->program, "UserVec4");
3946 p->loc_ViewTintColor = qglGetUniformLocationARB(p->program, "ViewTintColor");
3947 p->loc_ViewToLight = qglGetUniformLocationARB(p->program, "ViewToLight");
3948 p->loc_ModelToLight = qglGetUniformLocationARB(p->program, "ModelToLight");
3949 p->loc_TexMatrix = qglGetUniformLocationARB(p->program, "TexMatrix");
3950 p->loc_BackgroundTexMatrix = qglGetUniformLocationARB(p->program, "BackgroundTexMatrix");
3951 p->loc_ModelViewMatrix = qglGetUniformLocationARB(p->program, "ModelViewMatrix");
3952 p->loc_ModelViewProjectionMatrix = qglGetUniformLocationARB(p->program, "ModelViewProjectionMatrix");
3953 p->loc_PixelToScreenTexCoord = qglGetUniformLocationARB(p->program, "PixelToScreenTexCoord");
3954 p->loc_ModelToReflectCube = qglGetUniformLocationARB(p->program, "ModelToReflectCube");
3955 p->loc_ShadowMapMatrix = qglGetUniformLocationARB(p->program, "ShadowMapMatrix");
3956 p->loc_BloomColorSubtract = qglGetUniformLocationARB(p->program, "BloomColorSubtract");
3957 // initialize the samplers to refer to the texture units we use
3958 if (p->loc_Texture_First >= 0) qglUniform1iARB(p->loc_Texture_First , GL20TU_FIRST);
3959 if (p->loc_Texture_Second >= 0) qglUniform1iARB(p->loc_Texture_Second , GL20TU_SECOND);
3960 if (p->loc_Texture_GammaRamps >= 0) qglUniform1iARB(p->loc_Texture_GammaRamps , GL20TU_GAMMARAMPS);
3961 if (p->loc_Texture_Normal >= 0) qglUniform1iARB(p->loc_Texture_Normal , GL20TU_NORMAL);
3962 if (p->loc_Texture_Color >= 0) qglUniform1iARB(p->loc_Texture_Color , GL20TU_COLOR);
3963 if (p->loc_Texture_Gloss >= 0) qglUniform1iARB(p->loc_Texture_Gloss , GL20TU_GLOSS);
3964 if (p->loc_Texture_Glow >= 0) qglUniform1iARB(p->loc_Texture_Glow , GL20TU_GLOW);
3965 if (p->loc_Texture_SecondaryNormal >= 0) qglUniform1iARB(p->loc_Texture_SecondaryNormal, GL20TU_SECONDARY_NORMAL);
3966 if (p->loc_Texture_SecondaryColor >= 0) qglUniform1iARB(p->loc_Texture_SecondaryColor , GL20TU_SECONDARY_COLOR);
3967 if (p->loc_Texture_SecondaryGloss >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGloss , GL20TU_SECONDARY_GLOSS);
3968 if (p->loc_Texture_SecondaryGlow >= 0) qglUniform1iARB(p->loc_Texture_SecondaryGlow , GL20TU_SECONDARY_GLOW);
3969 if (p->loc_Texture_Pants >= 0) qglUniform1iARB(p->loc_Texture_Pants , GL20TU_PANTS);
3970 if (p->loc_Texture_Shirt >= 0) qglUniform1iARB(p->loc_Texture_Shirt , GL20TU_SHIRT);
3971 if (p->loc_Texture_FogHeightTexture>= 0) qglUniform1iARB(p->loc_Texture_FogHeightTexture, GL20TU_FOGHEIGHTTEXTURE);
3972 if (p->loc_Texture_FogMask >= 0) qglUniform1iARB(p->loc_Texture_FogMask , GL20TU_FOGMASK);
3973 if (p->loc_Texture_Lightmap >= 0) qglUniform1iARB(p->loc_Texture_Lightmap , GL20TU_LIGHTMAP);
3974 if (p->loc_Texture_Deluxemap >= 0) qglUniform1iARB(p->loc_Texture_Deluxemap , GL20TU_DELUXEMAP);
3975 if (p->loc_Texture_Attenuation >= 0) qglUniform1iARB(p->loc_Texture_Attenuation , GL20TU_ATTENUATION);
3976 if (p->loc_Texture_Cube >= 0) qglUniform1iARB(p->loc_Texture_Cube , GL20TU_CUBE);
3977 if (p->loc_Texture_Refraction >= 0) qglUniform1iARB(p->loc_Texture_Refraction , GL20TU_REFRACTION);
3978 if (p->loc_Texture_Reflection >= 0) qglUniform1iARB(p->loc_Texture_Reflection , GL20TU_REFLECTION);
3979 if (p->loc_Texture_ShadowMapRect >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapRect , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT);
3980 if (p->loc_Texture_ShadowMapCube >= 0) qglUniform1iARB(p->loc_Texture_ShadowMapCube , GL20TU_SHADOWMAPCUBE);
3981 if (p->loc_Texture_ShadowMap2D >= 0) qglUniform1iARB(p->loc_Texture_ShadowMap2D , permutation & SHADERPERMUTATION_SHADOWMAPORTHO ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D);
3982 if (p->loc_Texture_CubeProjection >= 0) qglUniform1iARB(p->loc_Texture_CubeProjection , GL20TU_CUBEPROJECTION);
3983 if (p->loc_Texture_ScreenDepth >= 0) qglUniform1iARB(p->loc_Texture_ScreenDepth , GL20TU_SCREENDEPTH);
3984 if (p->loc_Texture_ScreenNormalMap >= 0) qglUniform1iARB(p->loc_Texture_ScreenNormalMap, GL20TU_SCREENNORMALMAP);
3985 if (p->loc_Texture_ScreenDiffuse >= 0) qglUniform1iARB(p->loc_Texture_ScreenDiffuse , GL20TU_SCREENDIFFUSE);
3986 if (p->loc_Texture_ScreenSpecular >= 0) qglUniform1iARB(p->loc_Texture_ScreenSpecular , GL20TU_SCREENSPECULAR);
3987 if (p->loc_Texture_ReflectMask >= 0) qglUniform1iARB(p->loc_Texture_ReflectMask , GL20TU_REFLECTMASK);
3988 if (p->loc_Texture_ReflectCube >= 0) qglUniform1iARB(p->loc_Texture_ReflectCube , GL20TU_REFLECTCUBE);
3990 Con_DPrintf("^5GLSL shader %s compiled.\n", permutationname);
3993 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
3997 Mem_Free(vertexstring);
3999 Mem_Free(geometrystring);
4001 Mem_Free(fragmentstring);
4004 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
4006 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
4007 if (r_glsl_permutation != perm)
4009 r_glsl_permutation = perm;
4010 if (!r_glsl_permutation->program)
4012 if (!r_glsl_permutation->compiled)
4013 R_GLSL_CompilePermutation(perm, mode, permutation);
4014 if (!r_glsl_permutation->program)
4016 // remove features until we find a valid permutation
4018 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4020 // reduce i more quickly whenever it would not remove any bits
4021 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4022 if (!(permutation & j))
4025 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4026 if (!r_glsl_permutation->compiled)
4027 R_GLSL_CompilePermutation(perm, mode, permutation);
4028 if (r_glsl_permutation->program)
4031 if (i >= SHADERPERMUTATION_COUNT)
4033 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4034 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4035 qglUseProgramObjectARB(0);CHECKGLERROR
4036 return; // no bit left to clear, entire mode is broken
4041 qglUseProgramObjectARB(r_glsl_permutation->program);CHECKGLERROR
4043 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
4044 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
4045 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1fARB(r_glsl_permutation->loc_ClientTime, cl.time);
4049 #include <Cg/cgGL.h>
4050 struct r_cg_permutation_s;
4051 typedef struct r_cg_permutation_s
4053 /// hash lookup data
4054 struct r_cg_permutation_s *hashnext;
4056 unsigned int permutation;
4058 /// indicates if we have tried compiling this permutation already
4060 /// 0 if compilation failed
4063 /// locations of detected parameters in programs, or NULL if not found
4064 CGparameter vp_EyePosition;
4065 CGparameter vp_FogPlane;
4066 CGparameter vp_LightDir;
4067 CGparameter vp_LightPosition;
4068 CGparameter vp_ModelToLight;
4069 CGparameter vp_TexMatrix;
4070 CGparameter vp_BackgroundTexMatrix;
4071 CGparameter vp_ModelViewProjectionMatrix;
4072 CGparameter vp_ModelViewMatrix;
4073 CGparameter vp_ShadowMapMatrix;
4075 CGparameter fp_Texture_First;
4076 CGparameter fp_Texture_Second;
4077 CGparameter fp_Texture_GammaRamps;
4078 CGparameter fp_Texture_Normal;
4079 CGparameter fp_Texture_Color;
4080 CGparameter fp_Texture_Gloss;
4081 CGparameter fp_Texture_Glow;
4082 CGparameter fp_Texture_SecondaryNormal;
4083 CGparameter fp_Texture_SecondaryColor;
4084 CGparameter fp_Texture_SecondaryGloss;
4085 CGparameter fp_Texture_SecondaryGlow;
4086 CGparameter fp_Texture_Pants;
4087 CGparameter fp_Texture_Shirt;
4088 CGparameter fp_Texture_FogHeightTexture;
4089 CGparameter fp_Texture_FogMask;
4090 CGparameter fp_Texture_Lightmap;
4091 CGparameter fp_Texture_Deluxemap;
4092 CGparameter fp_Texture_Attenuation;
4093 CGparameter fp_Texture_Cube;
4094 CGparameter fp_Texture_Refraction;
4095 CGparameter fp_Texture_Reflection;
4096 CGparameter fp_Texture_ShadowMapRect;
4097 CGparameter fp_Texture_ShadowMapCube;
4098 CGparameter fp_Texture_ShadowMap2D;
4099 CGparameter fp_Texture_CubeProjection;
4100 CGparameter fp_Texture_ScreenDepth;
4101 CGparameter fp_Texture_ScreenNormalMap;
4102 CGparameter fp_Texture_ScreenDiffuse;
4103 CGparameter fp_Texture_ScreenSpecular;
4104 CGparameter fp_Texture_ReflectMask;
4105 CGparameter fp_Texture_ReflectCube;
4106 CGparameter fp_Alpha;
4107 CGparameter fp_BloomBlur_Parameters;
4108 CGparameter fp_ClientTime;
4109 CGparameter fp_Color_Ambient;
4110 CGparameter fp_Color_Diffuse;
4111 CGparameter fp_Color_Specular;
4112 CGparameter fp_Color_Glow;
4113 CGparameter fp_Color_Pants;
4114 CGparameter fp_Color_Shirt;
4115 CGparameter fp_DeferredColor_Ambient;
4116 CGparameter fp_DeferredColor_Diffuse;
4117 CGparameter fp_DeferredColor_Specular;
4118 CGparameter fp_DeferredMod_Diffuse;
4119 CGparameter fp_DeferredMod_Specular;
4120 CGparameter fp_DistortScaleRefractReflect;
4121 CGparameter fp_EyePosition;
4122 CGparameter fp_FogColor;
4123 CGparameter fp_FogHeightFade;
4124 CGparameter fp_FogPlane;
4125 CGparameter fp_FogPlaneViewDist;
4126 CGparameter fp_FogRangeRecip;
4127 CGparameter fp_LightColor;
4128 CGparameter fp_LightDir;
4129 CGparameter fp_LightPosition;
4130 CGparameter fp_OffsetMapping_Scale;
4131 CGparameter fp_PixelSize;
4132 CGparameter fp_ReflectColor;
4133 CGparameter fp_ReflectFactor;
4134 CGparameter fp_ReflectOffset;
4135 CGparameter fp_RefractColor;
4136 CGparameter fp_Saturation;
4137 CGparameter fp_ScreenCenterRefractReflect;
4138 CGparameter fp_ScreenScaleRefractReflect;
4139 CGparameter fp_ScreenToDepth;
4140 CGparameter fp_ShadowMap_Parameters;
4141 CGparameter fp_ShadowMap_TextureScale;
4142 CGparameter fp_SpecularPower;
4143 CGparameter fp_UserVec1;
4144 CGparameter fp_UserVec2;
4145 CGparameter fp_UserVec3;
4146 CGparameter fp_UserVec4;
4147 CGparameter fp_ViewTintColor;
4148 CGparameter fp_ViewToLight;
4149 CGparameter fp_PixelToScreenTexCoord;
4150 CGparameter fp_ModelToReflectCube;
4151 CGparameter fp_BloomColorSubtract;
4155 /// information about each possible shader permutation
4156 r_cg_permutation_t *r_cg_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4157 /// currently selected permutation
4158 r_cg_permutation_t *r_cg_permutation;
4159 /// storage for permutations linked in the hash table
4160 memexpandablearray_t r_cg_permutationarray;
4162 #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));}}
4164 static r_cg_permutation_t *R_CG_FindPermutation(unsigned int mode, unsigned int permutation)
4166 //unsigned int hashdepth = 0;
4167 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4168 r_cg_permutation_t *p;
4169 for (p = r_cg_permutationhash[mode][hashindex];p;p = p->hashnext)
4171 if (p->mode == mode && p->permutation == permutation)
4173 //if (hashdepth > 10)
4174 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4179 p = (r_cg_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_cg_permutationarray);
4181 p->permutation = permutation;
4182 p->hashnext = r_cg_permutationhash[mode][hashindex];
4183 r_cg_permutationhash[mode][hashindex] = p;
4184 //if (hashdepth > 10)
4185 // Con_Printf("R_CG_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4189 static char *R_CG_GetText(const char *filename, qboolean printfromdisknotice)
4192 if (!filename || !filename[0])
4194 if (!strcmp(filename, "cg/default.cg"))
4196 if (!cgshaderstring)
4198 cgshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4200 Con_DPrintf("Loading shaders from file %s...\n", filename);
4202 cgshaderstring = (char *)builtincgshaderstring;
4204 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(cgshaderstring) + 1);
4205 memcpy(shaderstring, cgshaderstring, strlen(cgshaderstring) + 1);
4206 return shaderstring;
4208 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4211 if (printfromdisknotice)
4212 Con_DPrintf("from disk %s... ", filename);
4213 return shaderstring;
4215 return shaderstring;
4218 static void R_CG_CacheShader(r_cg_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4220 // TODO: load or create .fp and .vp shader files
4223 static void R_CG_CompilePermutation(r_cg_permutation_t *p, unsigned int mode, unsigned int permutation)
4226 shadermodeinfo_t *modeinfo = cgshadermodeinfo + mode;
4227 int vertstrings_count = 0, vertstring_length = 0;
4228 int geomstrings_count = 0, geomstring_length = 0;
4229 int fragstrings_count = 0, fragstring_length = 0;
4231 char *vertexstring, *geometrystring, *fragmentstring;
4232 char *vertstring, *geomstring, *fragstring;
4233 const char *vertstrings_list[32+3];
4234 const char *geomstrings_list[32+3];
4235 const char *fragstrings_list[32+3];
4236 char permutationname[256];
4237 char cachename[256];
4238 CGprofile vertexProfile;
4239 CGprofile fragmentProfile;
4247 permutationname[0] = 0;
4249 vertexstring = R_CG_GetText(modeinfo->vertexfilename, true);
4250 geometrystring = R_CG_GetText(modeinfo->geometryfilename, false);
4251 fragmentstring = R_CG_GetText(modeinfo->fragmentfilename, false);
4253 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4254 strlcat(cachename, "cg/", sizeof(cachename));
4256 // the first pretext is which type of shader to compile as
4257 // (later these will all be bound together as a program object)
4258 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4259 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4260 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4262 // the second pretext is the mode (for example a light source)
4263 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4264 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4265 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4266 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4267 strlcat(cachename, modeinfo->name, sizeof(cachename));
4269 // now add all the permutation pretexts
4270 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4272 if (permutation & (1<<i))
4274 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4275 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4276 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4277 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4278 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4282 // keep line numbers correct
4283 vertstrings_list[vertstrings_count++] = "\n";
4284 geomstrings_list[geomstrings_count++] = "\n";
4285 fragstrings_list[fragstrings_count++] = "\n";
4289 // replace spaces in the cachename with _ characters
4290 for (i = 0;cachename[i];i++)
4291 if (cachename[i] == ' ')
4294 // now append the shader text itself
4295 vertstrings_list[vertstrings_count++] = vertexstring;
4296 geomstrings_list[geomstrings_count++] = geometrystring;
4297 fragstrings_list[fragstrings_count++] = fragmentstring;
4299 // if any sources were NULL, clear the respective list
4301 vertstrings_count = 0;
4302 if (!geometrystring)
4303 geomstrings_count = 0;
4304 if (!fragmentstring)
4305 fragstrings_count = 0;
4307 vertstring_length = 0;
4308 for (i = 0;i < vertstrings_count;i++)
4309 vertstring_length += strlen(vertstrings_list[i]);
4310 vertstring = t = Mem_Alloc(tempmempool, vertstring_length + 1);
4311 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4312 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4314 geomstring_length = 0;
4315 for (i = 0;i < geomstrings_count;i++)
4316 geomstring_length += strlen(geomstrings_list[i]);
4317 geomstring = t = Mem_Alloc(tempmempool, geomstring_length + 1);
4318 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4319 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4321 fragstring_length = 0;
4322 for (i = 0;i < fragstrings_count;i++)
4323 fragstring_length += strlen(fragstrings_list[i]);
4324 fragstring = t = Mem_Alloc(tempmempool, fragstring_length + 1);
4325 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4326 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4330 //vertexProfile = CG_PROFILE_ARBVP1;
4331 //fragmentProfile = CG_PROFILE_ARBFP1;
4332 vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);CHECKCGERROR
4333 fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);CHECKCGERROR
4334 //cgGLSetOptimalOptions(vertexProfile);CHECKCGERROR
4335 //cgGLSetOptimalOptions(fragmentProfile);CHECKCGERROR
4336 //cgSetAutoCompile(vid.cgcontext, CG_COMPILE_MANUAL);CHECKCGERROR
4339 // try to load the cached shader, or generate one
4340 R_CG_CacheShader(p, cachename, vertstring, fragstring);
4342 // if caching failed, do a dynamic compile for now
4344 if (vertstring[0] && !p->vprogram)
4345 p->vprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, vertstring, vertexProfile, NULL, NULL);
4347 if (fragstring[0] && !p->fprogram)
4348 p->fprogram = cgCreateProgram(vid.cgcontext, CG_SOURCE, fragstring, fragmentProfile, NULL, NULL);
4351 // look up all the uniform variable names we care about, so we don't
4352 // have to look them up every time we set them
4356 cgGLLoadProgram(p->vprogram);CHECKCGERROR CHECKGLERROR
4357 cgGLEnableProfile(vertexProfile);CHECKCGERROR CHECKGLERROR
4358 p->vp_EyePosition = cgGetNamedParameter(p->vprogram, "EyePosition");
4359 p->vp_FogPlane = cgGetNamedParameter(p->vprogram, "FogPlane");
4360 p->vp_LightDir = cgGetNamedParameter(p->vprogram, "LightDir");
4361 p->vp_LightPosition = cgGetNamedParameter(p->vprogram, "LightPosition");
4362 p->vp_ModelToLight = cgGetNamedParameter(p->vprogram, "ModelToLight");
4363 p->vp_TexMatrix = cgGetNamedParameter(p->vprogram, "TexMatrix");
4364 p->vp_BackgroundTexMatrix = cgGetNamedParameter(p->vprogram, "BackgroundTexMatrix");
4365 p->vp_ModelViewProjectionMatrix = cgGetNamedParameter(p->vprogram, "ModelViewProjectionMatrix");
4366 p->vp_ModelViewMatrix = cgGetNamedParameter(p->vprogram, "ModelViewMatrix");
4367 p->vp_ShadowMapMatrix = cgGetNamedParameter(p->vprogram, "ShadowMapMatrix");
4373 cgGLLoadProgram(p->fprogram);CHECKCGERROR CHECKGLERROR
4374 cgGLEnableProfile(fragmentProfile);CHECKCGERROR CHECKGLERROR
4375 p->fp_Texture_First = cgGetNamedParameter(p->fprogram, "Texture_First");
4376 p->fp_Texture_Second = cgGetNamedParameter(p->fprogram, "Texture_Second");
4377 p->fp_Texture_GammaRamps = cgGetNamedParameter(p->fprogram, "Texture_GammaRamps");
4378 p->fp_Texture_Normal = cgGetNamedParameter(p->fprogram, "Texture_Normal");
4379 p->fp_Texture_Color = cgGetNamedParameter(p->fprogram, "Texture_Color");
4380 p->fp_Texture_Gloss = cgGetNamedParameter(p->fprogram, "Texture_Gloss");
4381 p->fp_Texture_Glow = cgGetNamedParameter(p->fprogram, "Texture_Glow");
4382 p->fp_Texture_SecondaryNormal = cgGetNamedParameter(p->fprogram, "Texture_SecondaryNormal");
4383 p->fp_Texture_SecondaryColor = cgGetNamedParameter(p->fprogram, "Texture_SecondaryColor");
4384 p->fp_Texture_SecondaryGloss = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGloss");
4385 p->fp_Texture_SecondaryGlow = cgGetNamedParameter(p->fprogram, "Texture_SecondaryGlow");
4386 p->fp_Texture_Pants = cgGetNamedParameter(p->fprogram, "Texture_Pants");
4387 p->fp_Texture_Shirt = cgGetNamedParameter(p->fprogram, "Texture_Shirt");
4388 p->fp_Texture_FogHeightTexture = cgGetNamedParameter(p->fprogram, "Texture_FogHeightTexture");
4389 p->fp_Texture_FogMask = cgGetNamedParameter(p->fprogram, "Texture_FogMask");
4390 p->fp_Texture_Lightmap = cgGetNamedParameter(p->fprogram, "Texture_Lightmap");
4391 p->fp_Texture_Deluxemap = cgGetNamedParameter(p->fprogram, "Texture_Deluxemap");
4392 p->fp_Texture_Attenuation = cgGetNamedParameter(p->fprogram, "Texture_Attenuation");
4393 p->fp_Texture_Cube = cgGetNamedParameter(p->fprogram, "Texture_Cube");
4394 p->fp_Texture_Refraction = cgGetNamedParameter(p->fprogram, "Texture_Refraction");
4395 p->fp_Texture_Reflection = cgGetNamedParameter(p->fprogram, "Texture_Reflection");
4396 p->fp_Texture_ShadowMapRect = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapRect");
4397 p->fp_Texture_ShadowMapCube = cgGetNamedParameter(p->fprogram, "Texture_ShadowMapCube");
4398 p->fp_Texture_ShadowMap2D = cgGetNamedParameter(p->fprogram, "Texture_ShadowMap2D");
4399 p->fp_Texture_CubeProjection = cgGetNamedParameter(p->fprogram, "Texture_CubeProjection");
4400 p->fp_Texture_ScreenDepth = cgGetNamedParameter(p->fprogram, "Texture_ScreenDepth");
4401 p->fp_Texture_ScreenNormalMap = cgGetNamedParameter(p->fprogram, "Texture_ScreenNormalMap");
4402 p->fp_Texture_ScreenDiffuse = cgGetNamedParameter(p->fprogram, "Texture_ScreenDiffuse");
4403 p->fp_Texture_ScreenSpecular = cgGetNamedParameter(p->fprogram, "Texture_ScreenSpecular");
4404 p->fp_Texture_ReflectMask = cgGetNamedParameter(p->fprogram, "Texture_ReflectMask");
4405 p->fp_Texture_ReflectCube = cgGetNamedParameter(p->fprogram, "Texture_ReflectCube");
4406 p->fp_Alpha = cgGetNamedParameter(p->fprogram, "Alpha");
4407 p->fp_BloomBlur_Parameters = cgGetNamedParameter(p->fprogram, "BloomBlur_Parameters");
4408 p->fp_ClientTime = cgGetNamedParameter(p->fprogram, "ClientTime");
4409 p->fp_Color_Ambient = cgGetNamedParameter(p->fprogram, "Color_Ambient");
4410 p->fp_Color_Diffuse = cgGetNamedParameter(p->fprogram, "Color_Diffuse");
4411 p->fp_Color_Specular = cgGetNamedParameter(p->fprogram, "Color_Specular");
4412 p->fp_Color_Glow = cgGetNamedParameter(p->fprogram, "Color_Glow");
4413 p->fp_Color_Pants = cgGetNamedParameter(p->fprogram, "Color_Pants");
4414 p->fp_Color_Shirt = cgGetNamedParameter(p->fprogram, "Color_Shirt");
4415 p->fp_DeferredColor_Ambient = cgGetNamedParameter(p->fprogram, "DeferredColor_Ambient");
4416 p->fp_DeferredColor_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredColor_Diffuse");
4417 p->fp_DeferredColor_Specular = cgGetNamedParameter(p->fprogram, "DeferredColor_Specular");
4418 p->fp_DeferredMod_Diffuse = cgGetNamedParameter(p->fprogram, "DeferredMod_Diffuse");
4419 p->fp_DeferredMod_Specular = cgGetNamedParameter(p->fprogram, "DeferredMod_Specular");
4420 p->fp_DistortScaleRefractReflect = cgGetNamedParameter(p->fprogram, "DistortScaleRefractReflect");
4421 p->fp_EyePosition = cgGetNamedParameter(p->fprogram, "EyePosition");
4422 p->fp_FogColor = cgGetNamedParameter(p->fprogram, "FogColor");
4423 p->fp_FogHeightFade = cgGetNamedParameter(p->fprogram, "FogHeightFade");
4424 p->fp_FogPlane = cgGetNamedParameter(p->fprogram, "FogPlane");
4425 p->fp_FogPlaneViewDist = cgGetNamedParameter(p->fprogram, "FogPlaneViewDist");
4426 p->fp_FogRangeRecip = cgGetNamedParameter(p->fprogram, "FogRangeRecip");
4427 p->fp_LightColor = cgGetNamedParameter(p->fprogram, "LightColor");
4428 p->fp_LightDir = cgGetNamedParameter(p->fprogram, "LightDir");
4429 p->fp_LightPosition = cgGetNamedParameter(p->fprogram, "LightPosition");
4430 p->fp_OffsetMapping_Scale = cgGetNamedParameter(p->fprogram, "OffsetMapping_Scale");
4431 p->fp_PixelSize = cgGetNamedParameter(p->fprogram, "PixelSize");
4432 p->fp_ReflectColor = cgGetNamedParameter(p->fprogram, "ReflectColor");
4433 p->fp_ReflectFactor = cgGetNamedParameter(p->fprogram, "ReflectFactor");
4434 p->fp_ReflectOffset = cgGetNamedParameter(p->fprogram, "ReflectOffset");
4435 p->fp_RefractColor = cgGetNamedParameter(p->fprogram, "RefractColor");
4436 p->fp_Saturation = cgGetNamedParameter(p->fprogram, "Saturation");
4437 p->fp_ScreenCenterRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenCenterRefractReflect");
4438 p->fp_ScreenScaleRefractReflect = cgGetNamedParameter(p->fprogram, "ScreenScaleRefractReflect");
4439 p->fp_ScreenToDepth = cgGetNamedParameter(p->fprogram, "ScreenToDepth");
4440 p->fp_ShadowMap_Parameters = cgGetNamedParameter(p->fprogram, "ShadowMap_Parameters");
4441 p->fp_ShadowMap_TextureScale = cgGetNamedParameter(p->fprogram, "ShadowMap_TextureScale");
4442 p->fp_SpecularPower = cgGetNamedParameter(p->fprogram, "SpecularPower");
4443 p->fp_UserVec1 = cgGetNamedParameter(p->fprogram, "UserVec1");
4444 p->fp_UserVec2 = cgGetNamedParameter(p->fprogram, "UserVec2");
4445 p->fp_UserVec3 = cgGetNamedParameter(p->fprogram, "UserVec3");
4446 p->fp_UserVec4 = cgGetNamedParameter(p->fprogram, "UserVec4");
4447 p->fp_ViewTintColor = cgGetNamedParameter(p->fprogram, "ViewTintColor");
4448 p->fp_ViewToLight = cgGetNamedParameter(p->fprogram, "ViewToLight");
4449 p->fp_PixelToScreenTexCoord = cgGetNamedParameter(p->fprogram, "PixelToScreenTexCoord");
4450 p->fp_ModelToReflectCube = cgGetNamedParameter(p->fprogram, "ModelToReflectCube");
4451 p->fp_BloomColorSubtract = cgGetNamedParameter(p->fprogram, "BloomColorSubtract");
4455 if ((p->vprogram || !vertstring[0]) && (p->fprogram || !fragstring[0]))
4456 Con_DPrintf("^5CG shader %s compiled.\n", permutationname);
4458 Con_Printf("^1CG shader %s failed! some features may not work properly.\n", permutationname);
4462 Mem_Free(vertstring);
4464 Mem_Free(geomstring);
4466 Mem_Free(fragstring);
4468 Mem_Free(vertexstring);
4470 Mem_Free(geometrystring);
4472 Mem_Free(fragmentstring);
4475 void R_SetupShader_SetPermutationCG(unsigned int mode, unsigned int permutation)
4477 r_cg_permutation_t *perm = R_CG_FindPermutation(mode, permutation);
4480 if (r_cg_permutation != perm)
4482 r_cg_permutation = perm;
4483 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4485 if (!r_cg_permutation->compiled)
4486 R_CG_CompilePermutation(perm, mode, permutation);
4487 if (!r_cg_permutation->vprogram && !r_cg_permutation->fprogram)
4489 // remove features until we find a valid permutation
4491 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4493 // reduce i more quickly whenever it would not remove any bits
4494 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4495 if (!(permutation & j))
4498 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4499 if (!r_cg_permutation->compiled)
4500 R_CG_CompilePermutation(perm, mode, permutation);
4501 if (r_cg_permutation->vprogram || r_cg_permutation->fprogram)
4504 if (i >= SHADERPERMUTATION_COUNT)
4506 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4507 r_cg_permutation = R_CG_FindPermutation(mode, permutation);
4508 return; // no bit left to clear, entire mode is broken
4514 if (r_cg_permutation->vprogram)
4516 cgGLLoadProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4517 cgGLBindProgram(r_cg_permutation->vprogram);CHECKCGERROR CHECKGLERROR
4518 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4522 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4523 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4525 if (r_cg_permutation->fprogram)
4527 cgGLLoadProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4528 cgGLBindProgram(r_cg_permutation->fprogram);CHECKCGERROR CHECKGLERROR
4529 cgGLEnableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4533 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4534 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4538 if (r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
4539 if (r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
4540 if (r_cg_permutation->fp_ClientTime) cgGLSetParameter1f(r_cg_permutation->fp_ClientTime, cl.time);CHECKCGERROR
4543 void CG_BindTexture(CGparameter param, rtexture_t *tex)
4545 cgGLSetTextureParameter(param, R_GetTexture(tex));
4546 cgGLEnableTextureParameter(param);
4554 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
4555 extern D3DCAPS9 vid_d3d9caps;
4558 struct r_hlsl_permutation_s;
4559 typedef struct r_hlsl_permutation_s
4561 /// hash lookup data
4562 struct r_hlsl_permutation_s *hashnext;
4564 unsigned int permutation;
4566 /// indicates if we have tried compiling this permutation already
4568 /// NULL if compilation failed
4569 IDirect3DVertexShader9 *vertexshader;
4570 IDirect3DPixelShader9 *pixelshader;
4572 r_hlsl_permutation_t;
4574 typedef enum D3DVSREGISTER_e
4576 D3DVSREGISTER_TexMatrix = 0, // float4x4
4577 D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
4578 D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
4579 D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
4580 D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
4581 D3DVSREGISTER_ModelToLight = 20, // float4x4
4582 D3DVSREGISTER_EyePosition = 24,
4583 D3DVSREGISTER_FogPlane = 25,
4584 D3DVSREGISTER_LightDir = 26,
4585 D3DVSREGISTER_LightPosition = 27,
4589 typedef enum D3DPSREGISTER_e
4591 D3DPSREGISTER_Alpha = 0,
4592 D3DPSREGISTER_BloomBlur_Parameters = 1,
4593 D3DPSREGISTER_ClientTime = 2,
4594 D3DPSREGISTER_Color_Ambient = 3,
4595 D3DPSREGISTER_Color_Diffuse = 4,
4596 D3DPSREGISTER_Color_Specular = 5,
4597 D3DPSREGISTER_Color_Glow = 6,
4598 D3DPSREGISTER_Color_Pants = 7,
4599 D3DPSREGISTER_Color_Shirt = 8,
4600 D3DPSREGISTER_DeferredColor_Ambient = 9,
4601 D3DPSREGISTER_DeferredColor_Diffuse = 10,
4602 D3DPSREGISTER_DeferredColor_Specular = 11,
4603 D3DPSREGISTER_DeferredMod_Diffuse = 12,
4604 D3DPSREGISTER_DeferredMod_Specular = 13,
4605 D3DPSREGISTER_DistortScaleRefractReflect = 14,
4606 D3DPSREGISTER_EyePosition = 15, // unused
4607 D3DPSREGISTER_FogColor = 16,
4608 D3DPSREGISTER_FogHeightFade = 17,
4609 D3DPSREGISTER_FogPlane = 18,
4610 D3DPSREGISTER_FogPlaneViewDist = 19,
4611 D3DPSREGISTER_FogRangeRecip = 20,
4612 D3DPSREGISTER_LightColor = 21,
4613 D3DPSREGISTER_LightDir = 22, // unused
4614 D3DPSREGISTER_LightPosition = 23,
4615 D3DPSREGISTER_OffsetMapping_Scale = 24,
4616 D3DPSREGISTER_PixelSize = 25,
4617 D3DPSREGISTER_ReflectColor = 26,
4618 D3DPSREGISTER_ReflectFactor = 27,
4619 D3DPSREGISTER_ReflectOffset = 28,
4620 D3DPSREGISTER_RefractColor = 29,
4621 D3DPSREGISTER_Saturation = 30,
4622 D3DPSREGISTER_ScreenCenterRefractReflect = 31,
4623 D3DPSREGISTER_ScreenScaleRefractReflect = 32,
4624 D3DPSREGISTER_ScreenToDepth = 33,
4625 D3DPSREGISTER_ShadowMap_Parameters = 34,
4626 D3DPSREGISTER_ShadowMap_TextureScale = 35,
4627 D3DPSREGISTER_SpecularPower = 36,
4628 D3DPSREGISTER_UserVec1 = 37,
4629 D3DPSREGISTER_UserVec2 = 38,
4630 D3DPSREGISTER_UserVec3 = 39,
4631 D3DPSREGISTER_UserVec4 = 40,
4632 D3DPSREGISTER_ViewTintColor = 41,
4633 D3DPSREGISTER_PixelToScreenTexCoord = 42,
4634 D3DPSREGISTER_BloomColorSubtract = 43,
4635 D3DPSREGISTER_ViewToLight = 44, // float4x4
4636 D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
4641 /// information about each possible shader permutation
4642 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4643 /// currently selected permutation
4644 r_hlsl_permutation_t *r_hlsl_permutation;
4645 /// storage for permutations linked in the hash table
4646 memexpandablearray_t r_hlsl_permutationarray;
4648 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
4650 //unsigned int hashdepth = 0;
4651 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4652 r_hlsl_permutation_t *p;
4653 for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
4655 if (p->mode == mode && p->permutation == permutation)
4657 //if (hashdepth > 10)
4658 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4663 p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
4665 p->permutation = permutation;
4666 p->hashnext = r_hlsl_permutationhash[mode][hashindex];
4667 r_hlsl_permutationhash[mode][hashindex] = p;
4668 //if (hashdepth > 10)
4669 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4673 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
4676 if (!filename || !filename[0])
4678 if (!strcmp(filename, "hlsl/default.hlsl"))
4680 if (!hlslshaderstring)
4682 hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4683 if (hlslshaderstring)
4684 Con_DPrintf("Loading shaders from file %s...\n", filename);
4686 hlslshaderstring = (char *)builtincgshaderstring;
4688 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
4689 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
4690 return shaderstring;
4692 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4695 if (printfromdisknotice)
4696 Con_DPrintf("from disk %s... ", filename);
4697 return shaderstring;
4699 return shaderstring;
4703 #include <d3dx9mesh.h>
4705 #pragma comment(lib, "d3dx9.lib")
4708 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4710 DWORD *vsbin = NULL;
4711 DWORD *psbin = NULL;
4712 fs_offset_t vsbinsize;
4713 fs_offset_t psbinsize;
4714 // IDirect3DVertexShader9 *vs = NULL;
4715 // IDirect3DPixelShader9 *ps = NULL;
4716 ID3DXBuffer *vslog = NULL;
4717 ID3DXBuffer *vsbuffer = NULL;
4718 ID3DXConstantTable *vsconstanttable = NULL;
4719 ID3DXBuffer *pslog = NULL;
4720 ID3DXBuffer *psbuffer = NULL;
4721 ID3DXConstantTable *psconstanttable = NULL;
4724 char temp[MAX_INPUTLINE];
4725 const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
4726 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4727 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4728 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
4729 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
4730 if ((!vsbin && vertstring) || (!psbin && fragstring))
4732 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4733 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4734 if (vertstring && vertstring[0])
4736 vsresult = D3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, 0, &vsbuffer, &vslog, &vsconstanttable);
4739 vsbinsize = vsbuffer->GetBufferSize();
4740 vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
4741 memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
4742 vsbuffer->Release();
4746 strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
4747 Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
4751 if (fragstring && fragstring[0])
4753 psresult = D3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, 0, &psbuffer, &pslog, &psconstanttable);
4756 psbinsize = psbuffer->GetBufferSize();
4757 psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
4758 memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
4759 psbuffer->Release();
4763 strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
4764 Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
4771 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
4772 if (FAILED(vsresult))
4773 Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
4777 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
4778 if (FAILED(psresult))
4779 Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
4781 // free the shader data
4782 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4783 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4786 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
4789 shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
4790 int vertstrings_count = 0, vertstring_length = 0;
4791 int geomstrings_count = 0, geomstring_length = 0;
4792 int fragstrings_count = 0, fragstring_length = 0;
4794 char *vertexstring, *geometrystring, *fragmentstring;
4795 char *vertstring, *geomstring, *fragstring;
4796 const char *vertstrings_list[32+3];
4797 const char *geomstrings_list[32+3];
4798 const char *fragstrings_list[32+3];
4799 char permutationname[256];
4800 char cachename[256];
4805 p->vertexshader = NULL;
4806 p->pixelshader = NULL;
4808 permutationname[0] = 0;
4810 vertexstring = R_HLSL_GetText(modeinfo->vertexfilename, true);
4811 geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
4812 fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
4814 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4815 strlcat(cachename, "hlsl/", sizeof(cachename));
4817 // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
4818 vertstrings_list[vertstrings_count++] = "#define HLSL\n";
4819 geomstrings_list[geomstrings_count++] = "#define HLSL\n";
4820 fragstrings_list[fragstrings_count++] = "#define HLSL\n";
4822 // the first pretext is which type of shader to compile as
4823 // (later these will all be bound together as a program object)
4824 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4825 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4826 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4828 // the second pretext is the mode (for example a light source)
4829 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4830 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4831 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4832 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4833 strlcat(cachename, modeinfo->name, sizeof(cachename));
4835 // now add all the permutation pretexts
4836 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4838 if (permutation & (1<<i))
4840 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4841 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4842 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4843 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4844 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4848 // keep line numbers correct
4849 vertstrings_list[vertstrings_count++] = "\n";
4850 geomstrings_list[geomstrings_count++] = "\n";
4851 fragstrings_list[fragstrings_count++] = "\n";
4855 // replace spaces in the cachename with _ characters
4856 for (i = 0;cachename[i];i++)
4857 if (cachename[i] == ' ')
4860 // now append the shader text itself
4861 vertstrings_list[vertstrings_count++] = vertexstring;
4862 geomstrings_list[geomstrings_count++] = geometrystring;
4863 fragstrings_list[fragstrings_count++] = fragmentstring;
4865 // if any sources were NULL, clear the respective list
4867 vertstrings_count = 0;
4868 if (!geometrystring)
4869 geomstrings_count = 0;
4870 if (!fragmentstring)
4871 fragstrings_count = 0;
4873 vertstring_length = 0;
4874 for (i = 0;i < vertstrings_count;i++)
4875 vertstring_length += strlen(vertstrings_list[i]);
4876 vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
4877 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4878 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4880 geomstring_length = 0;
4881 for (i = 0;i < geomstrings_count;i++)
4882 geomstring_length += strlen(geomstrings_list[i]);
4883 geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
4884 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4885 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4887 fragstring_length = 0;
4888 for (i = 0;i < fragstrings_count;i++)
4889 fragstring_length += strlen(fragstrings_list[i]);
4890 fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
4891 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4892 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4894 // try to load the cached shader, or generate one
4895 R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
4897 if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
4898 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
4900 Con_Printf("^1HLSL shader %s failed! some features may not work properly.\n", permutationname);
4904 Mem_Free(vertstring);
4906 Mem_Free(geomstring);
4908 Mem_Free(fragstring);
4910 Mem_Free(vertexstring);
4912 Mem_Free(geometrystring);
4914 Mem_Free(fragmentstring);
4917 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
4918 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
4919 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4920 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4921 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4922 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4924 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
4925 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
4926 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4927 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4928 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4929 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4931 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
4933 r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
4934 if (r_hlsl_permutation != perm)
4936 r_hlsl_permutation = perm;
4937 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4939 if (!r_hlsl_permutation->compiled)
4940 R_HLSL_CompilePermutation(perm, mode, permutation);
4941 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4943 // remove features until we find a valid permutation
4945 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4947 // reduce i more quickly whenever it would not remove any bits
4948 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4949 if (!(permutation & j))
4952 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4953 if (!r_hlsl_permutation->compiled)
4954 R_HLSL_CompilePermutation(perm, mode, permutation);
4955 if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
4958 if (i >= SHADERPERMUTATION_COUNT)
4960 //Con_Printf("Could not find a working Cg shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4961 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4962 return; // no bit left to clear, entire mode is broken
4966 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
4967 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
4969 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
4970 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
4971 hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
4975 void R_GLSL_Restart_f(void)
4977 unsigned int i, limit;
4978 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4979 Mem_Free(glslshaderstring);
4980 glslshaderstring = NULL;
4981 if (cgshaderstring && cgshaderstring != builtincgshaderstring)
4982 Mem_Free(cgshaderstring);
4983 cgshaderstring = NULL;
4984 if (hlslshaderstring && hlslshaderstring != builtincgshaderstring)
4985 Mem_Free(hlslshaderstring);
4986 hlslshaderstring = NULL;
4987 switch(vid.renderpath)
4989 case RENDERPATH_D3D9:
4992 r_hlsl_permutation_t *p;
4993 r_hlsl_permutation = NULL;
4994 // cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4995 // cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
4996 // cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4997 // cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
4998 limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
4999 for (i = 0;i < limit;i++)
5001 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
5003 if (p->vertexshader)
5004 IDirect3DVertexShader9_Release(p->vertexshader);
5006 IDirect3DPixelShader9_Release(p->pixelshader);
5007 Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
5010 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
5014 case RENDERPATH_D3D10:
5015 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5017 case RENDERPATH_D3D11:
5018 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5020 case RENDERPATH_GL20:
5022 r_glsl_permutation_t *p;
5023 r_glsl_permutation = NULL;
5024 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
5025 for (i = 0;i < limit;i++)
5027 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
5029 GL_Backend_FreeProgram(p->program);
5030 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
5033 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
5036 case RENDERPATH_CGGL:
5039 r_cg_permutation_t *p;
5040 r_cg_permutation = NULL;
5041 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
5042 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_VERTEX));CHECKCGERROR CHECKGLERROR
5043 cgGLDisableProfile(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
5044 cgGLUnbindProgram(cgGLGetLatestProfile(CG_GL_FRAGMENT));CHECKCGERROR CHECKGLERROR
5045 limit = Mem_ExpandableArray_IndexRange(&r_cg_permutationarray);
5046 for (i = 0;i < limit;i++)
5048 if ((p = (r_cg_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_cg_permutationarray, i)))
5051 cgDestroyProgram(p->vprogram);
5053 cgDestroyProgram(p->fprogram);
5054 Mem_ExpandableArray_FreeRecord(&r_cg_permutationarray, (void*)p);
5057 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
5061 case RENDERPATH_GL13:
5062 case RENDERPATH_GL11:
5067 void R_GLSL_DumpShader_f(void)
5072 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
5075 FS_Print(file, "/* The engine may define the following macros:\n");
5076 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
5077 for (i = 0;i < SHADERMODE_COUNT;i++)
5078 FS_Print(file, glslshadermodeinfo[i].pretext);
5079 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
5080 FS_Print(file, shaderpermutationinfo[i].pretext);
5081 FS_Print(file, "*/\n");
5082 FS_Print(file, builtinshaderstring);
5084 Con_Printf("glsl/default.glsl written\n");
5087 Con_Printf("failed to write to glsl/default.glsl\n");
5090 file = FS_OpenRealFile("cg/default.cg", "w", false);
5093 FS_Print(file, "/* The engine may define the following macros:\n");
5094 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
5095 for (i = 0;i < SHADERMODE_COUNT;i++)
5096 FS_Print(file, cgshadermodeinfo[i].pretext);
5097 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
5098 FS_Print(file, shaderpermutationinfo[i].pretext);
5099 FS_Print(file, "*/\n");
5100 FS_Print(file, builtincgshaderstring);
5102 Con_Printf("cg/default.cg written\n");
5105 Con_Printf("failed to write to cg/default.cg\n");
5109 file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
5112 FS_Print(file, "/* The engine may define the following macros:\n");
5113 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
5114 for (i = 0;i < SHADERMODE_COUNT;i++)
5115 FS_Print(file, hlslshadermodeinfo[i].pretext);
5116 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
5117 FS_Print(file, shaderpermutationinfo[i].pretext);
5118 FS_Print(file, "*/\n");
5119 FS_Print(file, builtincgshaderstring);
5121 Con_Printf("hlsl/default.hlsl written\n");
5124 Con_Printf("failed to write to hlsl/default.hlsl\n");
5128 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
5131 texturemode = GL_MODULATE;
5132 switch (vid.renderpath)
5134 case RENDERPATH_D3D9:
5136 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (r_shadow_glossexact.integer ? SHADERPERMUTATION_EXACTSPECULARMATH : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
5137 R_Mesh_TexBind(GL20TU_FIRST , first );
5138 R_Mesh_TexBind(GL20TU_SECOND, second);
5141 case RENDERPATH_D3D10:
5142 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5144 case RENDERPATH_D3D11:
5145 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5147 case RENDERPATH_GL20:
5148 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))));
5149 R_Mesh_TexBind(GL20TU_FIRST , first );
5150 R_Mesh_TexBind(GL20TU_SECOND, second);
5152 case RENDERPATH_CGGL:
5155 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))));
5156 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , first );CHECKCGERROR
5157 if (r_cg_permutation->fp_Texture_Second) CG_BindTexture(r_cg_permutation->fp_Texture_Second, second);CHECKCGERROR
5160 case RENDERPATH_GL13:
5161 R_Mesh_TexBind(0, first );
5162 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
5163 R_Mesh_TexBind(1, second);
5165 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
5167 case RENDERPATH_GL11:
5168 R_Mesh_TexBind(0, first );
5173 void R_SetupShader_DepthOrShadow(void)
5175 switch (vid.renderpath)
5177 case RENDERPATH_D3D9:
5179 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5182 case RENDERPATH_D3D10:
5183 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5185 case RENDERPATH_D3D11:
5186 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5188 case RENDERPATH_GL20:
5189 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
5191 case RENDERPATH_CGGL:
5193 R_SetupShader_SetPermutationCG(SHADERMODE_DEPTH_OR_SHADOW, 0);
5196 case RENDERPATH_GL13:
5197 R_Mesh_TexBind(0, 0);
5198 R_Mesh_TexBind(1, 0);
5200 case RENDERPATH_GL11:
5201 R_Mesh_TexBind(0, 0);
5206 void R_SetupShader_ShowDepth(void)
5208 switch (vid.renderpath)
5210 case RENDERPATH_D3D9:
5212 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
5215 case RENDERPATH_D3D10:
5216 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5218 case RENDERPATH_D3D11:
5219 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5221 case RENDERPATH_GL20:
5222 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
5224 case RENDERPATH_CGGL:
5226 R_SetupShader_SetPermutationCG(SHADERMODE_SHOWDEPTH, 0);
5229 case RENDERPATH_GL13:
5231 case RENDERPATH_GL11:
5236 extern qboolean r_shadow_usingdeferredprepass;
5237 extern cvar_t r_shadow_deferred_8bitrange;
5238 extern rtexture_t *r_shadow_attenuationgradienttexture;
5239 extern rtexture_t *r_shadow_attenuation2dtexture;
5240 extern rtexture_t *r_shadow_attenuation3dtexture;
5241 extern qboolean r_shadow_usingshadowmaprect;
5242 extern qboolean r_shadow_usingshadowmapcube;
5243 extern qboolean r_shadow_usingshadowmap2d;
5244 extern qboolean r_shadow_usingshadowmaportho;
5245 extern float r_shadow_shadowmap_texturescale[2];
5246 extern float r_shadow_shadowmap_parameters[4];
5247 extern qboolean r_shadow_shadowmapvsdct;
5248 extern qboolean r_shadow_shadowmapsampler;
5249 extern int r_shadow_shadowmappcf;
5250 extern rtexture_t *r_shadow_shadowmaprectangletexture;
5251 extern rtexture_t *r_shadow_shadowmap2dtexture;
5252 extern rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS];
5253 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
5254 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
5255 extern matrix4x4_t r_shadow_shadowmapmatrix;
5256 extern int r_shadow_shadowmaplod; // changes for each light based on distance
5257 extern int r_shadow_prepass_width;
5258 extern int r_shadow_prepass_height;
5259 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
5260 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
5261 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
5262 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
5263 extern cvar_t gl_mesh_separatearrays;
5264 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
5266 // select a permutation of the lighting shader appropriate to this
5267 // combination of texture, entity, light source, and fogging, only use the
5268 // minimum features necessary to avoid wasting rendering time in the
5269 // fragment shader on features that are not being used
5270 unsigned int permutation = 0;
5271 unsigned int mode = 0;
5273 r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
5274 if (rsurfacepass == RSURFPASS_BACKGROUND)
5276 // distorted background
5277 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
5278 mode = SHADERMODE_WATER;
5279 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
5280 mode = SHADERMODE_REFRACTION;
5283 mode = SHADERMODE_GENERIC;
5284 permutation |= SHADERPERMUTATION_DIFFUSE;
5286 GL_AlphaTest(false);
5287 GL_BlendFunc(GL_ONE, GL_ZERO);
5289 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
5291 if (r_glsl_offsetmapping.integer)
5293 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5294 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5295 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5296 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5297 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5299 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5300 if (r_glsl_offsetmapping_reliefmapping.integer)
5301 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5304 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5305 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5306 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
5307 permutation |= SHADERPERMUTATION_ALPHAKILL;
5308 // normalmap (deferred prepass), may use alpha test on diffuse
5309 mode = SHADERMODE_DEFERREDGEOMETRY;
5310 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5311 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5312 GL_AlphaTest(false);
5313 GL_BlendFunc(GL_ONE, GL_ZERO);
5315 else if (rsurfacepass == RSURFPASS_RTLIGHT)
5317 if (r_glsl_offsetmapping.integer)
5319 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5320 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5321 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5322 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5323 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5325 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5326 if (r_glsl_offsetmapping_reliefmapping.integer)
5327 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5330 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5331 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5333 mode = SHADERMODE_LIGHTSOURCE;
5334 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5335 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5336 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
5337 permutation |= SHADERPERMUTATION_CUBEFILTER;
5338 if (diffusescale > 0)
5339 permutation |= SHADERPERMUTATION_DIFFUSE;
5340 if (specularscale > 0)
5342 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5343 if (r_shadow_glossexact.integer)
5344 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5346 if (r_refdef.fogenabled)
5347 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5348 if (rsurface.texture->colormapping)
5349 permutation |= SHADERPERMUTATION_COLORMAPPING;
5350 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
5352 if (r_shadow_usingshadowmaprect)
5353 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5354 if (r_shadow_usingshadowmap2d)
5355 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5356 if (r_shadow_usingshadowmapcube)
5357 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
5358 else if(r_shadow_shadowmapvsdct)
5359 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5361 if (r_shadow_shadowmapsampler)
5362 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5363 if (r_shadow_shadowmappcf > 1)
5364 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5365 else if (r_shadow_shadowmappcf)
5366 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5368 if (rsurface.texture->reflectmasktexture)
5369 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5370 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5371 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
5373 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5375 if (r_glsl_offsetmapping.integer)
5377 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5378 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5379 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5380 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5381 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5383 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5384 if (r_glsl_offsetmapping_reliefmapping.integer)
5385 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5388 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5389 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5390 // unshaded geometry (fullbright or ambient model lighting)
5391 mode = SHADERMODE_FLATCOLOR;
5392 ambientscale = diffusescale = specularscale = 0;
5393 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5394 permutation |= SHADERPERMUTATION_GLOW;
5395 if (r_refdef.fogenabled)
5396 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5397 if (rsurface.texture->colormapping)
5398 permutation |= SHADERPERMUTATION_COLORMAPPING;
5399 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5401 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5402 if (r_shadow_usingshadowmaprect)
5403 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5404 if (r_shadow_usingshadowmap2d)
5405 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5407 if (r_shadow_shadowmapsampler)
5408 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5409 if (r_shadow_shadowmappcf > 1)
5410 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5411 else if (r_shadow_shadowmappcf)
5412 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5414 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5415 permutation |= SHADERPERMUTATION_REFLECTION;
5416 if (rsurface.texture->reflectmasktexture)
5417 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5418 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5419 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5421 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
5423 if (r_glsl_offsetmapping.integer)
5425 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5426 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5427 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5428 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5429 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5431 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5432 if (r_glsl_offsetmapping_reliefmapping.integer)
5433 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5436 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5437 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5438 // directional model lighting
5439 mode = SHADERMODE_LIGHTDIRECTION;
5440 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5441 permutation |= SHADERPERMUTATION_GLOW;
5442 permutation |= SHADERPERMUTATION_DIFFUSE;
5443 if (specularscale > 0)
5445 permutation |= SHADERPERMUTATION_SPECULAR;
5446 if (r_shadow_glossexact.integer)
5447 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5449 if (r_refdef.fogenabled)
5450 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5451 if (rsurface.texture->colormapping)
5452 permutation |= SHADERPERMUTATION_COLORMAPPING;
5453 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5455 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5456 if (r_shadow_usingshadowmaprect)
5457 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5458 if (r_shadow_usingshadowmap2d)
5459 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5461 if (r_shadow_shadowmapsampler)
5462 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5463 if (r_shadow_shadowmappcf > 1)
5464 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5465 else if (r_shadow_shadowmappcf)
5466 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5468 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5469 permutation |= SHADERPERMUTATION_REFLECTION;
5470 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5471 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5472 if (rsurface.texture->reflectmasktexture)
5473 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5474 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5475 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5477 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5479 if (r_glsl_offsetmapping.integer)
5481 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5482 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5483 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5484 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5485 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5487 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5488 if (r_glsl_offsetmapping_reliefmapping.integer)
5489 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5492 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5493 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5494 // ambient model lighting
5495 mode = SHADERMODE_LIGHTDIRECTION;
5496 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5497 permutation |= SHADERPERMUTATION_GLOW;
5498 if (r_refdef.fogenabled)
5499 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5500 if (rsurface.texture->colormapping)
5501 permutation |= SHADERPERMUTATION_COLORMAPPING;
5502 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5504 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5505 if (r_shadow_usingshadowmaprect)
5506 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5507 if (r_shadow_usingshadowmap2d)
5508 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5510 if (r_shadow_shadowmapsampler)
5511 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5512 if (r_shadow_shadowmappcf > 1)
5513 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5514 else if (r_shadow_shadowmappcf)
5515 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5517 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5518 permutation |= SHADERPERMUTATION_REFLECTION;
5519 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5520 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5521 if (rsurface.texture->reflectmasktexture)
5522 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5523 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5524 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5528 if (r_glsl_offsetmapping.integer)
5530 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5531 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5532 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5533 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5534 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5536 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5537 if (r_glsl_offsetmapping_reliefmapping.integer)
5538 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5541 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5542 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5544 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5545 permutation |= SHADERPERMUTATION_GLOW;
5546 if (r_refdef.fogenabled)
5547 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5548 if (rsurface.texture->colormapping)
5549 permutation |= SHADERPERMUTATION_COLORMAPPING;
5550 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5552 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5553 if (r_shadow_usingshadowmaprect)
5554 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
5555 if (r_shadow_usingshadowmap2d)
5556 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5558 if (r_shadow_shadowmapsampler)
5559 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5560 if (r_shadow_shadowmappcf > 1)
5561 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5562 else if (r_shadow_shadowmappcf)
5563 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5565 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5566 permutation |= SHADERPERMUTATION_REFLECTION;
5567 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5568 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5569 if (rsurface.texture->reflectmasktexture)
5570 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5571 if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5573 // deluxemapping (light direction texture)
5574 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5575 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5577 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5578 permutation |= SHADERPERMUTATION_DIFFUSE;
5579 if (specularscale > 0)
5581 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5582 if (r_shadow_glossexact.integer)
5583 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5586 else if (r_glsl_deluxemapping.integer >= 2)
5588 // fake deluxemapping (uniform light direction in tangentspace)
5589 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5590 permutation |= SHADERPERMUTATION_DIFFUSE;
5591 if (specularscale > 0)
5593 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5594 if (r_shadow_glossexact.integer)
5595 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
5598 else if (rsurface.uselightmaptexture)
5600 // ordinary lightmapping (q1bsp, q3bsp)
5601 mode = SHADERMODE_LIGHTMAP;
5605 // ordinary vertex coloring (q3bsp)
5606 mode = SHADERMODE_VERTEXCOLOR;
5608 GL_AlphaTest((rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) != 0);
5609 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5611 switch(vid.renderpath)
5613 case RENDERPATH_D3D9:
5615 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5616 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5617 R_SetupShader_SetPermutationHLSL(mode, permutation);
5618 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
5619 if (mode == SHADERMODE_LIGHTSOURCE)
5621 Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
5622 hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5626 if (mode == SHADERMODE_LIGHTDIRECTION)
5628 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5631 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
5632 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
5633 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
5634 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5635 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5637 if (mode == SHADERMODE_LIGHTSOURCE)
5639 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5640 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5641 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
5642 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
5643 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5645 // additive passes are only darkened by fog, not tinted
5646 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5647 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5651 if (mode == SHADERMODE_FLATCOLOR)
5653 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
5655 else if (mode == SHADERMODE_LIGHTDIRECTION)
5657 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);
5658 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
5659 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5660 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);
5661 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5662 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5663 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5667 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
5668 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5669 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5670 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5671 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5673 // additive passes are only darkened by fog, not tinted
5674 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5675 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5677 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5678 hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
5679 hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5680 hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5681 hlslPSSetParameter4fv(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f);
5682 hlslPSSetParameter4fv(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f);
5683 hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5684 hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
5685 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5687 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5688 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5689 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5690 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3]);
5691 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5692 if (rsurface.texture->pantstexture)
5693 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5695 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
5696 if (rsurface.texture->shirttexture)
5697 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5699 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
5700 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5701 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
5702 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
5703 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
5704 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
5705 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5706 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5708 R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5709 R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5710 R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5711 R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5712 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5713 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5714 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5715 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5716 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5717 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5718 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5719 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5720 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5721 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5722 R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5723 R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5724 if (rsurface.rtlight ) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5725 if (rsurfacepass == RSURFPASS_BACKGROUND)
5727 R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5728 if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5729 R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5733 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5735 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5736 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5737 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5738 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5739 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5741 R_Mesh_TexBind((permutation & SHADERPERMUTATION_SHADOWMAPORTHO) ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, (permutation & SHADERPERMUTATION_SHADOWSAMPLER) ? r_shadow_shadowmap2dtexture : r_shadow_shadowmap2dcolortexture);
5742 if (rsurface.rtlight)
5744 if (permutation & SHADERPERMUTATION_CUBEFILTER ) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5745 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5750 case RENDERPATH_D3D10:
5751 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5753 case RENDERPATH_D3D11:
5754 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5756 case RENDERPATH_GL20:
5757 if (gl_mesh_separatearrays.integer)
5759 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5760 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5761 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5762 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5763 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5764 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5765 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5766 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5770 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5771 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5773 R_SetupShader_SetPermutationGLSL(mode, permutation);
5774 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5775 if (mode == SHADERMODE_LIGHTSOURCE)
5777 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5778 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5779 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3fARB(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5780 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);
5781 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);
5782 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);
5784 // additive passes are only darkened by fog, not tinted
5785 if (r_glsl_permutation->loc_FogColor >= 0)
5786 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5787 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5791 if (mode == SHADERMODE_FLATCOLOR)
5793 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);
5795 else if (mode == SHADERMODE_LIGHTDIRECTION)
5797 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);
5798 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);
5799 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);
5800 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);
5801 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);
5802 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]);
5803 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]);
5807 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);
5808 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]);
5809 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);
5810 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3fARB(r_glsl_permutation->loc_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5811 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);
5813 // additive passes are only darkened by fog, not tinted
5814 if (r_glsl_permutation->loc_FogColor >= 0)
5816 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5817 qglUniform3fARB(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5819 qglUniform3fARB(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5821 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);
5822 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]);
5823 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]);
5824 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_RefractColor, 1, rsurface.texture->refractcolor4f);
5825 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4fvARB(r_glsl_permutation->loc_ReflectColor, 1, rsurface.texture->reflectcolor4f);
5826 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5827 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1fARB(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5828 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1fARB(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
5830 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5831 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5832 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fvARB(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5833 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]);
5834 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]);
5836 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3fARB(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5837 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1fARB(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3]);
5838 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3fARB(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5839 if (r_glsl_permutation->loc_Color_Pants >= 0)
5841 if (rsurface.texture->pantstexture)
5842 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5844 qglUniform3fARB(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5846 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5848 if (rsurface.texture->shirttexture)
5849 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5851 qglUniform3fARB(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5853 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]);
5854 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5855 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5856 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1fARB(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5857 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1fARB(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5858 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]);
5859 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5861 // if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_texture_white );
5862 // if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_texture_white );
5863 // if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS , r_texture_gammaramps );
5864 if (r_glsl_permutation->loc_Texture_Normal >= 0) R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5865 if (r_glsl_permutation->loc_Texture_Color >= 0) R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5866 if (r_glsl_permutation->loc_Texture_Gloss >= 0) R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5867 if (r_glsl_permutation->loc_Texture_Glow >= 0) R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5868 if (r_glsl_permutation->loc_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5869 if (r_glsl_permutation->loc_Texture_SecondaryColor >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5870 if (r_glsl_permutation->loc_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5871 if (r_glsl_permutation->loc_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5872 if (r_glsl_permutation->loc_Texture_Pants >= 0) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5873 if (r_glsl_permutation->loc_Texture_Shirt >= 0) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5874 if (r_glsl_permutation->loc_Texture_ReflectMask >= 0) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5875 if (r_glsl_permutation->loc_Texture_ReflectCube >= 0) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5876 if (r_glsl_permutation->loc_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5877 if (r_glsl_permutation->loc_Texture_FogMask >= 0) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5878 if (r_glsl_permutation->loc_Texture_Lightmap >= 0) R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5879 if (r_glsl_permutation->loc_Texture_Deluxemap >= 0) R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5880 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5881 if (rsurfacepass == RSURFPASS_BACKGROUND)
5883 if(r_glsl_permutation->loc_Texture_Refraction >= 0) R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5884 else if(r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5885 if(r_glsl_permutation->loc_Texture_Reflection >= 0) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5889 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5891 // if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5892 // if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5893 if (r_glsl_permutation->loc_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5894 if (r_glsl_permutation->loc_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5895 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5897 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHO2D : GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dtexture );
5898 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(r_shadow_usingshadowmaportho ? GL20TU_SHADOWMAPORTHORECT : GL20TU_SHADOWMAPRECT, r_shadow_shadowmaprectangletexture );
5899 if (rsurface.rtlight)
5901 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5902 if (r_shadow_usingshadowmapcube)
5903 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
5904 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5909 case RENDERPATH_CGGL:
5911 if (gl_mesh_separatearrays.integer)
5913 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5914 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5915 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5916 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5917 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5918 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5919 R_Mesh_TexCoordPointer(3, 4, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5920 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5924 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5925 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5927 R_SetupShader_SetPermutationCG(mode, permutation);
5928 if (r_cg_permutation->fp_ModelToReflectCube) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->fp_ModelToReflectCube, m16f);}CHECKCGERROR
5929 if (mode == SHADERMODE_LIGHTSOURCE)
5931 if (r_cg_permutation->vp_ModelToLight) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelToLight, m16f);}CHECKCGERROR
5932 if (r_cg_permutation->vp_LightPosition) cgGLSetParameter3f(r_cg_permutation->vp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5936 if (mode == SHADERMODE_LIGHTDIRECTION)
5938 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
5941 if (r_cg_permutation->vp_TexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_TexMatrix, m16f);}CHECKCGERROR
5942 if (r_cg_permutation->vp_BackgroundTexMatrix) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_BackgroundTexMatrix, m16f);}CHECKCGERROR
5943 if (r_cg_permutation->vp_ShadowMapMatrix) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);cgGLSetMatrixParameterfc(r_cg_permutation->vp_ShadowMapMatrix, m16f);}CHECKGLERROR
5944 if (r_cg_permutation->vp_EyePosition) cgGLSetParameter3f(r_cg_permutation->vp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
5945 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
5948 if (mode == SHADERMODE_LIGHTSOURCE)
5950 if (r_cg_permutation->fp_LightPosition) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);CHECKCGERROR
5951 if (r_cg_permutation->fp_LightColor) cgGLSetParameter3f(r_cg_permutation->fp_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);CHECKCGERROR
5952 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0] * ambientscale, rsurface.colormod[1] * ambientscale, rsurface.colormod[2] * ambientscale);CHECKCGERROR
5953 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, rsurface.colormod[0] * diffusescale, rsurface.colormod[1] * diffusescale, rsurface.colormod[2] * diffusescale);CHECKCGERROR
5954 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
5956 // additive passes are only darkened by fog, not tinted
5957 if (r_cg_permutation->fp_FogColor) cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);CHECKCGERROR
5958 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
5962 if (mode == SHADERMODE_FLATCOLOR)
5964 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2]);CHECKCGERROR
5966 else if (mode == SHADERMODE_LIGHTDIRECTION)
5968 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * rsurface.colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * rsurface.colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * rsurface.colormod[2]);CHECKCGERROR
5969 if (r_cg_permutation->fp_Color_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_Color_Diffuse, r_refdef.lightmapintensity * rsurface.colormod[0], r_refdef.lightmapintensity * rsurface.colormod[1], r_refdef.lightmapintensity * rsurface.colormod[2]);CHECKCGERROR
5970 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
5971 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5972 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
5973 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
5974 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
5978 if (r_cg_permutation->fp_Color_Ambient) cgGLSetParameter3f(r_cg_permutation->fp_Color_Ambient, r_refdef.scene.ambient * rsurface.colormod[0], r_refdef.scene.ambient * rsurface.colormod[1], r_refdef.scene.ambient * rsurface.colormod[2]);CHECKCGERROR
5979 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
5980 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
5981 if (r_cg_permutation->fp_DeferredMod_Diffuse) cgGLSetParameter3f(r_cg_permutation->fp_DeferredMod_Diffuse, rsurface.colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, rsurface.colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);CHECKCGERROR
5982 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
5984 // additive passes are only darkened by fog, not tinted
5985 if (r_cg_permutation->fp_FogColor)
5987 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5988 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, 0, 0, 0);
5990 cgGLSetParameter3f(r_cg_permutation->fp_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5993 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
5994 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
5995 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
5996 if (r_cg_permutation->fp_RefractColor) cgGLSetParameter4fv(r_cg_permutation->fp_RefractColor, rsurface.texture->refractcolor4f);CHECKCGERROR
5997 if (r_cg_permutation->fp_ReflectColor) cgGLSetParameter4fv(r_cg_permutation->fp_ReflectColor, rsurface.texture->reflectcolor4f);CHECKCGERROR
5998 if (r_cg_permutation->fp_ReflectFactor) cgGLSetParameter1f(r_cg_permutation->fp_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);CHECKCGERROR
5999 if (r_cg_permutation->fp_ReflectOffset) cgGLSetParameter1f(r_cg_permutation->fp_ReflectOffset, rsurface.texture->reflectmin);CHECKCGERROR
6000 if (r_cg_permutation->fp_SpecularPower) cgGLSetParameter1f(r_cg_permutation->fp_SpecularPower, rsurface.texture->specularpower * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));CHECKCGERROR
6002 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
6003 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
6004 if (r_cg_permutation->fp_Color_Glow) cgGLSetParameter3f(r_cg_permutation->fp_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);CHECKCGERROR
6005 if (r_cg_permutation->fp_Alpha) cgGLSetParameter1f(r_cg_permutation->fp_Alpha, rsurface.texture->lightmapcolor[3]);CHECKCGERROR
6006 if (r_cg_permutation->fp_EyePosition) cgGLSetParameter3f(r_cg_permutation->fp_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);CHECKCGERROR
6007 if (r_cg_permutation->fp_Color_Pants)
6009 if (rsurface.texture->pantstexture)
6010 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
6012 cgGLSetParameter3f(r_cg_permutation->fp_Color_Pants, 0, 0, 0);
6015 if (r_cg_permutation->fp_Color_Shirt)
6017 if (rsurface.texture->shirttexture)
6018 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
6020 cgGLSetParameter3f(r_cg_permutation->fp_Color_Shirt, 0, 0, 0);
6023 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
6024 if (r_cg_permutation->fp_FogPlaneViewDist) cgGLSetParameter1f(r_cg_permutation->fp_FogPlaneViewDist, rsurface.fogplaneviewdist);CHECKCGERROR
6025 if (r_cg_permutation->fp_FogRangeRecip) cgGLSetParameter1f(r_cg_permutation->fp_FogRangeRecip, rsurface.fograngerecip);CHECKCGERROR
6026 if (r_cg_permutation->fp_FogHeightFade) cgGLSetParameter1f(r_cg_permutation->fp_FogHeightFade, rsurface.fogheightfade);CHECKCGERROR
6027 if (r_cg_permutation->fp_OffsetMapping_Scale) cgGLSetParameter1f(r_cg_permutation->fp_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);CHECKCGERROR
6028 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
6029 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
6031 // if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_texture_white );CHECKCGERROR
6032 // if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_texture_white );CHECKCGERROR
6033 // if (r_cg_permutation->fp_Texture_GammaRamps ) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps , r_texture_gammaramps );CHECKCGERROR
6034 if (r_cg_permutation->fp_Texture_Normal ) CG_BindTexture(r_cg_permutation->fp_Texture_Normal , rsurface.texture->nmaptexture );CHECKCGERROR
6035 if (r_cg_permutation->fp_Texture_Color ) CG_BindTexture(r_cg_permutation->fp_Texture_Color , rsurface.texture->basetexture );CHECKCGERROR
6036 if (r_cg_permutation->fp_Texture_Gloss ) CG_BindTexture(r_cg_permutation->fp_Texture_Gloss , rsurface.texture->glosstexture );CHECKCGERROR
6037 if (r_cg_permutation->fp_Texture_Glow ) CG_BindTexture(r_cg_permutation->fp_Texture_Glow , rsurface.texture->glowtexture );CHECKCGERROR
6038 if (r_cg_permutation->fp_Texture_SecondaryNormal) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryNormal, rsurface.texture->backgroundnmaptexture );CHECKCGERROR
6039 if (r_cg_permutation->fp_Texture_SecondaryColor ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );CHECKCGERROR
6040 if (r_cg_permutation->fp_Texture_SecondaryGloss ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );CHECKCGERROR
6041 if (r_cg_permutation->fp_Texture_SecondaryGlow ) CG_BindTexture(r_cg_permutation->fp_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );CHECKCGERROR
6042 if (r_cg_permutation->fp_Texture_Pants ) CG_BindTexture(r_cg_permutation->fp_Texture_Pants , rsurface.texture->pantstexture );CHECKCGERROR
6043 if (r_cg_permutation->fp_Texture_Shirt ) CG_BindTexture(r_cg_permutation->fp_Texture_Shirt , rsurface.texture->shirttexture );CHECKCGERROR
6044 if (r_cg_permutation->fp_Texture_ReflectMask ) CG_BindTexture(r_cg_permutation->fp_Texture_ReflectMask , rsurface.texture->reflectmasktexture );CHECKCGERROR
6045 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
6046 if (r_cg_permutation->fp_Texture_FogHeightTexture) CG_BindTexture(r_cg_permutation->fp_Texture_FogHeightTexture, r_texture_fogheighttexture );CHECKCGERROR
6047 if (r_cg_permutation->fp_Texture_FogMask ) CG_BindTexture(r_cg_permutation->fp_Texture_FogMask , r_texture_fogattenuation );CHECKCGERROR
6048 if (r_cg_permutation->fp_Texture_Lightmap ) CG_BindTexture(r_cg_permutation->fp_Texture_Lightmap , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);CHECKCGERROR
6049 if (r_cg_permutation->fp_Texture_Deluxemap ) CG_BindTexture(r_cg_permutation->fp_Texture_Deluxemap , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);CHECKCGERROR
6050 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
6051 if (rsurfacepass == RSURFPASS_BACKGROUND)
6053 if (r_cg_permutation->fp_Texture_Refraction ) CG_BindTexture(r_cg_permutation->fp_Texture_Refraction , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);CHECKCGERROR
6054 else if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);CHECKCGERROR
6055 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
6059 if (r_cg_permutation->fp_Texture_Reflection ) CG_BindTexture(r_cg_permutation->fp_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);CHECKCGERROR
6061 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
6062 if (r_cg_permutation->fp_Texture_ScreenNormalMap) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
6063 if (r_cg_permutation->fp_Texture_ScreenDiffuse ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );CHECKCGERROR
6064 if (r_cg_permutation->fp_Texture_ScreenSpecular ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );CHECKCGERROR
6065 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
6067 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
6068 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
6069 if (rsurface.rtlight)
6071 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
6072 if (r_shadow_usingshadowmapcube)
6073 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
6074 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
6081 case RENDERPATH_GL13:
6082 case RENDERPATH_GL11:
6087 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
6089 // select a permutation of the lighting shader appropriate to this
6090 // combination of texture, entity, light source, and fogging, only use the
6091 // minimum features necessary to avoid wasting rendering time in the
6092 // fragment shader on features that are not being used
6093 unsigned int permutation = 0;
6094 unsigned int mode = 0;
6095 const float *lightcolorbase = rtlight->currentcolor;
6096 float ambientscale = rtlight->ambientscale;
6097 float diffusescale = rtlight->diffusescale;
6098 float specularscale = rtlight->specularscale;
6099 // this is the location of the light in view space
6100 vec3_t viewlightorigin;
6101 // this transforms from view space (camera) to light space (cubemap)
6102 matrix4x4_t viewtolight;
6103 matrix4x4_t lighttoview;
6104 float viewtolight16f[16];
6105 float range = 1.0f / r_shadow_deferred_8bitrange.value;
6107 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
6108 if (rtlight->currentcubemap != r_texture_whitecube)
6109 permutation |= SHADERPERMUTATION_CUBEFILTER;
6110 if (diffusescale > 0)
6111 permutation |= SHADERPERMUTATION_DIFFUSE;
6112 if (specularscale > 0)
6114 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
6115 if (r_shadow_glossexact.integer)
6116 permutation |= SHADERPERMUTATION_EXACTSPECULARMATH;
6118 if (r_shadow_usingshadowmaprect || r_shadow_usingshadowmap2d || r_shadow_usingshadowmapcube)
6120 if (r_shadow_usingshadowmaprect)
6121 permutation |= SHADERPERMUTATION_SHADOWMAPRECT;
6122 if (r_shadow_usingshadowmap2d)
6123 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
6124 if (r_shadow_usingshadowmapcube)
6125 permutation |= SHADERPERMUTATION_SHADOWMAPCUBE;
6126 else if(r_shadow_shadowmapvsdct)
6127 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
6129 if (r_shadow_shadowmapsampler)
6130 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
6131 if (r_shadow_shadowmappcf > 1)
6132 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
6133 else if (r_shadow_shadowmappcf)
6134 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
6136 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
6137 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
6138 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
6139 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
6140 switch(vid.renderpath)
6142 case RENDERPATH_D3D9:
6144 R_SetupShader_SetPermutationHLSL(mode, permutation);
6145 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6146 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
6147 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
6148 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
6149 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
6150 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
6151 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
6152 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * ((permutation & SHADERPERMUTATION_EXACTSPECULARMATH) ? 0.25f : 1.0f));
6153 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
6154 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
6156 R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
6157 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
6158 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
6159 R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
6160 R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
6161 if (r_shadow_usingshadowmapcube)
6162 R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
6163 R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
6164 R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
6167 case RENDERPATH_D3D10:
6168 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6170 case RENDERPATH_D3D11:
6171 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6173 case RENDERPATH_GL20:
6174 R_SetupShader_SetPermutationGLSL(mode, permutation);
6175 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3fARB( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
6176 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
6177 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);
6178 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);
6179 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);
6180 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]);
6181 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]);
6182 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));
6183 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]);
6184 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
6186 if (r_glsl_permutation->loc_Texture_Attenuation >= 0) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
6187 if (r_glsl_permutation->loc_Texture_ScreenDepth >= 0) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
6188 if (r_glsl_permutation->loc_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
6189 if (r_glsl_permutation->loc_Texture_Cube >= 0) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
6190 if (r_glsl_permutation->loc_Texture_ShadowMapRect >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPRECT , r_shadow_shadowmaprectangletexture );
6191 if (r_shadow_usingshadowmapcube)
6192 if (r_glsl_permutation->loc_Texture_ShadowMapCube >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAPCUBE , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);
6193 if (r_glsl_permutation->loc_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
6194 if (r_glsl_permutation->loc_Texture_CubeProjection >= 0) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
6196 case RENDERPATH_CGGL:
6198 R_SetupShader_SetPermutationCG(mode, permutation);
6199 if (r_cg_permutation->fp_LightPosition ) cgGLSetParameter3f(r_cg_permutation->fp_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);CHECKCGERROR
6200 if (r_cg_permutation->fp_ViewToLight ) cgGLSetMatrixParameterfc(r_cg_permutation->fp_ViewToLight, viewtolight16f);CHECKCGERROR
6201 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
6202 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
6203 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
6204 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
6205 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
6206 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
6207 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
6208 if (r_cg_permutation->fp_PixelToScreenTexCoord ) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
6210 if (r_cg_permutation->fp_Texture_Attenuation ) CG_BindTexture(r_cg_permutation->fp_Texture_Attenuation , r_shadow_attenuationgradienttexture );CHECKCGERROR
6211 if (r_cg_permutation->fp_Texture_ScreenDepth ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );CHECKCGERROR
6212 if (r_cg_permutation->fp_Texture_ScreenNormalMap ) CG_BindTexture(r_cg_permutation->fp_Texture_ScreenNormalMap, r_shadow_prepassgeometrynormalmaptexture );CHECKCGERROR
6213 if (r_cg_permutation->fp_Texture_Cube ) CG_BindTexture(r_cg_permutation->fp_Texture_Cube , rsurface.rtlight->currentcubemap );CHECKCGERROR
6214 if (r_cg_permutation->fp_Texture_ShadowMapRect ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapRect , r_shadow_shadowmaprectangletexture );CHECKCGERROR
6215 if (r_shadow_usingshadowmapcube)
6216 if (r_cg_permutation->fp_Texture_ShadowMapCube ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMapCube , r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]);CHECKCGERROR
6217 if (r_cg_permutation->fp_Texture_ShadowMap2D ) CG_BindTexture(r_cg_permutation->fp_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );CHECKCGERROR
6218 if (r_cg_permutation->fp_Texture_CubeProjection ) CG_BindTexture(r_cg_permutation->fp_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );CHECKCGERROR
6221 case RENDERPATH_GL13:
6222 case RENDERPATH_GL11:
6227 #define SKINFRAME_HASH 1024
6231 int loadsequence; // incremented each level change
6232 memexpandablearray_t array;
6233 skinframe_t *hash[SKINFRAME_HASH];
6236 r_skinframe_t r_skinframe;
6238 void R_SkinFrame_PrepareForPurge(void)
6240 r_skinframe.loadsequence++;
6241 // wrap it without hitting zero
6242 if (r_skinframe.loadsequence >= 200)
6243 r_skinframe.loadsequence = 1;
6246 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
6250 // mark the skinframe as used for the purging code
6251 skinframe->loadsequence = r_skinframe.loadsequence;
6254 void R_SkinFrame_Purge(void)
6258 for (i = 0;i < SKINFRAME_HASH;i++)
6260 for (s = r_skinframe.hash[i];s;s = s->next)
6262 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
6264 if (s->merged == s->base)
6266 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
6267 R_PurgeTexture(s->stain );s->stain = NULL;
6268 R_PurgeTexture(s->merged);s->merged = NULL;
6269 R_PurgeTexture(s->base );s->base = NULL;
6270 R_PurgeTexture(s->pants );s->pants = NULL;
6271 R_PurgeTexture(s->shirt );s->shirt = NULL;
6272 R_PurgeTexture(s->nmap );s->nmap = NULL;
6273 R_PurgeTexture(s->gloss );s->gloss = NULL;
6274 R_PurgeTexture(s->glow );s->glow = NULL;
6275 R_PurgeTexture(s->fog );s->fog = NULL;
6276 R_PurgeTexture(s->reflect);s->reflect = NULL;
6277 s->loadsequence = 0;
6283 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
6285 char basename[MAX_QPATH];
6287 Image_StripImageExtension(name, basename, sizeof(basename));
6289 if( last == NULL ) {
6291 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6292 item = r_skinframe.hash[hashindex];
6297 // linearly search through the hash bucket
6298 for( ; item ; item = item->next ) {
6299 if( !strcmp( item->basename, basename ) ) {
6306 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
6310 char basename[MAX_QPATH];
6312 Image_StripImageExtension(name, basename, sizeof(basename));
6314 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
6315 for (item = r_skinframe.hash[hashindex];item;item = item->next)
6316 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
6320 rtexture_t *dyntexture;
6321 // check whether its a dynamic texture
6322 dyntexture = CL_GetDynTexture( basename );
6323 if (!add && !dyntexture)
6325 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
6326 memset(item, 0, sizeof(*item));
6327 strlcpy(item->basename, basename, sizeof(item->basename));
6328 item->base = dyntexture; // either NULL or dyntexture handle
6329 item->textureflags = textureflags;
6330 item->comparewidth = comparewidth;
6331 item->compareheight = compareheight;
6332 item->comparecrc = comparecrc;
6333 item->next = r_skinframe.hash[hashindex];
6334 r_skinframe.hash[hashindex] = item;
6336 else if( item->base == NULL )
6338 rtexture_t *dyntexture;
6339 // check whether its a dynamic texture
6340 // 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]
6341 dyntexture = CL_GetDynTexture( basename );
6342 item->base = dyntexture; // either NULL or dyntexture handle
6345 R_SkinFrame_MarkUsed(item);
6349 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
6351 unsigned long long avgcolor[5], wsum; \
6359 for(pix = 0; pix < cnt; ++pix) \
6362 for(comp = 0; comp < 3; ++comp) \
6364 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
6367 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6369 for(comp = 0; comp < 3; ++comp) \
6370 avgcolor[comp] += getpixel * w; \
6373 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
6374 avgcolor[4] += getpixel; \
6376 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
6378 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
6379 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
6380 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
6381 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
6384 extern cvar_t gl_picmip;
6385 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
6388 unsigned char *pixels;
6389 unsigned char *bumppixels;
6390 unsigned char *basepixels = NULL;
6391 int basepixels_width = 0;
6392 int basepixels_height = 0;
6393 skinframe_t *skinframe;
6394 rtexture_t *ddsbase = NULL;
6395 qboolean ddshasalpha = false;
6396 float ddsavgcolor[4];
6397 char basename[MAX_QPATH];
6398 int miplevel = R_PicmipForFlags(textureflags);
6399 int savemiplevel = miplevel;
6402 if (cls.state == ca_dedicated)
6405 // return an existing skinframe if already loaded
6406 // if loading of the first image fails, don't make a new skinframe as it
6407 // would cause all future lookups of this to be missing
6408 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
6409 if (skinframe && skinframe->base)
6412 Image_StripImageExtension(name, basename, sizeof(basename));
6414 // check for DDS texture file first
6415 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
6417 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
6418 if (basepixels == NULL)
6422 // FIXME handle miplevel
6424 if (developer_loading.integer)
6425 Con_Printf("loading skin \"%s\"\n", name);
6427 // we've got some pixels to store, so really allocate this new texture now
6429 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
6430 skinframe->stain = NULL;
6431 skinframe->merged = NULL;
6432 skinframe->base = NULL;
6433 skinframe->pants = NULL;
6434 skinframe->shirt = NULL;
6435 skinframe->nmap = NULL;
6436 skinframe->gloss = NULL;
6437 skinframe->glow = NULL;
6438 skinframe->fog = NULL;
6439 skinframe->reflect = NULL;
6440 skinframe->hasalpha = false;
6444 skinframe->base = ddsbase;
6445 skinframe->hasalpha = ddshasalpha;
6446 VectorCopy(ddsavgcolor, skinframe->avgcolor);
6447 if (r_loadfog && skinframe->hasalpha)
6448 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
6449 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6453 basepixels_width = image_width;
6454 basepixels_height = image_height;
6455 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);
6456 if (textureflags & TEXF_ALPHA)
6458 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
6460 if (basepixels[j] < 255)
6462 skinframe->hasalpha = true;
6466 if (r_loadfog && skinframe->hasalpha)
6468 // has transparent pixels
6469 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6470 for (j = 0;j < image_width * image_height * 4;j += 4)
6475 pixels[j+3] = basepixels[j+3];
6477 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);
6481 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
6482 //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]);
6483 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
6484 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true);
6485 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
6486 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true);
6491 mymiplevel = savemiplevel;
6492 if (r_loadnormalmap)
6493 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);
6494 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6496 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6497 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6498 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6499 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6502 // _norm is the name used by tenebrae and has been adopted as standard
6503 if (r_loadnormalmap && skinframe->nmap == NULL)
6505 mymiplevel = savemiplevel;
6506 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6508 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);
6512 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6514 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6515 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
6516 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);
6518 Mem_Free(bumppixels);
6520 else if (r_shadow_bumpscale_basetexture.value > 0)
6522 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
6523 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
6524 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);
6527 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
6528 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true);
6531 // _luma is supported only for tenebrae compatibility
6532 // _glow is the preferred name
6533 mymiplevel = savemiplevel;
6534 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
6536 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);
6537 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
6538 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true);
6539 Mem_Free(pixels);pixels = NULL;
6542 mymiplevel = savemiplevel;
6543 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6545 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);
6546 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
6547 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true);
6552 mymiplevel = savemiplevel;
6553 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6555 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);
6556 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
6557 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true);
6562 mymiplevel = savemiplevel;
6563 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6565 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);
6566 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
6567 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true);
6572 mymiplevel = savemiplevel;
6573 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6575 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);
6576 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
6577 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true);
6583 Mem_Free(basepixels);
6588 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
6589 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
6592 unsigned char *temp1, *temp2;
6593 skinframe_t *skinframe;
6595 if (cls.state == ca_dedicated)
6598 // if already loaded just return it, otherwise make a new skinframe
6599 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
6600 if (skinframe && skinframe->base)
6603 skinframe->stain = NULL;
6604 skinframe->merged = NULL;
6605 skinframe->base = NULL;
6606 skinframe->pants = NULL;
6607 skinframe->shirt = NULL;
6608 skinframe->nmap = NULL;
6609 skinframe->gloss = NULL;
6610 skinframe->glow = NULL;
6611 skinframe->fog = NULL;
6612 skinframe->reflect = NULL;
6613 skinframe->hasalpha = false;
6615 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6619 if (developer_loading.integer)
6620 Con_Printf("loading 32bit skin \"%s\"\n", name);
6622 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
6624 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6625 temp2 = temp1 + width * height * 4;
6626 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6627 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);
6630 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
6631 if (textureflags & TEXF_ALPHA)
6633 for (i = 3;i < width * height * 4;i += 4)
6635 if (skindata[i] < 255)
6637 skinframe->hasalpha = true;
6641 if (r_loadfog && skinframe->hasalpha)
6643 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6644 memcpy(fogpixels, skindata, width * height * 4);
6645 for (i = 0;i < width * height * 4;i += 4)
6646 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6647 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
6648 Mem_Free(fogpixels);
6652 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6653 //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]);
6658 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6662 skinframe_t *skinframe;
6664 if (cls.state == ca_dedicated)
6667 // if already loaded just return it, otherwise make a new skinframe
6668 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6669 if (skinframe && skinframe->base)
6672 skinframe->stain = NULL;
6673 skinframe->merged = NULL;
6674 skinframe->base = NULL;
6675 skinframe->pants = NULL;
6676 skinframe->shirt = NULL;
6677 skinframe->nmap = NULL;
6678 skinframe->gloss = NULL;
6679 skinframe->glow = NULL;
6680 skinframe->fog = NULL;
6681 skinframe->reflect = NULL;
6682 skinframe->hasalpha = false;
6684 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6688 if (developer_loading.integer)
6689 Con_Printf("loading quake skin \"%s\"\n", name);
6691 // 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)
6692 skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height);
6693 memcpy(skinframe->qpixels, skindata, width*height);
6694 skinframe->qwidth = width;
6695 skinframe->qheight = height;
6698 for (i = 0;i < width * height;i++)
6699 featuresmask |= palette_featureflags[skindata[i]];
6701 skinframe->hasalpha = false;
6702 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6703 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6704 skinframe->qgeneratemerged = true;
6705 skinframe->qgeneratebase = skinframe->qhascolormapping;
6706 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6708 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6709 //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]);
6714 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6718 unsigned char *skindata;
6720 if (!skinframe->qpixels)
6723 if (!skinframe->qhascolormapping)
6724 colormapped = false;
6728 if (!skinframe->qgeneratebase)
6733 if (!skinframe->qgeneratemerged)
6737 width = skinframe->qwidth;
6738 height = skinframe->qheight;
6739 skindata = skinframe->qpixels;
6741 if (skinframe->qgeneratenmap)
6743 unsigned char *temp1, *temp2;
6744 skinframe->qgeneratenmap = false;
6745 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6746 temp2 = temp1 + width * height * 4;
6747 // use either a custom palette or the quake palette
6748 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6749 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6750 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);
6754 if (skinframe->qgenerateglow)
6756 skinframe->qgenerateglow = false;
6757 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6762 skinframe->qgeneratebase = false;
6763 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);
6764 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6765 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6769 skinframe->qgeneratemerged = false;
6770 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);
6773 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6775 Mem_Free(skinframe->qpixels);
6776 skinframe->qpixels = NULL;
6780 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)
6783 skinframe_t *skinframe;
6785 if (cls.state == ca_dedicated)
6788 // if already loaded just return it, otherwise make a new skinframe
6789 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6790 if (skinframe && skinframe->base)
6793 skinframe->stain = NULL;
6794 skinframe->merged = NULL;
6795 skinframe->base = NULL;
6796 skinframe->pants = NULL;
6797 skinframe->shirt = NULL;
6798 skinframe->nmap = NULL;
6799 skinframe->gloss = NULL;
6800 skinframe->glow = NULL;
6801 skinframe->fog = NULL;
6802 skinframe->reflect = NULL;
6803 skinframe->hasalpha = false;
6805 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6809 if (developer_loading.integer)
6810 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6812 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6813 if (textureflags & TEXF_ALPHA)
6815 for (i = 0;i < width * height;i++)
6817 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6819 skinframe->hasalpha = true;
6823 if (r_loadfog && skinframe->hasalpha)
6824 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6827 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6828 //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]);
6833 skinframe_t *R_SkinFrame_LoadMissing(void)
6835 skinframe_t *skinframe;
6837 if (cls.state == ca_dedicated)
6840 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6841 skinframe->stain = NULL;
6842 skinframe->merged = NULL;
6843 skinframe->base = NULL;
6844 skinframe->pants = NULL;
6845 skinframe->shirt = NULL;
6846 skinframe->nmap = NULL;
6847 skinframe->gloss = NULL;
6848 skinframe->glow = NULL;
6849 skinframe->fog = NULL;
6850 skinframe->reflect = NULL;
6851 skinframe->hasalpha = false;
6853 skinframe->avgcolor[0] = rand() / RAND_MAX;
6854 skinframe->avgcolor[1] = rand() / RAND_MAX;
6855 skinframe->avgcolor[2] = rand() / RAND_MAX;
6856 skinframe->avgcolor[3] = 1;
6861 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6862 typedef struct suffixinfo_s
6865 qboolean flipx, flipy, flipdiagonal;
6868 static suffixinfo_t suffix[3][6] =
6871 {"px", false, false, false},
6872 {"nx", false, false, false},
6873 {"py", false, false, false},
6874 {"ny", false, false, false},
6875 {"pz", false, false, false},
6876 {"nz", false, false, false}
6879 {"posx", false, false, false},
6880 {"negx", false, false, false},
6881 {"posy", false, false, false},
6882 {"negy", false, false, false},
6883 {"posz", false, false, false},
6884 {"negz", false, false, false}
6887 {"rt", true, false, true},
6888 {"lf", false, true, true},
6889 {"ft", true, true, false},
6890 {"bk", false, false, false},
6891 {"up", true, false, true},
6892 {"dn", true, false, true}
6896 static int componentorder[4] = {0, 1, 2, 3};
6898 rtexture_t *R_LoadCubemap(const char *basename)
6900 int i, j, cubemapsize;
6901 unsigned char *cubemappixels, *image_buffer;
6902 rtexture_t *cubemaptexture;
6904 // must start 0 so the first loadimagepixels has no requested width/height
6906 cubemappixels = NULL;
6907 cubemaptexture = NULL;
6908 // keep trying different suffix groups (posx, px, rt) until one loads
6909 for (j = 0;j < 3 && !cubemappixels;j++)
6911 // load the 6 images in the suffix group
6912 for (i = 0;i < 6;i++)
6914 // generate an image name based on the base and and suffix
6915 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6917 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6919 // an image loaded, make sure width and height are equal
6920 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6922 // if this is the first image to load successfully, allocate the cubemap memory
6923 if (!cubemappixels && image_width >= 1)
6925 cubemapsize = image_width;
6926 // note this clears to black, so unavailable sides are black
6927 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6929 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6931 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);
6934 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6936 Mem_Free(image_buffer);
6940 // if a cubemap loaded, upload it
6943 if (developer_loading.integer)
6944 Con_Printf("loading cubemap \"%s\"\n", basename);
6946 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6947 Mem_Free(cubemappixels);
6951 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6952 if (developer_loading.integer)
6954 Con_Printf("(tried tried images ");
6955 for (j = 0;j < 3;j++)
6956 for (i = 0;i < 6;i++)
6957 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6958 Con_Print(" and was unable to find any of them).\n");
6961 return cubemaptexture;
6964 rtexture_t *R_GetCubemap(const char *basename)
6967 for (i = 0;i < r_texture_numcubemaps;i++)
6968 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6969 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6970 if (i >= MAX_CUBEMAPS)
6971 return r_texture_whitecube;
6972 r_texture_numcubemaps++;
6973 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6974 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6975 return r_texture_cubemaps[i].texture;
6978 void R_FreeCubemaps(void)
6981 for (i = 0;i < r_texture_numcubemaps;i++)
6983 if (developer_loading.integer)
6984 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6985 if (r_texture_cubemaps[i].texture)
6986 R_FreeTexture(r_texture_cubemaps[i].texture);
6988 r_texture_numcubemaps = 0;
6991 void R_Main_FreeViewCache(void)
6993 if (r_refdef.viewcache.entityvisible)
6994 Mem_Free(r_refdef.viewcache.entityvisible);
6995 if (r_refdef.viewcache.world_pvsbits)
6996 Mem_Free(r_refdef.viewcache.world_pvsbits);
6997 if (r_refdef.viewcache.world_leafvisible)
6998 Mem_Free(r_refdef.viewcache.world_leafvisible);
6999 if (r_refdef.viewcache.world_surfacevisible)
7000 Mem_Free(r_refdef.viewcache.world_surfacevisible);
7001 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
7004 void R_Main_ResizeViewCache(void)
7006 int numentities = r_refdef.scene.numentities;
7007 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
7008 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
7009 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
7010 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
7011 if (r_refdef.viewcache.maxentities < numentities)
7013 r_refdef.viewcache.maxentities = numentities;
7014 if (r_refdef.viewcache.entityvisible)
7015 Mem_Free(r_refdef.viewcache.entityvisible);
7016 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
7018 if (r_refdef.viewcache.world_numclusters != numclusters)
7020 r_refdef.viewcache.world_numclusters = numclusters;
7021 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
7022 if (r_refdef.viewcache.world_pvsbits)
7023 Mem_Free(r_refdef.viewcache.world_pvsbits);
7024 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
7026 if (r_refdef.viewcache.world_numleafs != numleafs)
7028 r_refdef.viewcache.world_numleafs = numleafs;
7029 if (r_refdef.viewcache.world_leafvisible)
7030 Mem_Free(r_refdef.viewcache.world_leafvisible);
7031 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
7033 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
7035 r_refdef.viewcache.world_numsurfaces = numsurfaces;
7036 if (r_refdef.viewcache.world_surfacevisible)
7037 Mem_Free(r_refdef.viewcache.world_surfacevisible);
7038 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
7042 extern rtexture_t *loadingscreentexture;
7043 void gl_main_start(void)
7045 loadingscreentexture = NULL;
7046 r_texture_blanknormalmap = NULL;
7047 r_texture_white = NULL;
7048 r_texture_grey128 = NULL;
7049 r_texture_black = NULL;
7050 r_texture_whitecube = NULL;
7051 r_texture_normalizationcube = NULL;
7052 r_texture_fogattenuation = NULL;
7053 r_texture_fogheighttexture = NULL;
7054 r_texture_gammaramps = NULL;
7055 r_texture_numcubemaps = 0;
7057 r_loaddds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_load.integer;
7058 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
7060 switch(vid.renderpath)
7062 case RENDERPATH_GL20:
7063 case RENDERPATH_CGGL:
7064 case RENDERPATH_D3D9:
7065 case RENDERPATH_D3D10:
7066 case RENDERPATH_D3D11:
7067 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7068 Cvar_SetValueQuick(&gl_combine, 1);
7069 Cvar_SetValueQuick(&r_glsl, 1);
7070 r_loadnormalmap = true;
7074 case RENDERPATH_GL13:
7075 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7076 Cvar_SetValueQuick(&gl_combine, 1);
7077 Cvar_SetValueQuick(&r_glsl, 0);
7078 r_loadnormalmap = false;
7079 r_loadgloss = false;
7082 case RENDERPATH_GL11:
7083 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
7084 Cvar_SetValueQuick(&gl_combine, 0);
7085 Cvar_SetValueQuick(&r_glsl, 0);
7086 r_loadnormalmap = false;
7087 r_loadgloss = false;
7093 R_FrameData_Reset();
7097 memset(r_queries, 0, sizeof(r_queries));
7099 r_qwskincache = NULL;
7100 r_qwskincache_size = 0;
7102 // set up r_skinframe loading system for textures
7103 memset(&r_skinframe, 0, sizeof(r_skinframe));
7104 r_skinframe.loadsequence = 1;
7105 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
7107 r_main_texturepool = R_AllocTexturePool();
7108 R_BuildBlankTextures();
7110 if (vid.support.arb_texture_cube_map)
7113 R_BuildNormalizationCube();
7115 r_texture_fogattenuation = NULL;
7116 r_texture_fogheighttexture = NULL;
7117 r_texture_gammaramps = NULL;
7118 //r_texture_fogintensity = NULL;
7119 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
7120 memset(&r_waterstate, 0, sizeof(r_waterstate));
7121 r_glsl_permutation = NULL;
7122 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
7123 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
7124 glslshaderstring = NULL;
7126 r_cg_permutation = NULL;
7127 memset(r_cg_permutationhash, 0, sizeof(r_cg_permutationhash));
7128 Mem_ExpandableArray_NewArray(&r_cg_permutationarray, r_main_mempool, sizeof(r_cg_permutation_t), 256);
7129 cgshaderstring = NULL;
7132 r_hlsl_permutation = NULL;
7133 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
7134 Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
7135 hlslshaderstring = NULL;
7137 memset(&r_svbsp, 0, sizeof (r_svbsp));
7139 r_refdef.fogmasktable_density = 0;
7142 void gl_main_shutdown(void)
7145 R_FrameData_Reset();
7147 R_Main_FreeViewCache();
7149 switch(vid.renderpath)
7151 case RENDERPATH_GL11:
7152 case RENDERPATH_GL13:
7153 case RENDERPATH_GL20:
7154 case RENDERPATH_CGGL:
7156 qglDeleteQueriesARB(r_maxqueries, r_queries);
7158 case RENDERPATH_D3D9:
7159 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7161 case RENDERPATH_D3D10:
7162 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7164 case RENDERPATH_D3D11:
7165 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
7171 memset(r_queries, 0, sizeof(r_queries));
7173 r_qwskincache = NULL;
7174 r_qwskincache_size = 0;
7176 // clear out the r_skinframe state
7177 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
7178 memset(&r_skinframe, 0, sizeof(r_skinframe));
7181 Mem_Free(r_svbsp.nodes);
7182 memset(&r_svbsp, 0, sizeof (r_svbsp));
7183 R_FreeTexturePool(&r_main_texturepool);
7184 loadingscreentexture = NULL;
7185 r_texture_blanknormalmap = NULL;
7186 r_texture_white = NULL;
7187 r_texture_grey128 = NULL;
7188 r_texture_black = NULL;
7189 r_texture_whitecube = NULL;
7190 r_texture_normalizationcube = NULL;
7191 r_texture_fogattenuation = NULL;
7192 r_texture_fogheighttexture = NULL;
7193 r_texture_gammaramps = NULL;
7194 r_texture_numcubemaps = 0;
7195 //r_texture_fogintensity = NULL;
7196 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
7197 memset(&r_waterstate, 0, sizeof(r_waterstate));
7201 extern void CL_ParseEntityLump(char *entitystring);
7202 void gl_main_newmap(void)
7204 // FIXME: move this code to client
7205 char *entities, entname[MAX_QPATH];
7207 Mem_Free(r_qwskincache);
7208 r_qwskincache = NULL;
7209 r_qwskincache_size = 0;
7212 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
7213 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
7215 CL_ParseEntityLump(entities);
7219 if (cl.worldmodel->brush.entities)
7220 CL_ParseEntityLump(cl.worldmodel->brush.entities);
7222 R_Main_FreeViewCache();
7224 R_FrameData_Reset();
7227 void GL_Main_Init(void)
7229 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
7231 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
7232 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
7233 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
7234 if (gamemode == GAME_NEHAHRA)
7236 Cvar_RegisterVariable (&gl_fogenable);
7237 Cvar_RegisterVariable (&gl_fogdensity);
7238 Cvar_RegisterVariable (&gl_fogred);
7239 Cvar_RegisterVariable (&gl_foggreen);
7240 Cvar_RegisterVariable (&gl_fogblue);
7241 Cvar_RegisterVariable (&gl_fogstart);
7242 Cvar_RegisterVariable (&gl_fogend);
7243 Cvar_RegisterVariable (&gl_skyclip);
7245 Cvar_RegisterVariable(&r_motionblur);
7246 Cvar_RegisterVariable(&r_motionblur_maxblur);
7247 Cvar_RegisterVariable(&r_motionblur_bmin);
7248 Cvar_RegisterVariable(&r_motionblur_vmin);
7249 Cvar_RegisterVariable(&r_motionblur_vmax);
7250 Cvar_RegisterVariable(&r_motionblur_vcoeff);
7251 Cvar_RegisterVariable(&r_motionblur_randomize);
7252 Cvar_RegisterVariable(&r_damageblur);
7253 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
7254 Cvar_RegisterVariable(&r_equalize_entities_minambient);
7255 Cvar_RegisterVariable(&r_equalize_entities_by);
7256 Cvar_RegisterVariable(&r_equalize_entities_to);
7257 Cvar_RegisterVariable(&r_depthfirst);
7258 Cvar_RegisterVariable(&r_useinfinitefarclip);
7259 Cvar_RegisterVariable(&r_farclip_base);
7260 Cvar_RegisterVariable(&r_farclip_world);
7261 Cvar_RegisterVariable(&r_nearclip);
7262 Cvar_RegisterVariable(&r_showbboxes);
7263 Cvar_RegisterVariable(&r_showsurfaces);
7264 Cvar_RegisterVariable(&r_showtris);
7265 Cvar_RegisterVariable(&r_shownormals);
7266 Cvar_RegisterVariable(&r_showlighting);
7267 Cvar_RegisterVariable(&r_showshadowvolumes);
7268 Cvar_RegisterVariable(&r_showcollisionbrushes);
7269 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
7270 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
7271 Cvar_RegisterVariable(&r_showdisabledepthtest);
7272 Cvar_RegisterVariable(&r_drawportals);
7273 Cvar_RegisterVariable(&r_drawentities);
7274 Cvar_RegisterVariable(&r_draw2d);
7275 Cvar_RegisterVariable(&r_drawworld);
7276 Cvar_RegisterVariable(&r_cullentities_trace);
7277 Cvar_RegisterVariable(&r_cullentities_trace_samples);
7278 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
7279 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
7280 Cvar_RegisterVariable(&r_cullentities_trace_delay);
7281 Cvar_RegisterVariable(&r_drawviewmodel);
7282 Cvar_RegisterVariable(&r_drawexteriormodel);
7283 Cvar_RegisterVariable(&r_speeds);
7284 Cvar_RegisterVariable(&r_fullbrights);
7285 Cvar_RegisterVariable(&r_wateralpha);
7286 Cvar_RegisterVariable(&r_dynamic);
7287 Cvar_RegisterVariable(&r_fullbright);
7288 Cvar_RegisterVariable(&r_shadows);
7289 Cvar_RegisterVariable(&r_shadows_darken);
7290 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
7291 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
7292 Cvar_RegisterVariable(&r_shadows_throwdistance);
7293 Cvar_RegisterVariable(&r_shadows_throwdirection);
7294 Cvar_RegisterVariable(&r_shadows_focus);
7295 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
7296 Cvar_RegisterVariable(&r_q1bsp_skymasking);
7297 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
7298 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
7299 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
7300 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
7301 Cvar_RegisterVariable(&r_fog_exp2);
7302 Cvar_RegisterVariable(&r_drawfog);
7303 Cvar_RegisterVariable(&r_transparentdepthmasking);
7304 Cvar_RegisterVariable(&r_texture_dds_load);
7305 Cvar_RegisterVariable(&r_texture_dds_save);
7306 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
7307 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
7308 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
7309 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
7310 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
7311 Cvar_RegisterVariable(&r_textureunits);
7312 Cvar_RegisterVariable(&gl_combine);
7313 Cvar_RegisterVariable(&r_glsl);
7314 Cvar_RegisterVariable(&r_glsl_deluxemapping);
7315 Cvar_RegisterVariable(&r_glsl_offsetmapping);
7316 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
7317 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
7318 Cvar_RegisterVariable(&r_glsl_postprocess);
7319 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
7320 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
7321 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
7322 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
7323 Cvar_RegisterVariable(&r_water);
7324 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
7325 Cvar_RegisterVariable(&r_water_clippingplanebias);
7326 Cvar_RegisterVariable(&r_water_refractdistort);
7327 Cvar_RegisterVariable(&r_water_reflectdistort);
7328 Cvar_RegisterVariable(&r_lerpsprites);
7329 Cvar_RegisterVariable(&r_lerpmodels);
7330 Cvar_RegisterVariable(&r_lerplightstyles);
7331 Cvar_RegisterVariable(&r_waterscroll);
7332 Cvar_RegisterVariable(&r_bloom);
7333 Cvar_RegisterVariable(&r_bloom_colorscale);
7334 Cvar_RegisterVariable(&r_bloom_brighten);
7335 Cvar_RegisterVariable(&r_bloom_blur);
7336 Cvar_RegisterVariable(&r_bloom_resolution);
7337 Cvar_RegisterVariable(&r_bloom_colorexponent);
7338 Cvar_RegisterVariable(&r_bloom_colorsubtract);
7339 Cvar_RegisterVariable(&r_hdr);
7340 Cvar_RegisterVariable(&r_hdr_scenebrightness);
7341 Cvar_RegisterVariable(&r_hdr_glowintensity);
7342 Cvar_RegisterVariable(&r_hdr_range);
7343 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
7344 Cvar_RegisterVariable(&developer_texturelogging);
7345 Cvar_RegisterVariable(&gl_lightmaps);
7346 Cvar_RegisterVariable(&r_test);
7347 Cvar_RegisterVariable(&r_glsl_saturation);
7348 Cvar_RegisterVariable(&r_framedatasize);
7349 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
7350 Cvar_SetValue("r_fullbrights", 0);
7351 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
7353 Cvar_RegisterVariable(&r_track_sprites);
7354 Cvar_RegisterVariable(&r_track_sprites_flags);
7355 Cvar_RegisterVariable(&r_track_sprites_scalew);
7356 Cvar_RegisterVariable(&r_track_sprites_scaleh);
7357 Cvar_RegisterVariable(&r_overheadsprites_perspective);
7358 Cvar_RegisterVariable(&r_overheadsprites_pushback);
7361 extern void R_Textures_Init(void);
7362 extern void GL_Draw_Init(void);
7363 extern void GL_Main_Init(void);
7364 extern void R_Shadow_Init(void);
7365 extern void R_Sky_Init(void);
7366 extern void GL_Surf_Init(void);
7367 extern void R_Particles_Init(void);
7368 extern void R_Explosion_Init(void);
7369 extern void gl_backend_init(void);
7370 extern void Sbar_Init(void);
7371 extern void R_LightningBeams_Init(void);
7372 extern void Mod_RenderInit(void);
7373 extern void Font_Init(void);
7375 void Render_Init(void)
7388 R_LightningBeams_Init();
7397 extern char *ENGINE_EXTENSIONS;
7400 gl_renderer = (const char *)qglGetString(GL_RENDERER);
7401 gl_vendor = (const char *)qglGetString(GL_VENDOR);
7402 gl_version = (const char *)qglGetString(GL_VERSION);
7403 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
7407 if (!gl_platformextensions)
7408 gl_platformextensions = "";
7410 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
7411 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
7412 Con_Printf("GL_VERSION: %s\n", gl_version);
7413 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
7414 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
7416 VID_CheckExtensions();
7418 // LordHavoc: report supported extensions
7419 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
7421 // clear to black (loading plaque will be seen over this)
7422 GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
7425 int R_CullBox(const vec3_t mins, const vec3_t maxs)
7429 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7431 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
7434 p = r_refdef.view.frustum + i;
7439 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7443 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7447 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7451 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7455 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7459 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7463 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7467 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7475 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
7479 for (i = 0;i < numplanes;i++)
7486 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7490 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7494 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7498 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7502 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7506 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7510 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7514 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7522 //==================================================================================
7524 // LordHavoc: this stores temporary data used within the same frame
7526 qboolean r_framedata_failed;
7527 static size_t r_framedata_size;
7528 static size_t r_framedata_current;
7529 static void *r_framedata_base;
7531 void R_FrameData_Reset(void)
7533 if (r_framedata_base)
7534 Mem_Free(r_framedata_base);
7535 r_framedata_base = NULL;
7536 r_framedata_size = 0;
7537 r_framedata_current = 0;
7538 r_framedata_failed = false;
7541 void R_FrameData_NewFrame(void)
7544 if (r_framedata_failed)
7545 Cvar_SetValueQuick(&r_framedatasize, r_framedatasize.value + 1.0f);
7546 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
7547 wantedsize = bound(65536, wantedsize, 128*1024*1024);
7548 if (r_framedata_size != wantedsize)
7550 r_framedata_size = wantedsize;
7551 if (r_framedata_base)
7552 Mem_Free(r_framedata_base);
7553 r_framedata_base = Mem_Alloc(r_main_mempool, r_framedata_size);
7555 r_framedata_current = 0;
7556 r_framedata_failed = false;
7559 void *R_FrameData_Alloc(size_t size)
7563 // align to 16 byte boundary
7564 size = (size + 15) & ~15;
7565 data = (void *)((unsigned char*)r_framedata_base + r_framedata_current);
7566 r_framedata_current += size;
7569 if (r_framedata_current > r_framedata_size)
7570 r_framedata_failed = true;
7572 // return NULL on everything after a failure
7573 if (r_framedata_failed)
7579 void *R_FrameData_Store(size_t size, void *data)
7581 void *d = R_FrameData_Alloc(size);
7583 memcpy(d, data, size);
7587 //==================================================================================
7589 // LordHavoc: animcache originally written by Echon, rewritten since then
7592 * Animation cache prevents re-generating mesh data for an animated model
7593 * multiple times in one frame for lighting, shadowing, reflections, etc.
7596 void R_AnimCache_Free(void)
7600 void R_AnimCache_ClearCache(void)
7603 entity_render_t *ent;
7605 for (i = 0;i < r_refdef.scene.numentities;i++)
7607 ent = r_refdef.scene.entities[i];
7608 ent->animcache_vertex3f = NULL;
7609 ent->animcache_normal3f = NULL;
7610 ent->animcache_svector3f = NULL;
7611 ent->animcache_tvector3f = NULL;
7612 ent->animcache_vertexposition = NULL;
7613 ent->animcache_vertexmesh = NULL;
7614 ent->animcache_vertexpositionbuffer = NULL;
7615 ent->animcache_vertexmeshbuffer = NULL;
7619 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
7622 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
7623 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
7624 if (!ent->animcache_vertexposition)
7625 ent->animcache_vertexposition = (r_vertexposition_t *)R_FrameData_Alloc(sizeof(r_vertexposition_t)*numvertices);
7626 if (ent->animcache_vertexposition)
7628 for (i = 0;i < numvertices;i++)
7629 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexposition[i].vertex3f);
7630 // TODO: upload vertex buffer?
7632 if (ent->animcache_vertexmesh)
7634 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
7635 for (i = 0;i < numvertices;i++)
7636 VectorCopy(ent->animcache_vertex3f + 3*i, ent->animcache_vertexmesh[i].vertex3f);
7637 if (ent->animcache_svector3f)
7638 for (i = 0;i < numvertices;i++)
7639 VectorCopy(ent->animcache_svector3f + 3*i, ent->animcache_vertexmesh[i].svector3f);
7640 if (ent->animcache_tvector3f)
7641 for (i = 0;i < numvertices;i++)
7642 VectorCopy(ent->animcache_tvector3f + 3*i, ent->animcache_vertexmesh[i].tvector3f);
7643 if (ent->animcache_normal3f)
7644 for (i = 0;i < numvertices;i++)
7645 VectorCopy(ent->animcache_normal3f + 3*i, ent->animcache_vertexmesh[i].normal3f);
7646 // TODO: upload vertex buffer?
7650 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
7652 dp_model_t *model = ent->model;
7654 // see if it's already cached this frame
7655 if (ent->animcache_vertex3f)
7657 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
7658 if (wantnormals || wanttangents)
7660 if (ent->animcache_normal3f)
7661 wantnormals = false;
7662 if (ent->animcache_svector3f)
7663 wanttangents = false;
7664 if (wantnormals || wanttangents)
7666 numvertices = model->surfmesh.num_vertices;
7668 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7671 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7672 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7674 if (!r_framedata_failed)
7676 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
7677 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7684 // see if this ent is worth caching
7685 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7687 // get some memory for this entity and generate mesh data
7688 numvertices = model->surfmesh.num_vertices;
7689 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7691 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7694 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7695 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7697 if (!r_framedata_failed)
7699 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7700 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7703 return !r_framedata_failed;
7706 void R_AnimCache_CacheVisibleEntities(void)
7709 qboolean wantnormals = true;
7710 qboolean wanttangents = !r_showsurfaces.integer;
7712 switch(vid.renderpath)
7714 case RENDERPATH_GL20:
7715 case RENDERPATH_CGGL:
7716 case RENDERPATH_D3D9:
7717 case RENDERPATH_D3D10:
7718 case RENDERPATH_D3D11:
7720 case RENDERPATH_GL13:
7721 case RENDERPATH_GL11:
7722 wanttangents = false;
7726 if (r_shownormals.integer)
7727 wanttangents = wantnormals = true;
7729 // TODO: thread this
7730 // NOTE: R_PrepareRTLights() also caches entities
7732 for (i = 0;i < r_refdef.scene.numentities;i++)
7733 if (r_refdef.viewcache.entityvisible[i])
7734 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7737 //==================================================================================
7739 static void R_View_UpdateEntityLighting (void)
7742 entity_render_t *ent;
7743 vec3_t tempdiffusenormal, avg;
7744 vec_t f, fa, fd, fdd;
7745 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7747 for (i = 0;i < r_refdef.scene.numentities;i++)
7749 ent = r_refdef.scene.entities[i];
7751 // skip unseen models
7752 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7756 if (ent->model && ent->model->brush.num_leafs)
7758 // TODO: use modellight for r_ambient settings on world?
7759 VectorSet(ent->modellight_ambient, 0, 0, 0);
7760 VectorSet(ent->modellight_diffuse, 0, 0, 0);
7761 VectorSet(ent->modellight_lightdir, 0, 0, 1);
7765 // fetch the lighting from the worldmodel data
7766 VectorClear(ent->modellight_ambient);
7767 VectorClear(ent->modellight_diffuse);
7768 VectorClear(tempdiffusenormal);
7769 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7772 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7773 r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, org, ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal);
7774 if(ent->flags & RENDER_EQUALIZE)
7776 // first fix up ambient lighting...
7777 if(r_equalize_entities_minambient.value > 0)
7779 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7782 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7783 if(fa < r_equalize_entities_minambient.value * fd)
7786 // fa'/fd' = minambient
7787 // fa'+0.25*fd' = fa+0.25*fd
7789 // fa' = fd' * minambient
7790 // fd'*(0.25+minambient) = fa+0.25*fd
7792 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7793 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7795 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7796 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
7797 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7798 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7803 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7805 VectorMA(ent->modellight_ambient, 0.25f, ent->modellight_diffuse, avg);
7806 f = 0.299f * avg[0] + 0.587f * avg[1] + 0.114f * avg[2];
7809 f = pow(f / r_equalize_entities_to.value, -r_equalize_entities_by.value);
7810 VectorScale(ent->modellight_ambient, f, ent->modellight_ambient);
7811 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7817 VectorSet(ent->modellight_ambient, 1, 1, 1);
7819 // move the light direction into modelspace coordinates for lighting code
7820 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7821 if(VectorLength2(ent->modellight_lightdir) == 0)
7822 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7823 VectorNormalize(ent->modellight_lightdir);
7827 #define MAX_LINEOFSIGHTTRACES 64
7829 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7832 vec3_t boxmins, boxmaxs;
7835 dp_model_t *model = r_refdef.scene.worldmodel;
7837 if (!model || !model->brush.TraceLineOfSight)
7840 // expand the box a little
7841 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7842 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7843 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7844 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7845 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7846 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7848 // return true if eye is inside enlarged box
7849 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7853 VectorCopy(eye, start);
7854 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7855 if (model->brush.TraceLineOfSight(model, start, end))
7858 // try various random positions
7859 for (i = 0;i < numsamples;i++)
7861 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7862 if (model->brush.TraceLineOfSight(model, start, end))
7870 static void R_View_UpdateEntityVisible (void)
7875 entity_render_t *ent;
7877 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7878 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7879 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
7880 : RENDER_EXTERIORMODEL;
7881 if (!r_drawviewmodel.integer)
7882 renderimask |= RENDER_VIEWMODEL;
7883 if (!r_drawexteriormodel.integer)
7884 renderimask |= RENDER_EXTERIORMODEL;
7885 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7887 // worldmodel can check visibility
7888 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7889 for (i = 0;i < r_refdef.scene.numentities;i++)
7891 ent = r_refdef.scene.entities[i];
7892 if (!(ent->flags & renderimask))
7893 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7894 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))
7895 r_refdef.viewcache.entityvisible[i] = true;
7897 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7898 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7900 for (i = 0;i < r_refdef.scene.numentities;i++)
7902 ent = r_refdef.scene.entities[i];
7903 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7905 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7907 continue; // temp entities do pvs only
7908 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7909 ent->last_trace_visibility = realtime;
7910 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7911 r_refdef.viewcache.entityvisible[i] = 0;
7918 // no worldmodel or it can't check visibility
7919 for (i = 0;i < r_refdef.scene.numentities;i++)
7921 ent = r_refdef.scene.entities[i];
7922 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));
7927 /// only used if skyrendermasked, and normally returns false
7928 int R_DrawBrushModelsSky (void)
7931 entity_render_t *ent;
7934 for (i = 0;i < r_refdef.scene.numentities;i++)
7936 if (!r_refdef.viewcache.entityvisible[i])
7938 ent = r_refdef.scene.entities[i];
7939 if (!ent->model || !ent->model->DrawSky)
7941 ent->model->DrawSky(ent);
7947 static void R_DrawNoModel(entity_render_t *ent);
7948 static void R_DrawModels(void)
7951 entity_render_t *ent;
7953 for (i = 0;i < r_refdef.scene.numentities;i++)
7955 if (!r_refdef.viewcache.entityvisible[i])
7957 ent = r_refdef.scene.entities[i];
7958 r_refdef.stats.entities++;
7959 if (ent->model && ent->model->Draw != NULL)
7960 ent->model->Draw(ent);
7966 static void R_DrawModelsDepth(void)
7969 entity_render_t *ent;
7971 for (i = 0;i < r_refdef.scene.numentities;i++)
7973 if (!r_refdef.viewcache.entityvisible[i])
7975 ent = r_refdef.scene.entities[i];
7976 if (ent->model && ent->model->DrawDepth != NULL)
7977 ent->model->DrawDepth(ent);
7981 static void R_DrawModelsDebug(void)
7984 entity_render_t *ent;
7986 for (i = 0;i < r_refdef.scene.numentities;i++)
7988 if (!r_refdef.viewcache.entityvisible[i])
7990 ent = r_refdef.scene.entities[i];
7991 if (ent->model && ent->model->DrawDebug != NULL)
7992 ent->model->DrawDebug(ent);
7996 static void R_DrawModelsAddWaterPlanes(void)
7999 entity_render_t *ent;
8001 for (i = 0;i < r_refdef.scene.numentities;i++)
8003 if (!r_refdef.viewcache.entityvisible[i])
8005 ent = r_refdef.scene.entities[i];
8006 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
8007 ent->model->DrawAddWaterPlanes(ent);
8011 static void R_View_SetFrustum(void)
8014 double slopex, slopey;
8015 vec3_t forward, left, up, origin;
8017 // we can't trust r_refdef.view.forward and friends in reflected scenes
8018 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
8021 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
8022 r_refdef.view.frustum[0].normal[1] = 0 - 0;
8023 r_refdef.view.frustum[0].normal[2] = -1 - 0;
8024 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
8025 r_refdef.view.frustum[1].normal[1] = 0 + 0;
8026 r_refdef.view.frustum[1].normal[2] = -1 + 0;
8027 r_refdef.view.frustum[2].normal[0] = 0 - 0;
8028 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
8029 r_refdef.view.frustum[2].normal[2] = -1 - 0;
8030 r_refdef.view.frustum[3].normal[0] = 0 + 0;
8031 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
8032 r_refdef.view.frustum[3].normal[2] = -1 + 0;
8036 zNear = r_refdef.nearclip;
8037 nudge = 1.0 - 1.0 / (1<<23);
8038 r_refdef.view.frustum[4].normal[0] = 0 - 0;
8039 r_refdef.view.frustum[4].normal[1] = 0 - 0;
8040 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
8041 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
8042 r_refdef.view.frustum[5].normal[0] = 0 + 0;
8043 r_refdef.view.frustum[5].normal[1] = 0 + 0;
8044 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
8045 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
8051 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
8052 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
8053 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
8054 r_refdef.view.frustum[0].dist = m[15] - m[12];
8056 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
8057 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
8058 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
8059 r_refdef.view.frustum[1].dist = m[15] + m[12];
8061 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
8062 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
8063 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
8064 r_refdef.view.frustum[2].dist = m[15] - m[13];
8066 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
8067 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
8068 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
8069 r_refdef.view.frustum[3].dist = m[15] + m[13];
8071 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
8072 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
8073 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
8074 r_refdef.view.frustum[4].dist = m[15] - m[14];
8076 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
8077 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
8078 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
8079 r_refdef.view.frustum[5].dist = m[15] + m[14];
8082 if (r_refdef.view.useperspective)
8084 slopex = 1.0 / r_refdef.view.frustum_x;
8085 slopey = 1.0 / r_refdef.view.frustum_y;
8086 VectorMA(forward, -slopex, left, r_refdef.view.frustum[0].normal);
8087 VectorMA(forward, slopex, left, r_refdef.view.frustum[1].normal);
8088 VectorMA(forward, -slopey, up , r_refdef.view.frustum[2].normal);
8089 VectorMA(forward, slopey, up , r_refdef.view.frustum[3].normal);
8090 VectorCopy(forward, r_refdef.view.frustum[4].normal);
8092 // Leaving those out was a mistake, those were in the old code, and they
8093 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
8094 // I couldn't reproduce it after adding those normalizations. --blub
8095 VectorNormalize(r_refdef.view.frustum[0].normal);
8096 VectorNormalize(r_refdef.view.frustum[1].normal);
8097 VectorNormalize(r_refdef.view.frustum[2].normal);
8098 VectorNormalize(r_refdef.view.frustum[3].normal);
8100 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
8101 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]);
8102 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]);
8103 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]);
8104 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]);
8106 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
8107 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
8108 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
8109 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
8110 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
8114 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
8115 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
8116 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
8117 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
8118 VectorCopy(forward, r_refdef.view.frustum[4].normal);
8119 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
8120 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
8121 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
8122 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
8123 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
8125 r_refdef.view.numfrustumplanes = 5;
8127 if (r_refdef.view.useclipplane)
8129 r_refdef.view.numfrustumplanes = 6;
8130 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
8133 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
8134 PlaneClassify(r_refdef.view.frustum + i);
8136 // LordHavoc: note to all quake engine coders, Quake had a special case
8137 // for 90 degrees which assumed a square view (wrong), so I removed it,
8138 // Quake2 has it disabled as well.
8140 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
8141 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
8142 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
8143 //PlaneClassify(&frustum[0]);
8145 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
8146 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
8147 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
8148 //PlaneClassify(&frustum[1]);
8150 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
8151 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
8152 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
8153 //PlaneClassify(&frustum[2]);
8155 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
8156 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
8157 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
8158 //PlaneClassify(&frustum[3]);
8161 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
8162 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
8163 //PlaneClassify(&frustum[4]);
8166 void R_View_Update(void)
8168 R_Main_ResizeViewCache();
8169 R_View_SetFrustum();
8170 R_View_WorldVisibility(r_refdef.view.useclipplane);
8171 R_View_UpdateEntityVisible();
8172 R_View_UpdateEntityLighting();
8175 void R_SetupView(qboolean allowwaterclippingplane)
8177 const float *customclipplane = NULL;
8179 if (r_refdef.view.useclipplane && allowwaterclippingplane)
8181 // LordHavoc: couldn't figure out how to make this approach the
8182 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
8183 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
8184 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
8185 dist = r_refdef.view.clipplane.dist;
8186 plane[0] = r_refdef.view.clipplane.normal[0];
8187 plane[1] = r_refdef.view.clipplane.normal[1];
8188 plane[2] = r_refdef.view.clipplane.normal[2];
8190 customclipplane = plane;
8193 if (!r_refdef.view.useperspective)
8194 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);
8195 else if (vid.stencil && r_useinfinitefarclip.integer)
8196 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);
8198 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);
8199 R_SetViewport(&r_refdef.view.viewport);
8202 void R_EntityMatrix(const matrix4x4_t *matrix)
8204 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
8206 gl_modelmatrixchanged = false;
8207 gl_modelmatrix = *matrix;
8208 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
8209 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
8210 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
8211 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
8213 switch(vid.renderpath)
8215 case RENDERPATH_D3D9:
8217 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
8218 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
8221 case RENDERPATH_D3D10:
8222 Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
8224 case RENDERPATH_D3D11:
8225 Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
8227 case RENDERPATH_GL20:
8228 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
8229 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fvARB(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
8230 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8232 case RENDERPATH_CGGL:
8235 if (r_cg_permutation && r_cg_permutation->vp_ModelViewProjectionMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewProjectionMatrix, gl_modelviewprojection16f);CHECKCGERROR
8236 if (r_cg_permutation && r_cg_permutation->vp_ModelViewMatrix) cgGLSetMatrixParameterfc(r_cg_permutation->vp_ModelViewMatrix, gl_modelview16f);CHECKCGERROR
8237 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8240 case RENDERPATH_GL13:
8241 case RENDERPATH_GL11:
8242 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8248 void R_ResetViewRendering2D(void)
8250 r_viewport_t viewport;
8253 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
8254 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);
8255 R_SetViewport(&viewport);
8256 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
8257 GL_Color(1, 1, 1, 1);
8258 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8259 GL_BlendFunc(GL_ONE, GL_ZERO);
8260 GL_AlphaTest(false);
8261 GL_ScissorTest(false);
8262 GL_DepthMask(false);
8263 GL_DepthRange(0, 1);
8264 GL_DepthTest(false);
8265 GL_DepthFunc(GL_LEQUAL);
8266 R_EntityMatrix(&identitymatrix);
8267 R_Mesh_ResetTextureState();
8268 GL_PolygonOffset(0, 0);
8269 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8270 switch(vid.renderpath)
8272 case RENDERPATH_GL11:
8273 case RENDERPATH_GL13:
8274 case RENDERPATH_GL20:
8275 case RENDERPATH_CGGL:
8276 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8278 case RENDERPATH_D3D9:
8279 case RENDERPATH_D3D10:
8280 case RENDERPATH_D3D11:
8283 GL_CullFace(GL_NONE);
8286 void R_ResetViewRendering3D(void)
8291 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8292 GL_Color(1, 1, 1, 1);
8293 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8294 GL_BlendFunc(GL_ONE, GL_ZERO);
8295 GL_AlphaTest(false);
8296 GL_ScissorTest(true);
8298 GL_DepthRange(0, 1);
8300 GL_DepthFunc(GL_LEQUAL);
8301 R_EntityMatrix(&identitymatrix);
8302 R_Mesh_ResetTextureState();
8303 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8304 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8305 switch(vid.renderpath)
8307 case RENDERPATH_GL11:
8308 case RENDERPATH_GL13:
8309 case RENDERPATH_GL20:
8310 case RENDERPATH_CGGL:
8311 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8313 case RENDERPATH_D3D9:
8314 case RENDERPATH_D3D10:
8315 case RENDERPATH_D3D11:
8318 GL_CullFace(r_refdef.view.cullface_back);
8323 R_RenderView_UpdateViewVectors
8326 static void R_RenderView_UpdateViewVectors(void)
8328 // break apart the view matrix into vectors for various purposes
8329 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
8330 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
8331 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
8332 VectorNegate(r_refdef.view.left, r_refdef.view.right);
8333 // make an inverted copy of the view matrix for tracking sprites
8334 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
8337 void R_RenderScene(void);
8338 void R_RenderWaterPlanes(void);
8340 static void R_Water_StartFrame(void)
8343 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
8344 r_waterstate_waterplane_t *p;
8346 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
8349 switch(vid.renderpath)
8351 case RENDERPATH_GL20:
8352 case RENDERPATH_CGGL:
8353 case RENDERPATH_D3D9:
8354 case RENDERPATH_D3D10:
8355 case RENDERPATH_D3D11:
8357 case RENDERPATH_GL13:
8358 case RENDERPATH_GL11:
8362 // set waterwidth and waterheight to the water resolution that will be
8363 // used (often less than the screen resolution for faster rendering)
8364 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
8365 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
8367 // calculate desired texture sizes
8368 // can't use water if the card does not support the texture size
8369 if (!r_water.integer || r_showsurfaces.integer)
8370 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
8371 else if (vid.support.arb_texture_non_power_of_two)
8373 texturewidth = waterwidth;
8374 textureheight = waterheight;
8375 camerawidth = waterwidth;
8376 cameraheight = waterheight;
8380 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
8381 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
8382 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
8383 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
8386 // allocate textures as needed
8387 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
8389 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8390 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
8392 if (p->texture_refraction)
8393 R_FreeTexture(p->texture_refraction);
8394 p->texture_refraction = NULL;
8395 if (p->texture_reflection)
8396 R_FreeTexture(p->texture_reflection);
8397 p->texture_reflection = NULL;
8398 if (p->texture_camera)
8399 R_FreeTexture(p->texture_camera);
8400 p->texture_camera = NULL;
8402 memset(&r_waterstate, 0, sizeof(r_waterstate));
8403 r_waterstate.texturewidth = texturewidth;
8404 r_waterstate.textureheight = textureheight;
8405 r_waterstate.camerawidth = camerawidth;
8406 r_waterstate.cameraheight = cameraheight;
8409 if (r_waterstate.texturewidth)
8411 r_waterstate.enabled = true;
8413 // when doing a reduced render (HDR) we want to use a smaller area
8414 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
8415 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
8417 // set up variables that will be used in shader setup
8418 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8419 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8420 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8421 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8424 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8425 r_waterstate.numwaterplanes = 0;
8428 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
8430 int triangleindex, planeindex;
8437 r_waterstate_waterplane_t *p;
8438 texture_t *t = R_GetCurrentTexture(surface->texture);
8439 cam_ent = t->camera_entity;
8440 if(!(t->currentmaterialflags & MATERIALFLAG_CAMERA))
8443 // just use the first triangle with a valid normal for any decisions
8444 VectorClear(normal);
8445 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
8447 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
8448 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
8449 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
8450 TriangleNormal(vert[0], vert[1], vert[2], normal);
8451 if (VectorLength2(normal) >= 0.001)
8455 VectorCopy(normal, plane.normal);
8456 VectorNormalize(plane.normal);
8457 plane.dist = DotProduct(vert[0], plane.normal);
8458 PlaneClassify(&plane);
8459 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
8461 // skip backfaces (except if nocullface is set)
8462 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
8464 VectorNegate(plane.normal, plane.normal);
8466 PlaneClassify(&plane);
8470 // find a matching plane if there is one
8471 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8472 if(p->camera_entity == t->camera_entity)
8473 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
8475 if (planeindex >= r_waterstate.maxwaterplanes)
8476 return; // nothing we can do, out of planes
8478 // if this triangle does not fit any known plane rendered this frame, add one
8479 if (planeindex >= r_waterstate.numwaterplanes)
8481 // store the new plane
8482 r_waterstate.numwaterplanes++;
8484 // clear materialflags and pvs
8485 p->materialflags = 0;
8486 p->pvsvalid = false;
8487 p->camera_entity = t->camera_entity;
8489 // merge this surface's materialflags into the waterplane
8490 p->materialflags |= t->currentmaterialflags;
8491 if(!(p->materialflags & MATERIALFLAG_CAMERA))
8493 // merge this surface's PVS into the waterplane
8494 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
8495 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
8496 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
8498 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
8504 static void R_Water_ProcessPlanes(void)
8506 r_refdef_view_t originalview;
8507 r_refdef_view_t myview;
8509 r_waterstate_waterplane_t *p;
8512 originalview = r_refdef.view;
8514 // make sure enough textures are allocated
8515 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8517 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8519 if (!p->texture_refraction)
8520 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8521 if (!p->texture_refraction)
8524 else if (p->materialflags & MATERIALFLAG_CAMERA)
8526 if (!p->texture_camera)
8527 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
8528 if (!p->texture_camera)
8532 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8534 if (!p->texture_reflection)
8535 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8536 if (!p->texture_reflection)
8542 r_refdef.view = originalview;
8543 r_refdef.view.showdebug = false;
8544 r_refdef.view.width = r_waterstate.waterwidth;
8545 r_refdef.view.height = r_waterstate.waterheight;
8546 r_refdef.view.useclipplane = true;
8547 myview = r_refdef.view;
8548 r_waterstate.renderingscene = true;
8549 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8551 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8553 r_refdef.view = myview;
8554 // render reflected scene and copy into texture
8555 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
8556 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
8557 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
8558 r_refdef.view.clipplane = p->plane;
8559 // reverse the cullface settings for this render
8560 r_refdef.view.cullface_front = GL_FRONT;
8561 r_refdef.view.cullface_back = GL_BACK;
8562 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
8564 r_refdef.view.usecustompvs = true;
8566 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8568 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8571 R_ResetViewRendering3D();
8572 R_ClearScreen(r_refdef.fogenabled);
8576 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);
8579 // render the normal view scene and copy into texture
8580 // (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)
8581 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8583 r_waterstate.renderingrefraction = true;
8584 r_refdef.view = myview;
8586 r_refdef.view.clipplane = p->plane;
8587 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8588 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8590 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
8592 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8593 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
8594 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8595 R_RenderView_UpdateViewVectors();
8596 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);
8599 PlaneClassify(&r_refdef.view.clipplane);
8601 R_ResetViewRendering3D();
8602 R_ClearScreen(r_refdef.fogenabled);
8606 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);
8607 r_waterstate.renderingrefraction = false;
8609 else if (p->materialflags & MATERIALFLAG_CAMERA)
8611 r_refdef.view = myview;
8613 r_refdef.view.clipplane = p->plane;
8614 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8615 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8617 r_refdef.view.width = r_waterstate.camerawidth;
8618 r_refdef.view.height = r_waterstate.cameraheight;
8619 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
8620 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
8622 if(p->camera_entity)
8624 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8625 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8628 // reverse the cullface settings for this render
8629 r_refdef.view.cullface_front = GL_FRONT;
8630 r_refdef.view.cullface_back = GL_BACK;
8631 // also reverse the view matrix
8632 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
8633 R_RenderView_UpdateViewVectors();
8634 if(p->camera_entity)
8635 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);
8637 // camera needs no clipplane
8638 r_refdef.view.useclipplane = false;
8640 PlaneClassify(&r_refdef.view.clipplane);
8642 R_ResetViewRendering3D();
8643 R_ClearScreen(r_refdef.fogenabled);
8647 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);
8648 r_waterstate.renderingrefraction = false;
8652 r_waterstate.renderingscene = false;
8653 r_refdef.view = originalview;
8654 R_ResetViewRendering3D();
8655 R_ClearScreen(r_refdef.fogenabled);
8659 r_refdef.view = originalview;
8660 r_waterstate.renderingscene = false;
8661 Cvar_SetValueQuick(&r_water, 0);
8662 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
8666 void R_Bloom_StartFrame(void)
8668 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8670 switch(vid.renderpath)
8672 case RENDERPATH_GL20:
8673 case RENDERPATH_CGGL:
8674 case RENDERPATH_D3D9:
8675 case RENDERPATH_D3D10:
8676 case RENDERPATH_D3D11:
8678 case RENDERPATH_GL13:
8679 case RENDERPATH_GL11:
8683 // set bloomwidth and bloomheight to the bloom resolution that will be
8684 // used (often less than the screen resolution for faster rendering)
8685 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8686 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8687 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8688 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8689 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8691 // calculate desired texture sizes
8692 if (vid.support.arb_texture_non_power_of_two)
8694 screentexturewidth = r_refdef.view.width;
8695 screentextureheight = r_refdef.view.height;
8696 bloomtexturewidth = r_bloomstate.bloomwidth;
8697 bloomtextureheight = r_bloomstate.bloomheight;
8701 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
8702 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
8703 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
8704 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
8707 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))
8709 Cvar_SetValueQuick(&r_hdr, 0);
8710 Cvar_SetValueQuick(&r_bloom, 0);
8711 Cvar_SetValueQuick(&r_motionblur, 0);
8712 Cvar_SetValueQuick(&r_damageblur, 0);
8715 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)))
8716 screentexturewidth = screentextureheight = 0;
8717 if (!r_hdr.integer && !r_bloom.integer)
8718 bloomtexturewidth = bloomtextureheight = 0;
8720 // allocate textures as needed
8721 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8723 if (r_bloomstate.texture_screen)
8724 R_FreeTexture(r_bloomstate.texture_screen);
8725 r_bloomstate.texture_screen = NULL;
8726 r_bloomstate.screentexturewidth = screentexturewidth;
8727 r_bloomstate.screentextureheight = screentextureheight;
8728 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8729 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8731 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8733 if (r_bloomstate.texture_bloom)
8734 R_FreeTexture(r_bloomstate.texture_bloom);
8735 r_bloomstate.texture_bloom = NULL;
8736 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8737 r_bloomstate.bloomtextureheight = bloomtextureheight;
8738 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8739 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8742 // when doing a reduced render (HDR) we want to use a smaller area
8743 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8744 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8745 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8746 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8747 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8749 // set up a texcoord array for the full resolution screen image
8750 // (we have to keep this around to copy back during final render)
8751 r_bloomstate.screentexcoord2f[0] = 0;
8752 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8753 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8754 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8755 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8756 r_bloomstate.screentexcoord2f[5] = 0;
8757 r_bloomstate.screentexcoord2f[6] = 0;
8758 r_bloomstate.screentexcoord2f[7] = 0;
8760 // set up a texcoord array for the reduced resolution bloom image
8761 // (which will be additive blended over the screen image)
8762 r_bloomstate.bloomtexcoord2f[0] = 0;
8763 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8764 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8765 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8766 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8767 r_bloomstate.bloomtexcoord2f[5] = 0;
8768 r_bloomstate.bloomtexcoord2f[6] = 0;
8769 r_bloomstate.bloomtexcoord2f[7] = 0;
8771 switch(vid.renderpath)
8773 case RENDERPATH_GL11:
8774 case RENDERPATH_GL13:
8775 case RENDERPATH_GL20:
8776 case RENDERPATH_CGGL:
8778 case RENDERPATH_D3D9:
8779 case RENDERPATH_D3D10:
8780 case RENDERPATH_D3D11:
8783 for (i = 0;i < 4;i++)
8785 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
8786 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
8787 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
8788 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
8794 if (r_hdr.integer || r_bloom.integer)
8796 r_bloomstate.enabled = true;
8797 r_bloomstate.hdr = r_hdr.integer != 0;
8800 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);
8803 void R_Bloom_CopyBloomTexture(float colorscale)
8805 r_refdef.stats.bloom++;
8807 // scale down screen texture to the bloom texture size
8809 R_SetViewport(&r_bloomstate.viewport);
8810 GL_BlendFunc(GL_ONE, GL_ZERO);
8811 GL_Color(colorscale, colorscale, colorscale, 1);
8812 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8813 switch(vid.renderpath)
8815 case RENDERPATH_GL11:
8816 case RENDERPATH_GL13:
8817 case RENDERPATH_GL20:
8818 case RENDERPATH_CGGL:
8819 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8821 case RENDERPATH_D3D9:
8822 case RENDERPATH_D3D10:
8823 case RENDERPATH_D3D11:
8824 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8827 // TODO: do boxfilter scale-down in shader?
8828 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8829 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8830 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8832 // we now have a bloom image in the framebuffer
8833 // copy it into the bloom image texture for later processing
8834 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);
8835 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8838 void R_Bloom_CopyHDRTexture(void)
8840 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);
8841 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8844 void R_Bloom_MakeTexture(void)
8847 float xoffset, yoffset, r, brighten;
8849 r_refdef.stats.bloom++;
8851 R_ResetViewRendering2D();
8853 // we have a bloom image in the framebuffer
8855 R_SetViewport(&r_bloomstate.viewport);
8857 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8860 r = bound(0, r_bloom_colorexponent.value / x, 1);
8861 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8863 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8864 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8865 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8866 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8868 // copy the vertically blurred bloom view to a texture
8869 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);
8870 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8873 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8874 brighten = r_bloom_brighten.value;
8876 brighten *= r_hdr_range.value;
8877 brighten = sqrt(brighten);
8879 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8880 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8882 for (dir = 0;dir < 2;dir++)
8884 // blend on at multiple vertical offsets to achieve a vertical blur
8885 // TODO: do offset blends using GLSL
8886 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8887 GL_BlendFunc(GL_ONE, GL_ZERO);
8888 for (x = -range;x <= range;x++)
8890 if (!dir){xoffset = 0;yoffset = x;}
8891 else {xoffset = x;yoffset = 0;}
8892 xoffset /= (float)r_bloomstate.bloomtexturewidth;
8893 yoffset /= (float)r_bloomstate.bloomtextureheight;
8894 // compute a texcoord array with the specified x and y offset
8895 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8896 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8897 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8898 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8899 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8900 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8901 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8902 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8903 // this r value looks like a 'dot' particle, fading sharply to
8904 // black at the edges
8905 // (probably not realistic but looks good enough)
8906 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8907 //r = brighten/(range*2+1);
8908 r = brighten / (range * 2 + 1);
8910 r *= (1 - x*x/(float)(range*range));
8911 GL_Color(r, r, r, 1);
8912 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8913 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8914 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8915 GL_BlendFunc(GL_ONE, GL_ONE);
8918 // copy the vertically blurred bloom view to a texture
8919 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);
8920 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8924 void R_HDR_RenderBloomTexture(void)
8926 int oldwidth, oldheight;
8927 float oldcolorscale;
8929 oldcolorscale = r_refdef.view.colorscale;
8930 oldwidth = r_refdef.view.width;
8931 oldheight = r_refdef.view.height;
8932 r_refdef.view.width = r_bloomstate.bloomwidth;
8933 r_refdef.view.height = r_bloomstate.bloomheight;
8935 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
8936 // TODO: add exposure compensation features
8937 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8939 r_refdef.view.showdebug = false;
8940 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8942 R_ResetViewRendering3D();
8944 R_ClearScreen(r_refdef.fogenabled);
8945 if (r_timereport_active)
8946 R_TimeReport("HDRclear");
8949 if (r_timereport_active)
8950 R_TimeReport("visibility");
8952 // only do secondary renders with HDR if r_hdr is 2 or higher
8953 r_waterstate.numwaterplanes = 0;
8954 if (r_waterstate.enabled && r_hdr.integer >= 2)
8955 R_RenderWaterPlanes();
8957 r_refdef.view.showdebug = true;
8959 r_waterstate.numwaterplanes = 0;
8961 R_ResetViewRendering2D();
8963 R_Bloom_CopyHDRTexture();
8964 R_Bloom_MakeTexture();
8966 // restore the view settings
8967 r_refdef.view.width = oldwidth;
8968 r_refdef.view.height = oldheight;
8969 r_refdef.view.colorscale = oldcolorscale;
8971 R_ResetViewRendering3D();
8973 R_ClearScreen(r_refdef.fogenabled);
8974 if (r_timereport_active)
8975 R_TimeReport("viewclear");
8978 static void R_BlendView(void)
8980 unsigned int permutation;
8981 float uservecs[4][4];
8983 switch (vid.renderpath)
8985 case RENDERPATH_GL20:
8986 case RENDERPATH_CGGL:
8987 case RENDERPATH_D3D9:
8988 case RENDERPATH_D3D10:
8989 case RENDERPATH_D3D11:
8991 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8992 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8993 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8994 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8995 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8997 if (r_bloomstate.texture_screen)
8999 // make sure the buffer is available
9000 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
9002 R_ResetViewRendering2D();
9004 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
9006 // declare variables
9008 static float avgspeed;
9010 speed = VectorLength(cl.movement_velocity);
9012 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
9013 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
9015 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
9016 speed = bound(0, speed, 1);
9017 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
9019 // calculate values into a standard alpha
9020 cl.motionbluralpha = 1 - exp(-
9022 (r_motionblur.value * speed / 80)
9024 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
9027 max(0.0001, cl.time - cl.oldtime) // fps independent
9030 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
9031 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
9033 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
9035 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9036 GL_Color(1, 1, 1, cl.motionbluralpha);
9037 switch(vid.renderpath)
9039 case RENDERPATH_GL11:
9040 case RENDERPATH_GL13:
9041 case RENDERPATH_GL20:
9042 case RENDERPATH_CGGL:
9043 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
9045 case RENDERPATH_D3D9:
9046 case RENDERPATH_D3D10:
9047 case RENDERPATH_D3D11:
9048 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
9051 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
9052 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9053 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9057 // copy view into the screen texture
9058 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);
9059 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9061 else if (!r_bloomstate.texture_bloom)
9063 // we may still have to do view tint...
9064 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9066 // apply a color tint to the whole view
9067 R_ResetViewRendering2D();
9068 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9069 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9070 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9071 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9072 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9074 break; // no screen processing, no bloom, skip it
9077 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
9079 // render simple bloom effect
9080 // copy the screen and shrink it and darken it for the bloom process
9081 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
9082 // make the bloom texture
9083 R_Bloom_MakeTexture();
9086 #if _MSC_VER >= 1400
9087 #define sscanf sscanf_s
9089 memset(uservecs, 0, sizeof(uservecs));
9090 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
9091 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
9092 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
9093 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
9095 R_ResetViewRendering2D();
9096 GL_Color(1, 1, 1, 1);
9097 GL_BlendFunc(GL_ONE, GL_ZERO);
9099 switch(vid.renderpath)
9101 case RENDERPATH_GL20:
9102 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9103 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
9104 if (r_glsl_permutation->loc_Texture_First >= 0) R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
9105 if (r_glsl_permutation->loc_Texture_Second >= 0) R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
9106 if (r_glsl_permutation->loc_Texture_GammaRamps >= 0) R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
9107 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]);
9108 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9109 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]);
9110 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]);
9111 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]);
9112 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]);
9113 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1fARB(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
9114 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2fARB(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
9115 if (r_glsl_permutation->loc_BloomColorSubtract >= 0) qglUniform4fARB(r_glsl_permutation->loc_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9117 case RENDERPATH_CGGL:
9119 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9120 R_SetupShader_SetPermutationCG(SHADERMODE_POSTPROCESS, permutation);
9121 if (r_cg_permutation->fp_Texture_First ) CG_BindTexture(r_cg_permutation->fp_Texture_First , r_bloomstate.texture_screen);CHECKCGERROR
9122 if (r_cg_permutation->fp_Texture_Second ) CG_BindTexture(r_cg_permutation->fp_Texture_Second , r_bloomstate.texture_bloom );CHECKCGERROR
9123 if (r_cg_permutation->fp_Texture_GammaRamps) CG_BindTexture(r_cg_permutation->fp_Texture_GammaRamps, r_texture_gammaramps );CHECKCGERROR
9124 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
9125 if (r_cg_permutation->fp_PixelSize ) cgGLSetParameter2f( r_cg_permutation->fp_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);CHECKCGERROR
9126 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
9127 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
9128 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
9129 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
9130 if (r_cg_permutation->fp_Saturation ) cgGLSetParameter1f( r_cg_permutation->fp_Saturation , r_glsl_saturation.value);CHECKCGERROR
9131 if (r_cg_permutation->fp_PixelToScreenTexCoord) cgGLSetParameter2f(r_cg_permutation->fp_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);CHECKCGERROR
9132 if (r_cg_permutation->fp_BloomColorSubtract ) cgGLSetParameter4f(r_cg_permutation->fp_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9135 case RENDERPATH_D3D9:
9137 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
9138 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
9139 R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
9140 R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
9141 R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
9142 R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
9143 hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9144 hlslPSSetParameter2f(D3DPSREGISTER_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9145 hlslPSSetParameter4f(D3DPSREGISTER_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9146 hlslPSSetParameter4f(D3DPSREGISTER_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9147 hlslPSSetParameter4f(D3DPSREGISTER_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9148 hlslPSSetParameter4f(D3DPSREGISTER_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9149 hlslPSSetParameter1f(D3DPSREGISTER_Saturation , r_glsl_saturation.value);
9150 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
9151 hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9154 case RENDERPATH_D3D10:
9155 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9157 case RENDERPATH_D3D11:
9158 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
9163 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9164 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9166 case RENDERPATH_GL13:
9167 case RENDERPATH_GL11:
9168 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9170 // apply a color tint to the whole view
9171 R_ResetViewRendering2D();
9172 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9173 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9174 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9175 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9176 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9182 matrix4x4_t r_waterscrollmatrix;
9184 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
9186 if (r_refdef.fog_density)
9188 r_refdef.fogcolor[0] = r_refdef.fog_red;
9189 r_refdef.fogcolor[1] = r_refdef.fog_green;
9190 r_refdef.fogcolor[2] = r_refdef.fog_blue;
9192 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
9193 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
9194 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
9195 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
9199 VectorCopy(r_refdef.fogcolor, fogvec);
9200 // color.rgb *= ContrastBoost * SceneBrightness;
9201 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
9202 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
9203 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
9204 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
9209 void R_UpdateVariables(void)
9213 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
9215 r_refdef.farclip = r_farclip_base.value;
9216 if (r_refdef.scene.worldmodel)
9217 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
9218 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
9220 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
9221 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
9222 r_refdef.polygonfactor = 0;
9223 r_refdef.polygonoffset = 0;
9224 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9225 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9227 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
9228 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
9229 r_refdef.scene.rtdlight = (r_shadow_realtime_world.integer || r_shadow_realtime_dlight.integer) && !gl_flashblend.integer && r_dynamic.integer;
9230 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
9231 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
9232 if (r_showsurfaces.integer)
9234 r_refdef.scene.rtworld = false;
9235 r_refdef.scene.rtworldshadows = false;
9236 r_refdef.scene.rtdlight = false;
9237 r_refdef.scene.rtdlightshadows = false;
9238 r_refdef.lightmapintensity = 0;
9241 if (gamemode == GAME_NEHAHRA)
9243 if (gl_fogenable.integer)
9245 r_refdef.oldgl_fogenable = true;
9246 r_refdef.fog_density = gl_fogdensity.value;
9247 r_refdef.fog_red = gl_fogred.value;
9248 r_refdef.fog_green = gl_foggreen.value;
9249 r_refdef.fog_blue = gl_fogblue.value;
9250 r_refdef.fog_alpha = 1;
9251 r_refdef.fog_start = 0;
9252 r_refdef.fog_end = gl_skyclip.value;
9253 r_refdef.fog_height = 1<<30;
9254 r_refdef.fog_fadedepth = 128;
9256 else if (r_refdef.oldgl_fogenable)
9258 r_refdef.oldgl_fogenable = false;
9259 r_refdef.fog_density = 0;
9260 r_refdef.fog_red = 0;
9261 r_refdef.fog_green = 0;
9262 r_refdef.fog_blue = 0;
9263 r_refdef.fog_alpha = 0;
9264 r_refdef.fog_start = 0;
9265 r_refdef.fog_end = 0;
9266 r_refdef.fog_height = 1<<30;
9267 r_refdef.fog_fadedepth = 128;
9271 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
9272 r_refdef.fog_start = max(0, r_refdef.fog_start);
9273 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
9275 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
9277 if (r_refdef.fog_density && r_drawfog.integer)
9279 r_refdef.fogenabled = true;
9280 // this is the point where the fog reaches 0.9986 alpha, which we
9281 // consider a good enough cutoff point for the texture
9282 // (0.9986 * 256 == 255.6)
9283 if (r_fog_exp2.integer)
9284 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
9286 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
9287 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
9288 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
9289 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
9290 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
9291 R_BuildFogHeightTexture();
9292 // fog color was already set
9293 // update the fog texture
9294 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)
9295 R_BuildFogTexture();
9296 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
9297 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
9300 r_refdef.fogenabled = false;
9302 switch(vid.renderpath)
9304 case RENDERPATH_GL20:
9305 case RENDERPATH_CGGL:
9306 case RENDERPATH_D3D9:
9307 case RENDERPATH_D3D10:
9308 case RENDERPATH_D3D11:
9309 if(v_glslgamma.integer && !vid_gammatables_trivial)
9311 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
9313 // build GLSL gamma texture
9314 #define RAMPWIDTH 256
9315 unsigned short ramp[RAMPWIDTH * 3];
9316 unsigned char rampbgr[RAMPWIDTH][4];
9319 r_texture_gammaramps_serial = vid_gammatables_serial;
9321 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
9322 for(i = 0; i < RAMPWIDTH; ++i)
9324 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9325 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9326 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
9329 if (r_texture_gammaramps)
9331 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, RAMPWIDTH, 1);
9335 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT | TEXF_ALLOWUPDATES, -1, NULL);
9341 // remove GLSL gamma texture
9344 case RENDERPATH_GL13:
9345 case RENDERPATH_GL11:
9350 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
9351 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
9357 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
9358 if( scenetype != r_currentscenetype ) {
9359 // store the old scenetype
9360 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
9361 r_currentscenetype = scenetype;
9362 // move in the new scene
9363 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
9372 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
9374 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
9375 if( scenetype == r_currentscenetype ) {
9376 return &r_refdef.scene;
9378 return &r_scenes_store[ scenetype ];
9387 void R_RenderView(void)
9389 if (r_timereport_active)
9390 R_TimeReport("start");
9391 r_textureframe++; // used only by R_GetCurrentTexture
9392 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
9394 if (!r_drawentities.integer)
9395 r_refdef.scene.numentities = 0;
9397 R_AnimCache_ClearCache();
9398 R_FrameData_NewFrame();
9400 if (r_refdef.view.isoverlay)
9402 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
9403 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
9404 R_TimeReport("depthclear");
9406 r_refdef.view.showdebug = false;
9408 r_waterstate.enabled = false;
9409 r_waterstate.numwaterplanes = 0;
9417 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
9418 return; //Host_Error ("R_RenderView: NULL worldmodel");
9420 r_refdef.view.colorscale = r_hdr_scenebrightness.value;
9422 R_RenderView_UpdateViewVectors();
9424 R_Shadow_UpdateWorldLightSelection();
9426 R_Bloom_StartFrame();
9427 R_Water_StartFrame();
9430 if (r_timereport_active)
9431 R_TimeReport("viewsetup");
9433 R_ResetViewRendering3D();
9435 if (r_refdef.view.clear || r_refdef.fogenabled)
9437 R_ClearScreen(r_refdef.fogenabled);
9438 if (r_timereport_active)
9439 R_TimeReport("viewclear");
9441 r_refdef.view.clear = true;
9443 // this produces a bloom texture to be used in R_BlendView() later
9444 if (r_hdr.integer && r_bloomstate.bloomwidth)
9446 R_HDR_RenderBloomTexture();
9447 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
9448 r_textureframe++; // used only by R_GetCurrentTexture
9451 r_refdef.view.showdebug = true;
9454 if (r_timereport_active)
9455 R_TimeReport("visibility");
9457 r_waterstate.numwaterplanes = 0;
9458 if (r_waterstate.enabled)
9459 R_RenderWaterPlanes();
9462 r_waterstate.numwaterplanes = 0;
9465 if (r_timereport_active)
9466 R_TimeReport("blendview");
9468 GL_Scissor(0, 0, vid.width, vid.height);
9469 GL_ScissorTest(false);
9473 void R_RenderWaterPlanes(void)
9475 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
9477 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
9478 if (r_timereport_active)
9479 R_TimeReport("waterworld");
9482 // don't let sound skip if going slow
9483 if (r_refdef.scene.extraupdate)
9486 R_DrawModelsAddWaterPlanes();
9487 if (r_timereport_active)
9488 R_TimeReport("watermodels");
9490 if (r_waterstate.numwaterplanes)
9492 R_Water_ProcessPlanes();
9493 if (r_timereport_active)
9494 R_TimeReport("waterscenes");
9498 extern void R_DrawLightningBeams (void);
9499 extern void VM_CL_AddPolygonsToMeshQueue (void);
9500 extern void R_DrawPortals (void);
9501 extern cvar_t cl_locs_show;
9502 static void R_DrawLocs(void);
9503 static void R_DrawEntityBBoxes(void);
9504 static void R_DrawModelDecals(void);
9505 extern void R_DrawModelShadows(void);
9506 extern void R_DrawModelShadowMaps(void);
9507 extern cvar_t cl_decals_newsystem;
9508 extern qboolean r_shadow_usingdeferredprepass;
9509 void R_RenderScene(void)
9511 qboolean shadowmapping = false;
9513 if (r_timereport_active)
9514 R_TimeReport("beginscene");
9516 r_refdef.stats.renders++;
9520 // don't let sound skip if going slow
9521 if (r_refdef.scene.extraupdate)
9524 R_MeshQueue_BeginScene();
9528 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);
9530 if (r_timereport_active)
9531 R_TimeReport("skystartframe");
9533 if (cl.csqc_vidvars.drawworld)
9535 // don't let sound skip if going slow
9536 if (r_refdef.scene.extraupdate)
9539 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
9541 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
9542 if (r_timereport_active)
9543 R_TimeReport("worldsky");
9546 if (R_DrawBrushModelsSky() && r_timereport_active)
9547 R_TimeReport("bmodelsky");
9549 if (skyrendermasked && skyrenderlater)
9551 // we have to force off the water clipping plane while rendering sky
9555 if (r_timereport_active)
9556 R_TimeReport("sky");
9560 R_AnimCache_CacheVisibleEntities();
9561 if (r_timereport_active)
9562 R_TimeReport("animation");
9564 R_Shadow_PrepareLights();
9565 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
9566 R_Shadow_PrepareModelShadows();
9567 if (r_timereport_active)
9568 R_TimeReport("preparelights");
9570 if (R_Shadow_ShadowMappingEnabled())
9571 shadowmapping = true;
9573 if (r_shadow_usingdeferredprepass)
9574 R_Shadow_DrawPrepass();
9576 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
9578 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
9579 if (r_timereport_active)
9580 R_TimeReport("worlddepth");
9582 if (r_depthfirst.integer >= 2)
9584 R_DrawModelsDepth();
9585 if (r_timereport_active)
9586 R_TimeReport("modeldepth");
9589 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
9591 R_DrawModelShadowMaps();
9592 R_ResetViewRendering3D();
9593 // don't let sound skip if going slow
9594 if (r_refdef.scene.extraupdate)
9598 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
9600 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
9601 if (r_timereport_active)
9602 R_TimeReport("world");
9605 // don't let sound skip if going slow
9606 if (r_refdef.scene.extraupdate)
9610 if (r_timereport_active)
9611 R_TimeReport("models");
9613 // don't let sound skip if going slow
9614 if (r_refdef.scene.extraupdate)
9617 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9619 R_DrawModelShadows();
9620 R_ResetViewRendering3D();
9621 // don't let sound skip if going slow
9622 if (r_refdef.scene.extraupdate)
9626 if (!r_shadow_usingdeferredprepass)
9628 R_Shadow_DrawLights();
9629 if (r_timereport_active)
9630 R_TimeReport("rtlights");
9633 // don't let sound skip if going slow
9634 if (r_refdef.scene.extraupdate)
9637 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9639 R_DrawModelShadows();
9640 R_ResetViewRendering3D();
9641 // don't let sound skip if going slow
9642 if (r_refdef.scene.extraupdate)
9646 if (cl.csqc_vidvars.drawworld)
9648 if (cl_decals_newsystem.integer)
9650 R_DrawModelDecals();
9651 if (r_timereport_active)
9652 R_TimeReport("modeldecals");
9657 if (r_timereport_active)
9658 R_TimeReport("decals");
9662 if (r_timereport_active)
9663 R_TimeReport("particles");
9666 if (r_timereport_active)
9667 R_TimeReport("explosions");
9669 R_DrawLightningBeams();
9670 if (r_timereport_active)
9671 R_TimeReport("lightning");
9674 VM_CL_AddPolygonsToMeshQueue();
9676 if (r_refdef.view.showdebug)
9678 if (cl_locs_show.integer)
9681 if (r_timereport_active)
9682 R_TimeReport("showlocs");
9685 if (r_drawportals.integer)
9688 if (r_timereport_active)
9689 R_TimeReport("portals");
9692 if (r_showbboxes.value > 0)
9694 R_DrawEntityBBoxes();
9695 if (r_timereport_active)
9696 R_TimeReport("bboxes");
9700 R_MeshQueue_RenderTransparent();
9701 if (r_timereport_active)
9702 R_TimeReport("drawtrans");
9704 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))
9706 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9707 if (r_timereport_active)
9708 R_TimeReport("worlddebug");
9709 R_DrawModelsDebug();
9710 if (r_timereport_active)
9711 R_TimeReport("modeldebug");
9714 if (cl.csqc_vidvars.drawworld)
9716 R_Shadow_DrawCoronas();
9717 if (r_timereport_active)
9718 R_TimeReport("coronas");
9721 // don't let sound skip if going slow
9722 if (r_refdef.scene.extraupdate)
9725 R_ResetViewRendering2D();
9728 static const unsigned short bboxelements[36] =
9738 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9741 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9743 RSurf_ActiveWorldEntity();
9745 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9746 GL_DepthMask(false);
9747 GL_DepthRange(0, 1);
9748 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9749 R_Mesh_ResetTextureState();
9751 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9752 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9753 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9754 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9755 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9756 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9757 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9758 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9759 R_FillColors(color4f, 8, cr, cg, cb, ca);
9760 if (r_refdef.fogenabled)
9762 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9764 f1 = RSurf_FogVertex(v);
9766 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9767 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9768 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9771 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
9772 R_Mesh_ResetTextureState();
9773 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9774 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
9777 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9781 prvm_edict_t *edict;
9782 prvm_prog_t *prog_save = prog;
9784 // this function draws bounding boxes of server entities
9788 GL_CullFace(GL_NONE);
9789 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9793 for (i = 0;i < numsurfaces;i++)
9795 edict = PRVM_EDICT_NUM(surfacelist[i]);
9796 switch ((int)edict->fields.server->solid)
9798 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
9799 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
9800 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
9801 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9802 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
9803 default: Vector4Set(color, 0, 0, 0, 0.50);break;
9805 color[3] *= r_showbboxes.value;
9806 color[3] = bound(0, color[3], 1);
9807 GL_DepthTest(!r_showdisabledepthtest.integer);
9808 GL_CullFace(r_refdef.view.cullface_front);
9809 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9815 static void R_DrawEntityBBoxes(void)
9818 prvm_edict_t *edict;
9820 prvm_prog_t *prog_save = prog;
9822 // this function draws bounding boxes of server entities
9828 for (i = 0;i < prog->num_edicts;i++)
9830 edict = PRVM_EDICT_NUM(i);
9831 if (edict->priv.server->free)
9833 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9834 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9836 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9838 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9839 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9845 static const int nomodelelement3i[24] =
9857 static const unsigned short nomodelelement3s[24] =
9869 static const float nomodelvertex3f[6*3] =
9879 static const float nomodelcolor4f[6*4] =
9881 0.0f, 0.0f, 0.5f, 1.0f,
9882 0.0f, 0.0f, 0.5f, 1.0f,
9883 0.0f, 0.5f, 0.0f, 1.0f,
9884 0.0f, 0.5f, 0.0f, 1.0f,
9885 0.5f, 0.0f, 0.0f, 1.0f,
9886 0.5f, 0.0f, 0.0f, 1.0f
9889 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9895 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);
9897 // this is only called once per entity so numsurfaces is always 1, and
9898 // surfacelist is always {0}, so this code does not handle batches
9900 if (rsurface.ent_flags & RENDER_ADDITIVE)
9902 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9903 GL_DepthMask(false);
9905 else if (rsurface.colormod[3] < 1)
9907 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9908 GL_DepthMask(false);
9912 GL_BlendFunc(GL_ONE, GL_ZERO);
9915 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9916 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9917 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9918 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9919 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9920 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9921 for (i = 0, c = color4f;i < 6;i++, c += 4)
9923 c[0] *= rsurface.colormod[0];
9924 c[1] *= rsurface.colormod[1];
9925 c[2] *= rsurface.colormod[2];
9926 c[3] *= rsurface.colormod[3];
9928 if (r_refdef.fogenabled)
9930 for (i = 0, c = color4f;i < 6;i++, c += 4)
9932 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9934 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9935 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9936 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9939 R_Mesh_ResetTextureState();
9940 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9941 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9944 void R_DrawNoModel(entity_render_t *ent)
9947 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9948 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9949 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9951 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9954 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9956 vec3_t right1, right2, diff, normal;
9958 VectorSubtract (org2, org1, normal);
9960 // calculate 'right' vector for start
9961 VectorSubtract (r_refdef.view.origin, org1, diff);
9962 CrossProduct (normal, diff, right1);
9963 VectorNormalize (right1);
9965 // calculate 'right' vector for end
9966 VectorSubtract (r_refdef.view.origin, org2, diff);
9967 CrossProduct (normal, diff, right2);
9968 VectorNormalize (right2);
9970 vert[ 0] = org1[0] + width * right1[0];
9971 vert[ 1] = org1[1] + width * right1[1];
9972 vert[ 2] = org1[2] + width * right1[2];
9973 vert[ 3] = org1[0] - width * right1[0];
9974 vert[ 4] = org1[1] - width * right1[1];
9975 vert[ 5] = org1[2] - width * right1[2];
9976 vert[ 6] = org2[0] - width * right2[0];
9977 vert[ 7] = org2[1] - width * right2[1];
9978 vert[ 8] = org2[2] - width * right2[2];
9979 vert[ 9] = org2[0] + width * right2[0];
9980 vert[10] = org2[1] + width * right2[1];
9981 vert[11] = org2[2] + width * right2[2];
9984 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)
9986 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9987 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9988 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9989 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9990 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9991 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9992 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9993 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9994 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9995 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9996 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9997 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
10000 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
10005 VectorSet(v, x, y, z);
10006 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
10007 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
10009 if (i == mesh->numvertices)
10011 if (mesh->numvertices < mesh->maxvertices)
10013 VectorCopy(v, vertex3f);
10014 mesh->numvertices++;
10016 return mesh->numvertices;
10022 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
10025 int *e, element[3];
10026 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
10027 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
10028 e = mesh->element3i + mesh->numtriangles * 3;
10029 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
10031 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
10032 if (mesh->numtriangles < mesh->maxtriangles)
10037 mesh->numtriangles++;
10039 element[1] = element[2];
10043 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
10046 int *e, element[3];
10047 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
10048 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
10049 e = mesh->element3i + mesh->numtriangles * 3;
10050 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
10052 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
10053 if (mesh->numtriangles < mesh->maxtriangles)
10058 mesh->numtriangles++;
10060 element[1] = element[2];
10064 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
10065 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
10067 int planenum, planenum2;
10070 mplane_t *plane, *plane2;
10072 double temppoints[2][256*3];
10073 // figure out how large a bounding box we need to properly compute this brush
10075 for (w = 0;w < numplanes;w++)
10076 maxdist = max(maxdist, fabs(planes[w].dist));
10077 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
10078 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
10079 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
10083 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
10084 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
10086 if (planenum2 == planenum)
10088 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);
10091 if (tempnumpoints < 3)
10093 // generate elements forming a triangle fan for this polygon
10094 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
10098 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)
10100 texturelayer_t *layer;
10101 layer = t->currentlayers + t->currentnumlayers++;
10102 layer->type = type;
10103 layer->depthmask = depthmask;
10104 layer->blendfunc1 = blendfunc1;
10105 layer->blendfunc2 = blendfunc2;
10106 layer->texture = texture;
10107 layer->texmatrix = *matrix;
10108 layer->color[0] = r;
10109 layer->color[1] = g;
10110 layer->color[2] = b;
10111 layer->color[3] = a;
10114 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
10116 if(parms[0] == 0 && parms[1] == 0)
10118 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10119 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
10124 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
10127 index = parms[2] + r_refdef.scene.time * parms[3];
10128 index -= floor(index);
10129 switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
10132 case Q3WAVEFUNC_NONE:
10133 case Q3WAVEFUNC_NOISE:
10134 case Q3WAVEFUNC_COUNT:
10137 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
10138 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
10139 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
10140 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
10141 case Q3WAVEFUNC_TRIANGLE:
10143 f = index - floor(index);
10146 else if (index < 2)
10148 else if (index < 3)
10154 f = parms[0] + parms[1] * f;
10155 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10156 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
10160 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
10165 matrix4x4_t matrix, temp;
10166 switch(tcmod->tcmod)
10168 case Q3TCMOD_COUNT:
10170 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10171 matrix = r_waterscrollmatrix;
10173 matrix = identitymatrix;
10175 case Q3TCMOD_ENTITYTRANSLATE:
10176 // this is used in Q3 to allow the gamecode to control texcoord
10177 // scrolling on the entity, which is not supported in darkplaces yet.
10178 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
10180 case Q3TCMOD_ROTATE:
10181 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
10182 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
10183 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
10185 case Q3TCMOD_SCALE:
10186 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
10188 case Q3TCMOD_SCROLL:
10189 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
10191 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
10192 w = (int) tcmod->parms[0];
10193 h = (int) tcmod->parms[1];
10194 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
10196 idx = (int) floor(f * w * h);
10197 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
10199 case Q3TCMOD_STRETCH:
10200 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
10201 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
10203 case Q3TCMOD_TRANSFORM:
10204 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
10205 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
10206 VectorSet(tcmat + 6, 0 , 0 , 1);
10207 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
10208 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
10210 case Q3TCMOD_TURBULENT:
10211 // this is handled in the RSurf_PrepareVertices function
10212 matrix = identitymatrix;
10216 Matrix4x4_Concat(texmatrix, &matrix, &temp);
10219 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
10221 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
10222 char name[MAX_QPATH];
10223 skinframe_t *skinframe;
10224 unsigned char pixels[296*194];
10225 strlcpy(cache->name, skinname, sizeof(cache->name));
10226 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
10227 if (developer_loading.integer)
10228 Con_Printf("loading %s\n", name);
10229 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
10230 if (!skinframe || !skinframe->base)
10233 fs_offset_t filesize;
10235 f = FS_LoadFile(name, tempmempool, true, &filesize);
10238 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
10239 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
10243 cache->skinframe = skinframe;
10246 texture_t *R_GetCurrentTexture(texture_t *t)
10249 const entity_render_t *ent = rsurface.entity;
10250 dp_model_t *model = ent->model;
10251 q3shaderinfo_layer_tcmod_t *tcmod;
10253 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
10254 return t->currentframe;
10255 t->update_lastrenderframe = r_textureframe;
10256 t->update_lastrenderentity = (void *)ent;
10258 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
10259 t->camera_entity = ent->entitynumber;
10261 t->camera_entity = 0;
10263 // switch to an alternate material if this is a q1bsp animated material
10265 texture_t *texture = t;
10266 int s = rsurface.ent_skinnum;
10267 if ((unsigned int)s >= (unsigned int)model->numskins)
10269 if (model->skinscenes)
10271 if (model->skinscenes[s].framecount > 1)
10272 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
10274 s = model->skinscenes[s].firstframe;
10277 t = t + s * model->num_surfaces;
10280 // use an alternate animation if the entity's frame is not 0,
10281 // and only if the texture has an alternate animation
10282 if (rsurface.ent_alttextures && t->anim_total[1])
10283 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
10285 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
10287 texture->currentframe = t;
10290 // update currentskinframe to be a qw skin or animation frame
10291 if (rsurface.ent_qwskin >= 0)
10293 i = rsurface.ent_qwskin;
10294 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
10296 r_qwskincache_size = cl.maxclients;
10298 Mem_Free(r_qwskincache);
10299 r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
10301 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
10302 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
10303 t->currentskinframe = r_qwskincache[i].skinframe;
10304 if (t->currentskinframe == NULL)
10305 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10307 else if (t->numskinframes >= 2)
10308 t->currentskinframe = t->skinframes[(int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10309 if (t->backgroundnumskinframes >= 2)
10310 t->backgroundcurrentskinframe = t->backgroundskinframes[(int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
10312 t->currentmaterialflags = t->basematerialflags;
10313 t->currentalpha = rsurface.colormod[3];
10314 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
10315 t->currentalpha *= r_wateralpha.value;
10316 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
10317 t->currentalpha *= t->r_water_wateralpha;
10318 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
10319 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
10320 if (!(rsurface.ent_flags & RENDER_LIGHT))
10321 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
10322 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
10324 // pick a model lighting mode
10325 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
10326 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
10328 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
10330 if (rsurface.ent_flags & RENDER_ADDITIVE)
10331 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10332 else if (t->currentalpha < 1)
10333 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10334 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
10335 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
10336 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
10337 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
10338 if (t->backgroundnumskinframes)
10339 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
10340 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
10342 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
10343 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
10346 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
10347 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
10348 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
10350 // there is no tcmod
10351 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10353 t->currenttexmatrix = r_waterscrollmatrix;
10354 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
10356 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
10358 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
10359 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
10362 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10363 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
10364 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10365 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
10367 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
10368 if (t->currentskinframe->qpixels)
10369 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
10370 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
10371 if (!t->basetexture)
10372 t->basetexture = r_texture_notexture;
10373 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
10374 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
10375 t->nmaptexture = t->currentskinframe->nmap;
10376 if (!t->nmaptexture)
10377 t->nmaptexture = r_texture_blanknormalmap;
10378 t->glosstexture = r_texture_black;
10379 t->glowtexture = t->currentskinframe->glow;
10380 t->fogtexture = t->currentskinframe->fog;
10381 t->reflectmasktexture = t->currentskinframe->reflect;
10382 if (t->backgroundnumskinframes)
10384 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
10385 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
10386 t->backgroundglosstexture = r_texture_black;
10387 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
10388 if (!t->backgroundnmaptexture)
10389 t->backgroundnmaptexture = r_texture_blanknormalmap;
10393 t->backgroundbasetexture = r_texture_white;
10394 t->backgroundnmaptexture = r_texture_blanknormalmap;
10395 t->backgroundglosstexture = r_texture_black;
10396 t->backgroundglowtexture = NULL;
10398 t->specularpower = r_shadow_glossexponent.value;
10399 // TODO: store reference values for these in the texture?
10400 t->specularscale = 0;
10401 if (r_shadow_gloss.integer > 0)
10403 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
10405 if (r_shadow_glossintensity.value > 0)
10407 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
10408 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
10409 t->specularscale = r_shadow_glossintensity.value;
10412 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
10414 t->glosstexture = r_texture_white;
10415 t->backgroundglosstexture = r_texture_white;
10416 t->specularscale = r_shadow_gloss2intensity.value;
10417 t->specularpower = r_shadow_gloss2exponent.value;
10420 t->specularscale *= t->specularscalemod;
10421 t->specularpower *= t->specularpowermod;
10423 // lightmaps mode looks bad with dlights using actual texturing, so turn
10424 // off the colormap and glossmap, but leave the normalmap on as it still
10425 // accurately represents the shading involved
10426 if (gl_lightmaps.integer)
10428 t->basetexture = r_texture_grey128;
10429 t->pantstexture = r_texture_black;
10430 t->shirttexture = r_texture_black;
10431 t->nmaptexture = r_texture_blanknormalmap;
10432 t->glosstexture = r_texture_black;
10433 t->glowtexture = NULL;
10434 t->fogtexture = NULL;
10435 t->reflectmasktexture = NULL;
10436 t->backgroundbasetexture = NULL;
10437 t->backgroundnmaptexture = r_texture_blanknormalmap;
10438 t->backgroundglosstexture = r_texture_black;
10439 t->backgroundglowtexture = NULL;
10440 t->specularscale = 0;
10441 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
10444 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
10445 // don't colormod customblend textures
10446 if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10447 VectorSet(t->lightmapcolor, 1, 1, 1);
10448 VectorClear(t->dlightcolor);
10449 t->currentnumlayers = 0;
10450 if (t->currentmaterialflags & MATERIALFLAG_WALL)
10452 int blendfunc1, blendfunc2;
10453 qboolean depthmask;
10454 if (t->currentmaterialflags & MATERIALFLAG_ADD)
10456 blendfunc1 = GL_SRC_ALPHA;
10457 blendfunc2 = GL_ONE;
10459 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
10461 blendfunc1 = GL_SRC_ALPHA;
10462 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
10464 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10466 blendfunc1 = t->customblendfunc[0];
10467 blendfunc2 = t->customblendfunc[1];
10471 blendfunc1 = GL_ONE;
10472 blendfunc2 = GL_ZERO;
10474 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
10475 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10477 // fullbright is not affected by r_refdef.lightmapintensity
10478 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]);
10479 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10480 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]);
10481 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10482 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]);
10486 vec3_t ambientcolor;
10488 // set the color tint used for lights affecting this surface
10489 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
10491 // q3bsp has no lightmap updates, so the lightstylevalue that
10492 // would normally be baked into the lightmap must be
10493 // applied to the color
10494 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
10495 if (model->type == mod_brushq3)
10496 colorscale *= r_refdef.scene.rtlightstylevalue[0];
10497 colorscale *= r_refdef.lightmapintensity;
10498 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
10499 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
10500 // basic lit geometry
10501 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]);
10502 // add pants/shirt if needed
10503 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10504 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]);
10505 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10506 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]);
10507 // now add ambient passes if needed
10508 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
10510 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]);
10511 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10512 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]);
10513 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10514 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]);
10517 if (t->glowtexture != NULL && !gl_lightmaps.integer)
10518 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]);
10519 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
10521 // if this is opaque use alpha blend which will darken the earlier
10524 // if this is an alpha blended material, all the earlier passes
10525 // were darkened by fog already, so we only need to add the fog
10526 // color ontop through the fog mask texture
10528 // if this is an additive blended material, all the earlier passes
10529 // were darkened by fog already, and we should not add fog color
10530 // (because the background was not darkened, there is no fog color
10531 // that was lost behind it).
10532 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]);
10536 return t->currentframe;
10539 rsurfacestate_t rsurface;
10541 void R_Mesh_ResizeArrays(int newvertices)
10543 unsigned char *base;
10545 if (rsurface.array_size >= newvertices)
10547 if (rsurface.array_base)
10548 Mem_Free(rsurface.array_base);
10549 rsurface.array_size = (newvertices + 1023) & ~1023;
10551 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10552 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10553 size += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10554 size += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10555 size += rsurface.array_size * sizeof(float[3]);
10556 size += rsurface.array_size * sizeof(float[3]);
10557 size += rsurface.array_size * sizeof(float[3]);
10558 size += rsurface.array_size * sizeof(float[3]);
10559 size += rsurface.array_size * sizeof(float[3]);
10560 size += rsurface.array_size * sizeof(float[3]);
10561 size += rsurface.array_size * sizeof(float[3]);
10562 size += rsurface.array_size * sizeof(float[3]);
10563 size += rsurface.array_size * sizeof(float[4]);
10564 size += rsurface.array_size * sizeof(float[2]);
10565 size += rsurface.array_size * sizeof(float[2]);
10566 size += rsurface.array_size * sizeof(float[4]);
10567 size += rsurface.array_size * sizeof(int[3]);
10568 size += rsurface.array_size * sizeof(unsigned short[3]);
10569 rsurface.array_base = base = (unsigned char *)Mem_Alloc(r_main_mempool, size);
10570 rsurface.array_modelvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexmesh);
10571 rsurface.array_batchvertexmesh = (r_vertexmesh_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexmesh);
10572 rsurface.array_modelvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_modelvertexposition);
10573 rsurface.array_batchvertexposition = (r_vertexposition_t *)base;base += rsurface.array_size * sizeof(*rsurface.array_batchvertexposition);
10574 rsurface.array_modelvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10575 rsurface.array_modelsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10576 rsurface.array_modeltvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10577 rsurface.array_modelnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10578 rsurface.array_batchvertex3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10579 rsurface.array_batchsvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10580 rsurface.array_batchtvector3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10581 rsurface.array_batchnormal3f = (float *)base;base += rsurface.array_size * sizeof(float[3]);
10582 rsurface.array_batchlightmapcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
10583 rsurface.array_batchtexcoordtexture2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
10584 rsurface.array_batchtexcoordlightmap2f = (float *)base;base += rsurface.array_size * sizeof(float[2]);
10585 rsurface.array_passcolor4f = (float *)base;base += rsurface.array_size * sizeof(float[4]);
10586 rsurface.array_batchelement3i = (int *)base;base += rsurface.array_size * sizeof(int[3]);
10587 rsurface.array_batchelement3s = (unsigned short *)base;base += rsurface.array_size * sizeof(unsigned short[3]);
10590 void RSurf_ActiveWorldEntity(void)
10592 dp_model_t *model = r_refdef.scene.worldmodel;
10593 //if (rsurface.entity == r_refdef.scene.worldentity)
10595 rsurface.entity = r_refdef.scene.worldentity;
10596 rsurface.skeleton = NULL;
10597 memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
10598 rsurface.ent_skinnum = 0;
10599 rsurface.ent_qwskin = -1;
10600 rsurface.ent_shadertime = 0;
10601 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
10602 if (rsurface.array_size < model->surfmesh.num_vertices)
10603 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10604 rsurface.matrix = identitymatrix;
10605 rsurface.inversematrix = identitymatrix;
10606 rsurface.matrixscale = 1;
10607 rsurface.inversematrixscale = 1;
10608 R_EntityMatrix(&identitymatrix);
10609 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
10610 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
10611 rsurface.fograngerecip = r_refdef.fograngerecip;
10612 rsurface.fogheightfade = r_refdef.fogheightfade;
10613 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
10614 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10615 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10616 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10617 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10618 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10619 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10620 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
10621 rsurface.colormod[3] = 1;
10622 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);
10623 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10624 rsurface.frameblend[0].lerp = 1;
10625 rsurface.ent_alttextures = false;
10626 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10627 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10628 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10629 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10630 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10631 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10632 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10633 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10634 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10635 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10636 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10637 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10638 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10639 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10640 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10641 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10642 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10643 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10644 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10645 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10646 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10647 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10648 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10649 rsurface.modelelement3i = model->surfmesh.data_element3i;
10650 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10651 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10652 rsurface.modelelement3s = model->surfmesh.data_element3s;
10653 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10654 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10655 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10656 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10657 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10658 rsurface.modelsurfaces = model->data_surfaces;
10659 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10660 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10661 rsurface.modelvertexposition = model->surfmesh.vertexposition;
10662 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10663 rsurface.modelgeneratedvertex = false;
10664 rsurface.batchgeneratedvertex = false;
10665 rsurface.batchfirstvertex = 0;
10666 rsurface.batchnumvertices = 0;
10667 rsurface.batchfirsttriangle = 0;
10668 rsurface.batchnumtriangles = 0;
10669 rsurface.batchvertex3f = NULL;
10670 rsurface.batchvertex3f_vertexbuffer = NULL;
10671 rsurface.batchvertex3f_bufferoffset = 0;
10672 rsurface.batchsvector3f = NULL;
10673 rsurface.batchsvector3f_vertexbuffer = NULL;
10674 rsurface.batchsvector3f_bufferoffset = 0;
10675 rsurface.batchtvector3f = NULL;
10676 rsurface.batchtvector3f_vertexbuffer = NULL;
10677 rsurface.batchtvector3f_bufferoffset = 0;
10678 rsurface.batchnormal3f = NULL;
10679 rsurface.batchnormal3f_vertexbuffer = NULL;
10680 rsurface.batchnormal3f_bufferoffset = 0;
10681 rsurface.batchlightmapcolor4f = NULL;
10682 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10683 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10684 rsurface.batchtexcoordtexture2f = NULL;
10685 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10686 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10687 rsurface.batchtexcoordlightmap2f = NULL;
10688 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10689 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10690 rsurface.batchvertexmesh = NULL;
10691 rsurface.batchvertexmeshbuffer = NULL;
10692 rsurface.batchvertexposition = NULL;
10693 rsurface.batchvertexpositionbuffer = NULL;
10694 rsurface.batchelement3i = NULL;
10695 rsurface.batchelement3i_indexbuffer = NULL;
10696 rsurface.batchelement3i_bufferoffset = 0;
10697 rsurface.batchelement3s = NULL;
10698 rsurface.batchelement3s_indexbuffer = NULL;
10699 rsurface.batchelement3s_bufferoffset = 0;
10700 rsurface.passcolor4f = NULL;
10701 rsurface.passcolor4f_vertexbuffer = NULL;
10702 rsurface.passcolor4f_bufferoffset = 0;
10705 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
10707 dp_model_t *model = ent->model;
10708 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
10710 rsurface.entity = (entity_render_t *)ent;
10711 rsurface.skeleton = ent->skeleton;
10712 memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
10713 rsurface.ent_skinnum = ent->skinnum;
10714 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;
10715 rsurface.ent_shadertime = ent->shadertime;
10716 rsurface.ent_flags = ent->flags;
10717 if (rsurface.array_size < model->surfmesh.num_vertices)
10718 R_Mesh_ResizeArrays(model->surfmesh.num_vertices);
10719 rsurface.matrix = ent->matrix;
10720 rsurface.inversematrix = ent->inversematrix;
10721 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10722 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10723 R_EntityMatrix(&rsurface.matrix);
10724 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10725 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10726 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10727 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10728 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10729 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10730 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10731 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10732 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10733 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10734 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10735 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10736 rsurface.colormod[3] = ent->alpha;
10737 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10738 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10739 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10740 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10741 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10742 if (ent->model->brush.submodel && !prepass)
10744 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10745 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10747 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10749 if (ent->animcache_vertex3f && !r_framedata_failed)
10751 rsurface.modelvertex3f = ent->animcache_vertex3f;
10752 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10753 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10754 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10755 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
10756 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
10757 rsurface.modelvertexposition = ent->animcache_vertexposition;
10758 rsurface.modelvertexpositionbuffer = ent->animcache_vertexpositionbuffer;
10760 else if (wanttangents)
10762 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10763 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
10764 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
10765 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10766 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, rsurface.array_modelsvector3f, rsurface.array_modeltvector3f);
10767 rsurface.modelvertexmesh = NULL;
10768 rsurface.modelvertexmeshbuffer = NULL;
10769 rsurface.modelvertexposition = NULL;
10770 rsurface.modelvertexpositionbuffer = NULL;
10772 else if (wantnormals)
10774 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10775 rsurface.modelsvector3f = NULL;
10776 rsurface.modeltvector3f = NULL;
10777 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
10778 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, rsurface.array_modelnormal3f, NULL, NULL);
10779 rsurface.modelvertexmesh = NULL;
10780 rsurface.modelvertexmeshbuffer = NULL;
10781 rsurface.modelvertexposition = NULL;
10782 rsurface.modelvertexpositionbuffer = NULL;
10786 rsurface.modelvertex3f = rsurface.array_modelvertex3f;
10787 rsurface.modelsvector3f = NULL;
10788 rsurface.modeltvector3f = NULL;
10789 rsurface.modelnormal3f = NULL;
10790 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.array_modelvertex3f, NULL, NULL, NULL);
10791 rsurface.modelvertexmesh = NULL;
10792 rsurface.modelvertexmeshbuffer = NULL;
10793 rsurface.modelvertexposition = NULL;
10794 rsurface.modelvertexpositionbuffer = NULL;
10796 rsurface.modelvertex3f_vertexbuffer = 0;
10797 rsurface.modelvertex3f_bufferoffset = 0;
10798 rsurface.modelsvector3f_vertexbuffer = 0;
10799 rsurface.modelsvector3f_bufferoffset = 0;
10800 rsurface.modeltvector3f_vertexbuffer = 0;
10801 rsurface.modeltvector3f_bufferoffset = 0;
10802 rsurface.modelnormal3f_vertexbuffer = 0;
10803 rsurface.modelnormal3f_bufferoffset = 0;
10804 rsurface.modelgeneratedvertex = true;
10808 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10809 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10810 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10811 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10812 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10813 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10814 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10815 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10816 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10817 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10818 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10819 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10820 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10821 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10822 rsurface.modelvertexposition = model->surfmesh.vertexposition;
10823 rsurface.modelvertexpositionbuffer = model->surfmesh.vertexpositionbuffer;
10824 rsurface.modelgeneratedvertex = false;
10826 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10827 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10828 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10829 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10830 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10831 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10832 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10833 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10834 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10835 rsurface.modelelement3i = model->surfmesh.data_element3i;
10836 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10837 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10838 rsurface.modelelement3s = model->surfmesh.data_element3s;
10839 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10840 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10841 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10842 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10843 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10844 rsurface.modelsurfaces = model->data_surfaces;
10845 rsurface.batchgeneratedvertex = false;
10846 rsurface.batchfirstvertex = 0;
10847 rsurface.batchnumvertices = 0;
10848 rsurface.batchfirsttriangle = 0;
10849 rsurface.batchnumtriangles = 0;
10850 rsurface.batchvertex3f = NULL;
10851 rsurface.batchvertex3f_vertexbuffer = NULL;
10852 rsurface.batchvertex3f_bufferoffset = 0;
10853 rsurface.batchsvector3f = NULL;
10854 rsurface.batchsvector3f_vertexbuffer = NULL;
10855 rsurface.batchsvector3f_bufferoffset = 0;
10856 rsurface.batchtvector3f = NULL;
10857 rsurface.batchtvector3f_vertexbuffer = NULL;
10858 rsurface.batchtvector3f_bufferoffset = 0;
10859 rsurface.batchnormal3f = NULL;
10860 rsurface.batchnormal3f_vertexbuffer = NULL;
10861 rsurface.batchnormal3f_bufferoffset = 0;
10862 rsurface.batchlightmapcolor4f = NULL;
10863 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10864 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10865 rsurface.batchtexcoordtexture2f = NULL;
10866 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10867 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10868 rsurface.batchtexcoordlightmap2f = NULL;
10869 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10870 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10871 rsurface.batchvertexmesh = NULL;
10872 rsurface.batchvertexmeshbuffer = NULL;
10873 rsurface.batchvertexposition = NULL;
10874 rsurface.batchvertexpositionbuffer = NULL;
10875 rsurface.batchelement3i = NULL;
10876 rsurface.batchelement3i_indexbuffer = NULL;
10877 rsurface.batchelement3i_bufferoffset = 0;
10878 rsurface.batchelement3s = NULL;
10879 rsurface.batchelement3s_indexbuffer = NULL;
10880 rsurface.batchelement3s_bufferoffset = 0;
10881 rsurface.passcolor4f = NULL;
10882 rsurface.passcolor4f_vertexbuffer = NULL;
10883 rsurface.passcolor4f_bufferoffset = 0;
10886 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)
10890 rsurface.entity = r_refdef.scene.worldentity;
10891 rsurface.skeleton = NULL;
10892 rsurface.ent_skinnum = 0;
10893 rsurface.ent_qwskin = -1;
10894 rsurface.ent_shadertime = shadertime;
10895 rsurface.ent_flags = entflags;
10896 rsurface.modelnumvertices = numvertices;
10897 rsurface.modelnumtriangles = numtriangles;
10898 if (rsurface.array_size < rsurface.modelnumvertices)
10899 R_Mesh_ResizeArrays(rsurface.modelnumvertices);
10900 rsurface.matrix = *matrix;
10901 rsurface.inversematrix = *inversematrix;
10902 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10903 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10904 R_EntityMatrix(&rsurface.matrix);
10905 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10906 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10907 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10908 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10909 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10910 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10911 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10912 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10913 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10914 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10915 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10916 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10917 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);
10918 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10919 rsurface.frameblend[0].lerp = 1;
10920 rsurface.ent_alttextures = false;
10921 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10922 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10925 rsurface.modelvertex3f = vertex3f;
10926 rsurface.modelsvector3f = svector3f ? svector3f : rsurface.array_modelsvector3f;
10927 rsurface.modeltvector3f = tvector3f ? tvector3f : rsurface.array_modeltvector3f;
10928 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10930 else if (wantnormals)
10932 rsurface.modelvertex3f = vertex3f;
10933 rsurface.modelsvector3f = NULL;
10934 rsurface.modeltvector3f = NULL;
10935 rsurface.modelnormal3f = normal3f ? normal3f : rsurface.array_modelnormal3f;
10939 rsurface.modelvertex3f = vertex3f;
10940 rsurface.modelsvector3f = NULL;
10941 rsurface.modeltvector3f = NULL;
10942 rsurface.modelnormal3f = NULL;
10944 rsurface.modelvertexmesh = NULL;
10945 rsurface.modelvertexmeshbuffer = NULL;
10946 rsurface.modelvertexposition = NULL;
10947 rsurface.modelvertexpositionbuffer = NULL;
10948 rsurface.modelvertex3f_vertexbuffer = 0;
10949 rsurface.modelvertex3f_bufferoffset = 0;
10950 rsurface.modelsvector3f_vertexbuffer = 0;
10951 rsurface.modelsvector3f_bufferoffset = 0;
10952 rsurface.modeltvector3f_vertexbuffer = 0;
10953 rsurface.modeltvector3f_bufferoffset = 0;
10954 rsurface.modelnormal3f_vertexbuffer = 0;
10955 rsurface.modelnormal3f_bufferoffset = 0;
10956 rsurface.modelgeneratedvertex = true;
10957 rsurface.modellightmapcolor4f = color4f;
10958 rsurface.modellightmapcolor4f_vertexbuffer = 0;
10959 rsurface.modellightmapcolor4f_bufferoffset = 0;
10960 rsurface.modeltexcoordtexture2f = texcoord2f;
10961 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10962 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10963 rsurface.modeltexcoordlightmap2f = NULL;
10964 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10965 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10966 rsurface.modelelement3i = element3i;
10967 rsurface.modelelement3i_indexbuffer = NULL;
10968 rsurface.modelelement3i_bufferoffset = 0;
10969 rsurface.modelelement3s = element3s;
10970 rsurface.modelelement3s_indexbuffer = NULL;
10971 rsurface.modelelement3s_bufferoffset = 0;
10972 rsurface.modellightmapoffsets = NULL;
10973 rsurface.modelsurfaces = NULL;
10974 rsurface.batchgeneratedvertex = false;
10975 rsurface.batchfirstvertex = 0;
10976 rsurface.batchnumvertices = 0;
10977 rsurface.batchfirsttriangle = 0;
10978 rsurface.batchnumtriangles = 0;
10979 rsurface.batchvertex3f = NULL;
10980 rsurface.batchvertex3f_vertexbuffer = NULL;
10981 rsurface.batchvertex3f_bufferoffset = 0;
10982 rsurface.batchsvector3f = NULL;
10983 rsurface.batchsvector3f_vertexbuffer = NULL;
10984 rsurface.batchsvector3f_bufferoffset = 0;
10985 rsurface.batchtvector3f = NULL;
10986 rsurface.batchtvector3f_vertexbuffer = NULL;
10987 rsurface.batchtvector3f_bufferoffset = 0;
10988 rsurface.batchnormal3f = NULL;
10989 rsurface.batchnormal3f_vertexbuffer = NULL;
10990 rsurface.batchnormal3f_bufferoffset = 0;
10991 rsurface.batchlightmapcolor4f = NULL;
10992 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10993 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10994 rsurface.batchtexcoordtexture2f = NULL;
10995 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10996 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10997 rsurface.batchtexcoordlightmap2f = NULL;
10998 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10999 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11000 rsurface.batchvertexmesh = NULL;
11001 rsurface.batchvertexmeshbuffer = NULL;
11002 rsurface.batchvertexposition = NULL;
11003 rsurface.batchvertexpositionbuffer = NULL;
11004 rsurface.batchelement3i = NULL;
11005 rsurface.batchelement3i_indexbuffer = NULL;
11006 rsurface.batchelement3i_bufferoffset = 0;
11007 rsurface.batchelement3s = NULL;
11008 rsurface.batchelement3s_indexbuffer = NULL;
11009 rsurface.batchelement3s_bufferoffset = 0;
11010 rsurface.passcolor4f = NULL;
11011 rsurface.passcolor4f_vertexbuffer = NULL;
11012 rsurface.passcolor4f_bufferoffset = 0;
11014 if (rsurface.modelnumvertices && rsurface.modelelement3i)
11016 if ((wantnormals || wanttangents) && !normal3f)
11018 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.array_modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
11019 rsurface.modelnormal3f = rsurface.array_modelnormal3f;
11021 if (wanttangents && !svector3f)
11023 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);
11024 rsurface.modelsvector3f = rsurface.array_modelsvector3f;
11025 rsurface.modeltvector3f = rsurface.array_modeltvector3f;
11029 // now convert arrays into vertexmesh structs
11030 for (i = 0;i < numvertices;i++)
11032 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexposition[i].vertex3f);
11033 VectorCopy(rsurface.modelvertex3f + 3*i, rsurface.array_modelvertexmesh[i].vertex3f);
11034 if (rsurface.modelsvector3f)
11035 VectorCopy(rsurface.modelsvector3f + 3*i, rsurface.array_modelvertexmesh[i].svector3f);
11036 if (rsurface.modeltvector3f)
11037 VectorCopy(rsurface.modeltvector3f + 3*i, rsurface.array_modelvertexmesh[i].tvector3f);
11038 if (rsurface.modelnormal3f)
11039 VectorCopy(rsurface.modelnormal3f + 3*i, rsurface.array_modelvertexmesh[i].normal3f);
11040 if (rsurface.modellightmapcolor4f)
11041 Vector4Scale(rsurface.modellightmapcolor4f + 4*i, 255.0f, rsurface.array_modelvertexmesh[i].color4ub);
11042 if (rsurface.modeltexcoordtexture2f)
11043 Vector2Copy(rsurface.modeltexcoordtexture2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordtexture2f);
11044 if (rsurface.modeltexcoordlightmap2f)
11045 Vector2Copy(rsurface.modeltexcoordlightmap2f + 2*i, rsurface.array_modelvertexmesh[i].texcoordlightmap2f);
11049 float RSurf_FogPoint(const float *v)
11051 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
11052 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
11053 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
11054 float FogHeightFade = r_refdef.fogheightfade;
11056 unsigned int fogmasktableindex;
11057 if (r_refdef.fogplaneviewabove)
11058 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
11060 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
11061 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
11062 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
11065 float RSurf_FogVertex(const float *v)
11067 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
11068 float FogPlaneViewDist = rsurface.fogplaneviewdist;
11069 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
11070 float FogHeightFade = rsurface.fogheightfade;
11072 unsigned int fogmasktableindex;
11073 if (r_refdef.fogplaneviewabove)
11074 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
11076 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
11077 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
11078 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
11081 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
11084 for (i = 0;i < numelements;i++)
11085 outelement3i[i] = inelement3i[i] + adjust;
11088 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
11089 extern cvar_t gl_vbo;
11090 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
11098 int surfacefirsttriangle;
11099 int surfacenumtriangles;
11100 int surfacefirstvertex;
11101 int surfaceendvertex;
11102 int surfacenumvertices;
11103 int surfaceadjustvertex;
11107 qboolean dynamicvertex;
11111 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
11112 float waveparms[4];
11113 q3shaderinfo_deform_t *deform;
11114 const msurface_t *surface, *firstsurface;
11115 r_vertexposition_t *vertexposition;
11116 r_vertexmesh_t *vertexmesh;
11117 if (!texturenumsurfaces)
11119 // find vertex range of this surface batch
11121 firstsurface = texturesurfacelist[0];
11122 firsttriangle = firstsurface->num_firsttriangle;
11124 firstvertex = endvertex = firstsurface->num_firstvertex;
11125 for (i = 0;i < texturenumsurfaces;i++)
11127 surface = texturesurfacelist[i];
11128 if (surface != firstsurface + i)
11130 surfacefirstvertex = surface->num_firstvertex;
11131 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
11132 surfacenumtriangles = surface->num_triangles;
11133 if (firstvertex > surfacefirstvertex)
11134 firstvertex = surfacefirstvertex;
11135 if (endvertex < surfaceendvertex)
11136 endvertex = surfaceendvertex;
11137 numtriangles += surfacenumtriangles;
11142 // we now know the vertex range used, and if there are any gaps in it
11143 rsurface.batchfirstvertex = firstvertex;
11144 rsurface.batchnumvertices = endvertex - firstvertex;
11145 rsurface.batchfirsttriangle = firsttriangle;
11146 rsurface.batchnumtriangles = numtriangles;
11148 // this variable holds flags for which properties have been updated that
11149 // may require regenerating vertexmesh or vertexposition arrays...
11152 // check if any dynamic vertex processing must occur
11153 dynamicvertex = false;
11155 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11156 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_NOGAPS;
11157 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11159 switch (deform->deform)
11162 case Q3DEFORM_PROJECTIONSHADOW:
11163 case Q3DEFORM_TEXT0:
11164 case Q3DEFORM_TEXT1:
11165 case Q3DEFORM_TEXT2:
11166 case Q3DEFORM_TEXT3:
11167 case Q3DEFORM_TEXT4:
11168 case Q3DEFORM_TEXT5:
11169 case Q3DEFORM_TEXT6:
11170 case Q3DEFORM_TEXT7:
11171 case Q3DEFORM_NONE:
11173 case Q3DEFORM_AUTOSPRITE:
11174 dynamicvertex = true;
11175 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11176 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11178 case Q3DEFORM_AUTOSPRITE2:
11179 dynamicvertex = true;
11180 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11181 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11183 case Q3DEFORM_NORMAL:
11184 dynamicvertex = true;
11185 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11186 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11188 case Q3DEFORM_WAVE:
11189 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11190 break; // if wavefunc is a nop, ignore this transform
11191 dynamicvertex = true;
11192 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11193 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11195 case Q3DEFORM_BULGE:
11196 dynamicvertex = true;
11197 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11198 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11200 case Q3DEFORM_MOVE:
11201 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11202 break; // if wavefunc is a nop, ignore this transform
11203 dynamicvertex = true;
11204 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11205 needsupdate |= BATCHNEED_VERTEXPOSITION | BATCHNEED_VERTEXMESH_VERTEX;
11209 switch(rsurface.texture->tcgen.tcgen)
11212 case Q3TCGEN_TEXTURE:
11214 case Q3TCGEN_LIGHTMAP:
11215 dynamicvertex = true;
11216 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
11217 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
11219 case Q3TCGEN_VECTOR:
11220 dynamicvertex = true;
11221 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11222 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11224 case Q3TCGEN_ENVIRONMENT:
11225 dynamicvertex = true;
11226 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
11227 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11230 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11232 dynamicvertex = true;
11233 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11234 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11237 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11239 dynamicvertex = true;
11240 batchneed |= BATCHNEED_NOGAPS;
11241 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
11244 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11246 dynamicvertex = true;
11247 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11248 needsupdate |= (batchneed & BATCHNEED_VERTEXPOSITION);
11251 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
11253 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
11254 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
11255 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
11256 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
11257 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
11258 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
11259 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
11262 // when the model data has no vertex buffer (dynamic mesh), we need to
11264 if (!rsurface.modelvertexmeshbuffer || (!gl_vbo.integer && !vid.forcevbo))
11265 batchneed |= BATCHNEED_NOGAPS;
11267 // if needsupdate, we have to do a dynamic vertex batch for sure
11268 if (needsupdate & batchneed)
11269 dynamicvertex = true;
11271 // see if we need to build vertexmesh from arrays
11272 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11273 dynamicvertex = true;
11275 // see if we need to build vertexposition from arrays
11276 if (!rsurface.modelvertexposition && (batchneed & BATCHNEED_VERTEXPOSITION))
11277 dynamicvertex = true;
11279 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
11280 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
11281 dynamicvertex = true;
11283 // if there is a chance of animated vertex colors, it's a dynamic batch
11284 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11285 dynamicvertex = true;
11287 rsurface.batchvertex3f = rsurface.modelvertex3f;
11288 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
11289 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
11290 rsurface.batchsvector3f = rsurface.modelsvector3f;
11291 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
11292 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
11293 rsurface.batchtvector3f = rsurface.modeltvector3f;
11294 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
11295 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
11296 rsurface.batchnormal3f = rsurface.modelnormal3f;
11297 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
11298 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
11299 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
11300 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
11301 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11302 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
11303 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
11304 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
11305 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
11306 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
11307 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
11308 rsurface.batchvertexposition = rsurface.modelvertexposition;
11309 rsurface.batchvertexpositionbuffer = rsurface.modelvertexpositionbuffer;
11310 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
11311 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
11312 rsurface.batchelement3i = rsurface.modelelement3i;
11313 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
11314 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
11315 rsurface.batchelement3s = rsurface.modelelement3s;
11316 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
11317 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
11319 // if any dynamic vertex processing has to occur in software, we copy the
11320 // entire surface list together before processing to rebase the vertices
11321 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
11323 // if any gaps exist and we do not have a static vertex buffer, we have to
11324 // copy the surface list together to avoid wasting upload bandwidth on the
11325 // vertices in the gaps.
11327 // if gaps exist and we have a static vertex buffer, we still have to
11328 // combine the index buffer ranges into one dynamic index buffer.
11330 // in all cases we end up with data that can be drawn in one call.
11332 if (!dynamicvertex)
11334 // static vertex data, just set pointers...
11335 rsurface.batchgeneratedvertex = false;
11336 // if there are gaps, we want to build a combined index buffer,
11337 // otherwise use the original static buffer with an appropriate offset
11342 for (i = 0;i < texturenumsurfaces;i++)
11344 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11345 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11346 memcpy(rsurface.array_batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
11347 numtriangles += surfacenumtriangles;
11349 rsurface.batchelement3i = rsurface.array_batchelement3i;
11350 rsurface.batchelement3i_indexbuffer = NULL;
11351 rsurface.batchelement3i_bufferoffset = 0;
11352 rsurface.batchelement3s = NULL;
11353 rsurface.batchelement3s_indexbuffer = NULL;
11354 rsurface.batchelement3s_bufferoffset = 0;
11355 if (endvertex <= 65536)
11357 rsurface.batchelement3s = rsurface.array_batchelement3s;
11358 for (i = 0;i < numtriangles*3;i++)
11359 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11361 rsurface.batchfirsttriangle = firsttriangle;
11362 rsurface.batchnumtriangles = numtriangles;
11367 // something needs software processing, do it for real...
11368 // we only directly handle interleaved array data in this case...
11369 rsurface.batchgeneratedvertex = true;
11371 // now copy the vertex data into a combined array and make an index array
11372 // (this is what Quake3 does all the time)
11373 //if (gaps || rsurface.batchfirstvertex)
11375 rsurface.batchvertexposition = NULL;
11376 rsurface.batchvertexpositionbuffer = NULL;
11377 rsurface.batchvertexmesh = NULL;
11378 rsurface.batchvertexmeshbuffer = NULL;
11379 rsurface.batchvertex3f = NULL;
11380 rsurface.batchvertex3f_vertexbuffer = NULL;
11381 rsurface.batchvertex3f_bufferoffset = 0;
11382 rsurface.batchsvector3f = NULL;
11383 rsurface.batchsvector3f_vertexbuffer = NULL;
11384 rsurface.batchsvector3f_bufferoffset = 0;
11385 rsurface.batchtvector3f = NULL;
11386 rsurface.batchtvector3f_vertexbuffer = NULL;
11387 rsurface.batchtvector3f_bufferoffset = 0;
11388 rsurface.batchnormal3f = NULL;
11389 rsurface.batchnormal3f_vertexbuffer = NULL;
11390 rsurface.batchnormal3f_bufferoffset = 0;
11391 rsurface.batchlightmapcolor4f = NULL;
11392 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11393 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11394 rsurface.batchtexcoordtexture2f = NULL;
11395 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11396 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11397 rsurface.batchtexcoordlightmap2f = NULL;
11398 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11399 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11400 rsurface.batchelement3i = rsurface.array_batchelement3i;
11401 rsurface.batchelement3i_indexbuffer = NULL;
11402 rsurface.batchelement3i_bufferoffset = 0;
11403 rsurface.batchelement3s = NULL;
11404 rsurface.batchelement3s_indexbuffer = NULL;
11405 rsurface.batchelement3s_bufferoffset = 0;
11406 // we'll only be setting up certain arrays as needed
11407 if (batchneed & BATCHNEED_VERTEXPOSITION)
11408 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11409 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11410 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11411 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11412 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11413 if (batchneed & BATCHNEED_ARRAY_NORMAL)
11414 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11415 if (batchneed & BATCHNEED_ARRAY_VECTOR)
11417 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11418 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11420 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
11421 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11422 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
11423 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11424 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
11425 rsurface.batchtexcoordlightmap2f = rsurface.array_batchtexcoordlightmap2f;
11428 for (i = 0;i < texturenumsurfaces;i++)
11430 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
11431 surfacenumvertices = texturesurfacelist[i]->num_vertices;
11432 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11433 surfaceadjustvertex = numvertices - surfacefirstvertex;
11434 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11435 // copy only the data requested
11436 if ((batchneed & BATCHNEED_VERTEXPOSITION) && rsurface.modelvertexposition)
11437 memcpy(rsurface.array_batchvertexposition + numvertices, rsurface.modelvertexposition + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexposition[0]));
11438 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
11439 memcpy(rsurface.array_batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
11440 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
11442 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11443 memcpy(rsurface.array_batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11444 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
11445 memcpy(rsurface.array_batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11446 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
11448 memcpy(rsurface.array_batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11449 memcpy(rsurface.array_batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11451 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
11452 memcpy(rsurface.array_batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
11453 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
11454 memcpy(rsurface.array_batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11455 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
11456 memcpy(rsurface.array_batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11458 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.array_batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
11459 numvertices += surfacenumvertices;
11460 numtriangles += surfacenumtriangles;
11463 // generate a 16bit index array as well if possible
11464 // (in general, dynamic batches fit)
11465 if (numvertices <= 65536)
11467 rsurface.batchelement3s = rsurface.array_batchelement3s;
11468 for (i = 0;i < numtriangles*3;i++)
11469 rsurface.array_batchelement3s[i] = rsurface.array_batchelement3i[i];
11472 // since we've copied everything, the batch now starts at 0
11473 rsurface.batchfirstvertex = 0;
11474 rsurface.batchnumvertices = numvertices;
11475 rsurface.batchfirsttriangle = 0;
11476 rsurface.batchnumtriangles = numtriangles;
11479 // q1bsp surfaces rendered in vertex color mode have to have colors
11480 // calculated based on lightstyles
11481 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11483 // generate color arrays for the surfaces in this list
11487 const int *offsets;
11488 const unsigned char *lm;
11490 rsurface.batchlightmapcolor4f = rsurface.array_batchlightmapcolor4f;
11491 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11492 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11493 for (i = 0;i < texturenumsurfaces;i++)
11495 surface = texturesurfacelist[i];
11496 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
11497 surfacenumvertices = surface->num_vertices;
11498 if (surface->lightmapinfo->samples)
11500 for (j = 0;j < surfacenumvertices;j++)
11502 lm = surface->lightmapinfo->samples + offsets[j];
11503 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
11504 VectorScale(lm, scale, c);
11505 if (surface->lightmapinfo->styles[1] != 255)
11507 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11509 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
11510 VectorMA(c, scale, lm, c);
11511 if (surface->lightmapinfo->styles[2] != 255)
11514 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
11515 VectorMA(c, scale, lm, c);
11516 if (surface->lightmapinfo->styles[3] != 255)
11519 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
11520 VectorMA(c, scale, lm, c);
11527 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);
11533 for (j = 0;j < surfacenumvertices;j++)
11535 Vector4Set(rsurface.array_batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
11542 // if vertices are deformed (sprite flares and things in maps, possibly
11543 // water waves, bulges and other deformations), modify the copied vertices
11545 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11547 switch (deform->deform)
11550 case Q3DEFORM_PROJECTIONSHADOW:
11551 case Q3DEFORM_TEXT0:
11552 case Q3DEFORM_TEXT1:
11553 case Q3DEFORM_TEXT2:
11554 case Q3DEFORM_TEXT3:
11555 case Q3DEFORM_TEXT4:
11556 case Q3DEFORM_TEXT5:
11557 case Q3DEFORM_TEXT6:
11558 case Q3DEFORM_TEXT7:
11559 case Q3DEFORM_NONE:
11561 case Q3DEFORM_AUTOSPRITE:
11562 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11563 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11564 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11565 VectorNormalize(newforward);
11566 VectorNormalize(newright);
11567 VectorNormalize(newup);
11568 // a single autosprite surface can contain multiple sprites...
11569 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11571 VectorClear(center);
11572 for (i = 0;i < 4;i++)
11573 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11574 VectorScale(center, 0.25f, center);
11575 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
11576 VectorCopy(rsurface.batchsvector3f + 3*j, right);
11577 VectorCopy(rsurface.batchtvector3f + 3*j, up);
11578 for (i = 0;i < 4;i++)
11580 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
11581 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.array_batchvertex3f + 3*(j+i));
11584 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11585 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);
11586 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11587 rsurface.batchvertex3f_vertexbuffer = NULL;
11588 rsurface.batchvertex3f_bufferoffset = 0;
11589 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11590 rsurface.batchsvector3f_vertexbuffer = NULL;
11591 rsurface.batchsvector3f_bufferoffset = 0;
11592 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11593 rsurface.batchtvector3f_vertexbuffer = NULL;
11594 rsurface.batchtvector3f_bufferoffset = 0;
11595 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11596 rsurface.batchnormal3f_vertexbuffer = NULL;
11597 rsurface.batchnormal3f_bufferoffset = 0;
11599 case Q3DEFORM_AUTOSPRITE2:
11600 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11601 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11602 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11603 VectorNormalize(newforward);
11604 VectorNormalize(newright);
11605 VectorNormalize(newup);
11607 const float *v1, *v2;
11617 memset(shortest, 0, sizeof(shortest));
11618 // a single autosprite surface can contain multiple sprites...
11619 for (j = 0;j < rsurface.batchnumvertices - 3;j += 4)
11621 VectorClear(center);
11622 for (i = 0;i < 4;i++)
11623 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11624 VectorScale(center, 0.25f, center);
11625 // find the two shortest edges, then use them to define the
11626 // axis vectors for rotating around the central axis
11627 for (i = 0;i < 6;i++)
11629 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
11630 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
11631 l = VectorDistance2(v1, v2);
11632 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
11633 if (v1[2] != v2[2])
11634 l += (1.0f / 1024.0f);
11635 if (shortest[0].length2 > l || i == 0)
11637 shortest[1] = shortest[0];
11638 shortest[0].length2 = l;
11639 shortest[0].v1 = v1;
11640 shortest[0].v2 = v2;
11642 else if (shortest[1].length2 > l || i == 1)
11644 shortest[1].length2 = l;
11645 shortest[1].v1 = v1;
11646 shortest[1].v2 = v2;
11649 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
11650 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
11651 // this calculates the right vector from the shortest edge
11652 // and the up vector from the edge midpoints
11653 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
11654 VectorNormalize(right);
11655 VectorSubtract(end, start, up);
11656 VectorNormalize(up);
11657 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
11658 VectorSubtract(rsurface.localvieworigin, center, forward);
11659 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
11660 VectorNegate(forward, forward);
11661 VectorReflect(forward, 0, up, forward);
11662 VectorNormalize(forward);
11663 CrossProduct(up, forward, newright);
11664 VectorNormalize(newright);
11665 // rotate the quad around the up axis vector, this is made
11666 // especially easy by the fact we know the quad is flat,
11667 // so we only have to subtract the center position and
11668 // measure distance along the right vector, and then
11669 // multiply that by the newright vector and add back the
11671 // we also need to subtract the old position to undo the
11672 // displacement from the center, which we do with a
11673 // DotProduct, the subtraction/addition of center is also
11674 // optimized into DotProducts here
11675 l = DotProduct(right, center);
11676 for (i = 0;i < 4;i++)
11678 v1 = rsurface.batchvertex3f + 3*(j+i);
11679 f = DotProduct(right, v1) - l;
11680 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.array_batchvertex3f + 3*(j+i));
11684 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11685 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);
11686 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11687 rsurface.batchvertex3f_vertexbuffer = NULL;
11688 rsurface.batchvertex3f_bufferoffset = 0;
11689 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11690 rsurface.batchsvector3f_vertexbuffer = NULL;
11691 rsurface.batchsvector3f_bufferoffset = 0;
11692 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11693 rsurface.batchtvector3f_vertexbuffer = NULL;
11694 rsurface.batchtvector3f_bufferoffset = 0;
11695 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11696 rsurface.batchnormal3f_vertexbuffer = NULL;
11697 rsurface.batchnormal3f_bufferoffset = 0;
11699 case Q3DEFORM_NORMAL:
11700 // deform the normals to make reflections wavey
11701 for (j = 0;j < rsurface.batchnumvertices;j++)
11704 float *normal = rsurface.array_batchnormal3f + 3*j;
11705 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
11706 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11707 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]);
11708 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]);
11709 VectorNormalize(normal);
11711 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);
11712 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11713 rsurface.batchsvector3f_vertexbuffer = NULL;
11714 rsurface.batchsvector3f_bufferoffset = 0;
11715 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11716 rsurface.batchtvector3f_vertexbuffer = NULL;
11717 rsurface.batchtvector3f_bufferoffset = 0;
11718 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11719 rsurface.batchnormal3f_vertexbuffer = NULL;
11720 rsurface.batchnormal3f_bufferoffset = 0;
11722 case Q3DEFORM_WAVE:
11723 // deform vertex array to make wavey water and flags and such
11724 waveparms[0] = deform->waveparms[0];
11725 waveparms[1] = deform->waveparms[1];
11726 waveparms[2] = deform->waveparms[2];
11727 waveparms[3] = deform->waveparms[3];
11728 if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
11729 break; // if wavefunc is a nop, don't make a dynamic vertex array
11730 // this is how a divisor of vertex influence on deformation
11731 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
11732 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11733 for (j = 0;j < rsurface.batchnumvertices;j++)
11735 // if the wavefunc depends on time, evaluate it per-vertex
11738 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
11739 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11741 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11743 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11744 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);
11745 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11746 rsurface.batchvertex3f_vertexbuffer = NULL;
11747 rsurface.batchvertex3f_bufferoffset = 0;
11748 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11749 rsurface.batchsvector3f_vertexbuffer = NULL;
11750 rsurface.batchsvector3f_bufferoffset = 0;
11751 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11752 rsurface.batchtvector3f_vertexbuffer = NULL;
11753 rsurface.batchtvector3f_bufferoffset = 0;
11754 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11755 rsurface.batchnormal3f_vertexbuffer = NULL;
11756 rsurface.batchnormal3f_bufferoffset = 0;
11758 case Q3DEFORM_BULGE:
11759 // deform vertex array to make the surface have moving bulges
11760 for (j = 0;j < rsurface.batchnumvertices;j++)
11762 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
11763 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.array_batchvertex3f + 3*j);
11765 Mod_BuildNormals(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.array_batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.array_batchnormal3f, true);
11766 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);
11767 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11768 rsurface.batchvertex3f_vertexbuffer = NULL;
11769 rsurface.batchvertex3f_bufferoffset = 0;
11770 rsurface.batchsvector3f = rsurface.array_batchsvector3f;
11771 rsurface.batchsvector3f_vertexbuffer = NULL;
11772 rsurface.batchsvector3f_bufferoffset = 0;
11773 rsurface.batchtvector3f = rsurface.array_batchtvector3f;
11774 rsurface.batchtvector3f_vertexbuffer = NULL;
11775 rsurface.batchtvector3f_bufferoffset = 0;
11776 rsurface.batchnormal3f = rsurface.array_batchnormal3f;
11777 rsurface.batchnormal3f_vertexbuffer = NULL;
11778 rsurface.batchnormal3f_bufferoffset = 0;
11780 case Q3DEFORM_MOVE:
11781 // deform vertex array
11782 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11783 break; // if wavefunc is a nop, don't make a dynamic vertex array
11784 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
11785 VectorScale(deform->parms, scale, waveparms);
11786 for (j = 0;j < rsurface.batchnumvertices;j++)
11787 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.array_batchvertex3f + 3*j);
11788 rsurface.batchvertex3f = rsurface.array_batchvertex3f;
11789 rsurface.batchvertex3f_vertexbuffer = NULL;
11790 rsurface.batchvertex3f_bufferoffset = 0;
11795 // generate texcoords based on the chosen texcoord source
11796 switch(rsurface.texture->tcgen.tcgen)
11799 case Q3TCGEN_TEXTURE:
11801 case Q3TCGEN_LIGHTMAP:
11802 if (rsurface.batchtexcoordlightmap2f)
11803 memcpy(rsurface.array_batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, rsurface.batchnumvertices * sizeof(float[2]));
11804 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11805 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11806 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11808 case Q3TCGEN_VECTOR:
11809 for (j = 0;j < rsurface.batchnumvertices;j++)
11811 rsurface.array_batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
11812 rsurface.array_batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
11814 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11815 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11816 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11818 case Q3TCGEN_ENVIRONMENT:
11819 // make environment reflections using a spheremap
11820 for (j = 0;j < rsurface.batchnumvertices;j++)
11822 // identical to Q3A's method, but executed in worldspace so
11823 // carried models can be shiny too
11825 float viewer[3], d, reflected[3], worldreflected[3];
11827 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
11828 // VectorNormalize(viewer);
11830 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
11832 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
11833 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
11834 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
11835 // note: this is proportinal to viewer, so we can normalize later
11837 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
11838 VectorNormalize(worldreflected);
11840 // note: this sphere map only uses world x and z!
11841 // so positive and negative y will LOOK THE SAME.
11842 rsurface.array_batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
11843 rsurface.array_batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
11845 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11846 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11847 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11850 // the only tcmod that needs software vertex processing is turbulent, so
11851 // check for it here and apply the changes if needed
11852 // and we only support that as the first one
11853 // (handling a mixture of turbulent and other tcmods would be problematic
11854 // without punting it entirely to a software path)
11855 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11857 amplitude = rsurface.texture->tcmods[0].parms[1];
11858 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
11859 for (j = 0;j < rsurface.batchnumvertices;j++)
11861 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);
11862 rsurface.array_batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11864 rsurface.batchtexcoordtexture2f = rsurface.array_batchtexcoordtexture2f;
11865 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11866 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11869 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11871 // convert the modified arrays to vertex structs
11872 rsurface.batchvertexmesh = rsurface.array_batchvertexmesh;
11873 rsurface.batchvertexmeshbuffer = NULL;
11874 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11875 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11876 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11877 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
11878 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11879 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
11880 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
11882 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11884 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
11885 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11888 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11889 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11890 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11891 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11892 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11893 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11894 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11895 for (j = 0, vertexmesh = rsurface.array_batchvertexmesh;j < rsurface.batchnumvertices;j++, vertexmesh++)
11896 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11899 if (needsupdate & batchneed & BATCHNEED_VERTEXPOSITION)
11901 // convert the modified arrays to vertex structs
11902 rsurface.batchvertexposition = rsurface.array_batchvertexposition;
11903 rsurface.batchvertexpositionbuffer = NULL;
11904 if (sizeof(r_vertexposition_t) == sizeof(float[3]))
11905 memcpy(rsurface.array_batchvertexposition, rsurface.batchvertex3f, rsurface.batchnumvertices * sizeof(r_vertexposition_t));
11907 for (j = 0, vertexposition = rsurface.array_batchvertexposition;j < rsurface.batchnumvertices;j++, vertexposition++)
11908 VectorCopy(rsurface.batchvertex3f + 3*j, vertexposition->vertex3f);
11912 void RSurf_DrawBatch(void)
11914 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);
11917 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11919 // pick the closest matching water plane
11920 int planeindex, vertexindex, bestplaneindex = -1;
11924 r_waterstate_waterplane_t *p;
11926 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11928 if(p->camera_entity != rsurface.texture->camera_entity)
11931 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, 1, &surface);
11932 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11934 Matrix4x4_Transform(&rsurface.matrix, v, vert);
11935 d += fabs(PlaneDiff(vert, &p->plane));
11937 if (bestd > d || bestplaneindex < 0)
11940 bestplaneindex = planeindex;
11943 return bestplaneindex;
11946 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11949 for (i = 0;i < rsurface.batchnumvertices;i++)
11950 Vector4Set(rsurface.array_passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11951 rsurface.passcolor4f = rsurface.array_passcolor4f;
11952 rsurface.passcolor4f_vertexbuffer = 0;
11953 rsurface.passcolor4f_bufferoffset = 0;
11956 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11963 if (rsurface.passcolor4f)
11965 // generate color arrays
11966 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)
11968 f = RSurf_FogVertex(v);
11977 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11979 f = RSurf_FogVertex(v);
11986 rsurface.passcolor4f = rsurface.array_passcolor4f;
11987 rsurface.passcolor4f_vertexbuffer = 0;
11988 rsurface.passcolor4f_bufferoffset = 0;
11991 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11998 if (!rsurface.passcolor4f)
12000 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)
12002 f = RSurf_FogVertex(v);
12003 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
12004 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
12005 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
12008 rsurface.passcolor4f = rsurface.array_passcolor4f;
12009 rsurface.passcolor4f_vertexbuffer = 0;
12010 rsurface.passcolor4f_bufferoffset = 0;
12013 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
12018 if (!rsurface.passcolor4f)
12020 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
12027 rsurface.passcolor4f = rsurface.array_passcolor4f;
12028 rsurface.passcolor4f_vertexbuffer = 0;
12029 rsurface.passcolor4f_bufferoffset = 0;
12032 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
12037 if (!rsurface.passcolor4f)
12039 for (i = 0, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
12041 c2[0] = c[0] + r_refdef.scene.ambient;
12042 c2[1] = c[1] + r_refdef.scene.ambient;
12043 c2[2] = c[2] + r_refdef.scene.ambient;
12046 rsurface.passcolor4f = rsurface.array_passcolor4f;
12047 rsurface.passcolor4f_vertexbuffer = 0;
12048 rsurface.passcolor4f_bufferoffset = 0;
12051 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12054 rsurface.passcolor4f = NULL;
12055 rsurface.passcolor4f_vertexbuffer = 0;
12056 rsurface.passcolor4f_bufferoffset = 0;
12057 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12058 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12059 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12060 GL_Color(r, g, b, a);
12061 R_Mesh_TexBind(0, rsurface.lightmaptexture);
12065 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12067 // TODO: optimize applyfog && applycolor case
12068 // just apply fog if necessary, and tint the fog color array if necessary
12069 rsurface.passcolor4f = NULL;
12070 rsurface.passcolor4f_vertexbuffer = 0;
12071 rsurface.passcolor4f_bufferoffset = 0;
12072 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12073 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12074 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12075 GL_Color(r, g, b, a);
12079 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12082 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12083 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12084 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12085 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12086 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12087 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12088 GL_Color(r, g, b, a);
12092 static void RSurf_DrawBatch_GL11_ClampColor(void)
12097 if (!rsurface.passcolor4f)
12099 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.array_passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
12101 c2[0] = bound(0.0f, c1[0], 1.0f);
12102 c2[1] = bound(0.0f, c1[1], 1.0f);
12103 c2[2] = bound(0.0f, c1[2], 1.0f);
12104 c2[3] = bound(0.0f, c1[3], 1.0f);
12108 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
12116 vec3_t ambientcolor;
12117 vec3_t diffusecolor;
12121 VectorCopy(rsurface.modellight_lightdir, lightdir);
12122 f = 0.5f * r_refdef.lightmapintensity;
12123 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
12124 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
12125 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
12126 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
12127 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
12128 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
12130 if (VectorLength2(diffusecolor) > 0)
12132 // q3-style directional shading
12133 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)
12135 if ((f = DotProduct(n, lightdir)) > 0)
12136 VectorMA(ambientcolor, f, diffusecolor, c);
12138 VectorCopy(ambientcolor, c);
12145 rsurface.passcolor4f = rsurface.array_passcolor4f;
12146 rsurface.passcolor4f_vertexbuffer = 0;
12147 rsurface.passcolor4f_bufferoffset = 0;
12148 *applycolor = false;
12152 *r = ambientcolor[0];
12153 *g = ambientcolor[1];
12154 *b = ambientcolor[2];
12155 rsurface.passcolor4f = NULL;
12156 rsurface.passcolor4f_vertexbuffer = 0;
12157 rsurface.passcolor4f_bufferoffset = 0;
12161 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12163 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
12164 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12165 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12166 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12167 GL_Color(r, g, b, a);
12171 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
12177 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.array_passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
12179 f = 1 - RSurf_FogVertex(v);
12187 void RSurf_SetupDepthAndCulling(void)
12189 // submodels are biased to avoid z-fighting with world surfaces that they
12190 // may be exactly overlapping (avoids z-fighting artifacts on certain
12191 // doors and things in Quake maps)
12192 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
12193 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
12194 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
12195 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
12198 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12200 // transparent sky would be ridiculous
12201 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12203 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12204 skyrenderlater = true;
12205 RSurf_SetupDepthAndCulling();
12206 GL_DepthMask(true);
12207 // LordHavoc: HalfLife maps have freaky skypolys so don't use
12208 // skymasking on them, and Quake3 never did sky masking (unlike
12209 // software Quake and software Quake2), so disable the sky masking
12210 // in Quake3 maps as it causes problems with q3map2 sky tricks,
12211 // and skymasking also looks very bad when noclipping outside the
12212 // level, so don't use it then either.
12213 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
12215 R_Mesh_ResetTextureState();
12216 if (skyrendermasked)
12218 R_SetupShader_DepthOrShadow();
12219 // depth-only (masking)
12220 GL_ColorMask(0,0,0,0);
12221 // just to make sure that braindead drivers don't draw
12222 // anything despite that colormask...
12223 GL_BlendFunc(GL_ZERO, GL_ONE);
12224 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12225 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12229 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12231 GL_BlendFunc(GL_ONE, GL_ZERO);
12232 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12233 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
12234 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12237 if (skyrendermasked)
12238 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12240 R_Mesh_ResetTextureState();
12241 GL_Color(1, 1, 1, 1);
12244 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
12245 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
12246 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12248 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
12252 // render screenspace normalmap to texture
12253 GL_DepthMask(true);
12254 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
12259 // bind lightmap texture
12261 // water/refraction/reflection/camera surfaces have to be handled specially
12262 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)) && !r_waterstate.renderingscene)
12264 int start, end, startplaneindex;
12265 for (start = 0;start < texturenumsurfaces;start = end)
12267 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
12268 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
12270 // now that we have a batch using the same planeindex, render it
12271 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)) && !r_waterstate.renderingscene)
12273 // render water or distortion background
12274 GL_DepthMask(true);
12275 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12277 // blend surface on top
12278 GL_DepthMask(false);
12279 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
12282 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION) && !r_waterstate.renderingscene)
12284 // render surface with reflection texture as input
12285 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12286 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12293 // render surface batch normally
12294 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12295 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
12299 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12301 // OpenGL 1.3 path - anything not completely ancient
12302 qboolean applycolor;
12305 const texturelayer_t *layer;
12306 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);
12307 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12309 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12312 int layertexrgbscale;
12313 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12315 if (layerindex == 0)
12316 GL_AlphaTest(true);
12319 GL_AlphaTest(false);
12320 GL_DepthFunc(GL_EQUAL);
12323 GL_DepthMask(layer->depthmask && writedepth);
12324 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12325 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
12327 layertexrgbscale = 4;
12328 VectorScale(layer->color, 0.25f, layercolor);
12330 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
12332 layertexrgbscale = 2;
12333 VectorScale(layer->color, 0.5f, layercolor);
12337 layertexrgbscale = 1;
12338 VectorScale(layer->color, 1.0f, layercolor);
12340 layercolor[3] = layer->color[3];
12341 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
12342 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12343 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12344 switch (layer->type)
12346 case TEXTURELAYERTYPE_LITTEXTURE:
12347 // single-pass lightmapped texture with 2x rgbscale
12348 R_Mesh_TexBind(0, r_texture_white);
12349 R_Mesh_TexMatrix(0, NULL);
12350 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12351 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12352 R_Mesh_TexBind(1, layer->texture);
12353 R_Mesh_TexMatrix(1, &layer->texmatrix);
12354 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12355 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12356 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12357 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12358 else if (rsurface.uselightmaptexture)
12359 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12361 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12363 case TEXTURELAYERTYPE_TEXTURE:
12364 // singletexture unlit texture with transparency support
12365 R_Mesh_TexBind(0, layer->texture);
12366 R_Mesh_TexMatrix(0, &layer->texmatrix);
12367 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12368 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12369 R_Mesh_TexBind(1, 0);
12370 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12371 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12373 case TEXTURELAYERTYPE_FOG:
12374 // singletexture fogging
12375 if (layer->texture)
12377 R_Mesh_TexBind(0, layer->texture);
12378 R_Mesh_TexMatrix(0, &layer->texmatrix);
12379 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12380 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12384 R_Mesh_TexBind(0, 0);
12385 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12387 R_Mesh_TexBind(1, 0);
12388 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12389 // generate a color array for the fog pass
12390 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12391 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
12395 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12398 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12400 GL_DepthFunc(GL_LEQUAL);
12401 GL_AlphaTest(false);
12405 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12407 // OpenGL 1.1 - crusty old voodoo path
12410 const texturelayer_t *layer;
12411 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);
12412 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12414 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12416 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12418 if (layerindex == 0)
12419 GL_AlphaTest(true);
12422 GL_AlphaTest(false);
12423 GL_DepthFunc(GL_EQUAL);
12426 GL_DepthMask(layer->depthmask && writedepth);
12427 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12428 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12429 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12430 switch (layer->type)
12432 case TEXTURELAYERTYPE_LITTEXTURE:
12433 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
12435 // two-pass lit texture with 2x rgbscale
12436 // first the lightmap pass
12437 R_Mesh_TexBind(0, r_texture_white);
12438 R_Mesh_TexMatrix(0, NULL);
12439 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12440 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12441 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12442 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
12443 else if (rsurface.uselightmaptexture)
12444 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
12446 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
12447 // then apply the texture to it
12448 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
12449 R_Mesh_TexBind(0, layer->texture);
12450 R_Mesh_TexMatrix(0, &layer->texmatrix);
12451 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12452 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12453 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);
12457 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
12458 R_Mesh_TexBind(0, layer->texture);
12459 R_Mesh_TexMatrix(0, &layer->texmatrix);
12460 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12461 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12462 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12463 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);
12465 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);
12468 case TEXTURELAYERTYPE_TEXTURE:
12469 // singletexture unlit texture with transparency support
12470 R_Mesh_TexBind(0, layer->texture);
12471 R_Mesh_TexMatrix(0, &layer->texmatrix);
12472 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12473 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12474 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);
12476 case TEXTURELAYERTYPE_FOG:
12477 // singletexture fogging
12478 if (layer->texture)
12480 R_Mesh_TexBind(0, layer->texture);
12481 R_Mesh_TexMatrix(0, &layer->texmatrix);
12482 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12483 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12487 R_Mesh_TexBind(0, 0);
12488 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12490 // generate a color array for the fog pass
12491 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.array_passcolor4f, 0, 0);
12492 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
12496 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12499 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12501 GL_DepthFunc(GL_LEQUAL);
12502 GL_AlphaTest(false);
12506 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12510 r_vertexgeneric_t *batchvertex;
12513 GL_AlphaTest(false);
12514 R_Mesh_ResetTextureState();
12515 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12517 if(rsurface.texture && rsurface.texture->currentskinframe)
12519 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
12520 c[3] *= rsurface.texture->currentalpha;
12530 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
12532 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
12533 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
12534 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
12537 // brighten it up (as texture value 127 means "unlit")
12538 c[0] *= 2 * r_refdef.view.colorscale;
12539 c[1] *= 2 * r_refdef.view.colorscale;
12540 c[2] *= 2 * r_refdef.view.colorscale;
12542 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
12543 c[3] *= r_wateralpha.value;
12545 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
12547 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12548 GL_DepthMask(false);
12550 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
12552 GL_BlendFunc(GL_ONE, GL_ONE);
12553 GL_DepthMask(false);
12555 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12557 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
12558 GL_DepthMask(false);
12560 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
12562 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
12563 GL_DepthMask(false);
12567 GL_BlendFunc(GL_ONE, GL_ZERO);
12568 GL_DepthMask(writedepth);
12571 if (r_showsurfaces.integer == 3)
12573 rsurface.passcolor4f = NULL;
12575 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
12577 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12579 rsurface.passcolor4f = NULL;
12580 rsurface.passcolor4f_vertexbuffer = 0;
12581 rsurface.passcolor4f_bufferoffset = 0;
12583 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12585 qboolean applycolor = true;
12588 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12590 r_refdef.lightmapintensity = 1;
12591 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
12592 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12596 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12598 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12599 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12600 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12603 if(!rsurface.passcolor4f)
12604 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
12606 RSurf_DrawBatch_GL11_ApplyAmbient();
12607 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
12608 if(r_refdef.fogenabled)
12609 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
12610 RSurf_DrawBatch_GL11_ClampColor();
12612 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
12613 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12616 else if (!r_refdef.view.showdebug)
12618 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12619 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12620 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12622 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12623 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
12625 R_Mesh_PrepareVertices_Generic_Unlock();
12628 else if (r_showsurfaces.integer == 4)
12630 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12631 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12632 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12634 unsigned char c = vi << 3;
12635 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12636 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
12638 R_Mesh_PrepareVertices_Generic_Unlock();
12641 else if (r_showsurfaces.integer == 2)
12644 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12645 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
12646 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
12648 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
12649 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
12650 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
12651 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
12652 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
12653 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
12654 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
12656 R_Mesh_PrepareVertices_Generic_Unlock();
12657 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
12661 int texturesurfaceindex;
12663 const msurface_t *surface;
12664 unsigned char surfacecolor4ub[4];
12665 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12666 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
12668 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
12670 surface = texturesurfacelist[texturesurfaceindex];
12671 k = (int)(((size_t)surface) / sizeof(msurface_t));
12672 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
12673 for (j = 0;j < surface->num_vertices;j++)
12675 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12676 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
12680 R_Mesh_PrepareVertices_Generic_Unlock();
12685 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12688 RSurf_SetupDepthAndCulling();
12689 if (r_showsurfaces.integer)
12691 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12694 switch (vid.renderpath)
12696 case RENDERPATH_GL20:
12697 case RENDERPATH_CGGL:
12698 case RENDERPATH_D3D9:
12699 case RENDERPATH_D3D10:
12700 case RENDERPATH_D3D11:
12701 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12703 case RENDERPATH_GL13:
12704 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12706 case RENDERPATH_GL11:
12707 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12713 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12716 RSurf_SetupDepthAndCulling();
12717 if (r_showsurfaces.integer)
12719 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12722 switch (vid.renderpath)
12724 case RENDERPATH_GL20:
12725 case RENDERPATH_CGGL:
12726 case RENDERPATH_D3D9:
12727 case RENDERPATH_D3D10:
12728 case RENDERPATH_D3D11:
12729 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12731 case RENDERPATH_GL13:
12732 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12734 case RENDERPATH_GL11:
12735 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12741 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12744 int texturenumsurfaces, endsurface;
12745 texture_t *texture;
12746 const msurface_t *surface;
12747 #define MAXBATCH_TRANSPARENTSURFACES 256
12748 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
12750 // if the model is static it doesn't matter what value we give for
12751 // wantnormals and wanttangents, so this logic uses only rules applicable
12752 // to a model, knowing that they are meaningless otherwise
12753 if (ent == r_refdef.scene.worldentity)
12754 RSurf_ActiveWorldEntity();
12755 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12756 RSurf_ActiveModelEntity(ent, false, false, false);
12759 switch (vid.renderpath)
12761 case RENDERPATH_GL20:
12762 case RENDERPATH_CGGL:
12763 case RENDERPATH_D3D9:
12764 case RENDERPATH_D3D10:
12765 case RENDERPATH_D3D11:
12766 RSurf_ActiveModelEntity(ent, true, true, false);
12768 case RENDERPATH_GL13:
12769 case RENDERPATH_GL11:
12770 RSurf_ActiveModelEntity(ent, true, false, false);
12775 if (r_transparentdepthmasking.integer)
12777 qboolean setup = false;
12778 for (i = 0;i < numsurfaces;i = j)
12781 surface = rsurface.modelsurfaces + surfacelist[i];
12782 texture = surface->texture;
12783 rsurface.texture = R_GetCurrentTexture(texture);
12784 rsurface.lightmaptexture = NULL;
12785 rsurface.deluxemaptexture = NULL;
12786 rsurface.uselightmaptexture = false;
12787 // scan ahead until we find a different texture
12788 endsurface = min(i + 1024, numsurfaces);
12789 texturenumsurfaces = 0;
12790 texturesurfacelist[texturenumsurfaces++] = surface;
12791 for (;j < endsurface;j++)
12793 surface = rsurface.modelsurfaces + surfacelist[j];
12794 if (texture != surface->texture)
12796 texturesurfacelist[texturenumsurfaces++] = surface;
12798 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
12800 // render the range of surfaces as depth
12804 GL_ColorMask(0,0,0,0);
12806 GL_DepthTest(true);
12807 GL_BlendFunc(GL_ONE, GL_ZERO);
12808 GL_DepthMask(true);
12809 GL_AlphaTest(false);
12810 R_Mesh_ResetTextureState();
12811 R_SetupShader_DepthOrShadow();
12813 RSurf_SetupDepthAndCulling();
12814 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12815 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12819 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12822 for (i = 0;i < numsurfaces;i = j)
12825 surface = rsurface.modelsurfaces + surfacelist[i];
12826 texture = surface->texture;
12827 rsurface.texture = R_GetCurrentTexture(texture);
12828 rsurface.lightmaptexture = surface->lightmaptexture;
12829 rsurface.deluxemaptexture = surface->deluxemaptexture;
12830 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
12831 // scan ahead until we find a different texture
12832 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12833 texturenumsurfaces = 0;
12834 texturesurfacelist[texturenumsurfaces++] = surface;
12835 for (;j < endsurface;j++)
12837 surface = rsurface.modelsurfaces + surfacelist[j];
12838 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
12840 texturesurfacelist[texturenumsurfaces++] = surface;
12842 // render the range of surfaces
12843 if (ent == r_refdef.scene.worldentity)
12844 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12846 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12848 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12849 GL_AlphaTest(false);
12852 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12854 // transparent surfaces get pushed off into the transparent queue
12855 int surfacelistindex;
12856 const msurface_t *surface;
12857 vec3_t tempcenter, center;
12858 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12860 surface = texturesurfacelist[surfacelistindex];
12861 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12862 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12863 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12864 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12865 if (queueentity->transparent_offset) // transparent offset
12867 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12868 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12869 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12871 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12875 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12877 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12879 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12881 RSurf_SetupDepthAndCulling();
12882 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXPOSITION, texturenumsurfaces, texturesurfacelist);
12883 R_Mesh_PrepareVertices_Position(rsurface.batchnumvertices, rsurface.batchvertexposition, rsurface.batchvertexpositionbuffer);
12887 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12889 const entity_render_t *queueentity = r_refdef.scene.worldentity;
12892 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12895 if (!rsurface.texture->currentnumlayers)
12897 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12898 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12900 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12902 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12903 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12904 else if (!rsurface.texture->currentnumlayers)
12906 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12908 // in the deferred case, transparent surfaces were queued during prepass
12909 if (!r_shadow_usingdeferredprepass)
12910 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12914 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12915 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12920 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12923 texture_t *texture;
12924 // break the surface list down into batches by texture and use of lightmapping
12925 for (i = 0;i < numsurfaces;i = j)
12928 // texture is the base texture pointer, rsurface.texture is the
12929 // current frame/skin the texture is directing us to use (for example
12930 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12931 // use skin 1 instead)
12932 texture = surfacelist[i]->texture;
12933 rsurface.texture = R_GetCurrentTexture(texture);
12934 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12935 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12936 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
12937 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12939 // if this texture is not the kind we want, skip ahead to the next one
12940 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12944 // simply scan ahead until we find a different texture or lightmap state
12945 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12947 // render the range of surfaces
12948 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12952 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12956 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12959 if (!rsurface.texture->currentnumlayers)
12961 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12962 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12964 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12966 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12967 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12968 else if (!rsurface.texture->currentnumlayers)
12970 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12972 // in the deferred case, transparent surfaces were queued during prepass
12973 if (!r_shadow_usingdeferredprepass)
12974 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12978 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12979 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12984 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12987 texture_t *texture;
12988 // break the surface list down into batches by texture and use of lightmapping
12989 for (i = 0;i < numsurfaces;i = j)
12992 // texture is the base texture pointer, rsurface.texture is the
12993 // current frame/skin the texture is directing us to use (for example
12994 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12995 // use skin 1 instead)
12996 texture = surfacelist[i]->texture;
12997 rsurface.texture = R_GetCurrentTexture(texture);
12998 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12999 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
13000 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL && !depthonly && !prepass;
13001 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
13003 // if this texture is not the kind we want, skip ahead to the next one
13004 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
13008 // simply scan ahead until we find a different texture or lightmap state
13009 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
13011 // render the range of surfaces
13012 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
13016 float locboxvertex3f[6*4*3] =
13018 1,0,1, 1,0,0, 1,1,0, 1,1,1,
13019 0,1,1, 0,1,0, 0,0,0, 0,0,1,
13020 1,1,1, 1,1,0, 0,1,0, 0,1,1,
13021 0,0,1, 0,0,0, 1,0,0, 1,0,1,
13022 0,0,1, 1,0,1, 1,1,1, 0,1,1,
13023 1,0,0, 0,0,0, 0,1,0, 1,1,0
13026 unsigned short locboxelements[6*2*3] =
13031 12,13,14, 12,14,15,
13032 16,17,18, 16,18,19,
13036 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
13039 cl_locnode_t *loc = (cl_locnode_t *)ent;
13041 float vertex3f[6*4*3];
13043 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13044 GL_DepthMask(false);
13045 GL_DepthRange(0, 1);
13046 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13047 GL_DepthTest(true);
13048 GL_CullFace(GL_NONE);
13049 R_EntityMatrix(&identitymatrix);
13051 R_Mesh_ResetTextureState();
13053 i = surfacelist[0];
13054 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13055 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13056 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13057 surfacelist[0] < 0 ? 0.5f : 0.125f);
13059 if (VectorCompare(loc->mins, loc->maxs))
13061 VectorSet(size, 2, 2, 2);
13062 VectorMA(loc->mins, -0.5f, size, mins);
13066 VectorCopy(loc->mins, mins);
13067 VectorSubtract(loc->maxs, loc->mins, size);
13070 for (i = 0;i < 6*4*3;)
13071 for (j = 0;j < 3;j++, i++)
13072 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
13074 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
13075 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13076 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
13079 void R_DrawLocs(void)
13082 cl_locnode_t *loc, *nearestloc;
13084 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
13085 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
13087 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
13088 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
13092 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
13094 if (decalsystem->decals)
13095 Mem_Free(decalsystem->decals);
13096 memset(decalsystem, 0, sizeof(*decalsystem));
13099 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)
13102 tridecal_t *decals;
13105 // expand or initialize the system
13106 if (decalsystem->maxdecals <= decalsystem->numdecals)
13108 decalsystem_t old = *decalsystem;
13109 qboolean useshortelements;
13110 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
13111 useshortelements = decalsystem->maxdecals * 3 <= 65536;
13112 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
13113 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
13114 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
13115 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
13116 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
13117 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
13118 if (decalsystem->numdecals)
13119 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
13121 Mem_Free(old.decals);
13122 for (i = 0;i < decalsystem->maxdecals*3;i++)
13123 decalsystem->element3i[i] = i;
13124 if (useshortelements)
13125 for (i = 0;i < decalsystem->maxdecals*3;i++)
13126 decalsystem->element3s[i] = i;
13129 // grab a decal and search for another free slot for the next one
13130 decals = decalsystem->decals;
13131 decal = decalsystem->decals + (i = decalsystem->freedecal++);
13132 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
13134 decalsystem->freedecal = i;
13135 if (decalsystem->numdecals <= i)
13136 decalsystem->numdecals = i + 1;
13138 // initialize the decal
13140 decal->triangleindex = triangleindex;
13141 decal->surfaceindex = surfaceindex;
13142 decal->decalsequence = decalsequence;
13143 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
13144 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
13145 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
13146 decal->color4ub[0][3] = 255;
13147 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
13148 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
13149 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
13150 decal->color4ub[1][3] = 255;
13151 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
13152 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
13153 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
13154 decal->color4ub[2][3] = 255;
13155 decal->vertex3f[0][0] = v0[0];
13156 decal->vertex3f[0][1] = v0[1];
13157 decal->vertex3f[0][2] = v0[2];
13158 decal->vertex3f[1][0] = v1[0];
13159 decal->vertex3f[1][1] = v1[1];
13160 decal->vertex3f[1][2] = v1[2];
13161 decal->vertex3f[2][0] = v2[0];
13162 decal->vertex3f[2][1] = v2[1];
13163 decal->vertex3f[2][2] = v2[2];
13164 decal->texcoord2f[0][0] = t0[0];
13165 decal->texcoord2f[0][1] = t0[1];
13166 decal->texcoord2f[1][0] = t1[0];
13167 decal->texcoord2f[1][1] = t1[1];
13168 decal->texcoord2f[2][0] = t2[0];
13169 decal->texcoord2f[2][1] = t2[1];
13172 extern cvar_t cl_decals_bias;
13173 extern cvar_t cl_decals_models;
13174 extern cvar_t cl_decals_newsystem_intensitymultiplier;
13175 // baseparms, parms, temps
13176 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)
13181 const float *vertex3f;
13183 float points[2][9][3];
13190 e = rsurface.modelelement3i + 3*triangleindex;
13192 vertex3f = rsurface.modelvertex3f;
13194 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13196 index = 3*e[cornerindex];
13197 VectorCopy(vertex3f + index, v[cornerindex]);
13200 //TriangleNormal(v[0], v[1], v[2], normal);
13201 //if (DotProduct(normal, localnormal) < 0.0f)
13203 // clip by each of the box planes formed from the projection matrix
13204 // if anything survives, we emit the decal
13205 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]);
13208 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]);
13211 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]);
13214 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]);
13217 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]);
13220 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]);
13223 // some part of the triangle survived, so we have to accept it...
13226 // dynamic always uses the original triangle
13228 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13230 index = 3*e[cornerindex];
13231 VectorCopy(vertex3f + index, v[cornerindex]);
13234 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
13236 // convert vertex positions to texcoords
13237 Matrix4x4_Transform(projection, v[cornerindex], temp);
13238 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
13239 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
13240 // calculate distance fade from the projection origin
13241 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
13242 f = bound(0.0f, f, 1.0f);
13243 c[cornerindex][0] = r * f;
13244 c[cornerindex][1] = g * f;
13245 c[cornerindex][2] = b * f;
13246 c[cornerindex][3] = 1.0f;
13247 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
13250 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);
13252 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
13253 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);
13255 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)
13257 matrix4x4_t projection;
13258 decalsystem_t *decalsystem;
13261 const msurface_t *surface;
13262 const msurface_t *surfaces;
13263 const int *surfacelist;
13264 const texture_t *texture;
13266 int numsurfacelist;
13267 int surfacelistindex;
13270 float localorigin[3];
13271 float localnormal[3];
13272 float localmins[3];
13273 float localmaxs[3];
13276 float planes[6][4];
13279 int bih_triangles_count;
13280 int bih_triangles[256];
13281 int bih_surfaces[256];
13283 decalsystem = &ent->decalsystem;
13284 model = ent->model;
13285 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
13287 R_DecalSystem_Reset(&ent->decalsystem);
13291 if (!model->brush.data_leafs && !cl_decals_models.integer)
13293 if (decalsystem->model)
13294 R_DecalSystem_Reset(decalsystem);
13298 if (decalsystem->model != model)
13299 R_DecalSystem_Reset(decalsystem);
13300 decalsystem->model = model;
13302 RSurf_ActiveModelEntity(ent, false, false, false);
13304 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
13305 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
13306 VectorNormalize(localnormal);
13307 localsize = worldsize*rsurface.inversematrixscale;
13308 localmins[0] = localorigin[0] - localsize;
13309 localmins[1] = localorigin[1] - localsize;
13310 localmins[2] = localorigin[2] - localsize;
13311 localmaxs[0] = localorigin[0] + localsize;
13312 localmaxs[1] = localorigin[1] + localsize;
13313 localmaxs[2] = localorigin[2] + localsize;
13315 //VectorCopy(localnormal, planes[4]);
13316 //VectorVectors(planes[4], planes[2], planes[0]);
13317 AnglesFromVectors(angles, localnormal, NULL, false);
13318 AngleVectors(angles, planes[0], planes[2], planes[4]);
13319 VectorNegate(planes[0], planes[1]);
13320 VectorNegate(planes[2], planes[3]);
13321 VectorNegate(planes[4], planes[5]);
13322 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
13323 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
13324 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
13325 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
13326 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
13327 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
13332 matrix4x4_t forwardprojection;
13333 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
13334 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
13339 float projectionvector[4][3];
13340 VectorScale(planes[0], ilocalsize, projectionvector[0]);
13341 VectorScale(planes[2], ilocalsize, projectionvector[1]);
13342 VectorScale(planes[4], ilocalsize, projectionvector[2]);
13343 projectionvector[0][0] = planes[0][0] * ilocalsize;
13344 projectionvector[0][1] = planes[1][0] * ilocalsize;
13345 projectionvector[0][2] = planes[2][0] * ilocalsize;
13346 projectionvector[1][0] = planes[0][1] * ilocalsize;
13347 projectionvector[1][1] = planes[1][1] * ilocalsize;
13348 projectionvector[1][2] = planes[2][1] * ilocalsize;
13349 projectionvector[2][0] = planes[0][2] * ilocalsize;
13350 projectionvector[2][1] = planes[1][2] * ilocalsize;
13351 projectionvector[2][2] = planes[2][2] * ilocalsize;
13352 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
13353 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
13354 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
13355 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
13359 dynamic = model->surfmesh.isanimated;
13360 numsurfacelist = model->nummodelsurfaces;
13361 surfacelist = model->sortedmodelsurfaces;
13362 surfaces = model->data_surfaces;
13365 bih_triangles_count = -1;
13368 if(model->render_bih.numleafs)
13369 bih = &model->render_bih;
13370 else if(model->collision_bih.numleafs)
13371 bih = &model->collision_bih;
13374 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
13375 if(bih_triangles_count == 0)
13377 if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
13379 if(bih_triangles_count > 0)
13381 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
13383 surfaceindex = bih_surfaces[triangleindex];
13384 surface = surfaces + surfaceindex;
13385 texture = surface->texture;
13386 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13388 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13390 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
13395 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
13397 surfaceindex = surfacelist[surfacelistindex];
13398 surface = surfaces + surfaceindex;
13399 // check cull box first because it rejects more than any other check
13400 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
13402 // skip transparent surfaces
13403 texture = surface->texture;
13404 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13406 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13408 numtriangles = surface->num_triangles;
13409 for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
13410 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
13415 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
13416 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)
13418 int renderentityindex;
13419 float worldmins[3];
13420 float worldmaxs[3];
13421 entity_render_t *ent;
13423 if (!cl_decals_newsystem.integer)
13426 worldmins[0] = worldorigin[0] - worldsize;
13427 worldmins[1] = worldorigin[1] - worldsize;
13428 worldmins[2] = worldorigin[2] - worldsize;
13429 worldmaxs[0] = worldorigin[0] + worldsize;
13430 worldmaxs[1] = worldorigin[1] + worldsize;
13431 worldmaxs[2] = worldorigin[2] + worldsize;
13433 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13435 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
13437 ent = r_refdef.scene.entities[renderentityindex];
13438 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
13441 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13445 typedef struct r_decalsystem_splatqueue_s
13447 vec3_t worldorigin;
13448 vec3_t worldnormal;
13454 r_decalsystem_splatqueue_t;
13456 int r_decalsystem_numqueued = 0;
13457 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
13459 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)
13461 r_decalsystem_splatqueue_t *queue;
13463 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
13466 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
13467 VectorCopy(worldorigin, queue->worldorigin);
13468 VectorCopy(worldnormal, queue->worldnormal);
13469 Vector4Set(queue->color, r, g, b, a);
13470 Vector4Set(queue->tcrange, s1, t1, s2, t2);
13471 queue->worldsize = worldsize;
13472 queue->decalsequence = cl.decalsequence++;
13475 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
13478 r_decalsystem_splatqueue_t *queue;
13480 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
13481 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);
13482 r_decalsystem_numqueued = 0;
13485 extern cvar_t cl_decals_max;
13486 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
13489 decalsystem_t *decalsystem = &ent->decalsystem;
13496 if (!decalsystem->numdecals)
13499 if (r_showsurfaces.integer)
13502 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13504 R_DecalSystem_Reset(decalsystem);
13508 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
13509 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
13511 if (decalsystem->lastupdatetime)
13512 frametime = (cl.time - decalsystem->lastupdatetime);
13515 decalsystem->lastupdatetime = cl.time;
13516 decal = decalsystem->decals;
13517 numdecals = decalsystem->numdecals;
13519 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13521 if (decal->color4ub[0][3])
13523 decal->lived += frametime;
13524 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
13526 memset(decal, 0, sizeof(*decal));
13527 if (decalsystem->freedecal > i)
13528 decalsystem->freedecal = i;
13532 decal = decalsystem->decals;
13533 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
13536 // collapse the array by shuffling the tail decals into the gaps
13539 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
13540 decalsystem->freedecal++;
13541 if (decalsystem->freedecal == numdecals)
13543 decal[decalsystem->freedecal] = decal[--numdecals];
13546 decalsystem->numdecals = numdecals;
13548 if (numdecals <= 0)
13550 // if there are no decals left, reset decalsystem
13551 R_DecalSystem_Reset(decalsystem);
13555 extern skinframe_t *decalskinframe;
13556 static void R_DrawModelDecals_Entity(entity_render_t *ent)
13559 decalsystem_t *decalsystem = &ent->decalsystem;
13568 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
13571 numdecals = decalsystem->numdecals;
13575 if (r_showsurfaces.integer)
13578 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13580 R_DecalSystem_Reset(decalsystem);
13584 // if the model is static it doesn't matter what value we give for
13585 // wantnormals and wanttangents, so this logic uses only rules applicable
13586 // to a model, knowing that they are meaningless otherwise
13587 if (ent == r_refdef.scene.worldentity)
13588 RSurf_ActiveWorldEntity();
13590 RSurf_ActiveModelEntity(ent, false, false, false);
13592 decalsystem->lastupdatetime = cl.time;
13593 decal = decalsystem->decals;
13595 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
13597 // update vertex positions for animated models
13598 v3f = decalsystem->vertex3f;
13599 c4f = decalsystem->color4f;
13600 t2f = decalsystem->texcoord2f;
13601 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13603 if (!decal->color4ub[0][3])
13606 if (surfacevisible && !surfacevisible[decal->surfaceindex])
13609 // update color values for fading decals
13610 if (decal->lived >= cl_decals_time.value)
13612 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
13613 alpha *= (1.0f/255.0f);
13616 alpha = 1.0f/255.0f;
13618 c4f[ 0] = decal->color4ub[0][0] * alpha;
13619 c4f[ 1] = decal->color4ub[0][1] * alpha;
13620 c4f[ 2] = decal->color4ub[0][2] * alpha;
13622 c4f[ 4] = decal->color4ub[1][0] * alpha;
13623 c4f[ 5] = decal->color4ub[1][1] * alpha;
13624 c4f[ 6] = decal->color4ub[1][2] * alpha;
13626 c4f[ 8] = decal->color4ub[2][0] * alpha;
13627 c4f[ 9] = decal->color4ub[2][1] * alpha;
13628 c4f[10] = decal->color4ub[2][2] * alpha;
13631 t2f[0] = decal->texcoord2f[0][0];
13632 t2f[1] = decal->texcoord2f[0][1];
13633 t2f[2] = decal->texcoord2f[1][0];
13634 t2f[3] = decal->texcoord2f[1][1];
13635 t2f[4] = decal->texcoord2f[2][0];
13636 t2f[5] = decal->texcoord2f[2][1];
13638 // update vertex positions for animated models
13639 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
13641 e = rsurface.modelelement3i + 3*decal->triangleindex;
13642 VectorCopy(rsurface.modelvertexposition[e[0]].vertex3f, v3f);
13643 VectorCopy(rsurface.modelvertexposition[e[1]].vertex3f, v3f + 3);
13644 VectorCopy(rsurface.modelvertexposition[e[2]].vertex3f, v3f + 6);
13648 VectorCopy(decal->vertex3f[0], v3f);
13649 VectorCopy(decal->vertex3f[1], v3f + 3);
13650 VectorCopy(decal->vertex3f[2], v3f + 6);
13653 if (r_refdef.fogenabled)
13655 alpha = RSurf_FogVertex(v3f);
13656 VectorScale(c4f, alpha, c4f);
13657 alpha = RSurf_FogVertex(v3f + 3);
13658 VectorScale(c4f + 4, alpha, c4f + 4);
13659 alpha = RSurf_FogVertex(v3f + 6);
13660 VectorScale(c4f + 8, alpha, c4f + 8);
13671 r_refdef.stats.drawndecals += numtris;
13673 // now render the decals all at once
13674 // (this assumes they all use one particle font texture!)
13675 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);
13676 R_Mesh_ResetTextureState();
13677 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
13678 GL_DepthMask(false);
13679 GL_DepthRange(0, 1);
13680 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
13681 GL_DepthTest(true);
13682 GL_CullFace(GL_NONE);
13683 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
13684 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
13685 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
13689 static void R_DrawModelDecals(void)
13693 // fade faster when there are too many decals
13694 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13695 for (i = 0;i < r_refdef.scene.numentities;i++)
13696 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13698 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
13699 for (i = 0;i < r_refdef.scene.numentities;i++)
13700 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13701 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
13703 R_DecalSystem_ApplySplatEntitiesQueue();
13705 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13706 for (i = 0;i < r_refdef.scene.numentities;i++)
13707 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13709 r_refdef.stats.totaldecals += numdecals;
13711 if (r_showsurfaces.integer)
13714 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
13716 for (i = 0;i < r_refdef.scene.numentities;i++)
13718 if (!r_refdef.viewcache.entityvisible[i])
13720 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13721 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
13725 extern cvar_t mod_collision_bih;
13726 void R_DrawDebugModel(void)
13728 entity_render_t *ent = rsurface.entity;
13729 int i, j, k, l, flagsmask;
13730 const msurface_t *surface;
13731 dp_model_t *model = ent->model;
13734 switch(vid.renderpath)
13736 case RENDERPATH_GL11:
13737 case RENDERPATH_GL13:
13738 case RENDERPATH_GL20:
13739 case RENDERPATH_CGGL:
13741 case RENDERPATH_D3D9:
13742 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13744 case RENDERPATH_D3D10:
13745 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13747 case RENDERPATH_D3D11:
13748 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13752 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
13754 R_Mesh_ResetTextureState();
13755 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13756 GL_DepthRange(0, 1);
13757 GL_DepthTest(!r_showdisabledepthtest.integer);
13758 GL_DepthMask(false);
13759 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13761 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
13765 qboolean cullbox = ent == r_refdef.scene.worldentity;
13766 const q3mbrush_t *brush;
13767 const bih_t *bih = &model->collision_bih;
13768 const bih_leaf_t *bihleaf;
13769 float vertex3f[3][3];
13770 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
13772 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
13774 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
13776 switch (bihleaf->type)
13779 brush = model->brush.data_brushes + bihleaf->itemindex;
13780 if (brush->colbrushf && brush->colbrushf->numtriangles)
13782 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);
13783 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
13784 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
13787 case BIH_COLLISIONTRIANGLE:
13788 triangleindex = bihleaf->itemindex;
13789 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
13790 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
13791 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
13792 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);
13793 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13794 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13796 case BIH_RENDERTRIANGLE:
13797 triangleindex = bihleaf->itemindex;
13798 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
13799 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
13800 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
13801 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);
13802 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13803 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13809 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13811 if (r_showtris.integer || r_shownormals.integer)
13813 if (r_showdisabledepthtest.integer)
13815 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13816 GL_DepthMask(false);
13820 GL_BlendFunc(GL_ONE, GL_ZERO);
13821 GL_DepthMask(true);
13823 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
13825 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
13827 rsurface.texture = R_GetCurrentTexture(surface->texture);
13828 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
13830 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
13831 if (r_showtris.value > 0)
13833 if (!rsurface.texture->currentlayers->depthmask)
13834 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
13835 else if (ent == r_refdef.scene.worldentity)
13836 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
13838 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
13839 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
13840 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
13842 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13845 if (r_shownormals.value < 0)
13847 qglBegin(GL_LINES);
13848 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13850 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13851 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13852 qglVertex3f(v[0], v[1], v[2]);
13853 VectorMA(v, -r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13854 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13855 qglVertex3f(v[0], v[1], v[2]);
13860 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13862 qglBegin(GL_LINES);
13863 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13865 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13866 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13867 qglVertex3f(v[0], v[1], v[2]);
13868 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13869 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13870 qglVertex3f(v[0], v[1], v[2]);
13874 qglBegin(GL_LINES);
13875 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13877 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13878 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13879 qglVertex3f(v[0], v[1], v[2]);
13880 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13881 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13882 qglVertex3f(v[0], v[1], v[2]);
13886 qglBegin(GL_LINES);
13887 for (k = 0, l = surface->num_firstvertex;k < surface->num_vertices;k++, l++)
13889 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13890 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13891 qglVertex3f(v[0], v[1], v[2]);
13892 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13893 GL_Color(r_refdef.view.colorscale, 1, 1, 1);
13894 qglVertex3f(v[0], v[1], v[2]);
13901 rsurface.texture = NULL;
13905 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13906 int r_maxsurfacelist = 0;
13907 const msurface_t **r_surfacelist = NULL;
13908 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13910 int i, j, endj, flagsmask;
13911 dp_model_t *model = r_refdef.scene.worldmodel;
13912 msurface_t *surfaces;
13913 unsigned char *update;
13914 int numsurfacelist = 0;
13918 if (r_maxsurfacelist < model->num_surfaces)
13920 r_maxsurfacelist = model->num_surfaces;
13922 Mem_Free((msurface_t**)r_surfacelist);
13923 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13926 RSurf_ActiveWorldEntity();
13928 surfaces = model->data_surfaces;
13929 update = model->brushq1.lightmapupdateflags;
13931 // update light styles on this submodel
13932 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13934 model_brush_lightstyleinfo_t *style;
13935 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13937 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13939 int *list = style->surfacelist;
13940 style->value = r_refdef.scene.lightstylevalue[style->style];
13941 for (j = 0;j < style->numsurfaces;j++)
13942 update[list[j]] = true;
13947 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13951 R_DrawDebugModel();
13952 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13956 rsurface.lightmaptexture = NULL;
13957 rsurface.deluxemaptexture = NULL;
13958 rsurface.uselightmaptexture = false;
13959 rsurface.texture = NULL;
13960 rsurface.rtlight = NULL;
13961 numsurfacelist = 0;
13962 // add visible surfaces to draw list
13963 for (i = 0;i < model->nummodelsurfaces;i++)
13965 j = model->sortedmodelsurfaces[i];
13966 if (r_refdef.viewcache.world_surfacevisible[j])
13967 r_surfacelist[numsurfacelist++] = surfaces + j;
13969 // update lightmaps if needed
13970 if (model->brushq1.firstrender)
13972 model->brushq1.firstrender = false;
13973 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13975 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13979 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13980 if (r_refdef.viewcache.world_surfacevisible[j])
13982 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13984 // don't do anything if there were no surfaces
13985 if (!numsurfacelist)
13987 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13990 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13991 GL_AlphaTest(false);
13993 // add to stats if desired
13994 if (r_speeds.integer && !skysurfaces && !depthonly)
13996 r_refdef.stats.world_surfaces += numsurfacelist;
13997 for (j = 0;j < numsurfacelist;j++)
13998 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
14001 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14004 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
14006 int i, j, endj, flagsmask;
14007 dp_model_t *model = ent->model;
14008 msurface_t *surfaces;
14009 unsigned char *update;
14010 int numsurfacelist = 0;
14014 if (r_maxsurfacelist < model->num_surfaces)
14016 r_maxsurfacelist = model->num_surfaces;
14018 Mem_Free((msurface_t **)r_surfacelist);
14019 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
14022 // if the model is static it doesn't matter what value we give for
14023 // wantnormals and wanttangents, so this logic uses only rules applicable
14024 // to a model, knowing that they are meaningless otherwise
14025 if (ent == r_refdef.scene.worldentity)
14026 RSurf_ActiveWorldEntity();
14027 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
14028 RSurf_ActiveModelEntity(ent, false, false, false);
14030 RSurf_ActiveModelEntity(ent, true, true, true);
14031 else if (depthonly)
14033 switch (vid.renderpath)
14035 case RENDERPATH_GL20:
14036 case RENDERPATH_CGGL:
14037 case RENDERPATH_D3D9:
14038 case RENDERPATH_D3D10:
14039 case RENDERPATH_D3D11:
14040 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
14042 case RENDERPATH_GL13:
14043 case RENDERPATH_GL11:
14044 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
14050 switch (vid.renderpath)
14052 case RENDERPATH_GL20:
14053 case RENDERPATH_CGGL:
14054 case RENDERPATH_D3D9:
14055 case RENDERPATH_D3D10:
14056 case RENDERPATH_D3D11:
14057 RSurf_ActiveModelEntity(ent, true, true, false);
14059 case RENDERPATH_GL13:
14060 case RENDERPATH_GL11:
14061 RSurf_ActiveModelEntity(ent, true, false, false);
14066 surfaces = model->data_surfaces;
14067 update = model->brushq1.lightmapupdateflags;
14069 // update light styles
14070 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
14072 model_brush_lightstyleinfo_t *style;
14073 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
14075 if (style->value != r_refdef.scene.lightstylevalue[style->style])
14077 int *list = style->surfacelist;
14078 style->value = r_refdef.scene.lightstylevalue[style->style];
14079 for (j = 0;j < style->numsurfaces;j++)
14080 update[list[j]] = true;
14085 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
14089 R_DrawDebugModel();
14090 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14094 rsurface.lightmaptexture = NULL;
14095 rsurface.deluxemaptexture = NULL;
14096 rsurface.uselightmaptexture = false;
14097 rsurface.texture = NULL;
14098 rsurface.rtlight = NULL;
14099 numsurfacelist = 0;
14100 // add visible surfaces to draw list
14101 for (i = 0;i < model->nummodelsurfaces;i++)
14102 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
14103 // don't do anything if there were no surfaces
14104 if (!numsurfacelist)
14106 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14109 // update lightmaps if needed
14113 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14118 R_BuildLightMap(ent, surfaces + j);
14123 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14125 R_BuildLightMap(ent, surfaces + j);
14126 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
14127 GL_AlphaTest(false);
14129 // add to stats if desired
14130 if (r_speeds.integer && !skysurfaces && !depthonly)
14132 r_refdef.stats.entities_surfaces += numsurfacelist;
14133 for (j = 0;j < numsurfacelist;j++)
14134 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
14137 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14140 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14142 static texture_t texture;
14143 static msurface_t surface;
14144 const msurface_t *surfacelist = &surface;
14146 // fake enough texture and surface state to render this geometry
14148 texture.update_lastrenderframe = -1; // regenerate this texture
14149 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
14150 texture.currentskinframe = skinframe;
14151 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
14152 texture.offsetmapping = OFFSETMAPPING_OFF;
14153 texture.offsetscale = 1;
14154 texture.specularscalemod = 1;
14155 texture.specularpowermod = 1;
14157 surface.texture = &texture;
14158 surface.num_triangles = numtriangles;
14159 surface.num_firsttriangle = firsttriangle;
14160 surface.num_vertices = numvertices;
14161 surface.num_firstvertex = firstvertex;
14164 rsurface.texture = R_GetCurrentTexture(surface.texture);
14165 rsurface.lightmaptexture = NULL;
14166 rsurface.deluxemaptexture = NULL;
14167 rsurface.uselightmaptexture = false;
14168 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14171 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)
14173 static msurface_t surface;
14174 const msurface_t *surfacelist = &surface;
14176 // fake enough texture and surface state to render this geometry
14178 surface.texture = texture;
14179 surface.num_triangles = numtriangles;
14180 surface.num_firsttriangle = firsttriangle;
14181 surface.num_vertices = numvertices;
14182 surface.num_firstvertex = firstvertex;
14185 rsurface.texture = R_GetCurrentTexture(surface.texture);
14186 rsurface.lightmaptexture = NULL;
14187 rsurface.deluxemaptexture = NULL;
14188 rsurface.uselightmaptexture = false;
14189 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);