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"
30 #include "dpsoftrast.h"
34 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
37 mempool_t *r_main_mempool;
38 rtexturepool_t *r_main_texturepool;
40 static int r_textureframe = 0; ///< used only by R_GetCurrentTexture
42 static qboolean r_loadnormalmap;
43 static qboolean r_loadgloss;
45 static qboolean r_loaddds;
46 static qboolean r_savedds;
53 cvar_t r_motionblur = {CVAR_SAVE, "r_motionblur", "0", "motionblur value scale - 0.5 recommended"};
54 cvar_t r_damageblur = {CVAR_SAVE, "r_damageblur", "0", "motionblur based on damage"};
55 cvar_t r_motionblur_vmin = {CVAR_SAVE, "r_motionblur_vmin", "300", "minimum influence from velocity"};
56 cvar_t r_motionblur_vmax = {CVAR_SAVE, "r_motionblur_vmax", "600", "maximum influence from velocity"};
57 cvar_t r_motionblur_bmin = {CVAR_SAVE, "r_motionblur_bmin", "0.5", "velocity at which there is no blur yet (may be negative to always have some blur)"};
58 cvar_t r_motionblur_vcoeff = {CVAR_SAVE, "r_motionblur_vcoeff", "0.05", "sliding average reaction time for velocity"};
59 cvar_t r_motionblur_maxblur = {CVAR_SAVE, "r_motionblur_maxblur", "0.88", "cap for motionblur alpha value"};
60 cvar_t r_motionblur_randomize = {CVAR_SAVE, "r_motionblur_randomize", "0.1", "randomizing coefficient to workaround ghosting"};
62 // TODO do we want a r_equalize_entities cvar that works on all ents, or would that be a cheat?
63 cvar_t r_equalize_entities_fullbright = {CVAR_SAVE, "r_equalize_entities_fullbright", "0", "render fullbright entities by equalizing their lightness, not by not rendering light"};
64 cvar_t r_equalize_entities_minambient = {CVAR_SAVE, "r_equalize_entities_minambient", "0.5", "light equalizing: ensure at least this ambient/diffuse ratio"};
65 cvar_t r_equalize_entities_by = {CVAR_SAVE, "r_equalize_entities_by", "0.7", "light equalizing: exponent of dynamics compression (0 = no compression, 1 = full compression)"};
66 cvar_t r_equalize_entities_to = {CVAR_SAVE, "r_equalize_entities_to", "0.8", "light equalizing: target light level"};
68 cvar_t r_depthfirst = {CVAR_SAVE, "r_depthfirst", "0", "renders a depth-only version of the scene before normal rendering begins to eliminate overdraw, values: 0 = off, 1 = world depth, 2 = world and model depth"};
69 cvar_t r_useinfinitefarclip = {CVAR_SAVE, "r_useinfinitefarclip", "1", "enables use of a special kind of projection matrix that has an extremely large farclip"};
70 cvar_t r_farclip_base = {0, "r_farclip_base", "65536", "farclip (furthest visible distance) for rendering when r_useinfinitefarclip is 0"};
71 cvar_t r_farclip_world = {0, "r_farclip_world", "2", "adds map size to farclip multiplied by this value"};
72 cvar_t r_nearclip = {0, "r_nearclip", "1", "distance from camera of nearclip plane" };
73 cvar_t r_showbboxes = {0, "r_showbboxes", "0", "shows bounding boxes of server entities, value controls opacity scaling (1 = 10%, 10 = 100%)"};
74 cvar_t r_showsurfaces = {0, "r_showsurfaces", "0", "1 shows surfaces as different colors, or a value of 2 shows triangle draw order (for analyzing whether meshes are optimized for vertex cache)"};
75 cvar_t r_showtris = {0, "r_showtris", "0", "shows triangle outlines, value controls brightness (can be above 1)"};
76 cvar_t r_shownormals = {0, "r_shownormals", "0", "shows per-vertex surface normals and tangent vectors for bumpmapped lighting"};
77 cvar_t r_showlighting = {0, "r_showlighting", "0", "shows areas lit by lights, useful for finding out why some areas of a map render slowly (bright orange = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
78 cvar_t r_showshadowvolumes = {0, "r_showshadowvolumes", "0", "shows areas shadowed by lights, useful for finding out why some areas of a map render slowly (bright blue = lots of passes = slow), a value of 2 disables depth testing which can be interesting but not very useful"};
79 cvar_t r_showcollisionbrushes = {0, "r_showcollisionbrushes", "0", "draws collision brushes in quake3 maps (mode 1), mode 2 disables rendering of world (trippy!)"};
80 cvar_t r_showcollisionbrushes_polygonfactor = {0, "r_showcollisionbrushes_polygonfactor", "-1", "expands outward the brush polygons a little bit, used to make collision brushes appear infront of walls"};
81 cvar_t r_showcollisionbrushes_polygonoffset = {0, "r_showcollisionbrushes_polygonoffset", "0", "nudges brush polygon depth in hardware depth units, used to make collision brushes appear infront of walls"};
82 cvar_t r_showdisabledepthtest = {0, "r_showdisabledepthtest", "0", "disables depth testing on r_show* cvars, allowing you to see what hidden geometry the graphics card is processing"};
83 cvar_t r_drawportals = {0, "r_drawportals", "0", "shows portals (separating polygons) in world interior in quake1 maps"};
84 cvar_t r_drawentities = {0, "r_drawentities","1", "draw entities (doors, players, projectiles, etc)"};
85 cvar_t r_draw2d = {0, "r_draw2d","1", "draw 2D stuff (dangerous to turn off)"};
86 cvar_t r_drawworld = {0, "r_drawworld","1", "draw world (most static stuff)"};
87 cvar_t r_drawviewmodel = {0, "r_drawviewmodel","1", "draw your weapon model"};
88 cvar_t r_drawexteriormodel = {0, "r_drawexteriormodel","1", "draw your player model (e.g. in chase cam, reflections)"};
89 cvar_t r_cullentities_trace = {0, "r_cullentities_trace", "1", "probabistically cull invisible entities"};
90 cvar_t r_cullentities_trace_samples = {0, "r_cullentities_trace_samples", "2", "number of samples to test for entity culling (in addition to center sample)"};
91 cvar_t r_cullentities_trace_tempentitysamples = {0, "r_cullentities_trace_tempentitysamples", "-1", "number of samples to test for entity culling of temp entities (including all CSQC entities), -1 disables trace culling on these entities to prevent flicker (pvs still applies)"};
92 cvar_t r_cullentities_trace_enlarge = {0, "r_cullentities_trace_enlarge", "0", "box enlargement for entity culling"};
93 cvar_t r_cullentities_trace_delay = {0, "r_cullentities_trace_delay", "1", "number of seconds until the entity gets actually culled"};
94 cvar_t r_speeds = {0, "r_speeds","0", "displays rendering statistics and per-subsystem timings"};
95 cvar_t r_fullbright = {0, "r_fullbright","0", "makes map very bright and renders faster"};
97 cvar_t r_fakelight = {0, "r_fakelight","0", "render 'fake' lighting instead of real lightmaps"};
98 cvar_t r_fakelight_intensity = {0, "r_fakelight_intensity","0.75", "fakelight intensity modifier"};
99 #define FAKELIGHT_ENABLED (r_fakelight.integer >= 2 || (r_fakelight.integer && r_refdef.scene.worldmodel && !r_refdef.scene.worldmodel->lit))
101 cvar_t r_wateralpha = {CVAR_SAVE, "r_wateralpha","1", "opacity of water polygons"};
102 cvar_t r_dynamic = {CVAR_SAVE, "r_dynamic","1", "enables dynamic lights (rocket glow and such)"};
103 cvar_t r_fullbrights = {CVAR_SAVE, "r_fullbrights", "1", "enables glowing pixels in quake textures (changes need r_restart to take effect)"};
104 cvar_t r_shadows = {CVAR_SAVE, "r_shadows", "0", "casts fake stencil shadows from models onto the world (rtlights are unaffected by this); when set to 2, always cast the shadows in the direction set by r_shadows_throwdirection, otherwise use the model lighting."};
105 cvar_t r_shadows_darken = {CVAR_SAVE, "r_shadows_darken", "0.5", "how much shadowed areas will be darkened"};
106 cvar_t r_shadows_throwdistance = {CVAR_SAVE, "r_shadows_throwdistance", "500", "how far to cast shadows from models"};
107 cvar_t r_shadows_throwdirection = {CVAR_SAVE, "r_shadows_throwdirection", "0 0 -1", "override throwing direction for r_shadows 2"};
108 cvar_t r_shadows_drawafterrtlighting = {CVAR_SAVE, "r_shadows_drawafterrtlighting", "0", "draw fake shadows AFTER realtime lightning is drawn. May be useful for simulating fast sunlight on large outdoor maps with only one noshadow rtlight. The price is less realistic appearance of dynamic light shadows."};
109 cvar_t r_shadows_castfrombmodels = {CVAR_SAVE, "r_shadows_castfrombmodels", "0", "do cast shadows from bmodels"};
110 cvar_t r_shadows_focus = {CVAR_SAVE, "r_shadows_focus", "0 0 0", "offset the shadowed area focus"};
111 cvar_t r_shadows_shadowmapscale = {CVAR_SAVE, "r_shadows_shadowmapscale", "1", "increases shadowmap quality (multiply global shadowmap precision) for fake shadows. Needs shadowmapping ON."};
112 cvar_t r_q1bsp_skymasking = {0, "r_q1bsp_skymasking", "1", "allows sky polygons in quake1 maps to obscure other geometry"};
113 cvar_t r_polygonoffset_submodel_factor = {0, "r_polygonoffset_submodel_factor", "0", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
114 cvar_t r_polygonoffset_submodel_offset = {0, "r_polygonoffset_submodel_offset", "14", "biases depth values of world submodels such as doors, to prevent z-fighting artifacts in Quake maps"};
115 cvar_t r_polygonoffset_decals_factor = {0, "r_polygonoffset_decals_factor", "0", "biases depth values of decals to prevent z-fighting artifacts"};
116 cvar_t r_polygonoffset_decals_offset = {0, "r_polygonoffset_decals_offset", "-14", "biases depth values of decals to prevent z-fighting artifacts"};
117 cvar_t r_fog_exp2 = {0, "r_fog_exp2", "0", "uses GL_EXP2 fog (as in Nehahra) rather than realistic GL_EXP fog"};
118 cvar_t r_drawfog = {CVAR_SAVE, "r_drawfog", "1", "allows one to disable fog rendering"};
119 cvar_t r_transparentdepthmasking = {CVAR_SAVE, "r_transparentdepthmasking", "0", "enables depth writes on transparent meshes whose materially is normally opaque, this prevents seeing the inside of a transparent mesh"};
121 cvar_t gl_fogenable = {0, "gl_fogenable", "0", "nehahra fog enable (for Nehahra compatibility only)"};
122 cvar_t gl_fogdensity = {0, "gl_fogdensity", "0.25", "nehahra fog density (recommend values below 0.1) (for Nehahra compatibility only)"};
123 cvar_t gl_fogred = {0, "gl_fogred","0.3", "nehahra fog color red value (for Nehahra compatibility only)"};
124 cvar_t gl_foggreen = {0, "gl_foggreen","0.3", "nehahra fog color green value (for Nehahra compatibility only)"};
125 cvar_t gl_fogblue = {0, "gl_fogblue","0.3", "nehahra fog color blue value (for Nehahra compatibility only)"};
126 cvar_t gl_fogstart = {0, "gl_fogstart", "0", "nehahra fog start distance (for Nehahra compatibility only)"};
127 cvar_t gl_fogend = {0, "gl_fogend","0", "nehahra fog end distance (for Nehahra compatibility only)"};
128 cvar_t gl_skyclip = {0, "gl_skyclip", "4608", "nehahra farclip distance - the real fog end (for Nehahra compatibility only)"};
130 cvar_t r_texture_dds_load = {CVAR_SAVE, "r_texture_dds_load", "0", "load compressed dds/filename.dds texture instead of filename.tga, if the file exists (requires driver support)"};
131 cvar_t r_texture_dds_save = {CVAR_SAVE, "r_texture_dds_save", "0", "save compressed dds/filename.dds texture when filename.tga is loaded, so that it can be loaded instead next time"};
133 cvar_t r_texture_convertsRGB_2d = {0, "r_texture_convertsRGB_2d", "0", "load textures as sRGB and convert to linear for proper shading"};
134 cvar_t r_texture_convertsRGB_skin = {0, "r_texture_convertsRGB_skin", "0", "load textures as sRGB and convert to linear for proper shading"};
135 cvar_t r_texture_convertsRGB_cubemap = {0, "r_texture_convertsRGB_cubemap", "0", "load textures as sRGB and convert to linear for proper shading"};
136 cvar_t r_texture_convertsRGB_skybox = {0, "r_texture_convertsRGB_skybox", "0", "load textures as sRGB and convert to linear for proper shading"};
137 cvar_t r_texture_convertsRGB_particles = {0, "r_texture_convertsRGB_particles", "0", "load textures as sRGB and convert to linear for proper shading"};
139 cvar_t r_textureunits = {0, "r_textureunits", "32", "number of texture units to use in GL 1.1 and GL 1.3 rendering paths"};
140 static cvar_t gl_combine = {CVAR_READONLY, "gl_combine", "1", "indicates whether the OpenGL 1.3 rendering path is active"};
141 static cvar_t r_glsl = {CVAR_READONLY, "r_glsl", "1", "indicates whether the OpenGL 2.0 rendering path is active"};
143 cvar_t r_glsl_deluxemapping = {CVAR_SAVE, "r_glsl_deluxemapping", "1", "use per pixel lighting on deluxemap-compiled q3bsp maps (or a value of 2 forces deluxemap shading even without deluxemaps)"};
144 cvar_t r_glsl_offsetmapping = {CVAR_SAVE, "r_glsl_offsetmapping", "0", "offset mapping effect (also known as parallax mapping or virtual displacement mapping)"};
145 cvar_t r_glsl_offsetmapping_reliefmapping = {CVAR_SAVE, "r_glsl_offsetmapping_reliefmapping", "0", "relief mapping effect (higher quality)"};
146 cvar_t r_glsl_offsetmapping_scale = {CVAR_SAVE, "r_glsl_offsetmapping_scale", "0.04", "how deep the offset mapping effect is"};
147 cvar_t r_glsl_postprocess = {CVAR_SAVE, "r_glsl_postprocess", "0", "use a GLSL postprocessing shader"};
148 cvar_t r_glsl_postprocess_uservec1 = {CVAR_SAVE, "r_glsl_postprocess_uservec1", "0 0 0 0", "a 4-component vector to pass as uservec1 to the postprocessing shader (only useful if default.glsl has been customized)"};
149 cvar_t r_glsl_postprocess_uservec2 = {CVAR_SAVE, "r_glsl_postprocess_uservec2", "0 0 0 0", "a 4-component vector to pass as uservec2 to the postprocessing shader (only useful if default.glsl has been customized)"};
150 cvar_t r_glsl_postprocess_uservec3 = {CVAR_SAVE, "r_glsl_postprocess_uservec3", "0 0 0 0", "a 4-component vector to pass as uservec3 to the postprocessing shader (only useful if default.glsl has been customized)"};
151 cvar_t r_glsl_postprocess_uservec4 = {CVAR_SAVE, "r_glsl_postprocess_uservec4", "0 0 0 0", "a 4-component vector to pass as uservec4 to the postprocessing shader (only useful if default.glsl has been customized)"};
152 cvar_t r_glsl_postprocess_uservec1_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec1_enable", "1", "enables postprocessing uservec1 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
153 cvar_t r_glsl_postprocess_uservec2_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec2_enable", "1", "enables postprocessing uservec2 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
154 cvar_t r_glsl_postprocess_uservec3_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec3_enable", "1", "enables postprocessing uservec3 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
155 cvar_t r_glsl_postprocess_uservec4_enable = {CVAR_SAVE, "r_glsl_postprocess_uservec4_enable", "1", "enables postprocessing uservec4 usage, creates USERVEC1 define (only useful if default.glsl has been customized)"};
157 cvar_t r_water = {CVAR_SAVE, "r_water", "0", "whether to use reflections and refraction on water surfaces (note: r_wateralpha must be set below 1)"};
158 cvar_t r_water_clippingplanebias = {CVAR_SAVE, "r_water_clippingplanebias", "1", "a rather technical setting which avoids black pixels around water edges"};
159 cvar_t r_water_resolutionmultiplier = {CVAR_SAVE, "r_water_resolutionmultiplier", "0.5", "multiplier for screen resolution when rendering refracted/reflected scenes, 1 is full quality, lower values are faster"};
160 cvar_t r_water_refractdistort = {CVAR_SAVE, "r_water_refractdistort", "0.01", "how much water refractions shimmer"};
161 cvar_t r_water_reflectdistort = {CVAR_SAVE, "r_water_reflectdistort", "0.01", "how much water reflections shimmer"};
162 cvar_t r_water_scissormode = {0, "r_water_scissormode", "3", "scissor (1) or cull (2) or both (3) water renders"};
164 cvar_t r_lerpsprites = {CVAR_SAVE, "r_lerpsprites", "0", "enables animation smoothing on sprites"};
165 cvar_t r_lerpmodels = {CVAR_SAVE, "r_lerpmodels", "1", "enables animation smoothing on models"};
166 cvar_t r_lerplightstyles = {CVAR_SAVE, "r_lerplightstyles", "0", "enable animation smoothing on flickering lights"};
167 cvar_t r_waterscroll = {CVAR_SAVE, "r_waterscroll", "1", "makes water scroll around, value controls how much"};
169 cvar_t r_bloom = {CVAR_SAVE, "r_bloom", "0", "enables bloom effect (makes bright pixels affect neighboring pixels)"};
170 cvar_t r_bloom_colorscale = {CVAR_SAVE, "r_bloom_colorscale", "1", "how bright the glow is"};
171 cvar_t r_bloom_brighten = {CVAR_SAVE, "r_bloom_brighten", "2", "how bright the glow is, after subtract/power"};
172 cvar_t r_bloom_blur = {CVAR_SAVE, "r_bloom_blur", "4", "how large the glow is"};
173 cvar_t r_bloom_resolution = {CVAR_SAVE, "r_bloom_resolution", "320", "what resolution to perform the bloom effect at (independent of screen resolution)"};
174 cvar_t r_bloom_colorexponent = {CVAR_SAVE, "r_bloom_colorexponent", "1", "how exaggerated the glow is"};
175 cvar_t r_bloom_colorsubtract = {CVAR_SAVE, "r_bloom_colorsubtract", "0.125", "reduces bloom colors by a certain amount"};
177 cvar_t r_hdr = {CVAR_SAVE, "r_hdr", "0", "enables High Dynamic Range bloom effect (higher quality version of r_bloom)"};
178 cvar_t r_hdr_scenebrightness = {CVAR_SAVE, "r_hdr_scenebrightness", "1", "global rendering brightness"};
179 cvar_t r_hdr_glowintensity = {CVAR_SAVE, "r_hdr_glowintensity", "1", "how bright light emitting textures should appear"};
180 cvar_t r_hdr_range = {CVAR_SAVE, "r_hdr_range", "4", "how much dynamic range to render bloom with (equivalent to multiplying r_bloom_brighten by this value and dividing r_bloom_colorscale by this value)"};
181 cvar_t r_hdr_irisadaptation = {CVAR_SAVE, "r_hdr_irisadaptation", "0", "adjust scene brightness according to light intensity at player location"};
182 cvar_t r_hdr_irisadaptation_multiplier = {CVAR_SAVE, "r_hdr_irisadaptation_multiplier", "2", "brightness at which value will be 1.0"};
183 cvar_t r_hdr_irisadaptation_minvalue = {CVAR_SAVE, "r_hdr_irisadaptation_minvalue", "0.5", "minimum value that can result from multiplier / brightness"};
184 cvar_t r_hdr_irisadaptation_maxvalue = {CVAR_SAVE, "r_hdr_irisadaptation_maxvalue", "4", "maximum value that can result from multiplier / brightness"};
185 cvar_t r_hdr_irisadaptation_value = {0, "r_hdr_irisadaptation_value", "1", "current value as scenebrightness multiplier, changes continuously when irisadaptation is active"};
186 cvar_t r_hdr_irisadaptation_fade = {CVAR_SAVE, "r_hdr_irisadaptation_fade", "1", "fade rate at which value adjusts"};
188 cvar_t r_smoothnormals_areaweighting = {0, "r_smoothnormals_areaweighting", "1", "uses significantly faster (and supposedly higher quality) area-weighted vertex normals and tangent vectors rather than summing normalized triangle normals and tangents"};
190 cvar_t developer_texturelogging = {0, "developer_texturelogging", "0", "produces a textures.log file containing names of skins and map textures the engine tried to load"};
192 cvar_t gl_lightmaps = {0, "gl_lightmaps", "0", "draws only lightmaps, no texture (for level designers)"};
194 cvar_t r_test = {0, "r_test", "0", "internal development use only, leave it alone (usually does nothing anyway)"};
195 cvar_t r_track_sprites = {CVAR_SAVE, "r_track_sprites", "1", "track SPR_LABEL* sprites by putting them as indicator at the screen border to rotate to"};
196 cvar_t r_track_sprites_flags = {CVAR_SAVE, "r_track_sprites_flags", "1", "1: Rotate sprites accordingly, 2: Make it a continuous rotation"};
197 cvar_t r_track_sprites_scalew = {CVAR_SAVE, "r_track_sprites_scalew", "1", "width scaling of tracked sprites"};
198 cvar_t r_track_sprites_scaleh = {CVAR_SAVE, "r_track_sprites_scaleh", "1", "height scaling of tracked sprites"};
199 cvar_t r_overheadsprites_perspective = {CVAR_SAVE, "r_overheadsprites_perspective", "5", "fake perspective effect for SPR_OVERHEAD sprites"};
200 cvar_t r_overheadsprites_pushback = {CVAR_SAVE, "r_overheadsprites_pushback", "15", "how far to pull the SPR_OVERHEAD sprites toward the eye (used to avoid intersections with 3D models)"};
201 cvar_t r_overheadsprites_scalex = {CVAR_SAVE, "r_overheadsprites_scalex", "1", "additional scale for overhead sprites for x axis"};
202 cvar_t r_overheadsprites_scaley = {CVAR_SAVE, "r_overheadsprites_scaley", "1", "additional scale for overhead sprites for y axis"};
204 cvar_t r_glsl_saturation = {CVAR_SAVE, "r_glsl_saturation", "1", "saturation multiplier (only working in glsl!)"};
205 cvar_t r_glsl_saturation_redcompensate = {CVAR_SAVE, "r_glsl_saturation_redcompensate", "0", "a 'vampire sight' addition to desaturation effect, does compensation for red color, r_glsl_restart is required"};
207 cvar_t r_framedatasize = {CVAR_SAVE, "r_framedatasize", "0.5", "size of renderer data cache used during one frame (for skeletal animation caching, light processing, etc)"};
209 extern cvar_t v_glslgamma;
211 extern qboolean v_flipped_state;
213 static struct r_bloomstate_s
218 int bloomwidth, bloomheight;
220 int screentexturewidth, screentextureheight;
221 rtexture_t *texture_screen; /// \note also used for motion blur if enabled!
223 int bloomtexturewidth, bloomtextureheight;
224 rtexture_t *texture_bloom;
226 // arrays for rendering the screen passes
227 float screentexcoord2f[8];
228 float bloomtexcoord2f[8];
229 float offsettexcoord2f[8];
231 r_viewport_t viewport;
235 r_waterstate_t r_waterstate;
237 /// shadow volume bsp struct with automatically growing nodes buffer
240 rtexture_t *r_texture_blanknormalmap;
241 rtexture_t *r_texture_white;
242 rtexture_t *r_texture_grey128;
243 rtexture_t *r_texture_black;
244 rtexture_t *r_texture_notexture;
245 rtexture_t *r_texture_whitecube;
246 rtexture_t *r_texture_normalizationcube;
247 rtexture_t *r_texture_fogattenuation;
248 rtexture_t *r_texture_fogheighttexture;
249 rtexture_t *r_texture_gammaramps;
250 unsigned int r_texture_gammaramps_serial;
251 //rtexture_t *r_texture_fogintensity;
252 rtexture_t *r_texture_reflectcube;
254 // TODO: hash lookups?
255 typedef struct cubemapinfo_s
262 int r_texture_numcubemaps;
263 cubemapinfo_t r_texture_cubemaps[MAX_CUBEMAPS];
265 unsigned int r_queries[MAX_OCCLUSION_QUERIES];
266 unsigned int r_numqueries;
267 unsigned int r_maxqueries;
269 typedef struct r_qwskincache_s
271 char name[MAX_QPATH];
272 skinframe_t *skinframe;
276 static r_qwskincache_t *r_qwskincache;
277 static int r_qwskincache_size;
279 /// vertex coordinates for a quad that covers the screen exactly
280 extern const float r_screenvertex3f[12];
281 extern const float r_d3dscreenvertex3f[12];
282 const float r_screenvertex3f[12] =
289 const float r_d3dscreenvertex3f[12] =
297 void R_ModulateColors(float *in, float *out, int verts, float r, float g, float b)
300 for (i = 0;i < verts;i++)
311 void R_FillColors(float *out, int verts, float r, float g, float b, float a)
314 for (i = 0;i < verts;i++)
324 // FIXME: move this to client?
327 if (gamemode == GAME_NEHAHRA)
329 Cvar_Set("gl_fogenable", "0");
330 Cvar_Set("gl_fogdensity", "0.2");
331 Cvar_Set("gl_fogred", "0.3");
332 Cvar_Set("gl_foggreen", "0.3");
333 Cvar_Set("gl_fogblue", "0.3");
335 r_refdef.fog_density = 0;
336 r_refdef.fog_red = 0;
337 r_refdef.fog_green = 0;
338 r_refdef.fog_blue = 0;
339 r_refdef.fog_alpha = 1;
340 r_refdef.fog_start = 0;
341 r_refdef.fog_end = 16384;
342 r_refdef.fog_height = 1<<30;
343 r_refdef.fog_fadedepth = 128;
344 memset(r_refdef.fog_height_texturename, 0, sizeof(r_refdef.fog_height_texturename));
347 static void R_BuildBlankTextures(void)
349 unsigned char data[4];
350 data[2] = 128; // normal X
351 data[1] = 128; // normal Y
352 data[0] = 255; // normal Z
353 data[3] = 128; // height
354 r_texture_blanknormalmap = R_LoadTexture2D(r_main_texturepool, "blankbump", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
359 r_texture_white = R_LoadTexture2D(r_main_texturepool, "blankwhite", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
364 r_texture_grey128 = R_LoadTexture2D(r_main_texturepool, "blankgrey128", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
369 r_texture_black = R_LoadTexture2D(r_main_texturepool, "blankblack", 1, 1, data, TEXTYPE_BGRA, TEXF_PERSISTENT, -1, NULL);
372 static void R_BuildNoTexture(void)
375 unsigned char pix[16][16][4];
376 // this makes a light grey/dark grey checkerboard texture
377 for (y = 0;y < 16;y++)
379 for (x = 0;x < 16;x++)
381 if ((y < 8) ^ (x < 8))
397 r_texture_notexture = R_LoadTexture2D(r_main_texturepool, "notexture", 16, 16, &pix[0][0][0], TEXTYPE_BGRA, TEXF_MIPMAP | TEXF_PERSISTENT, -1, NULL);
400 static void R_BuildWhiteCube(void)
402 unsigned char data[6*1*1*4];
403 memset(data, 255, sizeof(data));
404 r_texture_whitecube = R_LoadTextureCubeMap(r_main_texturepool, "whitecube", 1, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
407 static void R_BuildNormalizationCube(void)
411 vec_t s, t, intensity;
414 data = (unsigned char *)Mem_Alloc(tempmempool, 6*NORMSIZE*NORMSIZE*4);
415 for (side = 0;side < 6;side++)
417 for (y = 0;y < NORMSIZE;y++)
419 for (x = 0;x < NORMSIZE;x++)
421 s = (x + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
422 t = (y + 0.5f) * (2.0f / NORMSIZE) - 1.0f;
457 intensity = 127.0f / sqrt(DotProduct(v, v));
458 data[((side*64+y)*64+x)*4+2] = (unsigned char)(128.0f + intensity * v[0]);
459 data[((side*64+y)*64+x)*4+1] = (unsigned char)(128.0f + intensity * v[1]);
460 data[((side*64+y)*64+x)*4+0] = (unsigned char)(128.0f + intensity * v[2]);
461 data[((side*64+y)*64+x)*4+3] = 255;
465 r_texture_normalizationcube = R_LoadTextureCubeMap(r_main_texturepool, "normalcube", NORMSIZE, data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
469 static void R_BuildFogTexture(void)
473 unsigned char data1[FOGWIDTH][4];
474 //unsigned char data2[FOGWIDTH][4];
477 r_refdef.fogmasktable_start = r_refdef.fog_start;
478 r_refdef.fogmasktable_alpha = r_refdef.fog_alpha;
479 r_refdef.fogmasktable_range = r_refdef.fogrange;
480 r_refdef.fogmasktable_density = r_refdef.fog_density;
482 r = r_refdef.fogmasktable_range / FOGMASKTABLEWIDTH;
483 for (x = 0;x < FOGMASKTABLEWIDTH;x++)
485 d = (x * r - r_refdef.fogmasktable_start);
486 if(developer_extra.integer)
487 Con_DPrintf("%f ", d);
489 if (r_fog_exp2.integer)
490 alpha = exp(-r_refdef.fogmasktable_density * r_refdef.fogmasktable_density * 0.0001 * d * d);
492 alpha = exp(-r_refdef.fogmasktable_density * 0.004 * d);
493 if(developer_extra.integer)
494 Con_DPrintf(" : %f ", alpha);
495 alpha = 1 - (1 - alpha) * r_refdef.fogmasktable_alpha;
496 if(developer_extra.integer)
497 Con_DPrintf(" = %f\n", alpha);
498 r_refdef.fogmasktable[x] = bound(0, alpha, 1);
501 for (x = 0;x < FOGWIDTH;x++)
503 b = (int)(r_refdef.fogmasktable[x * (FOGMASKTABLEWIDTH - 1) / (FOGWIDTH - 1)] * 255);
508 //data2[x][0] = 255 - b;
509 //data2[x][1] = 255 - b;
510 //data2[x][2] = 255 - b;
513 if (r_texture_fogattenuation)
515 R_UpdateTexture(r_texture_fogattenuation, &data1[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
516 //R_UpdateTexture(r_texture_fogattenuation, &data2[0][0], 0, 0, 0, FOGWIDTH, 1, 1);
520 r_texture_fogattenuation = R_LoadTexture2D(r_main_texturepool, "fogattenuation", FOGWIDTH, 1, &data1[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
521 //r_texture_fogintensity = R_LoadTexture2D(r_main_texturepool, "fogintensity", FOGWIDTH, 1, &data2[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP, NULL);
525 static void R_BuildFogHeightTexture(void)
527 unsigned char *inpixels;
535 strlcpy(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename, sizeof(r_refdef.fogheighttexturename));
536 if (r_refdef.fogheighttexturename[0])
537 inpixels = loadimagepixelsbgra(r_refdef.fogheighttexturename, true, false, false, NULL);
540 r_refdef.fog_height_tablesize = 0;
541 if (r_texture_fogheighttexture)
542 R_FreeTexture(r_texture_fogheighttexture);
543 r_texture_fogheighttexture = NULL;
544 if (r_refdef.fog_height_table2d)
545 Mem_Free(r_refdef.fog_height_table2d);
546 r_refdef.fog_height_table2d = NULL;
547 if (r_refdef.fog_height_table1d)
548 Mem_Free(r_refdef.fog_height_table1d);
549 r_refdef.fog_height_table1d = NULL;
553 r_refdef.fog_height_tablesize = size;
554 r_refdef.fog_height_table1d = (unsigned char *)Mem_Alloc(r_main_mempool, size * 4);
555 r_refdef.fog_height_table2d = (unsigned char *)Mem_Alloc(r_main_mempool, size * size * 4);
556 memcpy(r_refdef.fog_height_table1d, inpixels, size * 4);
558 // LordHavoc: now the magic - what is that table2d for? it is a cooked
559 // average fog color table accounting for every fog layer between a point
560 // and the camera. (Note: attenuation is handled separately!)
561 for (y = 0;y < size;y++)
563 for (x = 0;x < size;x++)
569 for (j = x;j <= y;j++)
571 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
577 for (j = x;j >= y;j--)
579 Vector4Add(c, r_refdef.fog_height_table1d + j*4, c);
584 r_refdef.fog_height_table2d[(y*size+x)*4+0] = (unsigned char)(c[0] * f);
585 r_refdef.fog_height_table2d[(y*size+x)*4+1] = (unsigned char)(c[1] * f);
586 r_refdef.fog_height_table2d[(y*size+x)*4+2] = (unsigned char)(c[2] * f);
587 r_refdef.fog_height_table2d[(y*size+x)*4+3] = (unsigned char)(c[3] * f);
590 r_texture_fogheighttexture = R_LoadTexture2D(r_main_texturepool, "fogheighttable", size, size, r_refdef.fog_height_table2d, TEXTYPE_BGRA, TEXF_ALPHA | TEXF_CLAMP, -1, NULL);
593 //=======================================================================================================================================================
595 static const char *builtinshaderstring =
596 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
597 "// written by Forest 'LordHavoc' Hale\n"
598 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
600 "// GL ES shaders use precision modifiers, standard GL does not\n"
607 "#ifdef VERTEX_SHADER\n"
608 "attribute vec4 Attrib_Position; // vertex\n"
609 "attribute vec4 Attrib_Color; // color\n"
610 "attribute vec4 Attrib_TexCoord0; // material texcoords\n"
611 "attribute vec3 Attrib_TexCoord1; // svector\n"
612 "attribute vec3 Attrib_TexCoord2; // tvector\n"
613 "attribute vec3 Attrib_TexCoord3; // normal\n"
614 "attribute vec4 Attrib_TexCoord4; // lightmap texcoords\n"
616 "varying lowp vec4 VertexColor;\n"
618 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
621 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
622 "#define USELIGHTMAP\n"
624 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
625 "#define USEEYEVECTOR\n"
628 "#ifdef USESHADOWMAP2D\n"
629 "# ifdef GL_EXT_gpu_shader4\n"
630 "# extension GL_EXT_gpu_shader4 : enable\n"
632 "# ifdef GL_ARB_texture_gather\n"
633 "# extension GL_ARB_texture_gather : enable\n"
635 "# ifdef GL_AMD_texture_texture4\n"
636 "# extension GL_AMD_texture_texture4 : enable\n"
641 "//#ifdef USESHADOWSAMPLER\n"
642 "//# extension GL_ARB_shadow : enable\n"
645 "//#ifdef __GLSL_CG_DATA_TYPES\n"
646 "//# define myhalf half\n"
647 "//# define myhalf2 half2\n"
648 "//# define myhalf3 half3\n"
649 "//# define myhalf4 half4\n"
651 "# define myhalf mediump float\n"
652 "# define myhalf2 mediump vec2\n"
653 "# define myhalf3 mediump vec3\n"
654 "# define myhalf4 mediump vec4\n"
657 "#ifdef VERTEX_SHADER\n"
658 "uniform highp mat4 ModelViewProjectionMatrix;\n"
661 "#ifdef MODE_DEPTH_OR_SHADOW\n"
662 "#ifdef VERTEX_SHADER\n"
665 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
668 "#else // !MODE_DEPTH_ORSHADOW\n"
673 "#ifdef MODE_SHOWDEPTH\n"
674 "#ifdef VERTEX_SHADER\n"
677 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
678 " VertexColor = vec4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
682 "#ifdef FRAGMENT_SHADER\n"
685 " gl_FragColor = VertexColor;\n"
688 "#else // !MODE_SHOWDEPTH\n"
693 "#ifdef MODE_POSTPROCESS\n"
694 "varying mediump vec2 TexCoord1;\n"
695 "varying mediump vec2 TexCoord2;\n"
697 "#ifdef VERTEX_SHADER\n"
700 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
701 " TexCoord1 = Attrib_TexCoord0.xy;\n"
703 " TexCoord2 = Attrib_TexCoord4.xy;\n"
708 "#ifdef FRAGMENT_SHADER\n"
709 "uniform sampler2D Texture_First;\n"
711 "uniform sampler2D Texture_Second;\n"
712 "uniform lowp vec4 BloomColorSubtract;\n"
714 "#ifdef USEGAMMARAMPS\n"
715 "uniform sampler2D Texture_GammaRamps;\n"
717 "#ifdef USESATURATION\n"
718 "uniform lowp float Saturation;\n"
720 "#ifdef USEVIEWTINT\n"
721 "uniform lowp vec4 ViewTintColor;\n"
723 "//uncomment these if you want to use them:\n"
724 "uniform mediump vec4 UserVec1;\n"
725 "uniform mediump vec4 UserVec2;\n"
726 "// uniform mediump vec4 UserVec3;\n"
727 "// uniform mediump vec4 UserVec4;\n"
728 "// uniform highp float ClientTime;\n"
729 "uniform mediump vec2 PixelSize;\n"
732 " gl_FragColor = texture2D(Texture_First, TexCoord1);\n"
734 " gl_FragColor += max(vec4(0,0,0,0), texture2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
736 "#ifdef USEVIEWTINT\n"
737 " gl_FragColor = mix(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
740 "#ifdef USEPOSTPROCESSING\n"
741 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
742 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
743 " float sobel = 1.0;\n"
744 " // vec2 ts = textureSize(Texture_First, 0);\n"
745 " // vec2 px = vec2(1/ts.x, 1/ts.y);\n"
746 " vec2 px = PixelSize;\n"
747 " vec3 x1 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
748 " vec3 x2 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, 0.0)).rgb;\n"
749 " vec3 x3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
750 " vec3 x4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
751 " vec3 x5 = texture2D(Texture_First, TexCoord1 + vec2( px.x, 0.0)).rgb;\n"
752 " vec3 x6 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
753 " vec3 y1 = texture2D(Texture_First, TexCoord1 + vec2( px.x,-px.y)).rgb;\n"
754 " vec3 y2 = texture2D(Texture_First, TexCoord1 + vec2( 0.0,-px.y)).rgb;\n"
755 " vec3 y3 = texture2D(Texture_First, TexCoord1 + vec2(-px.x,-px.y)).rgb;\n"
756 " vec3 y4 = texture2D(Texture_First, TexCoord1 + vec2( px.x, px.y)).rgb;\n"
757 " vec3 y5 = texture2D(Texture_First, TexCoord1 + vec2( 0.0, px.y)).rgb;\n"
758 " vec3 y6 = texture2D(Texture_First, TexCoord1 + vec2(-px.x, px.y)).rgb;\n"
759 " float px1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x1);\n"
760 " float px2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), x2);\n"
761 " float px3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), x3);\n"
762 " float px4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x4);\n"
763 " float px5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), x5);\n"
764 " float px6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), x6);\n"
765 " float py1 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y1);\n"
766 " float py2 = -2.0 * dot(vec3(0.3, 0.59, 0.11), y2);\n"
767 " float py3 = -1.0 * dot(vec3(0.3, 0.59, 0.11), y3);\n"
768 " float py4 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y4);\n"
769 " float py5 = 2.0 * dot(vec3(0.3, 0.59, 0.11), y5);\n"
770 " float py6 = 1.0 * dot(vec3(0.3, 0.59, 0.11), y6);\n"
771 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
772 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.987688, -0.156434)) * UserVec1.y;\n"
773 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.156434, -0.891007)) * UserVec1.y;\n"
774 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.891007, -0.453990)) * UserVec1.y;\n"
775 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2( 0.707107, 0.707107)) * UserVec1.y;\n"
776 " gl_FragColor += texture2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*vec2(-0.453990, 0.891007)) * UserVec1.y;\n"
777 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
778 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + vec3(max(0.0, sobel - UserVec2.z))*UserVec2.y;\n"
781 "#ifdef USESATURATION\n"
782 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
783 " float y = dot(gl_FragColor.rgb, vec3(0.299, 0.587, 0.114));\n"
784 " // 'vampire sight' effect, wheres red is compensated\n"
785 " #ifdef SATURATION_REDCOMPENSATE\n"
786 " float rboost = max(0.0, (gl_FragColor.r - max(gl_FragColor.g, gl_FragColor.b))*(1.0 - Saturation));\n"
787 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
788 " gl_FragColor.r += rboost;\n"
790 " // normal desaturation\n"
791 " //gl_FragColor = vec3(y) + (gl_FragColor.rgb - vec3(y)) * Saturation;\n"
792 " gl_FragColor.rgb = mix(vec3(y), gl_FragColor.rgb, Saturation);\n"
796 "#ifdef USEGAMMARAMPS\n"
797 " gl_FragColor.r = texture2D(Texture_GammaRamps, vec2(gl_FragColor.r, 0)).r;\n"
798 " gl_FragColor.g = texture2D(Texture_GammaRamps, vec2(gl_FragColor.g, 0)).g;\n"
799 " gl_FragColor.b = texture2D(Texture_GammaRamps, vec2(gl_FragColor.b, 0)).b;\n"
803 "#else // !MODE_POSTPROCESS\n"
808 "#ifdef MODE_GENERIC\n"
809 "#ifdef USEDIFFUSE\n"
810 "varying mediump vec2 TexCoord1;\n"
812 "#ifdef USESPECULAR\n"
813 "varying mediump vec2 TexCoord2;\n"
815 "#ifdef VERTEX_SHADER\n"
818 " VertexColor = Attrib_Color;\n"
819 "#ifdef USEDIFFUSE\n"
820 " TexCoord1 = Attrib_TexCoord0.xy;\n"
822 "#ifdef USESPECULAR\n"
823 " TexCoord2 = Attrib_TexCoord1.xy;\n"
825 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
829 "#ifdef FRAGMENT_SHADER\n"
830 "#ifdef USEDIFFUSE\n"
831 "uniform sampler2D Texture_First;\n"
833 "#ifdef USESPECULAR\n"
834 "uniform sampler2D Texture_Second;\n"
839 "#ifdef USEVIEWTINT\n"
840 " gl_FragColor = VertexColor;\n"
842 " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
844 "#ifdef USEDIFFUSE\n"
845 " gl_FragColor *= texture2D(Texture_First, TexCoord1);\n"
848 "#ifdef USESPECULAR\n"
849 " vec4 tex2 = texture2D(Texture_Second, TexCoord2);\n"
850 "# ifdef USECOLORMAPPING\n"
851 " gl_FragColor *= tex2;\n"
854 " gl_FragColor += tex2;\n"
856 "# ifdef USEVERTEXTEXTUREBLEND\n"
857 " gl_FragColor = mix(gl_FragColor, tex2, tex2.a);\n"
862 "#else // !MODE_GENERIC\n"
867 "#ifdef MODE_BLOOMBLUR\n"
868 "varying mediump vec2 TexCoord;\n"
869 "#ifdef VERTEX_SHADER\n"
872 " VertexColor = Attrib_Color;\n"
873 " TexCoord = Attrib_TexCoord0.xy;\n"
874 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
878 "#ifdef FRAGMENT_SHADER\n"
879 "uniform sampler2D Texture_First;\n"
880 "uniform mediump vec4 BloomBlur_Parameters;\n"
885 " vec2 tc = TexCoord;\n"
886 " vec3 color = texture2D(Texture_First, tc).rgb;\n"
887 " tc += BloomBlur_Parameters.xy;\n"
888 " for (i = 1;i < SAMPLES;i++)\n"
890 " color += texture2D(Texture_First, tc).rgb;\n"
891 " tc += BloomBlur_Parameters.xy;\n"
893 " gl_FragColor = vec4(color * BloomBlur_Parameters.z + vec3(BloomBlur_Parameters.w), 1);\n"
896 "#else // !MODE_BLOOMBLUR\n"
897 "#ifdef MODE_REFRACTION\n"
898 "varying mediump vec2 TexCoord;\n"
899 "varying highp vec4 ModelViewProjectionPosition;\n"
900 "uniform highp mat4 TexMatrix;\n"
901 "#ifdef VERTEX_SHADER\n"
905 " TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
906 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
907 " ModelViewProjectionPosition = gl_Position;\n"
911 "#ifdef FRAGMENT_SHADER\n"
912 "uniform sampler2D Texture_Normal;\n"
913 "uniform sampler2D Texture_Refraction;\n"
914 "uniform sampler2D Texture_Reflection;\n"
916 "uniform mediump vec4 DistortScaleRefractReflect;\n"
917 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
918 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
919 "uniform lowp vec4 RefractColor;\n"
920 "uniform lowp vec4 ReflectColor;\n"
921 "uniform mediump float ReflectFactor;\n"
922 "uniform mediump float ReflectOffset;\n"
926 " vec2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
927 " //vec2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
928 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
929 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xy * DistortScaleRefractReflect.xy;\n"
930 " // FIXME temporary hack to detect the case that the reflection\n"
931 " // gets blackened at edges due to leaving the area that contains actual\n"
933 " // Remove this 'ack once we have a better way to stop this thing from\n"
935 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
936 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
937 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
938 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
939 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
940 " gl_FragColor = vec4(texture2D(Texture_Refraction, ScreenTexCoord).rgb, 1.0) * RefractColor;\n"
943 "#else // !MODE_REFRACTION\n"
948 "#ifdef MODE_WATER\n"
949 "varying mediump vec2 TexCoord;\n"
950 "varying highp vec3 EyeVector;\n"
951 "varying highp vec4 ModelViewProjectionPosition;\n"
952 "#ifdef VERTEX_SHADER\n"
953 "uniform highp vec3 EyePosition;\n"
954 "uniform highp mat4 TexMatrix;\n"
958 " TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
959 " vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
960 " EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
961 " EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
962 " EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
963 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
964 " ModelViewProjectionPosition = gl_Position;\n"
968 "#ifdef FRAGMENT_SHADER\n"
969 "uniform sampler2D Texture_Normal;\n"
970 "uniform sampler2D Texture_Refraction;\n"
971 "uniform sampler2D Texture_Reflection;\n"
973 "uniform mediump vec4 DistortScaleRefractReflect;\n"
974 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
975 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
976 "uniform lowp vec4 RefractColor;\n"
977 "uniform lowp vec4 ReflectColor;\n"
978 "uniform mediump float ReflectFactor;\n"
979 "uniform mediump float ReflectOffset;\n"
980 "uniform highp float ClientTime;\n"
981 "#ifdef USENORMALMAPSCROLLBLEND\n"
982 "uniform highp vec2 NormalmapScrollBlend;\n"
987 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
988 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
989 " vec4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
990 " //SafeScreenTexCoord = gl_FragCoord.xyxy * vec4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
991 " // slight water animation via 2 layer scrolling (todo: tweak)\n"
992 " #ifdef USENORMALMAPSCROLLBLEND\n"
993 " vec3 normal = texture2D(Texture_Normal, (TexCoord + vec2(0.08, 0.08)*ClientTime*NormalmapScrollBlend.x*0.5)*NormalmapScrollBlend.y).rgb - vec3(1.0);\n"
994 " normal += texture2D(Texture_Normal, (TexCoord + vec2(-0.06, -0.09)*ClientTime*NormalmapScrollBlend.x)*NormalmapScrollBlend.y*0.75).rgb;\n"
995 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(normal) + vec3(0.15)).xyxy * DistortScaleRefractReflect;\n"
997 " vec4 ScreenTexCoord = SafeScreenTexCoord + vec2(normalize(vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5))).xyxy * DistortScaleRefractReflect;\n"
999 " // FIXME temporary hack to detect the case that the reflection\n"
1000 " // gets blackened at edges due to leaving the area that contains actual\n"
1002 " // Remove this 'ack once we have a better way to stop this thing from\n"
1004 " float f = min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.005, 0.01)).rgb) / 0.002);\n"
1005 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(0.005, -0.01)).rgb) / 0.002);\n"
1006 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.005, 0.01)).rgb) / 0.002);\n"
1007 " f *= min(1.0, length(texture2D(Texture_Refraction, ScreenTexCoord.xy + vec2(-0.005, -0.01)).rgb) / 0.002);\n"
1008 " ScreenTexCoord.xy = mix(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
1009 " f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.005, 0.005)).rgb) / 0.002);\n"
1010 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(0.005, -0.005)).rgb) / 0.002);\n"
1011 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.005, 0.005)).rgb) / 0.002);\n"
1012 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord.zw + vec2(-0.005, -0.005)).rgb) / 0.002);\n"
1013 " ScreenTexCoord.zw = mix(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
1014 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
1015 " gl_FragColor = mix(vec4(texture2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, vec4(texture2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
1018 "#else // !MODE_WATER\n"
1023 "// common definitions between vertex shader and fragment shader:\n"
1025 "varying mediump vec2 TexCoord;\n"
1026 "#ifdef USEVERTEXTEXTUREBLEND\n"
1027 "varying mediump vec2 TexCoord2;\n"
1029 "#ifdef USELIGHTMAP\n"
1030 "varying mediump vec2 TexCoordLightmap;\n"
1033 "#ifdef MODE_LIGHTSOURCE\n"
1034 "varying mediump vec3 CubeVector;\n"
1037 "#if (defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)) && defined(USEDIFFUSE)\n"
1038 "varying mediump vec3 LightVector;\n"
1041 "#ifdef USEEYEVECTOR\n"
1042 "varying highp vec3 EyeVector;\n"
1045 "varying highp vec4 EyeVectorModelSpaceFogPlaneVertexDist;\n"
1048 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
1049 "varying lowp vec3 VectorS; // direction of S texcoord (sometimes crudely called tangent)\n"
1050 "varying lowp vec3 VectorT; // direction of T texcoord (sometimes crudely called binormal)\n"
1051 "varying lowp vec3 VectorR; // direction of R texcoord (surface normal)\n"
1054 "#ifdef USEREFLECTION\n"
1055 "varying highp vec4 ModelViewProjectionPosition;\n"
1057 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1058 "uniform highp vec3 LightPosition;\n"
1059 "varying highp vec4 ModelViewPosition;\n"
1061 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1062 "varying highp vec4 ModelViewPosition;\n"
1063 "varying highp vec4 LightOriginInvRadius;\n"
1064 "varying mediump vec4 LightColor;\n"
1067 "#ifdef MODE_LIGHTSOURCE\n"
1068 "uniform highp vec3 LightPosition;\n"
1070 "uniform highp vec3 EyePosition;\n"
1071 "#ifdef MODE_LIGHTDIRECTION\n"
1072 "uniform highp vec3 LightDir;\n"
1074 "uniform highp vec4 FogPlane;\n"
1076 "#ifdef USESHADOWMAPORTHO\n"
1077 "varying mediump vec3 ShadowMapTC;\n"
1080 "#ifdef USEBOUNCEGRID\n"
1081 "varying mediump vec3 BounceGridTexCoord;\n"
1089 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
1091 "// fragment shader specific:\n"
1092 "#ifdef FRAGMENT_SHADER\n"
1094 "uniform sampler2D Texture_Normal;\n"
1095 "uniform sampler2D Texture_Color;\n"
1096 "uniform sampler2D Texture_Gloss;\n"
1098 "uniform sampler2D Texture_Glow;\n"
1100 "#ifdef USEVERTEXTEXTUREBLEND\n"
1101 "uniform sampler2D Texture_SecondaryNormal;\n"
1102 "uniform sampler2D Texture_SecondaryColor;\n"
1103 "uniform sampler2D Texture_SecondaryGloss;\n"
1105 "uniform sampler2D Texture_SecondaryGlow;\n"
1108 "#ifdef USECOLORMAPPING\n"
1109 "uniform sampler2D Texture_Pants;\n"
1110 "uniform sampler2D Texture_Shirt;\n"
1113 "#ifdef USEFOGHEIGHTTEXTURE\n"
1114 "uniform sampler2D Texture_FogHeightTexture;\n"
1116 "uniform sampler2D Texture_FogMask;\n"
1118 "#ifdef USELIGHTMAP\n"
1119 "uniform sampler2D Texture_Lightmap;\n"
1121 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1122 "uniform sampler2D Texture_Deluxemap;\n"
1124 "#ifdef USEREFLECTION\n"
1125 "uniform sampler2D Texture_Reflection;\n"
1128 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1129 "uniform sampler2D Texture_ScreenDepth;\n"
1130 "uniform sampler2D Texture_ScreenNormalMap;\n"
1132 "#ifdef USEDEFERREDLIGHTMAP\n"
1133 "uniform sampler2D Texture_ScreenDiffuse;\n"
1134 "uniform sampler2D Texture_ScreenSpecular;\n"
1136 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1137 "uniform sampler2D Texture_ScreenDepth;\n"
1140 "uniform lowp vec3 Color_Pants;\n"
1141 "uniform lowp vec3 Color_Shirt;\n"
1142 "uniform lowp vec3 FogColor;\n"
1145 "uniform highp float FogRangeRecip;\n"
1146 "uniform highp float FogPlaneViewDist;\n"
1147 "uniform highp float FogHeightFade;\n"
1148 "vec3 FogVertex(vec3 surfacecolor)\n"
1150 " vec3 EyeVectorModelSpace = EyeVectorModelSpaceFogPlaneVertexDist.xyz;\n"
1151 " float FogPlaneVertexDist = EyeVectorModelSpaceFogPlaneVertexDist.w;\n"
1153 "#ifdef USEFOGHEIGHTTEXTURE\n"
1154 " vec4 fogheightpixel = texture2D(Texture_FogHeightTexture, vec2(1,1) + vec2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
1155 " fogfrac = fogheightpixel.a;\n"
1156 " return mix(fogheightpixel.rgb * FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1158 "# ifdef USEFOGOUTSIDE\n"
1159 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
1161 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
1163 " return mix(FogColor, surfacecolor, texture2D(Texture_FogMask, myhalf2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
1168 "#ifdef USEOFFSETMAPPING\n"
1169 "uniform mediump float OffsetMapping_Scale;\n"
1170 "vec2 OffsetMapping(vec2 TexCoord)\n"
1172 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
1173 " // 14 sample relief mapping: linear search and then binary search\n"
1174 " // this basically steps forward a small amount repeatedly until it finds\n"
1175 " // itself inside solid, then jitters forward and back using decreasing\n"
1176 " // amounts to find the impact\n"
1177 " //vec3 OffsetVector = vec3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1), -1);\n"
1178 " //vec3 OffsetVector = vec3(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1179 " vec3 OffsetVector = vec3(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1), -1);\n"
1180 " vec3 RT = vec3(TexCoord, 1);\n"
1181 " OffsetVector *= 0.1;\n"
1182 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1183 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1184 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1185 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1186 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1187 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1188 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1189 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1190 " RT += OffsetVector * step(texture2D(Texture_Normal, RT.xy).a, RT.z);\n"
1191 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
1192 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
1193 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
1194 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
1195 " RT += OffsetVector * (step(texture2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
1198 " // 2 sample offset mapping (only 2 samples because of ATI Radeon 9500-9800/X300 limits)\n"
1199 " // this basically moves forward the full distance, and then backs up based\n"
1200 " // on height of samples\n"
1201 " //vec2 OffsetVector = vec2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * vec2(-1, 1));\n"
1202 " //vec2 OffsetVector = vec2(normalize(EyeVector.xy) * OffsetMapping_Scale * vec2(-1, 1));\n"
1203 " vec2 OffsetVector = vec2(normalize(EyeVector).xy * OffsetMapping_Scale * vec2(-1, 1));\n"
1204 " TexCoord += OffsetVector;\n"
1205 " OffsetVector *= 0.5;\n"
1206 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1207 " TexCoord -= OffsetVector * texture2D(Texture_Normal, TexCoord).a;\n"
1208 " return TexCoord;\n"
1211 "#endif // USEOFFSETMAPPING\n"
1213 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
1214 "uniform sampler2D Texture_Attenuation;\n"
1215 "uniform samplerCube Texture_Cube;\n"
1218 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
1220 "#ifdef USESHADOWMAP2D\n"
1221 "# ifdef USESHADOWSAMPLER\n"
1222 "uniform sampler2DShadow Texture_ShadowMap2D;\n"
1224 "uniform sampler2D Texture_ShadowMap2D;\n"
1228 "#ifdef USESHADOWMAPVSDCT\n"
1229 "uniform samplerCube Texture_CubeProjection;\n"
1232 "#if defined(USESHADOWMAP2D)\n"
1233 "uniform mediump vec2 ShadowMap_TextureScale;\n"
1234 "uniform mediump vec4 ShadowMap_Parameters;\n"
1237 "#if defined(USESHADOWMAP2D)\n"
1238 "# ifdef USESHADOWMAPORTHO\n"
1239 "# define GetShadowMapTC2D(dir) (min(dir, ShadowMap_Parameters.xyz))\n"
1241 "# ifdef USESHADOWMAPVSDCT\n"
1242 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1244 " vec3 adir = abs(dir);\n"
1245 " vec2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
1246 " vec4 proj = textureCube(Texture_CubeProjection, dir);\n"
1247 " return vec3(mix(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1250 "vec3 GetShadowMapTC2D(vec3 dir)\n"
1252 " vec3 adir = abs(dir);\n"
1253 " float ma = adir.z;\n"
1254 " vec4 proj = vec4(dir, 2.5);\n"
1255 " if (adir.x > ma) { ma = adir.x; proj = vec4(dir.zyx, 0.5); }\n"
1256 " if (adir.y > ma) { ma = adir.y; proj = vec4(dir.xzy, 1.5); }\n"
1257 " vec2 aparams = ShadowMap_Parameters.xy / ma;\n"
1258 " return vec3(proj.xy * aparams.x + vec2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
1262 "#endif // defined(USESHADOWMAP2D)\n"
1264 "# ifdef USESHADOWMAP2D\n"
1265 "float ShadowMapCompare(vec3 dir)\n"
1267 " vec3 shadowmaptc = GetShadowMapTC2D(dir);\n"
1270 "# ifdef USESHADOWSAMPLER\n"
1271 "# ifdef USESHADOWMAPPCF\n"
1272 "# define texval(x, y) shadow2D(Texture_ShadowMap2D, vec3(center + vec2(x, y)*ShadowMap_TextureScale, shadowmaptc.z)).r \n"
1273 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
1274 " f = dot(vec4(0.25), vec4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
1276 " f = shadow2D(Texture_ShadowMap2D, vec3(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z)).r;\n"
1279 "# ifdef USESHADOWMAPPCF\n"
1280 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
1281 "# ifdef GL_ARB_texture_gather\n"
1282 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, ivec2(x, y))\n"
1284 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale)\n"
1286 " vec2 offset = fract(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
1287 "# if USESHADOWMAPPCF > 1\n"
1288 " vec4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
1289 " vec4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
1290 " vec4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
1291 " vec4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
1292 " vec4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
1293 " vec4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
1294 " vec4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
1295 " vec4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
1296 " vec4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
1297 " vec4 locols = vec4(group1.ab, group3.ab);\n"
1298 " vec4 hicols = vec4(group7.rg, group9.rg);\n"
1299 " locols.yz += group2.ab;\n"
1300 " hicols.yz += group8.rg;\n"
1301 " vec4 midcols = vec4(group1.rg, group3.rg) + vec4(group7.ab, group9.ab) +\n"
1302 " vec4(group4.rg, group6.rg) + vec4(group4.ab, group6.ab) +\n"
1303 " mix(locols, hicols, offset.y);\n"
1304 " vec4 cols = group5 + vec4(group2.rg, group8.ab);\n"
1305 " cols.xyz += mix(midcols.xyz, midcols.yzw, offset.x);\n"
1306 " f = dot(cols, vec4(1.0/25.0));\n"
1308 " vec4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
1309 " vec4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
1310 " vec4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
1311 " vec4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
1312 " vec4 cols = vec4(group1.rg, group2.rg) + vec4(group3.ab, group4.ab) +\n"
1313 " mix(vec4(group1.ab, group2.ab), vec4(group3.rg, group4.rg), offset.y);\n"
1314 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1317 "# ifdef GL_EXT_gpu_shader4\n"
1318 "# define texval(x, y) texture2DOffset(Texture_ShadowMap2D, center, ivec2(x, y)).r\n"
1320 "# define texval(x, y) texture2D(Texture_ShadowMap2D, center + vec2(x, y)*ShadowMap_TextureScale).r \n"
1322 "# if USESHADOWMAPPCF > 1\n"
1323 " vec2 center = shadowmaptc.xy - 0.5, offset = fract(center);\n"
1324 " center *= ShadowMap_TextureScale;\n"
1325 " vec4 row1 = step(shadowmaptc.z, vec4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
1326 " vec4 row2 = step(shadowmaptc.z, vec4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
1327 " vec4 row3 = step(shadowmaptc.z, vec4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
1328 " vec4 row4 = step(shadowmaptc.z, vec4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
1329 " vec4 cols = row2 + row3 + mix(row1, row4, offset.y);\n"
1330 " f = dot(mix(cols.xyz, cols.yzw, offset.x), vec3(1.0/9.0));\n"
1332 " vec2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = fract(shadowmaptc.xy);\n"
1333 " vec3 row1 = step(shadowmaptc.z, vec3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
1334 " vec3 row2 = step(shadowmaptc.z, vec3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
1335 " vec3 row3 = step(shadowmaptc.z, vec3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
1336 " vec3 cols = row2 + mix(row1, row3, offset.y);\n"
1337 " f = dot(mix(cols.xy, cols.yz, offset.x), vec2(0.25));\n"
1341 " f = step(shadowmaptc.z, texture2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
1344 "# ifdef USESHADOWMAPORTHO\n"
1345 " return mix(ShadowMap_Parameters.w, 1.0, f);\n"
1351 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
1352 "#endif // FRAGMENT_SHADER\n"
1357 "#ifdef MODE_DEFERREDGEOMETRY\n"
1358 "#ifdef VERTEX_SHADER\n"
1359 "uniform highp mat4 TexMatrix;\n"
1360 "#ifdef USEVERTEXTEXTUREBLEND\n"
1361 "uniform highp mat4 BackgroundTexMatrix;\n"
1363 "uniform highp mat4 ModelViewMatrix;\n"
1366 " TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
1367 "#ifdef USEVERTEXTEXTUREBLEND\n"
1368 " VertexColor = Attrib_Color;\n"
1369 " TexCoord2 = vec2(BackgroundTexMatrix * Attrib_TexCoord0);\n"
1372 " // transform unnormalized eye direction into tangent space\n"
1373 "#ifdef USEOFFSETMAPPING\n"
1374 " vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
1375 " EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
1376 " EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
1377 " EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
1380 " VectorS = (ModelViewMatrix * vec4(Attrib_TexCoord1.xyz, 0)).xyz;\n"
1381 " VectorT = (ModelViewMatrix * vec4(Attrib_TexCoord2.xyz, 0)).xyz;\n"
1382 " VectorR = (ModelViewMatrix * vec4(Attrib_TexCoord3.xyz, 0)).xyz;\n"
1383 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1385 "#endif // VERTEX_SHADER\n"
1387 "#ifdef FRAGMENT_SHADER\n"
1390 "#ifdef USEOFFSETMAPPING\n"
1391 " // apply offsetmapping\n"
1392 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1393 "#define TexCoord TexCoordOffset\n"
1396 "#ifdef USEALPHAKILL\n"
1397 " if (texture2D(Texture_Color, TexCoord).a < 0.5)\n"
1401 "#ifdef USEVERTEXTEXTUREBLEND\n"
1402 " float alpha = texture2D(Texture_Color, TexCoord).a;\n"
1403 " float terrainblend = clamp(float(VertexColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
1404 " //float terrainblend = min(float(VertexColor.a) * alpha * 2.0, float(1.0));\n"
1405 " //float terrainblend = float(VertexColor.a) * alpha > 0.5;\n"
1408 "#ifdef USEVERTEXTEXTUREBLEND\n"
1409 " vec3 surfacenormal = mix(vec3(texture2D(Texture_SecondaryNormal, TexCoord2)), vec3(texture2D(Texture_Normal, TexCoord)), terrainblend) - vec3(0.5, 0.5, 0.5);\n"
1410 " float a = mix(texture2D(Texture_SecondaryGloss, TexCoord2).a, texture2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
1412 " vec3 surfacenormal = vec3(texture2D(Texture_Normal, TexCoord)) - vec3(0.5, 0.5, 0.5);\n"
1413 " float a = texture2D(Texture_Gloss, TexCoord).a;\n"
1416 " gl_FragColor = vec4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + vec3(0.5, 0.5, 0.5), a);\n"
1418 "#endif // FRAGMENT_SHADER\n"
1419 "#else // !MODE_DEFERREDGEOMETRY\n"
1424 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
1425 "#ifdef VERTEX_SHADER\n"
1426 "uniform highp mat4 ModelViewMatrix;\n"
1429 " ModelViewPosition = ModelViewMatrix * Attrib_Position;\n"
1430 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1432 "#endif // VERTEX_SHADER\n"
1434 "#ifdef FRAGMENT_SHADER\n"
1435 "uniform highp mat4 ViewToLight;\n"
1436 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1437 "uniform highp vec2 ScreenToDepth;\n"
1438 "uniform myhalf3 DeferredColor_Ambient;\n"
1439 "uniform myhalf3 DeferredColor_Diffuse;\n"
1440 "#ifdef USESPECULAR\n"
1441 "uniform myhalf3 DeferredColor_Specular;\n"
1442 "uniform myhalf SpecularPower;\n"
1444 "uniform myhalf2 PixelToScreenTexCoord;\n"
1447 " // calculate viewspace pixel position\n"
1448 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1450 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1451 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1452 " // decode viewspace pixel normal\n"
1453 " myhalf4 normalmap = texture2D(Texture_ScreenNormalMap, ScreenTexCoord);\n"
1454 " myhalf3 surfacenormal = normalize(normalmap.rgb - myhalf3(0.5,0.5,0.5));\n"
1455 " // surfacenormal = pixel normal in viewspace\n"
1456 " // LightVector = pixel to light in viewspace\n"
1457 " // CubeVector = position in lightspace\n"
1458 " // eyevector = pixel to view in viewspace\n"
1459 " vec3 CubeVector = vec3(ViewToLight * vec4(position,1));\n"
1460 " myhalf fade = myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1461 "#ifdef USEDIFFUSE\n"
1462 " // calculate diffuse shading\n"
1463 " myhalf3 lightnormal = myhalf3(normalize(LightPosition - position));\n"
1464 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1466 "#ifdef USESPECULAR\n"
1467 " // calculate directional shading\n"
1468 " vec3 eyevector = position * -1.0;\n"
1469 "# ifdef USEEXACTSPECULARMATH\n"
1470 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a);\n"
1472 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(eyevector)));\n"
1473 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a);\n"
1477 "#if defined(USESHADOWMAP2D)\n"
1478 " fade *= ShadowMapCompare(CubeVector);\n"
1481 "#ifdef USEDIFFUSE\n"
1482 " gl_FragData[0] = vec4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
1484 " gl_FragData[0] = vec4(DeferredColor_Ambient * fade, 1.0);\n"
1486 "#ifdef USESPECULAR\n"
1487 " gl_FragData[1] = vec4(DeferredColor_Specular * (specular * fade), 1.0);\n"
1489 " gl_FragData[1] = vec4(0.0, 0.0, 0.0, 1.0);\n"
1492 "# ifdef USECUBEFILTER\n"
1493 " vec3 cubecolor = textureCube(Texture_Cube, CubeVector).rgb;\n"
1494 " gl_FragData[0].rgb *= cubecolor;\n"
1495 " gl_FragData[1].rgb *= cubecolor;\n"
1498 "#endif // FRAGMENT_SHADER\n"
1499 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
1504 "#ifdef MODE_DEFERREDBOUNCELIGHT\n"
1505 "#ifdef VERTEX_SHADER\n"
1506 "uniform highp mat4 ModelViewMatrix;\n"
1509 " ModelViewPosition = ModelViewMatrix * Attrib_Position;\n"
1510 " LightOriginInvRadius.xyz = (ModelViewMatrix * vec4(Attrib_TexCoord0.xyz, 1.0)).xyz;\n"
1511 " LightOriginInvRadius.w = Attrib_TexCoord0.w;\n"
1512 " LightColor = Attrib_Color;\n"
1513 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1515 "#endif // VERTEX_SHADER\n"
1517 "#ifdef FRAGMENT_SHADER\n"
1518 "// ScreenToDepth = vec2(Far / (Far - Near), Far * Near / (Near - Far));\n"
1519 "uniform highp vec2 ScreenToDepth;\n"
1520 "uniform myhalf2 PixelToScreenTexCoord;\n"
1523 " // calculate viewspace pixel position\n"
1524 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1526 " position.z = ScreenToDepth.y / (texture2D(Texture_ScreenDepth, ScreenTexCoord).r + ScreenToDepth.x);\n"
1527 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
1528 " vec3 CubeVector = (position - LightOriginInvRadius.xyz) * LightOriginInvRadius.w;\n"
1529 " gl_FragData[0] = vec4(LightColor.rgb * max(0.0, 1.0 - length(CubeVector)), 1.0);\n"
1531 "#endif // FRAGMENT_SHADER\n"
1532 "#else // !MODE_DEFERREDBOUNCELIGHT\n"
1537 "#ifdef VERTEX_SHADER\n"
1538 "uniform highp mat4 TexMatrix;\n"
1539 "#ifdef USEVERTEXTEXTUREBLEND\n"
1540 "uniform highp mat4 BackgroundTexMatrix;\n"
1542 "#ifdef MODE_LIGHTSOURCE\n"
1543 "uniform highp mat4 ModelToLight;\n"
1545 "#ifdef USESHADOWMAPORTHO\n"
1546 "uniform highp mat4 ShadowMapMatrix;\n"
1548 "#ifdef USEBOUNCEGRID\n"
1549 "uniform highp mat4 BounceGridMatrix;\n"
1553 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
1554 " VertexColor = Attrib_Color;\n"
1556 " // copy the surface texcoord\n"
1557 " TexCoord = vec2(TexMatrix * Attrib_TexCoord0);\n"
1558 "#ifdef USEVERTEXTEXTUREBLEND\n"
1559 " TexCoord2 = vec2(BackgroundTexMatrix * Attrib_TexCoord0);\n"
1561 "#ifdef USELIGHTMAP\n"
1562 " TexCoordLightmap = vec2(Attrib_TexCoord4);\n"
1565 "#ifdef USEBOUNCEGRID\n"
1566 " BounceGridTexCoord = vec3(BounceGridMatrix * Attrib_Position);\n"
1569 "#ifdef MODE_LIGHTSOURCE\n"
1570 " // transform vertex position into light attenuation/cubemap space\n"
1571 " // (-1 to +1 across the light box)\n"
1572 " CubeVector = vec3(ModelToLight * Attrib_Position);\n"
1574 "# ifdef USEDIFFUSE\n"
1575 " // transform unnormalized light direction into tangent space\n"
1576 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
1577 " // normalize it per pixel)\n"
1578 " vec3 lightminusvertex = LightPosition - Attrib_Position.xyz;\n"
1579 " LightVector.x = dot(lightminusvertex, Attrib_TexCoord1.xyz);\n"
1580 " LightVector.y = dot(lightminusvertex, Attrib_TexCoord2.xyz);\n"
1581 " LightVector.z = dot(lightminusvertex, Attrib_TexCoord3.xyz);\n"
1585 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
1586 " LightVector.x = dot(LightDir, Attrib_TexCoord1.xyz);\n"
1587 " LightVector.y = dot(LightDir, Attrib_TexCoord2.xyz);\n"
1588 " LightVector.z = dot(LightDir, Attrib_TexCoord3.xyz);\n"
1591 " // transform unnormalized eye direction into tangent space\n"
1592 "#ifdef USEEYEVECTOR\n"
1593 " vec3 EyeVectorModelSpace = EyePosition - Attrib_Position.xyz;\n"
1594 " EyeVector.x = dot(EyeVectorModelSpace, Attrib_TexCoord1.xyz);\n"
1595 " EyeVector.y = dot(EyeVectorModelSpace, Attrib_TexCoord2.xyz);\n"
1596 " EyeVector.z = dot(EyeVectorModelSpace, Attrib_TexCoord3.xyz);\n"
1600 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - Attrib_Position.xyz;\n"
1601 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, Attrib_Position);\n"
1604 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(USEREFLECTCUBE)\n"
1605 " VectorS = Attrib_TexCoord1.xyz;\n"
1606 " VectorT = Attrib_TexCoord2.xyz;\n"
1607 " VectorR = Attrib_TexCoord3.xyz;\n"
1610 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
1611 " gl_Position = ModelViewProjectionMatrix * Attrib_Position;\n"
1613 "#ifdef USESHADOWMAPORTHO\n"
1614 " ShadowMapTC = vec3(ShadowMapMatrix * gl_Position);\n"
1617 "#ifdef USEREFLECTION\n"
1618 " ModelViewProjectionPosition = gl_Position;\n"
1621 "#endif // VERTEX_SHADER\n"
1626 "#ifdef FRAGMENT_SHADER\n"
1627 "#ifdef USEDEFERREDLIGHTMAP\n"
1628 "uniform myhalf2 PixelToScreenTexCoord;\n"
1629 "uniform myhalf3 DeferredMod_Diffuse;\n"
1630 "uniform myhalf3 DeferredMod_Specular;\n"
1632 "uniform myhalf3 Color_Ambient;\n"
1633 "uniform myhalf3 Color_Diffuse;\n"
1634 "uniform myhalf3 Color_Specular;\n"
1635 "uniform myhalf SpecularPower;\n"
1637 "uniform myhalf3 Color_Glow;\n"
1639 "uniform myhalf Alpha;\n"
1640 "#ifdef USEREFLECTION\n"
1641 "uniform mediump vec4 DistortScaleRefractReflect;\n"
1642 "uniform mediump vec4 ScreenScaleRefractReflect;\n"
1643 "uniform mediump vec4 ScreenCenterRefractReflect;\n"
1644 "uniform lowp vec4 ReflectColor;\n"
1646 "#ifdef USEREFLECTCUBE\n"
1647 "uniform highp mat4 ModelToReflectCube;\n"
1648 "uniform sampler2D Texture_ReflectMask;\n"
1649 "uniform samplerCube Texture_ReflectCube;\n"
1651 "#ifdef MODE_LIGHTDIRECTION\n"
1652 "uniform myhalf3 LightColor;\n"
1654 "#ifdef MODE_LIGHTSOURCE\n"
1655 "uniform myhalf3 LightColor;\n"
1657 "#ifdef USEBOUNCEGRID\n"
1658 "uniform sampler3D Texture_BounceGrid;\n"
1659 "uniform float BounceGridIntensity;\n"
1663 "#ifdef USEOFFSETMAPPING\n"
1664 " // apply offsetmapping\n"
1665 " vec2 TexCoordOffset = OffsetMapping(TexCoord);\n"
1666 "#define TexCoord TexCoordOffset\n"
1669 " // combine the diffuse textures (base, pants, shirt)\n"
1670 " myhalf4 color = myhalf4(texture2D(Texture_Color, TexCoord));\n"
1671 "#ifdef USEALPHAKILL\n"
1672 " if (color.a < 0.5)\n"
1675 " color.a *= Alpha;\n"
1676 "#ifdef USECOLORMAPPING\n"
1677 " color.rgb += myhalf3(texture2D(Texture_Pants, TexCoord)) * Color_Pants + myhalf3(texture2D(Texture_Shirt, TexCoord)) * Color_Shirt;\n"
1679 "#ifdef USEVERTEXTEXTUREBLEND\n"
1680 " myhalf terrainblend = clamp(myhalf(VertexColor.a) * color.a * 2.0 - 0.5, myhalf(0.0), myhalf(1.0));\n"
1681 " //myhalf terrainblend = min(myhalf(VertexColor.a) * color.a * 2.0, myhalf(1.0));\n"
1682 " //myhalf terrainblend = myhalf(VertexColor.a) * color.a > 0.5;\n"
1683 " color.rgb = mix(myhalf3(texture2D(Texture_SecondaryColor, TexCoord2)), color.rgb, terrainblend);\n"
1685 " //color = mix(myhalf4(1, 0, 0, 1), color, terrainblend);\n"
1688 " // get the surface normal\n"
1689 "#ifdef USEVERTEXTEXTUREBLEND\n"
1690 " myhalf3 surfacenormal = normalize(mix(myhalf3(texture2D(Texture_SecondaryNormal, TexCoord2)), myhalf3(texture2D(Texture_Normal, TexCoord)), terrainblend) - myhalf3(0.5, 0.5, 0.5));\n"
1692 " myhalf3 surfacenormal = normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5, 0.5, 0.5));\n"
1695 " // get the material colors\n"
1696 " myhalf3 diffusetex = color.rgb;\n"
1697 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
1698 "# ifdef USEVERTEXTEXTUREBLEND\n"
1699 " myhalf4 glosstex = mix(myhalf4(texture2D(Texture_SecondaryGloss, TexCoord2)), myhalf4(texture2D(Texture_Gloss, TexCoord)), terrainblend);\n"
1701 " myhalf4 glosstex = myhalf4(texture2D(Texture_Gloss, TexCoord));\n"
1705 "#ifdef USEREFLECTCUBE\n"
1706 " vec3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
1707 " vec3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
1708 " vec3 ReflectCubeTexCoord = vec3(ModelToReflectCube * vec4(ModelReflectVector, 0));\n"
1709 " diffusetex += myhalf3(texture2D(Texture_ReflectMask, TexCoord)) * myhalf3(textureCube(Texture_ReflectCube, ReflectCubeTexCoord));\n"
1715 "#ifdef MODE_LIGHTSOURCE\n"
1716 " // light source\n"
1717 "#ifdef USEDIFFUSE\n"
1718 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1719 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1720 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
1721 "#ifdef USESPECULAR\n"
1722 "#ifdef USEEXACTSPECULARMATH\n"
1723 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1725 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1726 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1728 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
1731 " color.rgb = diffusetex * Color_Ambient;\n"
1733 " color.rgb *= LightColor;\n"
1734 " color.rgb *= myhalf(texture2D(Texture_Attenuation, vec2(length(CubeVector), 0.0)));\n"
1735 "#if defined(USESHADOWMAP2D)\n"
1736 " color.rgb *= ShadowMapCompare(CubeVector);\n"
1738 "# ifdef USECUBEFILTER\n"
1739 " color.rgb *= myhalf3(textureCube(Texture_Cube, CubeVector));\n"
1741 "#endif // MODE_LIGHTSOURCE\n"
1746 "#ifdef MODE_LIGHTDIRECTION\n"
1748 "#ifdef USEDIFFUSE\n"
1749 " myhalf3 lightnormal = myhalf3(normalize(LightVector));\n"
1751 "#define lightcolor LightColor\n"
1752 "#endif // MODE_LIGHTDIRECTION\n"
1753 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1755 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
1756 " myhalf3 lightnormal_modelspace = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1757 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1758 " // convert modelspace light vector to tangentspace\n"
1759 " myhalf3 lightnormal;\n"
1760 " lightnormal.x = dot(lightnormal_modelspace, myhalf3(VectorS));\n"
1761 " lightnormal.y = dot(lightnormal_modelspace, myhalf3(VectorT));\n"
1762 " lightnormal.z = dot(lightnormal_modelspace, myhalf3(VectorR));\n"
1763 " lightnormal = normalize(lightnormal); // VectorS/T/R are not always perfectly normalized, and EXACTSPECULARMATH is very picky about this\n"
1764 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
1765 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
1766 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
1767 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
1768 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
1769 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
1770 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
1771 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
1772 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
1773 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
1774 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
1775 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
1777 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
1778 " myhalf3 lightnormal = myhalf3(texture2D(Texture_Deluxemap, TexCoordLightmap)) * 2.0 + myhalf3(-1.0, -1.0, -1.0);\n"
1779 " myhalf3 lightcolor = myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap));\n"
1785 "#ifdef MODE_FAKELIGHT\n"
1787 "myhalf3 lightnormal = myhalf3(normalize(EyeVector));\n"
1788 "myhalf3 lightcolor = myhalf3(1.0);\n"
1789 "#endif // MODE_FAKELIGHT\n"
1794 "#ifdef MODE_LIGHTMAP\n"
1795 " color.rgb = diffusetex * (Color_Ambient + myhalf3(texture2D(Texture_Lightmap, TexCoordLightmap)) * Color_Diffuse);\n"
1796 "#endif // MODE_LIGHTMAP\n"
1797 "#ifdef MODE_VERTEXCOLOR\n"
1798 " color.rgb = diffusetex * (Color_Ambient + myhalf3(VertexColor.rgb) * Color_Diffuse);\n"
1799 "#endif // MODE_VERTEXCOLOR\n"
1800 "#ifdef MODE_FLATCOLOR\n"
1801 " color.rgb = diffusetex * Color_Ambient;\n"
1802 "#endif // MODE_FLATCOLOR\n"
1808 "# ifdef USEDIFFUSE\n"
1809 " myhalf diffuse = myhalf(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
1810 "# ifdef USESPECULAR\n"
1811 "# ifdef USEEXACTSPECULARMATH\n"
1812 " myhalf specular = pow(myhalf(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a);\n"
1814 " myhalf3 specularnormal = normalize(lightnormal + myhalf3(normalize(EyeVector)));\n"
1815 " myhalf specular = pow(myhalf(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a);\n"
1817 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
1819 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
1822 " color.rgb = diffusetex * Color_Ambient;\n"
1826 "#ifdef USESHADOWMAPORTHO\n"
1827 " color.rgb *= ShadowMapCompare(ShadowMapTC);\n"
1830 "#ifdef USEDEFERREDLIGHTMAP\n"
1831 " vec2 ScreenTexCoord = gl_FragCoord.xy * PixelToScreenTexCoord;\n"
1832 " color.rgb += diffusetex * myhalf3(texture2D(Texture_ScreenDiffuse, ScreenTexCoord)) * DeferredMod_Diffuse;\n"
1833 " color.rgb += glosstex.rgb * myhalf3(texture2D(Texture_ScreenSpecular, ScreenTexCoord)) * DeferredMod_Specular;\n"
1836 "#ifdef USEBOUNCEGRID\n"
1837 " color.rgb += diffusetex * myhalf3(texture3D(Texture_BounceGrid, BounceGridTexCoord)) * BounceGridIntensity;\n"
1841 "#ifdef USEVERTEXTEXTUREBLEND\n"
1842 " color.rgb += mix(myhalf3(texture2D(Texture_SecondaryGlow, TexCoord2)), myhalf3(texture2D(Texture_Glow, TexCoord)), terrainblend) * Color_Glow;\n"
1844 " color.rgb += myhalf3(texture2D(Texture_Glow, TexCoord)) * Color_Glow;\n"
1849 " color.rgb = FogVertex(color.rgb);\n"
1852 " // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
1853 "#ifdef USEREFLECTION\n"
1854 " vec4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
1855 " //vec4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
1856 " vec2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
1857 " vec2 ScreenTexCoord = SafeScreenTexCoord + vec3(normalize(myhalf3(texture2D(Texture_Normal, TexCoord)) - myhalf3(0.5))).xy * DistortScaleRefractReflect.zw;\n"
1858 " // FIXME temporary hack to detect the case that the reflection\n"
1859 " // gets blackened at edges due to leaving the area that contains actual\n"
1861 " // Remove this 'ack once we have a better way to stop this thing from\n"
1863 " float f = min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, 0.01)).rgb) / 0.05);\n"
1864 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(0.01, -0.01)).rgb) / 0.05);\n"
1865 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, 0.01)).rgb) / 0.05);\n"
1866 " f *= min(1.0, length(texture2D(Texture_Reflection, ScreenTexCoord + vec2(-0.01, -0.01)).rgb) / 0.05);\n"
1867 " ScreenTexCoord = mix(SafeScreenTexCoord, ScreenTexCoord, f);\n"
1868 " color.rgb = mix(color.rgb, myhalf3(texture2D(Texture_Reflection, ScreenTexCoord)) * ReflectColor.rgb, ReflectColor.a);\n"
1871 " gl_FragColor = vec4(color);\n"
1873 "#endif // FRAGMENT_SHADER\n"
1875 "#endif // !MODE_DEFERREDBOUNCELIGHT\n"
1876 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
1877 "#endif // !MODE_DEFERREDGEOMETRY\n"
1878 "#endif // !MODE_WATER\n"
1879 "#endif // !MODE_REFRACTION\n"
1880 "#endif // !MODE_BLOOMBLUR\n"
1881 "#endif // !MODE_GENERIC\n"
1882 "#endif // !MODE_POSTPROCESS\n"
1883 "#endif // !MODE_SHOWDEPTH\n"
1884 "#endif // !MODE_DEPTH_OR_SHADOW\n"
1888 =========================================================================================================================================================
1892 =========================================================================================================================================================
1896 =========================================================================================================================================================
1900 =========================================================================================================================================================
1904 =========================================================================================================================================================
1908 =========================================================================================================================================================
1912 =========================================================================================================================================================
1915 const char *builtinhlslshaderstring =
1916 "// ambient+diffuse+specular+normalmap+attenuation+cubemap+fog shader\n"
1917 "// written by Forest 'LordHavoc' Hale\n"
1918 "// shadowmapping enhancements by Lee 'eihrul' Salzman\n"
1920 "// FIXME: we need to get rid of ModelViewProjectionPosition to make room for the texcoord for this\n"
1921 "#if defined(USEREFLECTION)\n"
1922 "#undef USESHADOWMAPORTHO\n"
1925 "#if defined(USEFOGINSIDE) || defined(USEFOGOUTSIDE) || defined(USEFOGHEIGHTTEXTURE)\n"
1928 "#if defined(MODE_LIGHTMAP) || defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
1929 "#define USELIGHTMAP\n"
1931 "#if defined(USESPECULAR) || defined(USEOFFSETMAPPING) || defined(USEREFLECTCUBE) || defined(MODE_FAKELIGHT)\n"
1932 "#define USEEYEVECTOR\n"
1935 "#ifdef FRAGMENT_SHADER\n"
1937 "//#undef USESHADOWMAPPCF\n"
1938 "//#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1939 "#define texDepth2D(tex,texcoord) dot(tex2D(tex,texcoord).rgb, float3(1.0, 255.0/65536.0, 255.0/16777216.0))\n"
1941 "#define texDepth2D(tex,texcoord) tex2D(tex,texcoord).r\n"
1945 "#ifdef MODE_DEPTH_OR_SHADOW\n"
1946 "#ifdef VERTEX_SHADER\n"
1949 "float4 gl_Vertex : POSITION,\n"
1950 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1951 "out float4 gl_Position : POSITION,\n"
1952 "out float Depth : TEXCOORD0\n"
1955 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1956 " Depth = gl_Position.z;\n"
1960 "#ifdef FRAGMENT_SHADER\n"
1963 "float Depth : TEXCOORD0,\n"
1964 "out float4 gl_FragColor : COLOR\n"
1967 "// float4 temp = float4(Depth,Depth*(65536.0/255.0),Depth*(16777216.0/255.0),0.0);\n"
1968 " float4 temp = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
1969 " temp.yz -= floor(temp.yz);\n"
1970 " gl_FragColor = temp;\n"
1971 "// gl_FragColor = float4(Depth,0,0,0);\n"
1974 "#else // !MODE_DEPTH_ORSHADOW\n"
1979 "#ifdef MODE_SHOWDEPTH\n"
1980 "#ifdef VERTEX_SHADER\n"
1983 "float4 gl_Vertex : POSITION,\n"
1984 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
1985 "out float4 gl_Position : POSITION,\n"
1986 "out float4 gl_FrontColor : COLOR0\n"
1989 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
1990 " gl_FrontColor = float4(gl_Position.z, gl_Position.z, gl_Position.z, 1.0);\n"
1994 "#ifdef FRAGMENT_SHADER\n"
1997 "float4 gl_FrontColor : COLOR0,\n"
1998 "out float4 gl_FragColor : COLOR\n"
2001 " gl_FragColor = gl_FrontColor;\n"
2004 "#else // !MODE_SHOWDEPTH\n"
2009 "#ifdef MODE_POSTPROCESS\n"
2011 "#ifdef VERTEX_SHADER\n"
2014 "float4 gl_Vertex : POSITION,\n"
2015 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2016 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2017 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2018 "out float4 gl_Position : POSITION,\n"
2019 "out float2 TexCoord1 : TEXCOORD0,\n"
2020 "out float2 TexCoord2 : TEXCOORD1\n"
2023 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2024 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2026 " TexCoord2 = gl_MultiTexCoord4.xy;\n"
2031 "#ifdef FRAGMENT_SHADER\n"
2034 "float2 TexCoord1 : TEXCOORD0,\n"
2035 "float2 TexCoord2 : TEXCOORD1,\n"
2036 "uniform sampler Texture_First : register(s0),\n"
2038 "uniform sampler Texture_Second : register(s1),\n"
2040 "#ifdef USEGAMMARAMPS\n"
2041 "uniform sampler Texture_GammaRamps : register(s2),\n"
2043 "#ifdef USESATURATION\n"
2044 "uniform float Saturation : register(c30),\n"
2046 "#ifdef USEVIEWTINT\n"
2047 "uniform float4 ViewTintColor : register(c41),\n"
2049 "uniform float4 UserVec1 : register(c37),\n"
2050 "uniform float4 UserVec2 : register(c38),\n"
2051 "uniform float4 UserVec3 : register(c39),\n"
2052 "uniform float4 UserVec4 : register(c40),\n"
2053 "uniform float ClientTime : register(c2),\n"
2054 "uniform float2 PixelSize : register(c25),\n"
2055 "uniform float4 BloomColorSubtract : register(c43),\n"
2056 "out float4 gl_FragColor : COLOR\n"
2059 " gl_FragColor = tex2D(Texture_First, TexCoord1);\n"
2061 " gl_FragColor += max(float4(0,0,0,0), tex2D(Texture_Second, TexCoord2) - BloomColorSubtract);\n"
2063 "#ifdef USEVIEWTINT\n"
2064 " gl_FragColor = lerp(gl_FragColor, ViewTintColor, ViewTintColor.a);\n"
2067 "#ifdef USEPOSTPROCESSING\n"
2068 "// do r_glsl_dumpshader, edit glsl/default.glsl, and replace this by your own postprocessing if you want\n"
2069 "// this code does a blur with the radius specified in the first component of r_glsl_postprocess_uservec1 and blends it using the second component\n"
2070 " float sobel = 1.0;\n"
2071 " // float2 ts = textureSize(Texture_First, 0);\n"
2072 " // float2 px = float2(1/ts.x, 1/ts.y);\n"
2073 " float2 px = PixelSize;\n"
2074 " float3 x1 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2075 " float3 x2 = tex2D(Texture_First, TexCoord1 + float2(-px.x, 0.0)).rgb;\n"
2076 " float3 x3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2077 " float3 x4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2078 " float3 x5 = tex2D(Texture_First, TexCoord1 + float2( px.x, 0.0)).rgb;\n"
2079 " float3 x6 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2080 " float3 y1 = tex2D(Texture_First, TexCoord1 + float2( px.x,-px.y)).rgb;\n"
2081 " float3 y2 = tex2D(Texture_First, TexCoord1 + float2( 0.0,-px.y)).rgb;\n"
2082 " float3 y3 = tex2D(Texture_First, TexCoord1 + float2(-px.x,-px.y)).rgb;\n"
2083 " float3 y4 = tex2D(Texture_First, TexCoord1 + float2( px.x, px.y)).rgb;\n"
2084 " float3 y5 = tex2D(Texture_First, TexCoord1 + float2( 0.0, px.y)).rgb;\n"
2085 " float3 y6 = tex2D(Texture_First, TexCoord1 + float2(-px.x, px.y)).rgb;\n"
2086 " float px1 = -1.0 * dot(float3(0.3, 0.59, 0.11), x1);\n"
2087 " float px2 = -2.0 * dot(float3(0.3, 0.59, 0.11), x2);\n"
2088 " float px3 = -1.0 * dot(float3(0.3, 0.59, 0.11), x3);\n"
2089 " float px4 = 1.0 * dot(float3(0.3, 0.59, 0.11), x4);\n"
2090 " float px5 = 2.0 * dot(float3(0.3, 0.59, 0.11), x5);\n"
2091 " float px6 = 1.0 * dot(float3(0.3, 0.59, 0.11), x6);\n"
2092 " float py1 = -1.0 * dot(float3(0.3, 0.59, 0.11), y1);\n"
2093 " float py2 = -2.0 * dot(float3(0.3, 0.59, 0.11), y2);\n"
2094 " float py3 = -1.0 * dot(float3(0.3, 0.59, 0.11), y3);\n"
2095 " float py4 = 1.0 * dot(float3(0.3, 0.59, 0.11), y4);\n"
2096 " float py5 = 2.0 * dot(float3(0.3, 0.59, 0.11), y5);\n"
2097 " float py6 = 1.0 * dot(float3(0.3, 0.59, 0.11), y6);\n"
2098 " sobel = 0.25 * abs(px1 + px2 + px3 + px4 + px5 + px6) + 0.25 * abs(py1 + py2 + py3 + py4 + py5 + py6);\n"
2099 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.987688, -0.156434)) * UserVec1.y;\n"
2100 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.156434, -0.891007)) * UserVec1.y;\n"
2101 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.891007, -0.453990)) * UserVec1.y;\n"
2102 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2( 0.707107, 0.707107)) * UserVec1.y;\n"
2103 " gl_FragColor += tex2D(Texture_First, TexCoord1 + PixelSize*UserVec1.x*float2(-0.453990, 0.891007)) * UserVec1.y;\n"
2104 " gl_FragColor /= (1.0 + 5.0 * UserVec1.y);\n"
2105 " gl_FragColor.rgb = gl_FragColor.rgb * (1.0 + UserVec2.x) + float3(1,1,1)*max(0.0, sobel - UserVec2.z)*UserVec2.y;\n"
2108 "#ifdef USESATURATION\n"
2109 " //apply saturation BEFORE gamma ramps, so v_glslgamma value does not matter\n"
2110 " float y = dot(gl_FragColor.rgb, float3(0.299, 0.587, 0.114));\n"
2111 " // 'vampire sight' effect, wheres red is compensated\n"
2112 " #ifdef SATURATION_REDCOMPENSATE\n"
2113 " float rboost = max(0.0, (gl_FragColor.r - max(gl_FragColor.g, gl_FragColor.b))*(1.0 - Saturation));\n"
2114 " gl_FragColor.rgb = lerp(float3(y,y,y), gl_FragColor.rgb, Saturation);\n"
2115 " gl_FragColor.r += r;\n"
2117 " // normal desaturation\n"
2118 " //gl_FragColor = float3(y,y,y) + (gl_FragColor.rgb - float3(y)) * Saturation;\n"
2119 " gl_FragColor.rgb = lerp(float3(y,y,y), gl_FragColor.rgb, Saturation);\n"
2123 "#ifdef USEGAMMARAMPS\n"
2124 " gl_FragColor.r = tex2D(Texture_GammaRamps, float2(gl_FragColor.r, 0)).r;\n"
2125 " gl_FragColor.g = tex2D(Texture_GammaRamps, float2(gl_FragColor.g, 0)).g;\n"
2126 " gl_FragColor.b = tex2D(Texture_GammaRamps, float2(gl_FragColor.b, 0)).b;\n"
2130 "#else // !MODE_POSTPROCESS\n"
2135 "#ifdef MODE_GENERIC\n"
2136 "#ifdef VERTEX_SHADER\n"
2139 "float4 gl_Vertex : POSITION,\n"
2140 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2141 "float4 gl_Color : COLOR0,\n"
2142 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2143 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2144 "out float4 gl_Position : POSITION,\n"
2145 "#ifdef USEDIFFUSE\n"
2146 "out float2 TexCoord1 : TEXCOORD0,\n"
2148 "#ifdef USESPECULAR\n"
2149 "out float2 TexCoord2 : TEXCOORD1,\n"
2151 "out float4 gl_FrontColor : COLOR\n"
2155 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2157 " gl_FrontColor = gl_Color; // Cg is forward\n"
2159 "#ifdef USEDIFFUSE\n"
2160 " TexCoord1 = gl_MultiTexCoord0.xy;\n"
2162 "#ifdef USESPECULAR\n"
2163 " TexCoord2 = gl_MultiTexCoord1.xy;\n"
2165 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2169 "#ifdef FRAGMENT_SHADER\n"
2173 "float4 gl_FrontColor : COLOR0,\n"
2174 "float2 TexCoord1 : TEXCOORD0,\n"
2175 "float2 TexCoord2 : TEXCOORD1,\n"
2176 "#ifdef USEDIFFUSE\n"
2177 "uniform sampler Texture_First : register(s0),\n"
2179 "#ifdef USESPECULAR\n"
2180 "uniform sampler Texture_Second : register(s1),\n"
2182 "out float4 gl_FragColor : COLOR\n"
2185 "#ifdef USEVIEWTINT\n"
2186 " gl_FragColor = gl_FrontColor;\n"
2188 " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n"
2190 "#ifdef USEDIFFUSE\n"
2191 " gl_FragColor *= tex2D(Texture_First, TexCoord1);\n"
2194 "#ifdef USESPECULAR\n"
2195 " float4 tex2 = tex2D(Texture_Second, TexCoord2);\n"
2196 "# ifdef USECOLORMAPPING\n"
2197 " gl_FragColor *= tex2;\n"
2200 " gl_FragColor += tex2;\n"
2202 "# ifdef USEVERTEXTEXTUREBLEND\n"
2203 " gl_FragColor = lerp(gl_FragColor, tex2, tex2.a);\n"
2208 "#else // !MODE_GENERIC\n"
2213 "#ifdef MODE_BLOOMBLUR\n"
2214 "#ifdef VERTEX_SHADER\n"
2217 "float4 gl_Vertex : POSITION,\n"
2218 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2219 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2220 "out float4 gl_Position : POSITION,\n"
2221 "out float2 TexCoord : TEXCOORD0\n"
2224 " TexCoord = gl_MultiTexCoord0.xy;\n"
2225 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2229 "#ifdef FRAGMENT_SHADER\n"
2233 "float2 TexCoord : TEXCOORD0,\n"
2234 "uniform sampler Texture_First : register(s0),\n"
2235 "uniform float4 BloomBlur_Parameters : register(c1),\n"
2236 "out float4 gl_FragColor : COLOR\n"
2240 " float2 tc = TexCoord;\n"
2241 " float3 color = tex2D(Texture_First, tc).rgb;\n"
2242 " tc += BloomBlur_Parameters.xy;\n"
2243 " for (i = 1;i < SAMPLES;i++)\n"
2245 " color += tex2D(Texture_First, tc).rgb;\n"
2246 " tc += BloomBlur_Parameters.xy;\n"
2248 " gl_FragColor = float4(color * BloomBlur_Parameters.z + float3(BloomBlur_Parameters.w), 1);\n"
2251 "#else // !MODE_BLOOMBLUR\n"
2252 "#ifdef MODE_REFRACTION\n"
2253 "#ifdef VERTEX_SHADER\n"
2256 "float4 gl_Vertex : POSITION,\n"
2257 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2258 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2259 "uniform float4x4 TexMatrix : register(c0),\n"
2260 "uniform float3 EyePosition : register(c24),\n"
2261 "out float4 gl_Position : POSITION,\n"
2262 "out float2 TexCoord : TEXCOORD0,\n"
2263 "out float3 EyeVector : TEXCOORD1,\n"
2264 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2267 " TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2268 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2269 " ModelViewProjectionPosition = gl_Position;\n"
2273 "#ifdef FRAGMENT_SHADER\n"
2276 "float2 TexCoord : TEXCOORD0,\n"
2277 "float3 EyeVector : TEXCOORD1,\n"
2278 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2279 "uniform sampler Texture_Normal : register(s0),\n"
2280 "uniform sampler Texture_Refraction : register(s3),\n"
2281 "uniform sampler Texture_Reflection : register(s7),\n"
2282 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2283 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2284 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2285 "uniform float4 RefractColor : register(c29),\n"
2286 "out float4 gl_FragColor : COLOR\n"
2289 " float2 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect.xy * (1.0 / ModelViewProjectionPosition.w);\n"
2290 " //float2 ScreenTexCoord = (ModelViewProjectionPosition.xy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2291 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect.xy;\n"
2292 " float2 ScreenTexCoord = SafeScreenTexCoord + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy * DistortScaleRefractReflect.xy;\n"
2293 " // FIXME temporary hack to detect the case that the reflection\n"
2294 " // gets blackened at edges due to leaving the area that contains actual\n"
2296 " // Remove this 'ack once we have a better way to stop this thing from\n"
2298 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
2299 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
2300 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2301 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2302 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
2303 " gl_FragColor = float4(tex2D(Texture_Refraction, ScreenTexCoord).rgb, 1) * RefractColor;\n"
2306 "#else // !MODE_REFRACTION\n"
2311 "#ifdef MODE_WATER\n"
2312 "#ifdef VERTEX_SHADER\n"
2316 "float4 gl_Vertex : POSITION,\n"
2317 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2318 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2319 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2320 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2321 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2322 "uniform float4x4 TexMatrix : register(c0),\n"
2323 "uniform float3 EyePosition : register(c24),\n"
2324 "out float4 gl_Position : POSITION,\n"
2325 "out float2 TexCoord : TEXCOORD0,\n"
2326 "out float3 EyeVector : TEXCOORD1,\n"
2327 "out float4 ModelViewProjectionPosition : TEXCOORD2\n"
2330 " TexCoord = mul(TexMatrix, gl_MultiTexCoord0).xy;\n"
2331 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2332 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2333 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2334 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2335 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2336 " ModelViewProjectionPosition = gl_Position;\n"
2340 "#ifdef FRAGMENT_SHADER\n"
2343 "float2 TexCoord : TEXCOORD0,\n"
2344 "float3 EyeVector : TEXCOORD1,\n"
2345 "float4 ModelViewProjectionPosition : TEXCOORD2,\n"
2346 "uniform sampler Texture_Normal : register(s0),\n"
2347 "uniform sampler Texture_Refraction : register(s3),\n"
2348 "uniform sampler Texture_Reflection : register(s7),\n"
2349 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
2350 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
2351 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
2352 "uniform float4 RefractColor : register(c29),\n"
2353 "uniform float4 ReflectColor : register(c26),\n"
2354 "uniform float ReflectFactor : register(c27),\n"
2355 "uniform float ReflectOffset : register(c28),\n"
2356 "out float4 gl_FragColor : COLOR\n"
2359 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
2360 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2361 " float4 SafeScreenTexCoord = ModelViewProjectionPosition.xyxy * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
2362 " //SafeScreenTexCoord = gl_FragCoord.xyxy * float4(1.0 / 1920.0, 1.0 / 1200.0, 1.0 / 1920.0, 1.0 / 1200.0);\n"
2363 " float4 ScreenTexCoord = SafeScreenTexCoord + float2(normalize(tex2D(Texture_Normal, TexCoord).rgb - float3(0.5,0.5,0.5)).xy).xyxy * DistortScaleRefractReflect;\n"
2364 " // FIXME temporary hack to detect the case that the reflection\n"
2365 " // gets blackened at edges due to leaving the area that contains actual\n"
2367 " // Remove this 'ack once we have a better way to stop this thing from\n"
2369 " float f = min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, 0.01)).rgb) / 0.05);\n"
2370 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(0.01, -0.01)).rgb) / 0.05);\n"
2371 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2372 " f *= min(1.0, length(tex2D(Texture_Refraction, ScreenTexCoord.xy + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2373 " ScreenTexCoord.xy = lerp(SafeScreenTexCoord.xy, ScreenTexCoord.xy, f);\n"
2374 " f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, 0.01)).rgb) / 0.05);\n"
2375 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(0.01, -0.01)).rgb) / 0.05);\n"
2376 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, 0.01)).rgb) / 0.05);\n"
2377 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord.zw + float2(-0.01, -0.01)).rgb) / 0.05);\n"
2378 " ScreenTexCoord.zw = lerp(SafeScreenTexCoord.zw, ScreenTexCoord.zw, f);\n"
2379 " float Fresnel = pow(min(1.0, 1.0 - float(normalize(EyeVector).z)), 2.0) * ReflectFactor + ReflectOffset;\n"
2380 " gl_FragColor = lerp(float4(tex2D(Texture_Refraction, ScreenTexCoord.xy).rgb, 1) * RefractColor, float4(tex2D(Texture_Reflection, ScreenTexCoord.zw).rgb, 1) * ReflectColor, Fresnel);\n"
2383 "#else // !MODE_WATER\n"
2388 "// TODO: get rid of tangentt (texcoord2) and use a crossproduct to regenerate it from tangents (texcoord1) and normal (texcoord3), this would require sending a 4 component texcoord1 with W as 1 or -1 according to which side the texcoord2 should be on\n"
2390 "// fragment shader specific:\n"
2391 "#ifdef FRAGMENT_SHADER\n"
2394 "float3 FogVertex(float3 surfacecolor, float3 FogColor, float3 EyeVectorModelSpace, float FogPlaneVertexDist, float FogRangeRecip, float FogPlaneViewDist, float FogHeightFade, sampler Texture_FogMask, sampler Texture_FogHeightTexture)\n"
2397 "#ifdef USEFOGHEIGHTTEXTURE\n"
2398 " float4 fogheightpixel = tex2D(Texture_FogHeightTexture, float2(1,1) + float2(FogPlaneVertexDist, FogPlaneViewDist) * (-2.0 * FogHeightFade));\n"
2399 " fogfrac = fogheightpixel.a;\n"
2400 " return lerp(fogheightpixel.rgb * FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2402 "# ifdef USEFOGOUTSIDE\n"
2403 " fogfrac = min(0.0, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0, min(0.0, FogPlaneVertexDist) * FogHeightFade);\n"
2405 " fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0, FogPlaneVertexDist)) * min(1.0, (min(0.0, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);\n"
2407 " return lerp(FogColor, surfacecolor, tex2D(Texture_FogMask, float2(length(EyeVectorModelSpace)*fogfrac*FogRangeRecip, 0.0)).r);\n"
2412 "#ifdef USEOFFSETMAPPING\n"
2413 "float2 OffsetMapping(float2 TexCoord, float OffsetMapping_Scale, float3 EyeVector, sampler Texture_Normal)\n"
2415 "#ifdef USEOFFSETMAPPING_RELIEFMAPPING\n"
2416 " // 14 sample relief mapping: linear search and then binary search\n"
2417 " // this basically steps forward a small amount repeatedly until it finds\n"
2418 " // itself inside solid, then jitters forward and back using decreasing\n"
2419 " // amounts to find the impact\n"
2420 " //float3 OffsetVector = float3(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1), -1);\n"
2421 " //float3 OffsetVector = float3(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2422 " float3 OffsetVector = float3(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1), -1);\n"
2423 " float3 RT = float3(TexCoord, 1);\n"
2424 " OffsetVector *= 0.1;\n"
2425 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2426 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2427 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2428 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2429 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2430 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2431 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2432 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2433 " RT += OffsetVector * step(tex2D(Texture_Normal, RT.xy).a, RT.z);\n"
2434 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) - 0.5);\n"
2435 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.5 - 0.25);\n"
2436 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.25 - 0.125);\n"
2437 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.125 - 0.0625);\n"
2438 " RT += OffsetVector * (step(tex2D(Texture_Normal, RT.xy).a, RT.z) * 0.0625 - 0.03125);\n"
2441 " // 3 sample offset mapping (only 3 samples because of ATI Radeon 9500-9800/X300 limits)\n"
2442 " // this basically moves forward the full distance, and then backs up based\n"
2443 " // on height of samples\n"
2444 " //float2 OffsetVector = float2(EyeVector.xy * ((1.0 / EyeVector.z) * OffsetMapping_Scale) * float2(-1, 1));\n"
2445 " //float2 OffsetVector = float2(normalize(EyeVector.xy) * OffsetMapping_Scale * float2(-1, 1));\n"
2446 " float2 OffsetVector = float2(normalize(EyeVector).xy * OffsetMapping_Scale * float2(-1, 1));\n"
2447 " TexCoord += OffsetVector;\n"
2448 " OffsetVector *= 0.333;\n"
2449 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2450 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2451 " TexCoord -= OffsetVector * tex2D(Texture_Normal, TexCoord).a;\n"
2452 " return TexCoord;\n"
2455 "#endif // USEOFFSETMAPPING\n"
2457 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
2458 "#if defined(USESHADOWMAP2D)\n"
2459 "# ifdef USESHADOWMAPORTHO\n"
2460 "# define GetShadowMapTC2D(dir, ShadowMap_Parameters) (min(dir, ShadowMap_Parameters.xyz))\n"
2462 "# ifdef USESHADOWMAPVSDCT\n"
2463 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters, samplerCUBE Texture_CubeProjection)\n"
2465 " float3 adir = abs(dir);\n"
2466 " float2 aparams = ShadowMap_Parameters.xy / max(max(adir.x, adir.y), adir.z);\n"
2467 " float4 proj = texCUBE(Texture_CubeProjection, dir);\n"
2468 " return float3(lerp(dir.xy, dir.zz, proj.xy) * aparams.x + proj.zw * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2471 "float3 GetShadowMapTC2D(float3 dir, float4 ShadowMap_Parameters)\n"
2473 " float3 adir = abs(dir);\n"
2474 " float ma = adir.z;\n"
2475 " float4 proj = float4(dir, 2.5);\n"
2476 " if (adir.x > ma) { ma = adir.x; proj = float4(dir.zyx, 0.5); }\n"
2477 " if (adir.y > ma) { ma = adir.y; proj = float4(dir.xzy, 1.5); }\n"
2479 " return float3(proj.xy * ShadowMap_Parameters.x / ma + float2(0.5,0.5) + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, ma + 64 * ShadowMap_Parameters.w);\n"
2481 " float2 aparams = ShadowMap_Parameters.xy / ma;\n"
2482 " return float3(proj.xy * aparams.x + float2(proj.z < 0.0 ? 1.5 : 0.5, proj.w) * ShadowMap_Parameters.z, aparams.y + ShadowMap_Parameters.w);\n"
2487 "#endif // defined(USESHADOWMAP2D)\n"
2489 "# ifdef USESHADOWMAP2D\n"
2490 "#ifdef USESHADOWMAPVSDCT\n"
2491 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale, samplerCUBE Texture_CubeProjection)\n"
2493 "float ShadowMapCompare(float3 dir, sampler Texture_ShadowMap2D, float4 ShadowMap_Parameters, float2 ShadowMap_TextureScale)\n"
2496 "#ifdef USESHADOWMAPVSDCT\n"
2497 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters, Texture_CubeProjection);\n"
2499 " float3 shadowmaptc = GetShadowMapTC2D(dir, ShadowMap_Parameters);\n"
2503 "# ifdef USESHADOWSAMPLER\n"
2504 "# ifdef USESHADOWMAPPCF\n"
2505 "# define texval(x, y) tex2Dproj(Texture_ShadowMap2D, float4(center + float2(x, y)*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r \n"
2506 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale;\n"
2507 " f = dot(float4(0.25,0.25,0.25,0.25), float4(texval(-0.4, 1.0), texval(-1.0, -0.4), texval(0.4, -1.0), texval(1.0, 0.4)));\n"
2509 " f = tex2Dproj(Texture_ShadowMap2D, float4(shadowmaptc.xy*ShadowMap_TextureScale, shadowmaptc.z, 1.0)).r;\n"
2512 "# ifdef USESHADOWMAPPCF\n"
2513 "# if defined(GL_ARB_texture_gather) || defined(GL_AMD_texture_texture4)\n"
2514 "# ifdef GL_ARB_texture_gather\n"
2515 "# define texval(x, y) textureGatherOffset(Texture_ShadowMap2D, center, int2(x, y))\n"
2517 "# define texval(x, y) texture4(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale)\n"
2519 " float2 offset = frac(shadowmaptc.xy - 0.5), center = (shadowmaptc.xy - offset)*ShadowMap_TextureScale;\n"
2520 "# if USESHADOWMAPPCF > 1\n"
2521 " float4 group1 = step(shadowmaptc.z, texval(-2.0, -2.0));\n"
2522 " float4 group2 = step(shadowmaptc.z, texval( 0.0, -2.0));\n"
2523 " float4 group3 = step(shadowmaptc.z, texval( 2.0, -2.0));\n"
2524 " float4 group4 = step(shadowmaptc.z, texval(-2.0, 0.0));\n"
2525 " float4 group5 = step(shadowmaptc.z, texval( 0.0, 0.0));\n"
2526 " float4 group6 = step(shadowmaptc.z, texval( 2.0, 0.0));\n"
2527 " float4 group7 = step(shadowmaptc.z, texval(-2.0, 2.0));\n"
2528 " float4 group8 = step(shadowmaptc.z, texval( 0.0, 2.0));\n"
2529 " float4 group9 = step(shadowmaptc.z, texval( 2.0, 2.0));\n"
2530 " float4 locols = float4(group1.ab, group3.ab);\n"
2531 " float4 hicols = float4(group7.rg, group9.rg);\n"
2532 " locols.yz += group2.ab;\n"
2533 " hicols.yz += group8.rg;\n"
2534 " float4 midcols = float4(group1.rg, group3.rg) + float4(group7.ab, group9.ab) +\n"
2535 " float4(group4.rg, group6.rg) + float4(group4.ab, group6.ab) +\n"
2536 " lerp(locols, hicols, offset.y);\n"
2537 " float4 cols = group5 + float4(group2.rg, group8.ab);\n"
2538 " cols.xyz += lerp(midcols.xyz, midcols.yzw, offset.x);\n"
2539 " f = dot(cols, float4(1.0/25.0));\n"
2541 " float4 group1 = step(shadowmaptc.z, texval(-1.0, -1.0));\n"
2542 " float4 group2 = step(shadowmaptc.z, texval( 1.0, -1.0));\n"
2543 " float4 group3 = step(shadowmaptc.z, texval(-1.0, 1.0));\n"
2544 " float4 group4 = step(shadowmaptc.z, texval( 1.0, 1.0));\n"
2545 " float4 cols = float4(group1.rg, group2.rg) + float4(group3.ab, group4.ab) +\n"
2546 " lerp(float4(group1.ab, group2.ab), float4(group3.rg, group4.rg), offset.y);\n"
2547 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2550 "# ifdef GL_EXT_gpu_shader4\n"
2551 "# define texval(x, y) tex2DOffset(Texture_ShadowMap2D, center, int2(x, y)).r\n"
2553 "# define texval(x, y) texDepth2D(Texture_ShadowMap2D, center + float2(x, y)*ShadowMap_TextureScale).r \n"
2555 "# if USESHADOWMAPPCF > 1\n"
2556 " float2 center = shadowmaptc.xy - 0.5, offset = frac(center);\n"
2557 " center *= ShadowMap_TextureScale;\n"
2558 " float4 row1 = step(shadowmaptc.z, float4(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0), texval( 2.0, -1.0)));\n"
2559 " float4 row2 = step(shadowmaptc.z, float4(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0), texval( 2.0, 0.0)));\n"
2560 " float4 row3 = step(shadowmaptc.z, float4(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0), texval( 2.0, 1.0)));\n"
2561 " float4 row4 = step(shadowmaptc.z, float4(texval(-1.0, 2.0), texval( 0.0, 2.0), texval( 1.0, 2.0), texval( 2.0, 2.0)));\n"
2562 " float4 cols = row2 + row3 + lerp(row1, row4, offset.y);\n"
2563 " f = dot(lerp(cols.xyz, cols.yzw, offset.x), float3(1.0/9.0));\n"
2565 " float2 center = shadowmaptc.xy*ShadowMap_TextureScale, offset = frac(shadowmaptc.xy);\n"
2566 " float3 row1 = step(shadowmaptc.z, float3(texval(-1.0, -1.0), texval( 0.0, -1.0), texval( 1.0, -1.0)));\n"
2567 " float3 row2 = step(shadowmaptc.z, float3(texval(-1.0, 0.0), texval( 0.0, 0.0), texval( 1.0, 0.0)));\n"
2568 " float3 row3 = step(shadowmaptc.z, float3(texval(-1.0, 1.0), texval( 0.0, 1.0), texval( 1.0, 1.0)));\n"
2569 " float3 cols = row2 + lerp(row1, row3, offset.y);\n"
2570 " f = dot(lerp(cols.xy, cols.yz, offset.x), float2(0.25,0.25));\n"
2574 " f = step(shadowmaptc.z, tex2D(Texture_ShadowMap2D, shadowmaptc.xy*ShadowMap_TextureScale).r);\n"
2577 "# ifdef USESHADOWMAPORTHO\n"
2578 " return lerp(ShadowMap_Parameters.w, 1.0, f);\n"
2584 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
2585 "#endif // FRAGMENT_SHADER\n"
2590 "#ifdef MODE_DEFERREDGEOMETRY\n"
2591 "#ifdef VERTEX_SHADER\n"
2594 "float4 gl_Vertex : POSITION,\n"
2595 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2596 "#ifdef USEVERTEXTEXTUREBLEND\n"
2597 "float4 gl_Color : COLOR0,\n"
2599 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2600 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2601 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2602 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2603 "uniform float4x4 TexMatrix : register(c0),\n"
2604 "#ifdef USEVERTEXTEXTUREBLEND\n"
2605 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2607 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2608 "#ifdef USEOFFSETMAPPING\n"
2609 "uniform float3 EyePosition : register(c24),\n"
2611 "out float4 gl_Position : POSITION,\n"
2612 "#ifdef USEVERTEXTEXTUREBLEND\n"
2613 "out float4 gl_FrontColor : COLOR,\n"
2615 "out float4 TexCoordBoth : TEXCOORD0,\n"
2616 "#ifdef USEOFFSETMAPPING\n"
2617 "out float3 EyeVector : TEXCOORD2,\n"
2619 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2620 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2621 "out float4 VectorR : TEXCOORD7 // direction of R texcoord (surface normal), Depth value\n"
2624 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2625 "#ifdef USEVERTEXTEXTUREBLEND\n"
2627 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2629 " gl_FrontColor = gl_Color; // Cg is forward\n"
2631 " TexCoordBoth.zw = float2(Backgroundmul(TexMatrix, gl_MultiTexCoord0));\n"
2634 " // transform unnormalized eye direction into tangent space\n"
2635 "#ifdef USEOFFSETMAPPING\n"
2636 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2637 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2638 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2639 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2642 " VectorS = mul(ModelViewMatrix, float4(gl_MultiTexCoord1.xyz, 0)).xyz;\n"
2643 " VectorT = mul(ModelViewMatrix, float4(gl_MultiTexCoord2.xyz, 0)).xyz;\n"
2644 " VectorR.xyz = mul(ModelViewMatrix, float4(gl_MultiTexCoord3.xyz, 0)).xyz;\n"
2645 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2646 " VectorR.w = gl_Position.z;\n"
2648 "#endif // VERTEX_SHADER\n"
2650 "#ifdef FRAGMENT_SHADER\n"
2653 "float4 TexCoordBoth : TEXCOORD0,\n"
2654 "float3 EyeVector : TEXCOORD2,\n"
2655 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2656 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2657 "float4 VectorR : TEXCOORD7, // direction of R texcoord (surface normal), Depth value\n"
2658 "uniform sampler Texture_Normal : register(s0),\n"
2659 "#ifdef USEALPHAKILL\n"
2660 "uniform sampler Texture_Color : register(s1),\n"
2662 "uniform sampler Texture_Gloss : register(s2),\n"
2663 "#ifdef USEVERTEXTEXTUREBLEND\n"
2664 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
2665 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
2667 "#ifdef USEOFFSETMAPPING\n"
2668 "uniform float OffsetMapping_Scale : register(c24),\n"
2670 "uniform half SpecularPower : register(c36),\n"
2672 "out float4 gl_FragData0 : COLOR0,\n"
2673 "out float4 gl_FragData1 : COLOR1\n"
2675 "out float4 gl_FragColor : COLOR\n"
2679 " float2 TexCoord = TexCoordBoth.xy;\n"
2680 "#ifdef USEOFFSETMAPPING\n"
2681 " // apply offsetmapping\n"
2682 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
2683 "#define TexCoord TexCoordOffset\n"
2686 "#ifdef USEALPHAKILL\n"
2687 " if (tex2D(Texture_Color, TexCoord).a < 0.5)\n"
2691 "#ifdef USEVERTEXTEXTUREBLEND\n"
2692 " float alpha = tex2D(Texture_Color, TexCoord).a;\n"
2693 " float terrainblend = clamp(float(gl_FrontColor.a) * alpha * 2.0 - 0.5, float(0.0), float(1.0));\n"
2694 " //float terrainblend = min(float(gl_FrontColor.a) * alpha * 2.0, float(1.0));\n"
2695 " //float terrainblend = float(gl_FrontColor.a) * alpha > 0.5;\n"
2698 "#ifdef USEVERTEXTEXTUREBLEND\n"
2699 " float3 surfacenormal = lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend) - float3(0.5, 0.5, 0.5);\n"
2700 " float a = lerp(tex2D(Texture_SecondaryGloss, TexCoord2).a, tex2D(Texture_Gloss, TexCoord).a, terrainblend);\n"
2702 " float3 surfacenormal = tex2D(Texture_Normal, TexCoord).rgb - float3(0.5, 0.5, 0.5);\n"
2703 " float a = tex2D(Texture_Gloss, TexCoord).a;\n"
2707 " gl_FragData0 = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR.xyz) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2708 " float Depth = VectorR.w / 256.0;\n"
2709 " float4 depthcolor = float4(Depth,Depth*65536.0/255.0,Depth*16777216.0/255.0,0.0);\n"
2710 "// float4 depthcolor = float4(Depth,Depth*256.0,Depth*65536.0,0.0);\n"
2711 " depthcolor.yz -= floor(depthcolor.yz);\n"
2712 " gl_FragData1 = depthcolor;\n"
2714 " gl_FragColor = float4(normalize(surfacenormal.x * VectorS + surfacenormal.y * VectorT + surfacenormal.z * VectorR) * 0.5 + float3(0.5, 0.5, 0.5), a);\n"
2717 "#endif // FRAGMENT_SHADER\n"
2718 "#else // !MODE_DEFERREDGEOMETRY\n"
2723 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2724 "#ifdef VERTEX_SHADER\n"
2727 "float4 gl_Vertex : POSITION,\n"
2728 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2729 "uniform float4x4 ModelViewMatrix : register(c12),\n"
2730 "out float4 gl_Position : POSITION,\n"
2731 "out float4 ModelViewPosition : TEXCOORD0\n"
2734 " ModelViewPosition = mul(ModelViewMatrix, gl_Vertex);\n"
2735 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2737 "#endif // VERTEX_SHADER\n"
2739 "#ifdef FRAGMENT_SHADER\n"
2743 "float2 Pixel : VPOS,\n"
2745 "float2 Pixel : WPOS,\n"
2747 "float4 ModelViewPosition : TEXCOORD0,\n"
2748 "uniform float4x4 ViewToLight : register(c44),\n"
2749 "uniform float2 ScreenToDepth : register(c33), // ScreenToDepth = float2(Far / (Far - Near), Far * Near / (Near - Far));\n"
2750 "uniform float3 LightPosition : register(c23),\n"
2751 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
2752 "uniform half3 DeferredColor_Ambient : register(c9),\n"
2753 "uniform half3 DeferredColor_Diffuse : register(c10),\n"
2754 "#ifdef USESPECULAR\n"
2755 "uniform half3 DeferredColor_Specular : register(c11),\n"
2756 "uniform half SpecularPower : register(c36),\n"
2758 "uniform sampler Texture_Attenuation : register(s9),\n"
2759 "uniform sampler Texture_ScreenDepth : register(s13),\n"
2760 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
2762 "#ifdef USECUBEFILTER\n"
2763 "uniform samplerCUBE Texture_Cube : register(s10),\n"
2766 "#ifdef USESHADOWMAP2D\n"
2767 "# ifdef USESHADOWSAMPLER\n"
2768 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2770 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
2774 "#ifdef USESHADOWMAPVSDCT\n"
2775 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
2778 "#if defined(USESHADOWMAP2D)\n"
2779 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
2780 "uniform float4 ShadowMap_Parameters : register(c34),\n"
2783 "out float4 gl_FragData0 : COLOR0,\n"
2784 "out float4 gl_FragData1 : COLOR1\n"
2787 " // calculate viewspace pixel position\n"
2788 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
2789 " //ScreenTexCoord.y = ScreenTexCoord.y * -1 + 1; // Cg is opposite?\n"
2790 " float3 position;\n"
2792 " position.z = texDepth2D(Texture_ScreenDepth, ScreenTexCoord) * 256.0;\n"
2794 " position.z = ScreenToDepth.y / (texDepth2D(Texture_ScreenDepth, ScreenTexCoord) + ScreenToDepth.x);\n"
2796 " position.xy = ModelViewPosition.xy * (position.z / ModelViewPosition.z);\n"
2797 " // decode viewspace pixel normal\n"
2798 " half4 normalmap = half4(tex2D(Texture_ScreenNormalMap, ScreenTexCoord));\n"
2799 " half3 surfacenormal = half3(normalize(normalmap.rgb - half3(0.5,0.5,0.5)));\n"
2800 " // surfacenormal = pixel normal in viewspace\n"
2801 " // LightVector = pixel to light in viewspace\n"
2802 " // CubeVector = position in lightspace\n"
2803 " // eyevector = pixel to view in viewspace\n"
2804 " float3 CubeVector = mul(ViewToLight, float4(position,1)).xyz;\n"
2805 " half fade = half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
2806 "#ifdef USEDIFFUSE\n"
2807 " // calculate diffuse shading\n"
2808 " half3 lightnormal = half3(normalize(LightPosition - position));\n"
2809 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
2811 "#ifdef USESPECULAR\n"
2812 " // calculate directional shading\n"
2813 " float3 eyevector = position * -1.0;\n"
2814 "# ifdef USEEXACTSPECULARMATH\n"
2815 " half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(eyevector)))*-1.0, 0.0)), SpecularPower * normalmap.a));\n"
2817 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(eyevector))));\n"
2818 " half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * normalmap.a));\n"
2822 "#if defined(USESHADOWMAP2D)\n"
2823 " fade *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
2824 "#ifdef USESHADOWMAPVSDCT\n"
2825 ", Texture_CubeProjection\n"
2830 "#ifdef USEDIFFUSE\n"
2831 " gl_FragData0 = float4((DeferredColor_Ambient + DeferredColor_Diffuse * diffuse) * fade, 1.0);\n"
2833 " gl_FragData0 = float4(DeferredColor_Ambient * fade, 1.0);\n"
2835 "#ifdef USESPECULAR\n"
2836 " gl_FragData1 = float4(DeferredColor_Specular * (specular * fade), 1.0);\n"
2838 " gl_FragData1 = float4(0.0, 0.0, 0.0, 1.0);\n"
2841 "# ifdef USECUBEFILTER\n"
2842 " float3 cubecolor = texCUBE(Texture_Cube, CubeVector).rgb;\n"
2843 " gl_FragData0.rgb *= cubecolor;\n"
2844 " gl_FragData1.rgb *= cubecolor;\n"
2847 "#endif // FRAGMENT_SHADER\n"
2848 "#else // !MODE_DEFERREDLIGHTSOURCE\n"
2853 "#ifdef VERTEX_SHADER\n"
2856 "float4 gl_Vertex : POSITION,\n"
2857 "uniform float4x4 ModelViewProjectionMatrix : register(c8),\n"
2858 "#if defined(USEVERTEXTEXTUREBLEND) || defined(MODE_VERTEXCOLOR)\n"
2859 "float4 gl_Color : COLOR0,\n"
2861 "float4 gl_MultiTexCoord0 : TEXCOORD0,\n"
2862 "float4 gl_MultiTexCoord1 : TEXCOORD1,\n"
2863 "float4 gl_MultiTexCoord2 : TEXCOORD2,\n"
2864 "float4 gl_MultiTexCoord3 : TEXCOORD3,\n"
2865 "float4 gl_MultiTexCoord4 : TEXCOORD4,\n"
2867 "uniform float3 EyePosition : register(c24),\n"
2868 "uniform float4x4 TexMatrix : register(c0),\n"
2869 "#ifdef USEVERTEXTEXTUREBLEND\n"
2870 "uniform float4x4 BackgroundTexMatrix : register(c4),\n"
2872 "#ifdef MODE_LIGHTSOURCE\n"
2873 "uniform float4x4 ModelToLight : register(c20),\n"
2875 "#ifdef MODE_LIGHTSOURCE\n"
2876 "uniform float3 LightPosition : register(c27),\n"
2878 "#ifdef MODE_LIGHTDIRECTION\n"
2879 "uniform float3 LightDir : register(c26),\n"
2881 "uniform float4 FogPlane : register(c25),\n"
2882 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
2883 "uniform float3 LightPosition : register(c27),\n"
2885 "#ifdef USESHADOWMAPORTHO\n"
2886 "uniform float4x4 ShadowMapMatrix : register(c16),\n"
2888 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2889 "out float4 gl_FrontColor : COLOR,\n"
2891 "out float4 TexCoordBoth : TEXCOORD0,\n"
2892 "#ifdef USELIGHTMAP\n"
2893 "out float2 TexCoordLightmap : TEXCOORD1,\n"
2895 "#ifdef USEEYEVECTOR\n"
2896 "out float3 EyeVector : TEXCOORD2,\n"
2898 "#ifdef USEREFLECTION\n"
2899 "out float4 ModelViewProjectionPosition : TEXCOORD3,\n"
2902 "out float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
2904 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE) || defined(USEDIFFUSE)\n"
2905 "out float3 LightVector : TEXCOORD1,\n"
2907 "#ifdef MODE_LIGHTSOURCE\n"
2908 "out float3 CubeVector : TEXCOORD3,\n"
2910 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
2911 "out float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
2912 "out float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
2913 "out float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
2915 "#ifdef USESHADOWMAPORTHO\n"
2916 "out float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
2918 "out float4 gl_Position : POSITION\n"
2921 "#if defined(MODE_VERTEXCOLOR) || defined(USEVERTEXTEXTUREBLEND)\n"
2923 " gl_FrontColor = gl_Color.bgra; // NOTE: D3DCOLOR is backwards\n"
2925 " gl_FrontColor = gl_Color; // Cg is forward\n"
2928 " // copy the surface texcoord\n"
2929 " TexCoordBoth = mul(TexMatrix, gl_MultiTexCoord0);\n"
2930 "#ifdef USEVERTEXTEXTUREBLEND\n"
2931 " TexCoordBoth.zw = mul(BackgroundTexMatrix, gl_MultiTexCoord0).xy;\n"
2933 "#ifdef USELIGHTMAP\n"
2934 " TexCoordLightmap = gl_MultiTexCoord4.xy;\n"
2937 "#ifdef MODE_LIGHTSOURCE\n"
2938 " // transform vertex position into light attenuation/cubemap space\n"
2939 " // (-1 to +1 across the light box)\n"
2940 " CubeVector = mul(ModelToLight, gl_Vertex).xyz;\n"
2942 "# ifdef USEDIFFUSE\n"
2943 " // transform unnormalized light direction into tangent space\n"
2944 " // (we use unnormalized to ensure that it interpolates correctly and then\n"
2945 " // normalize it per pixel)\n"
2946 " float3 lightminusvertex = LightPosition - gl_Vertex.xyz;\n"
2947 " LightVector.x = dot(lightminusvertex, gl_MultiTexCoord1.xyz);\n"
2948 " LightVector.y = dot(lightminusvertex, gl_MultiTexCoord2.xyz);\n"
2949 " LightVector.z = dot(lightminusvertex, gl_MultiTexCoord3.xyz);\n"
2953 "#if defined(MODE_LIGHTDIRECTION) && defined(USEDIFFUSE)\n"
2954 " LightVector.x = dot(LightDir, gl_MultiTexCoord1.xyz);\n"
2955 " LightVector.y = dot(LightDir, gl_MultiTexCoord2.xyz);\n"
2956 " LightVector.z = dot(LightDir, gl_MultiTexCoord3.xyz);\n"
2959 " // transform unnormalized eye direction into tangent space\n"
2960 "#ifdef USEEYEVECTOR\n"
2961 " float3 EyeVectorModelSpace = EyePosition - gl_Vertex.xyz;\n"
2962 " EyeVector.x = dot(EyeVectorModelSpace, gl_MultiTexCoord1.xyz);\n"
2963 " EyeVector.y = dot(EyeVectorModelSpace, gl_MultiTexCoord2.xyz);\n"
2964 " EyeVector.z = dot(EyeVectorModelSpace, gl_MultiTexCoord3.xyz);\n"
2968 " EyeVectorModelSpaceFogPlaneVertexDist.xyz = EyePosition - gl_Vertex.xyz;\n"
2969 " EyeVectorModelSpaceFogPlaneVertexDist.w = dot(FogPlane, gl_Vertex);\n"
2972 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
2973 " VectorS = gl_MultiTexCoord1.xyz;\n"
2974 " VectorT = gl_MultiTexCoord2.xyz;\n"
2975 " VectorR = gl_MultiTexCoord3.xyz;\n"
2978 " // transform vertex to camera space, using ftransform to match non-VS rendering\n"
2979 " gl_Position = mul(ModelViewProjectionMatrix, gl_Vertex);\n"
2981 "#ifdef USESHADOWMAPORTHO\n"
2982 " ShadowMapTC = mul(ShadowMapMatrix, gl_Position).xyz;\n"
2985 "#ifdef USEREFLECTION\n"
2986 " ModelViewProjectionPosition = gl_Position;\n"
2989 "#endif // VERTEX_SHADER\n"
2994 "#ifdef FRAGMENT_SHADER\n"
2997 "#ifdef USEDEFERREDLIGHTMAP\n"
2999 "float2 Pixel : VPOS,\n"
3001 "float2 Pixel : WPOS,\n"
3004 "float4 gl_FrontColor : COLOR,\n"
3005 "float4 TexCoordBoth : TEXCOORD0,\n"
3006 "#ifdef USELIGHTMAP\n"
3007 "float2 TexCoordLightmap : TEXCOORD1,\n"
3009 "#ifdef USEEYEVECTOR\n"
3010 "float3 EyeVector : TEXCOORD2,\n"
3012 "#ifdef USEREFLECTION\n"
3013 "float4 ModelViewProjectionPosition : TEXCOORD3,\n"
3016 "float4 EyeVectorModelSpaceFogPlaneVertexDist : TEXCOORD4,\n"
3018 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_LIGHTDIRECTION)\n"
3019 "float3 LightVector : TEXCOORD1,\n"
3021 "#ifdef MODE_LIGHTSOURCE\n"
3022 "float3 CubeVector : TEXCOORD3,\n"
3024 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3025 "float4 ModelViewPosition : TEXCOORD0,\n"
3027 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_DEFERREDGEOMETRY) || defined(USEREFLECTCUBE)\n"
3028 "float3 VectorS : TEXCOORD5, // direction of S texcoord (sometimes crudely called tangent)\n"
3029 "float3 VectorT : TEXCOORD6, // direction of T texcoord (sometimes crudely called binormal)\n"
3030 "float3 VectorR : TEXCOORD7, // direction of R texcoord (surface normal)\n"
3032 "#ifdef USESHADOWMAPORTHO\n"
3033 "float3 ShadowMapTC : TEXCOORD3, // CONFLICTS WITH USEREFLECTION!\n"
3036 "uniform sampler Texture_Normal : register(s0),\n"
3037 "uniform sampler Texture_Color : register(s1),\n"
3038 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3039 "uniform sampler Texture_Gloss : register(s2),\n"
3042 "uniform sampler Texture_Glow : register(s3),\n"
3044 "#ifdef USEVERTEXTEXTUREBLEND\n"
3045 "uniform sampler Texture_SecondaryNormal : register(s4),\n"
3046 "uniform sampler Texture_SecondaryColor : register(s5),\n"
3047 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3048 "uniform sampler Texture_SecondaryGloss : register(s6),\n"
3051 "uniform sampler Texture_SecondaryGlow : register(s7),\n"
3054 "#ifdef USECOLORMAPPING\n"
3055 "uniform sampler Texture_Pants : register(s4),\n"
3056 "uniform sampler Texture_Shirt : register(s7),\n"
3059 "uniform sampler Texture_FogHeightTexture : register(s14),\n"
3060 "uniform sampler Texture_FogMask : register(s8),\n"
3062 "#ifdef USELIGHTMAP\n"
3063 "uniform sampler Texture_Lightmap : register(s9),\n"
3065 "#if defined(MODE_LIGHTDIRECTIONMAP_MODELSPACE) || defined(MODE_LIGHTDIRECTIONMAP_TANGENTSPACE)\n"
3066 "uniform sampler Texture_Deluxemap : register(s10),\n"
3068 "#ifdef USEREFLECTION\n"
3069 "uniform sampler Texture_Reflection : register(s7),\n"
3072 "#ifdef MODE_DEFERREDLIGHTSOURCE\n"
3073 "uniform sampler Texture_ScreenDepth : register(s13),\n"
3074 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
3076 "#ifdef USEDEFERREDLIGHTMAP\n"
3077 "uniform sampler Texture_ScreenDepth : register(s13),\n"
3078 "uniform sampler Texture_ScreenNormalMap : register(s14),\n"
3079 "uniform sampler Texture_ScreenDiffuse : register(s11),\n"
3080 "uniform sampler Texture_ScreenSpecular : register(s12),\n"
3083 "#ifdef USECOLORMAPPING\n"
3084 "uniform half3 Color_Pants : register(c7),\n"
3085 "uniform half3 Color_Shirt : register(c8),\n"
3088 "uniform float3 FogColor : register(c16),\n"
3089 "uniform float FogRangeRecip : register(c20),\n"
3090 "uniform float FogPlaneViewDist : register(c19),\n"
3091 "uniform float FogHeightFade : register(c17),\n"
3094 "#ifdef USEOFFSETMAPPING\n"
3095 "uniform float OffsetMapping_Scale : register(c24),\n"
3098 "#ifdef USEDEFERREDLIGHTMAP\n"
3099 "uniform half2 PixelToScreenTexCoord : register(c42),\n"
3100 "uniform half3 DeferredMod_Diffuse : register(c12),\n"
3101 "uniform half3 DeferredMod_Specular : register(c13),\n"
3103 "uniform half3 Color_Ambient : register(c3),\n"
3104 "uniform half3 Color_Diffuse : register(c4),\n"
3105 "uniform half3 Color_Specular : register(c5),\n"
3106 "uniform half SpecularPower : register(c36),\n"
3108 "uniform half3 Color_Glow : register(c6),\n"
3110 "uniform half Alpha : register(c0),\n"
3111 "#ifdef USEREFLECTION\n"
3112 "uniform float4 DistortScaleRefractReflect : register(c14),\n"
3113 "uniform float4 ScreenScaleRefractReflect : register(c32),\n"
3114 "uniform float4 ScreenCenterRefractReflect : register(c31),\n"
3115 "uniform half4 ReflectColor : register(c26),\n"
3117 "#ifdef USEREFLECTCUBE\n"
3118 "uniform float4x4 ModelToReflectCube : register(c48),\n"
3119 "uniform sampler Texture_ReflectMask : register(s5),\n"
3120 "uniform samplerCUBE Texture_ReflectCube : register(s6),\n"
3122 "#ifdef MODE_LIGHTDIRECTION\n"
3123 "uniform half3 LightColor : register(c21),\n"
3125 "#ifdef MODE_LIGHTSOURCE\n"
3126 "uniform half3 LightColor : register(c21),\n"
3129 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE)\n"
3130 "uniform sampler Texture_Attenuation : register(s9),\n"
3131 "uniform samplerCUBE Texture_Cube : register(s10),\n"
3134 "#if defined(MODE_LIGHTSOURCE) || defined(MODE_DEFERREDLIGHTSOURCE) || defined(USESHADOWMAPORTHO)\n"
3136 "#ifdef USESHADOWMAP2D\n"
3137 "# ifdef USESHADOWSAMPLER\n"
3138 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3140 "uniform sampler Texture_ShadowMap2D : register(s15),\n"
3144 "#ifdef USESHADOWMAPVSDCT\n"
3145 "uniform samplerCUBE Texture_CubeProjection : register(s12),\n"
3148 "#if defined(USESHADOWMAP2D)\n"
3149 "uniform float2 ShadowMap_TextureScale : register(c35),\n"
3150 "uniform float4 ShadowMap_Parameters : register(c34),\n"
3152 "#endif // !defined(MODE_LIGHTSOURCE) && !defined(MODE_DEFERREDLIGHTSOURCE) && !defined(USESHADOWMAPORTHO)\n"
3154 "out float4 gl_FragColor : COLOR\n"
3157 " float2 TexCoord = TexCoordBoth.xy;\n"
3158 "#ifdef USEVERTEXTEXTUREBLEND\n"
3159 " float2 TexCoord2 = TexCoordBoth.zw;\n"
3161 "#ifdef USEOFFSETMAPPING\n"
3162 " // apply offsetmapping\n"
3163 " float2 TexCoordOffset = OffsetMapping(TexCoord, OffsetMapping_Scale, EyeVector, Texture_Normal);\n"
3164 "#define TexCoord TexCoordOffset\n"
3167 " // combine the diffuse textures (base, pants, shirt)\n"
3168 " half4 color = half4(tex2D(Texture_Color, TexCoord));\n"
3169 "#ifdef USEALPHAKILL\n"
3170 " if (color.a < 0.5)\n"
3173 " color.a *= Alpha;\n"
3174 "#ifdef USECOLORMAPPING\n"
3175 " color.rgb += half3(tex2D(Texture_Pants, TexCoord).rgb) * Color_Pants + half3(tex2D(Texture_Shirt, TexCoord).rgb) * Color_Shirt;\n"
3177 "#ifdef USEVERTEXTEXTUREBLEND\n"
3178 " half terrainblend = clamp(half(gl_FrontColor.a) * color.a * 2.0 - 0.5, half(0.0), half(1.0));\n"
3179 " //half terrainblend = min(half(gl_FrontColor.a) * color.a * 2.0, half(1.0));\n"
3180 " //half terrainblend = half(gl_FrontColor.a) * color.a > 0.5;\n"
3181 " color.rgb = half3(lerp(tex2D(Texture_SecondaryColor, TexCoord2).rgb, float3(color.rgb), terrainblend));\n"
3183 " //color = half4(lerp(float4(1, 0, 0, 1), color, terrainblend));\n"
3186 " // get the surface normal\n"
3187 "#ifdef USEVERTEXTEXTUREBLEND\n"
3188 " half3 surfacenormal = normalize(half3(lerp(tex2D(Texture_SecondaryNormal, TexCoord2).rgb, tex2D(Texture_Normal, TexCoord).rgb, terrainblend)) - half3(0.5, 0.5, 0.5));\n"
3190 " half3 surfacenormal = half3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5, 0.5, 0.5)));\n"
3193 " // get the material colors\n"
3194 " half3 diffusetex = color.rgb;\n"
3195 "#if defined(USESPECULAR) || defined(USEDEFERREDLIGHTMAP)\n"
3196 "# ifdef USEVERTEXTEXTUREBLEND\n"
3197 " half4 glosstex = half4(lerp(tex2D(Texture_SecondaryGloss, TexCoord2), tex2D(Texture_Gloss, TexCoord), terrainblend));\n"
3199 " half4 glosstex = half4(tex2D(Texture_Gloss, TexCoord));\n"
3203 "#ifdef USEREFLECTCUBE\n"
3204 " float3 TangentReflectVector = reflect(-EyeVector, surfacenormal);\n"
3205 " float3 ModelReflectVector = TangentReflectVector.x * VectorS + TangentReflectVector.y * VectorT + TangentReflectVector.z * VectorR;\n"
3206 " float3 ReflectCubeTexCoord = mul(ModelToReflectCube, float4(ModelReflectVector, 0)).xyz;\n"
3207 " diffusetex += half3(tex2D(Texture_ReflectMask, TexCoord).rgb) * half3(texCUBE(Texture_ReflectCube, ReflectCubeTexCoord).rgb);\n"
3213 "#ifdef MODE_LIGHTSOURCE\n"
3214 " // light source\n"
3215 "#ifdef USEDIFFUSE\n"
3216 " half3 lightnormal = half3(normalize(LightVector));\n"
3217 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3218 " color.rgb = diffusetex * (Color_Ambient + diffuse * Color_Diffuse);\n"
3219 "#ifdef USESPECULAR\n"
3220 "#ifdef USEEXACTSPECULARMATH\n"
3221 " half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3223 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3224 " half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3226 " color.rgb += glosstex.rgb * (specular * Color_Specular);\n"
3229 " color.rgb = diffusetex * Color_Ambient;\n"
3231 " color.rgb *= LightColor;\n"
3232 " color.rgb *= half(tex2D(Texture_Attenuation, float2(length(CubeVector), 0.0)).r);\n"
3233 "#if defined(USESHADOWMAP2D)\n"
3234 " color.rgb *= half(ShadowMapCompare(CubeVector, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale\n"
3235 "#ifdef USESHADOWMAPVSDCT\n"
3236 ", Texture_CubeProjection\n"
3241 "# ifdef USECUBEFILTER\n"
3242 " color.rgb *= half3(texCUBE(Texture_Cube, CubeVector).rgb);\n"
3245 "#ifdef USESHADOWMAP2D\n"
3246 "#ifdef USESHADOWMAPVSDCT\n"
3247 "// float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters, Texture_CubeProjection);\n"
3249 "// float3 shadowmaptc = GetShadowMapTC2D(CubeVector, ShadowMap_Parameters);\n"
3251 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3252 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3253 "// color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3254 "// color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3255 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, float2(0.1,0.1)).rgb);\n"
3256 "// color.rgb = half3(tex2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale).rgb);\n"
3257 "// color.rgb = half3(shadowmaptc.xyz * float3(ShadowMap_TextureScale,1.0));\n"
3258 "// color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3259 "// color.r = half(shadowmaptc.z - texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3260 "// color.r = half(shadowmaptc.z);\n"
3261 "// color.r = half(texDepth2D(Texture_ShadowMap2D, shadowmaptc.xy * ShadowMap_TextureScale));\n"
3262 "// color.r = half(shadowmaptc.z);\n"
3264 "// color.rgb = abs(CubeVector);\n"
3266 "// color.rgb = half3(1,1,1);\n"
3267 "#endif // MODE_LIGHTSOURCE\n"
3272 "#ifdef MODE_LIGHTDIRECTION\n"
3274 "#ifdef USEDIFFUSE\n"
3275 " half3 lightnormal = half3(normalize(LightVector));\n"
3277 "#define lightcolor LightColor\n"
3278 "#endif // MODE_LIGHTDIRECTION\n"
3279 "#ifdef MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3281 " // deluxemap lightmapping using light vectors in modelspace (q3map2 -light -deluxe)\n"
3282 " half3 lightnormal_modelspace = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3283 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3284 " // convert modelspace light vector to tangentspace\n"
3285 " half3 lightnormal;\n"
3286 " lightnormal.x = dot(lightnormal_modelspace, half3(VectorS));\n"
3287 " lightnormal.y = dot(lightnormal_modelspace, half3(VectorT));\n"
3288 " lightnormal.z = dot(lightnormal_modelspace, half3(VectorR));\n"
3289 " // calculate directional shading (and undoing the existing angle attenuation on the lightmap by the division)\n"
3290 " // note that q3map2 is too stupid to calculate proper surface normals when q3map_nonplanar\n"
3291 " // is used (the lightmap and deluxemap coords correspond to virtually random coordinates\n"
3292 " // on that luxel, and NOT to its center, because recursive triangle subdivision is used\n"
3293 " // to map the luxels to coordinates on the draw surfaces), which also causes\n"
3294 " // deluxemaps to be wrong because light contributions from the wrong side of the surface\n"
3295 " // are added up. To prevent divisions by zero or strong exaggerations, a max()\n"
3296 " // nudge is done here at expense of some additional fps. This is ONLY needed for\n"
3297 " // deluxemaps, tangentspace deluxemap avoid this problem by design.\n"
3298 " lightcolor *= 1.0 / max(0.25, lightnormal.z);\n"
3299 "#endif // MODE_LIGHTDIRECTIONMAP_MODELSPACE\n"
3300 "#ifdef MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n"
3302 " // deluxemap lightmapping using light vectors in tangentspace (hmap2 -light)\n"
3303 " half3 lightnormal = half3(tex2D(Texture_Deluxemap, TexCoordLightmap).rgb) * 2.0 + half3(-1.0, -1.0, -1.0);\n"
3304 " half3 lightcolor = half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb);\n"
3310 "#ifdef MODE_FAKELIGHT\n"
3312 "half3 lightnormal = half3(normalize(EyeVector));\n"
3313 "half3 lightcolor = half3(1.0,1.0,1.0);\n"
3314 "#endif // MODE_FAKELIGHT\n"
3319 "#ifdef MODE_LIGHTMAP\n"
3320 " color.rgb = diffusetex * (Color_Ambient + half3(tex2D(Texture_Lightmap, TexCoordLightmap).rgb) * Color_Diffuse);\n"
3321 "#endif // MODE_LIGHTMAP\n"
3322 "#ifdef MODE_VERTEXCOLOR\n"
3323 " color.rgb = diffusetex * (Color_Ambient + half3(gl_FrontColor.rgb) * Color_Diffuse);\n"
3324 "#endif // MODE_VERTEXCOLOR\n"
3325 "#ifdef MODE_FLATCOLOR\n"
3326 " color.rgb = diffusetex * Color_Ambient;\n"
3327 "#endif // MODE_FLATCOLOR\n"
3333 "# ifdef USEDIFFUSE\n"
3334 " half diffuse = half(max(float(dot(surfacenormal, lightnormal)), 0.0));\n"
3335 "# ifdef USESPECULAR\n"
3336 "# ifdef USEEXACTSPECULARMATH\n"
3337 " half specular = half(pow(half(max(float(dot(reflect(lightnormal, surfacenormal), normalize(EyeVector)))*-1.0, 0.0)), SpecularPower * glosstex.a));\n"
3339 " half3 specularnormal = half3(normalize(lightnormal + half3(normalize(EyeVector))));\n"
3340 " half specular = half(pow(half(max(float(dot(surfacenormal, specularnormal)), 0.0)), SpecularPower * glosstex.a));\n"
3342 " color.rgb = diffusetex * Color_Ambient + (diffusetex * Color_Diffuse * diffuse + glosstex.rgb * Color_Specular * specular) * lightcolor;\n"
3344 " color.rgb = diffusetex * (Color_Ambient + Color_Diffuse * diffuse * lightcolor);\n"
3347 " color.rgb = diffusetex * Color_Ambient;\n"
3351 "#ifdef USESHADOWMAPORTHO\n"
3352 " color.rgb *= half(ShadowMapCompare(ShadowMapTC, Texture_ShadowMap2D, ShadowMap_Parameters, ShadowMap_TextureScale));\n"
3355 "#ifdef USEDEFERREDLIGHTMAP\n"
3356 " float2 ScreenTexCoord = Pixel * PixelToScreenTexCoord;\n"
3357 " color.rgb += diffusetex * half3(tex2D(Texture_ScreenDiffuse, ScreenTexCoord).rgb) * DeferredMod_Diffuse;\n"
3358 " color.rgb += glosstex.rgb * half3(tex2D(Texture_ScreenSpecular, ScreenTexCoord).rgb) * DeferredMod_Specular;\n"
3359 "// color.rgb = half3(tex2D(Texture_ScreenDepth, ScreenTexCoord).rgb);\n"
3360 "// color.r = half(texDepth2D(Texture_ScreenDepth, ScreenTexCoord)) * 1.0;\n"
3364 "#ifdef USEVERTEXTEXTUREBLEND\n"
3365 " color.rgb += half3(lerp(tex2D(Texture_SecondaryGlow, TexCoord2).rgb, tex2D(Texture_Glow, TexCoord).rgb, terrainblend)) * Color_Glow;\n"
3367 " color.rgb += half3(tex2D(Texture_Glow, TexCoord).rgb) * Color_Glow;\n"
3372 " color.rgb = FogVertex(color.rgb, FogColor, EyeVectorModelSpaceFogPlaneVertexDist.xyz, EyeVectorModelSpaceFogPlaneVertexDist.w, FogRangeRecip, FogPlaneViewDist, FogHeightFade, Texture_FogMask, Texture_FogHeightTexture);\n"
3375 " // reflection must come last because it already contains exactly the correct fog (the reflection render preserves camera distance from the plane, it only flips the side) and ContrastBoost/SceneBrightness\n"
3376 "#ifdef USEREFLECTION\n"
3377 " float4 ScreenScaleRefractReflectIW = ScreenScaleRefractReflect * (1.0 / ModelViewProjectionPosition.w);\n"
3378 " //float4 ScreenTexCoord = (ModelViewProjectionPosition.xyxy + normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5)).xyxy * DistortScaleRefractReflect * 100) * ScreenScaleRefractReflectIW + ScreenCenterRefractReflect;\n"
3379 " float2 SafeScreenTexCoord = ModelViewProjectionPosition.xy * ScreenScaleRefractReflectIW.zw + ScreenCenterRefractReflect.zw;\n"
3380 " float2 ScreenTexCoord = SafeScreenTexCoord + float3(normalize(half3(tex2D(Texture_Normal, TexCoord).rgb) - half3(0.5,0.5,0.5))).xy * DistortScaleRefractReflect.zw;\n"
3381 " // FIXME temporary hack to detect the case that the reflection\n"
3382 " // gets blackened at edges due to leaving the area that contains actual\n"
3384 " // Remove this 'ack once we have a better way to stop this thing from\n"
3386 " float f = min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, 0.01)).rgb) / 0.05);\n"
3387 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(0.01, -0.01)).rgb) / 0.05);\n"
3388 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, 0.01)).rgb) / 0.05);\n"
3389 " f *= min(1.0, length(tex2D(Texture_Reflection, ScreenTexCoord + float2(-0.01, -0.01)).rgb) / 0.05);\n"
3390 " ScreenTexCoord = lerp(SafeScreenTexCoord, ScreenTexCoord, f);\n"
3391 " color.rgb = lerp(color.rgb, half3(tex2D(Texture_Reflection, ScreenTexCoord).rgb) * ReflectColor.rgb, ReflectColor.a);\n"
3394 " gl_FragColor = float4(color);\n"
3396 "#endif // FRAGMENT_SHADER\n"
3398 "#endif // !MODE_DEFERREDLIGHTSOURCE\n"
3399 "#endif // !MODE_DEFERREDGEOMETRY\n"
3400 "#endif // !MODE_WATER\n"
3401 "#endif // !MODE_REFRACTION\n"
3402 "#endif // !MODE_BLOOMBLUR\n"
3403 "#endif // !MODE_GENERIC\n"
3404 "#endif // !MODE_POSTPROCESS\n"
3405 "#endif // !MODE_SHOWDEPTH\n"
3406 "#endif // !MODE_DEPTH_OR_SHADOW\n"
3409 char *glslshaderstring = NULL;
3410 char *hlslshaderstring = NULL;
3412 //=======================================================================================================================================================
3414 typedef struct shaderpermutationinfo_s
3416 const char *pretext;
3419 shaderpermutationinfo_t;
3421 typedef struct shadermodeinfo_s
3423 const char *vertexfilename;
3424 const char *geometryfilename;
3425 const char *fragmentfilename;
3426 const char *pretext;
3431 // NOTE: MUST MATCH ORDER OF SHADERPERMUTATION_* DEFINES!
3432 shaderpermutationinfo_t shaderpermutationinfo[SHADERPERMUTATION_COUNT] =
3434 {"#define USEDIFFUSE\n", " diffuse"},
3435 {"#define USEVERTEXTEXTUREBLEND\n", " vertextextureblend"},
3436 {"#define USEVIEWTINT\n", " viewtint"},
3437 {"#define USECOLORMAPPING\n", " colormapping"},
3438 {"#define USESATURATION\n", " saturation"},
3439 {"#define USEFOGINSIDE\n", " foginside"},
3440 {"#define USEFOGOUTSIDE\n", " fogoutside"},
3441 {"#define USEFOGHEIGHTTEXTURE\n", " fogheighttexture"},
3442 {"#define USEGAMMARAMPS\n", " gammaramps"},
3443 {"#define USECUBEFILTER\n", " cubefilter"},
3444 {"#define USEGLOW\n", " glow"},
3445 {"#define USEBLOOM\n", " bloom"},
3446 {"#define USESPECULAR\n", " specular"},
3447 {"#define USEPOSTPROCESSING\n", " postprocessing"},
3448 {"#define USEREFLECTION\n", " reflection"},
3449 {"#define USEOFFSETMAPPING\n", " offsetmapping"},
3450 {"#define USEOFFSETMAPPING_RELIEFMAPPING\n", " reliefmapping"},
3451 {"#define USESHADOWMAP2D\n", " shadowmap2d"},
3452 {"#define USESHADOWMAPPCF 1\n", " shadowmappcf"},
3453 {"#define USESHADOWMAPPCF 2\n", " shadowmappcf2"},
3454 {"#define USESHADOWSAMPLER\n", " shadowsampler"},
3455 {"#define USESHADOWMAPVSDCT\n", " shadowmapvsdct"},
3456 {"#define USESHADOWMAPORTHO\n", " shadowmaportho"},
3457 {"#define USEDEFERREDLIGHTMAP\n", " deferredlightmap"},
3458 {"#define USEALPHAKILL\n", " alphakill"},
3459 {"#define USEREFLECTCUBE\n", " reflectcube"},
3460 {"#define USENORMALMAPSCROLLBLEND\n", " normalmapscrollblend"},
3461 {"#define USEBOUNCEGRID\n", " bouncegrid"},
3464 // NOTE: MUST MATCH ORDER OF SHADERMODE_* ENUMS!
3465 shadermodeinfo_t glslshadermodeinfo[SHADERMODE_COUNT] =
3467 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_GENERIC\n", " generic"},
3468 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3469 {"glsl/default.glsl", NULL, NULL , "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3470 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3471 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3472 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3473 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3474 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3475 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3476 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3477 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3478 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_REFRACTION\n", " refraction"},
3479 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_WATER\n", " water"},
3480 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3481 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3482 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3483 {"glsl/default.glsl", NULL, "glsl/default.glsl", "#define MODE_DEFERREDBOUNCELIGHT\n", " deferredbouncelight"},
3486 shadermodeinfo_t hlslshadermodeinfo[SHADERMODE_COUNT] =
3488 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_GENERIC\n", " generic"},
3489 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_POSTPROCESS\n", " postprocess"},
3490 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEPTH_OR_SHADOW\n", " depth/shadow"},
3491 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FLATCOLOR\n", " flatcolor"},
3492 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_VERTEXCOLOR\n", " vertexcolor"},
3493 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTMAP\n", " lightmap"},
3494 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_FAKELIGHT\n", " fakelight"},
3495 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_MODELSPACE\n", " lightdirectionmap_modelspace"},
3496 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTIONMAP_TANGENTSPACE\n", " lightdirectionmap_tangentspace"},
3497 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTDIRECTION\n", " lightdirection"},
3498 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_LIGHTSOURCE\n", " lightsource"},
3499 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_REFRACTION\n", " refraction"},
3500 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_WATER\n", " water"},
3501 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_SHOWDEPTH\n", " showdepth"},
3502 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDGEOMETRY\n", " deferredgeometry"},
3503 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDLIGHTSOURCE\n", " deferredlightsource"},
3504 {"hlsl/default.hlsl", NULL, "hlsl/default.hlsl", "#define MODE_DEFERREDBOUNCELIGHT\n", " deferredbouncelight"},
3507 struct r_glsl_permutation_s;
3508 typedef struct r_glsl_permutation_s
3510 /// hash lookup data
3511 struct r_glsl_permutation_s *hashnext;
3513 unsigned int permutation;
3515 /// indicates if we have tried compiling this permutation already
3517 /// 0 if compilation failed
3519 // texture units assigned to each detected uniform
3520 int tex_Texture_First;
3521 int tex_Texture_Second;
3522 int tex_Texture_GammaRamps;
3523 int tex_Texture_Normal;
3524 int tex_Texture_Color;
3525 int tex_Texture_Gloss;
3526 int tex_Texture_Glow;
3527 int tex_Texture_SecondaryNormal;
3528 int tex_Texture_SecondaryColor;
3529 int tex_Texture_SecondaryGloss;
3530 int tex_Texture_SecondaryGlow;
3531 int tex_Texture_Pants;
3532 int tex_Texture_Shirt;
3533 int tex_Texture_FogHeightTexture;
3534 int tex_Texture_FogMask;
3535 int tex_Texture_Lightmap;
3536 int tex_Texture_Deluxemap;
3537 int tex_Texture_Attenuation;
3538 int tex_Texture_Cube;
3539 int tex_Texture_Refraction;
3540 int tex_Texture_Reflection;
3541 int tex_Texture_ShadowMap2D;
3542 int tex_Texture_CubeProjection;
3543 int tex_Texture_ScreenDepth;
3544 int tex_Texture_ScreenNormalMap;
3545 int tex_Texture_ScreenDiffuse;
3546 int tex_Texture_ScreenSpecular;
3547 int tex_Texture_ReflectMask;
3548 int tex_Texture_ReflectCube;
3549 int tex_Texture_BounceGrid;
3550 /// locations of detected uniforms in program object, or -1 if not found
3551 int loc_Texture_First;
3552 int loc_Texture_Second;
3553 int loc_Texture_GammaRamps;
3554 int loc_Texture_Normal;
3555 int loc_Texture_Color;
3556 int loc_Texture_Gloss;
3557 int loc_Texture_Glow;
3558 int loc_Texture_SecondaryNormal;
3559 int loc_Texture_SecondaryColor;
3560 int loc_Texture_SecondaryGloss;
3561 int loc_Texture_SecondaryGlow;
3562 int loc_Texture_Pants;
3563 int loc_Texture_Shirt;
3564 int loc_Texture_FogHeightTexture;
3565 int loc_Texture_FogMask;
3566 int loc_Texture_Lightmap;
3567 int loc_Texture_Deluxemap;
3568 int loc_Texture_Attenuation;
3569 int loc_Texture_Cube;
3570 int loc_Texture_Refraction;
3571 int loc_Texture_Reflection;
3572 int loc_Texture_ShadowMap2D;
3573 int loc_Texture_CubeProjection;
3574 int loc_Texture_ScreenDepth;
3575 int loc_Texture_ScreenNormalMap;
3576 int loc_Texture_ScreenDiffuse;
3577 int loc_Texture_ScreenSpecular;
3578 int loc_Texture_ReflectMask;
3579 int loc_Texture_ReflectCube;
3580 int loc_Texture_BounceGrid;
3582 int loc_BloomBlur_Parameters;
3584 int loc_Color_Ambient;
3585 int loc_Color_Diffuse;
3586 int loc_Color_Specular;
3588 int loc_Color_Pants;
3589 int loc_Color_Shirt;
3590 int loc_DeferredColor_Ambient;
3591 int loc_DeferredColor_Diffuse;
3592 int loc_DeferredColor_Specular;
3593 int loc_DeferredMod_Diffuse;
3594 int loc_DeferredMod_Specular;
3595 int loc_DistortScaleRefractReflect;
3596 int loc_EyePosition;
3598 int loc_FogHeightFade;
3600 int loc_FogPlaneViewDist;
3601 int loc_FogRangeRecip;
3604 int loc_LightPosition;
3605 int loc_OffsetMapping_Scale;
3607 int loc_ReflectColor;
3608 int loc_ReflectFactor;
3609 int loc_ReflectOffset;
3610 int loc_RefractColor;
3612 int loc_ScreenCenterRefractReflect;
3613 int loc_ScreenScaleRefractReflect;
3614 int loc_ScreenToDepth;
3615 int loc_ShadowMap_Parameters;
3616 int loc_ShadowMap_TextureScale;
3617 int loc_SpecularPower;
3622 int loc_ViewTintColor;
3623 int loc_ViewToLight;
3624 int loc_ModelToLight;
3626 int loc_BackgroundTexMatrix;
3627 int loc_ModelViewProjectionMatrix;
3628 int loc_ModelViewMatrix;
3629 int loc_PixelToScreenTexCoord;
3630 int loc_ModelToReflectCube;
3631 int loc_ShadowMapMatrix;
3632 int loc_BloomColorSubtract;
3633 int loc_NormalmapScrollBlend;
3634 int loc_BounceGridMatrix;
3635 int loc_BounceGridIntensity;
3637 r_glsl_permutation_t;
3639 #define SHADERPERMUTATION_HASHSIZE 256
3642 // non-degradable "lightweight" shader parameters to keep the permutations simpler
3643 // these can NOT degrade! only use for simple stuff
3646 SHADERSTATICPARM_SATURATION_REDCOMPENSATE = 0, ///< red compensation filter for saturation
3647 SHADERSTATICPARM_EXACTSPECULARMATH = 1, ///< (lightsource or deluxemapping) use exact reflection map for specular effects, as opposed to the usual OpenGL approximation
3648 SHADERSTATICPARM_POSTPROCESS_USERVEC1 = 2, ///< postprocess uservec1 is enabled
3649 SHADERSTATICPARM_POSTPROCESS_USERVEC2 = 3, ///< postprocess uservec2 is enabled
3650 SHADERSTATICPARM_POSTPROCESS_USERVEC3 = 4, ///< postprocess uservec3 is enabled
3651 SHADERSTATICPARM_POSTPROCESS_USERVEC4 = 5 ///< postprocess uservec4 is enabled
3653 #define SHADERSTATICPARMS_COUNT 6
3655 static const char *shaderstaticparmstrings_list[SHADERSTATICPARMS_COUNT];
3656 static int shaderstaticparms_count = 0;
3658 static unsigned int r_compileshader_staticparms[(SHADERSTATICPARMS_COUNT + 0x1F) >> 5] = {0};
3659 #define R_COMPILESHADER_STATICPARM_ENABLE(p) r_compileshader_staticparms[(p) >> 5] |= (1 << ((p) & 0x1F))
3660 qboolean R_CompileShader_CheckStaticParms(void)
3662 static int r_compileshader_staticparms_save[1];
3663 memcpy(r_compileshader_staticparms_save, r_compileshader_staticparms, sizeof(r_compileshader_staticparms));
3664 memset(r_compileshader_staticparms, 0, sizeof(r_compileshader_staticparms));
3667 if (r_glsl_saturation_redcompensate.integer)
3668 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_SATURATION_REDCOMPENSATE);
3669 if (r_shadow_glossexact.integer)
3670 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_EXACTSPECULARMATH);
3671 if (r_glsl_postprocess.integer)
3673 if (r_glsl_postprocess_uservec1_enable.integer)
3674 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC1);
3675 if (r_glsl_postprocess_uservec2_enable.integer)
3676 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC2);
3677 if (r_glsl_postprocess_uservec3_enable.integer)
3678 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC3);
3679 if (r_glsl_postprocess_uservec4_enable.integer)
3680 R_COMPILESHADER_STATICPARM_ENABLE(SHADERSTATICPARM_POSTPROCESS_USERVEC4);
3682 return memcmp(r_compileshader_staticparms, r_compileshader_staticparms_save, sizeof(r_compileshader_staticparms)) != 0;
3685 #define R_COMPILESHADER_STATICPARM_EMIT(p, n) \
3686 if(r_compileshader_staticparms[(p) >> 5] & (1 << ((p) & 0x1F))) \
3687 shaderstaticparmstrings_list[shaderstaticparms_count++] = "#define " n "\n"; \
3689 shaderstaticparmstrings_list[shaderstaticparms_count++] = "\n"
3690 void R_CompileShader_AddStaticParms(unsigned int mode, unsigned int permutation)
3692 shaderstaticparms_count = 0;
3695 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_SATURATION_REDCOMPENSATE, "SATURATION_REDCOMPENSATE");
3696 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_EXACTSPECULARMATH, "USEEXACTSPECULARMATH");
3697 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC1, "USERVEC1");
3698 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC2, "USERVEC2");
3699 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC3, "USERVEC3");
3700 R_COMPILESHADER_STATICPARM_EMIT(SHADERSTATICPARM_POSTPROCESS_USERVEC4, "USERVEC4");
3703 /// information about each possible shader permutation
3704 r_glsl_permutation_t *r_glsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
3705 /// currently selected permutation
3706 r_glsl_permutation_t *r_glsl_permutation;
3707 /// storage for permutations linked in the hash table
3708 memexpandablearray_t r_glsl_permutationarray;
3710 static r_glsl_permutation_t *R_GLSL_FindPermutation(unsigned int mode, unsigned int permutation)
3712 //unsigned int hashdepth = 0;
3713 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
3714 r_glsl_permutation_t *p;
3715 for (p = r_glsl_permutationhash[mode][hashindex];p;p = p->hashnext)
3717 if (p->mode == mode && p->permutation == permutation)
3719 //if (hashdepth > 10)
3720 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3725 p = (r_glsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_glsl_permutationarray);
3727 p->permutation = permutation;
3728 p->hashnext = r_glsl_permutationhash[mode][hashindex];
3729 r_glsl_permutationhash[mode][hashindex] = p;
3730 //if (hashdepth > 10)
3731 // Con_Printf("R_GLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
3735 static char *R_GLSL_GetText(const char *filename, qboolean printfromdisknotice)
3738 if (!filename || !filename[0])
3740 if (!strcmp(filename, "glsl/default.glsl"))
3742 if (!glslshaderstring)
3744 glslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3745 if (glslshaderstring)
3746 Con_DPrintf("Loading shaders from file %s...\n", filename);
3748 glslshaderstring = (char *)builtinshaderstring;
3750 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(glslshaderstring) + 1);
3751 memcpy(shaderstring, glslshaderstring, strlen(glslshaderstring) + 1);
3752 return shaderstring;
3754 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
3757 if (printfromdisknotice)
3758 Con_DPrintf("from disk %s... ", filename);
3759 return shaderstring;
3761 return shaderstring;
3764 static void R_GLSL_CompilePermutation(r_glsl_permutation_t *p, unsigned int mode, unsigned int permutation)
3768 shadermodeinfo_t *modeinfo = glslshadermodeinfo + mode;
3769 char *vertexstring, *geometrystring, *fragmentstring;
3770 char permutationname[256];
3771 int vertstrings_count = 0;
3772 int geomstrings_count = 0;
3773 int fragstrings_count = 0;
3774 const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3775 const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3776 const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
3783 permutationname[0] = 0;
3784 vertexstring = R_GLSL_GetText(modeinfo->vertexfilename, true);
3785 geometrystring = R_GLSL_GetText(modeinfo->geometryfilename, false);
3786 fragmentstring = R_GLSL_GetText(modeinfo->fragmentfilename, false);
3788 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
3790 // the first pretext is which type of shader to compile as
3791 // (later these will all be bound together as a program object)
3792 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
3793 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
3794 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
3796 // the second pretext is the mode (for example a light source)
3797 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
3798 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
3799 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
3800 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
3802 // now add all the permutation pretexts
3803 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
3805 if (permutation & (1<<i))
3807 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
3808 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
3809 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
3810 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
3814 // keep line numbers correct
3815 vertstrings_list[vertstrings_count++] = "\n";
3816 geomstrings_list[geomstrings_count++] = "\n";
3817 fragstrings_list[fragstrings_count++] = "\n";
3822 R_CompileShader_AddStaticParms(mode, permutation);
3823 memcpy((char *)(vertstrings_list + vertstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3824 vertstrings_count += shaderstaticparms_count;
3825 memcpy((char *)(geomstrings_list + geomstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3826 geomstrings_count += shaderstaticparms_count;
3827 memcpy((char *)(fragstrings_list + fragstrings_count), shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
3828 fragstrings_count += shaderstaticparms_count;
3830 // now append the shader text itself
3831 vertstrings_list[vertstrings_count++] = vertexstring;
3832 geomstrings_list[geomstrings_count++] = geometrystring;
3833 fragstrings_list[fragstrings_count++] = fragmentstring;
3835 // if any sources were NULL, clear the respective list
3837 vertstrings_count = 0;
3838 if (!geometrystring)
3839 geomstrings_count = 0;
3840 if (!fragmentstring)
3841 fragstrings_count = 0;
3843 // compile the shader program
3844 if (vertstrings_count + geomstrings_count + fragstrings_count)
3845 p->program = GL_Backend_CompileProgram(vertstrings_count, vertstrings_list, geomstrings_count, geomstrings_list, fragstrings_count, fragstrings_list);
3849 qglUseProgram(p->program);CHECKGLERROR
3850 // look up all the uniform variable names we care about, so we don't
3851 // have to look them up every time we set them
3853 p->loc_Texture_First = qglGetUniformLocation(p->program, "Texture_First");
3854 p->loc_Texture_Second = qglGetUniformLocation(p->program, "Texture_Second");
3855 p->loc_Texture_GammaRamps = qglGetUniformLocation(p->program, "Texture_GammaRamps");
3856 p->loc_Texture_Normal = qglGetUniformLocation(p->program, "Texture_Normal");
3857 p->loc_Texture_Color = qglGetUniformLocation(p->program, "Texture_Color");
3858 p->loc_Texture_Gloss = qglGetUniformLocation(p->program, "Texture_Gloss");
3859 p->loc_Texture_Glow = qglGetUniformLocation(p->program, "Texture_Glow");
3860 p->loc_Texture_SecondaryNormal = qglGetUniformLocation(p->program, "Texture_SecondaryNormal");
3861 p->loc_Texture_SecondaryColor = qglGetUniformLocation(p->program, "Texture_SecondaryColor");
3862 p->loc_Texture_SecondaryGloss = qglGetUniformLocation(p->program, "Texture_SecondaryGloss");
3863 p->loc_Texture_SecondaryGlow = qglGetUniformLocation(p->program, "Texture_SecondaryGlow");
3864 p->loc_Texture_Pants = qglGetUniformLocation(p->program, "Texture_Pants");
3865 p->loc_Texture_Shirt = qglGetUniformLocation(p->program, "Texture_Shirt");
3866 p->loc_Texture_FogHeightTexture = qglGetUniformLocation(p->program, "Texture_FogHeightTexture");
3867 p->loc_Texture_FogMask = qglGetUniformLocation(p->program, "Texture_FogMask");
3868 p->loc_Texture_Lightmap = qglGetUniformLocation(p->program, "Texture_Lightmap");
3869 p->loc_Texture_Deluxemap = qglGetUniformLocation(p->program, "Texture_Deluxemap");
3870 p->loc_Texture_Attenuation = qglGetUniformLocation(p->program, "Texture_Attenuation");
3871 p->loc_Texture_Cube = qglGetUniformLocation(p->program, "Texture_Cube");
3872 p->loc_Texture_Refraction = qglGetUniformLocation(p->program, "Texture_Refraction");
3873 p->loc_Texture_Reflection = qglGetUniformLocation(p->program, "Texture_Reflection");
3874 p->loc_Texture_ShadowMap2D = qglGetUniformLocation(p->program, "Texture_ShadowMap2D");
3875 p->loc_Texture_CubeProjection = qglGetUniformLocation(p->program, "Texture_CubeProjection");
3876 p->loc_Texture_ScreenDepth = qglGetUniformLocation(p->program, "Texture_ScreenDepth");
3877 p->loc_Texture_ScreenNormalMap = qglGetUniformLocation(p->program, "Texture_ScreenNormalMap");
3878 p->loc_Texture_ScreenDiffuse = qglGetUniformLocation(p->program, "Texture_ScreenDiffuse");
3879 p->loc_Texture_ScreenSpecular = qglGetUniformLocation(p->program, "Texture_ScreenSpecular");
3880 p->loc_Texture_ReflectMask = qglGetUniformLocation(p->program, "Texture_ReflectMask");
3881 p->loc_Texture_ReflectCube = qglGetUniformLocation(p->program, "Texture_ReflectCube");
3882 p->loc_Texture_BounceGrid = qglGetUniformLocation(p->program, "Texture_BounceGrid");
3883 p->loc_Alpha = qglGetUniformLocation(p->program, "Alpha");
3884 p->loc_BloomBlur_Parameters = qglGetUniformLocation(p->program, "BloomBlur_Parameters");
3885 p->loc_ClientTime = qglGetUniformLocation(p->program, "ClientTime");
3886 p->loc_Color_Ambient = qglGetUniformLocation(p->program, "Color_Ambient");
3887 p->loc_Color_Diffuse = qglGetUniformLocation(p->program, "Color_Diffuse");
3888 p->loc_Color_Specular = qglGetUniformLocation(p->program, "Color_Specular");
3889 p->loc_Color_Glow = qglGetUniformLocation(p->program, "Color_Glow");
3890 p->loc_Color_Pants = qglGetUniformLocation(p->program, "Color_Pants");
3891 p->loc_Color_Shirt = qglGetUniformLocation(p->program, "Color_Shirt");
3892 p->loc_DeferredColor_Ambient = qglGetUniformLocation(p->program, "DeferredColor_Ambient");
3893 p->loc_DeferredColor_Diffuse = qglGetUniformLocation(p->program, "DeferredColor_Diffuse");
3894 p->loc_DeferredColor_Specular = qglGetUniformLocation(p->program, "DeferredColor_Specular");
3895 p->loc_DeferredMod_Diffuse = qglGetUniformLocation(p->program, "DeferredMod_Diffuse");
3896 p->loc_DeferredMod_Specular = qglGetUniformLocation(p->program, "DeferredMod_Specular");
3897 p->loc_DistortScaleRefractReflect = qglGetUniformLocation(p->program, "DistortScaleRefractReflect");
3898 p->loc_EyePosition = qglGetUniformLocation(p->program, "EyePosition");
3899 p->loc_FogColor = qglGetUniformLocation(p->program, "FogColor");
3900 p->loc_FogHeightFade = qglGetUniformLocation(p->program, "FogHeightFade");
3901 p->loc_FogPlane = qglGetUniformLocation(p->program, "FogPlane");
3902 p->loc_FogPlaneViewDist = qglGetUniformLocation(p->program, "FogPlaneViewDist");
3903 p->loc_FogRangeRecip = qglGetUniformLocation(p->program, "FogRangeRecip");
3904 p->loc_LightColor = qglGetUniformLocation(p->program, "LightColor");
3905 p->loc_LightDir = qglGetUniformLocation(p->program, "LightDir");
3906 p->loc_LightPosition = qglGetUniformLocation(p->program, "LightPosition");
3907 p->loc_OffsetMapping_Scale = qglGetUniformLocation(p->program, "OffsetMapping_Scale");
3908 p->loc_PixelSize = qglGetUniformLocation(p->program, "PixelSize");
3909 p->loc_ReflectColor = qglGetUniformLocation(p->program, "ReflectColor");
3910 p->loc_ReflectFactor = qglGetUniformLocation(p->program, "ReflectFactor");
3911 p->loc_ReflectOffset = qglGetUniformLocation(p->program, "ReflectOffset");
3912 p->loc_RefractColor = qglGetUniformLocation(p->program, "RefractColor");
3913 p->loc_Saturation = qglGetUniformLocation(p->program, "Saturation");
3914 p->loc_ScreenCenterRefractReflect = qglGetUniformLocation(p->program, "ScreenCenterRefractReflect");
3915 p->loc_ScreenScaleRefractReflect = qglGetUniformLocation(p->program, "ScreenScaleRefractReflect");
3916 p->loc_ScreenToDepth = qglGetUniformLocation(p->program, "ScreenToDepth");
3917 p->loc_ShadowMap_Parameters = qglGetUniformLocation(p->program, "ShadowMap_Parameters");
3918 p->loc_ShadowMap_TextureScale = qglGetUniformLocation(p->program, "ShadowMap_TextureScale");
3919 p->loc_SpecularPower = qglGetUniformLocation(p->program, "SpecularPower");
3920 p->loc_UserVec1 = qglGetUniformLocation(p->program, "UserVec1");
3921 p->loc_UserVec2 = qglGetUniformLocation(p->program, "UserVec2");
3922 p->loc_UserVec3 = qglGetUniformLocation(p->program, "UserVec3");
3923 p->loc_UserVec4 = qglGetUniformLocation(p->program, "UserVec4");
3924 p->loc_ViewTintColor = qglGetUniformLocation(p->program, "ViewTintColor");
3925 p->loc_ViewToLight = qglGetUniformLocation(p->program, "ViewToLight");
3926 p->loc_ModelToLight = qglGetUniformLocation(p->program, "ModelToLight");
3927 p->loc_TexMatrix = qglGetUniformLocation(p->program, "TexMatrix");
3928 p->loc_BackgroundTexMatrix = qglGetUniformLocation(p->program, "BackgroundTexMatrix");
3929 p->loc_ModelViewMatrix = qglGetUniformLocation(p->program, "ModelViewMatrix");
3930 p->loc_ModelViewProjectionMatrix = qglGetUniformLocation(p->program, "ModelViewProjectionMatrix");
3931 p->loc_PixelToScreenTexCoord = qglGetUniformLocation(p->program, "PixelToScreenTexCoord");
3932 p->loc_ModelToReflectCube = qglGetUniformLocation(p->program, "ModelToReflectCube");
3933 p->loc_ShadowMapMatrix = qglGetUniformLocation(p->program, "ShadowMapMatrix");
3934 p->loc_BloomColorSubtract = qglGetUniformLocation(p->program, "BloomColorSubtract");
3935 p->loc_NormalmapScrollBlend = qglGetUniformLocation(p->program, "NormalmapScrollBlend");
3936 p->loc_BounceGridMatrix = qglGetUniformLocation(p->program, "BounceGridMatrix");
3937 p->loc_BounceGridIntensity = qglGetUniformLocation(p->program, "BounceGridIntensity");
3938 // initialize the samplers to refer to the texture units we use
3939 p->tex_Texture_First = -1;
3940 p->tex_Texture_Second = -1;
3941 p->tex_Texture_GammaRamps = -1;
3942 p->tex_Texture_Normal = -1;
3943 p->tex_Texture_Color = -1;
3944 p->tex_Texture_Gloss = -1;
3945 p->tex_Texture_Glow = -1;
3946 p->tex_Texture_SecondaryNormal = -1;
3947 p->tex_Texture_SecondaryColor = -1;
3948 p->tex_Texture_SecondaryGloss = -1;
3949 p->tex_Texture_SecondaryGlow = -1;
3950 p->tex_Texture_Pants = -1;
3951 p->tex_Texture_Shirt = -1;
3952 p->tex_Texture_FogHeightTexture = -1;
3953 p->tex_Texture_FogMask = -1;
3954 p->tex_Texture_Lightmap = -1;
3955 p->tex_Texture_Deluxemap = -1;
3956 p->tex_Texture_Attenuation = -1;
3957 p->tex_Texture_Cube = -1;
3958 p->tex_Texture_Refraction = -1;
3959 p->tex_Texture_Reflection = -1;
3960 p->tex_Texture_ShadowMap2D = -1;
3961 p->tex_Texture_CubeProjection = -1;
3962 p->tex_Texture_ScreenDepth = -1;
3963 p->tex_Texture_ScreenNormalMap = -1;
3964 p->tex_Texture_ScreenDiffuse = -1;
3965 p->tex_Texture_ScreenSpecular = -1;
3966 p->tex_Texture_ReflectMask = -1;
3967 p->tex_Texture_ReflectCube = -1;
3968 p->tex_Texture_BounceGrid = -1;
3970 if (p->loc_Texture_First >= 0) {p->tex_Texture_First = sampler;qglUniform1i(p->loc_Texture_First , sampler);sampler++;}
3971 if (p->loc_Texture_Second >= 0) {p->tex_Texture_Second = sampler;qglUniform1i(p->loc_Texture_Second , sampler);sampler++;}
3972 if (p->loc_Texture_GammaRamps >= 0) {p->tex_Texture_GammaRamps = sampler;qglUniform1i(p->loc_Texture_GammaRamps , sampler);sampler++;}
3973 if (p->loc_Texture_Normal >= 0) {p->tex_Texture_Normal = sampler;qglUniform1i(p->loc_Texture_Normal , sampler);sampler++;}
3974 if (p->loc_Texture_Color >= 0) {p->tex_Texture_Color = sampler;qglUniform1i(p->loc_Texture_Color , sampler);sampler++;}
3975 if (p->loc_Texture_Gloss >= 0) {p->tex_Texture_Gloss = sampler;qglUniform1i(p->loc_Texture_Gloss , sampler);sampler++;}
3976 if (p->loc_Texture_Glow >= 0) {p->tex_Texture_Glow = sampler;qglUniform1i(p->loc_Texture_Glow , sampler);sampler++;}
3977 if (p->loc_Texture_SecondaryNormal >= 0) {p->tex_Texture_SecondaryNormal = sampler;qglUniform1i(p->loc_Texture_SecondaryNormal , sampler);sampler++;}
3978 if (p->loc_Texture_SecondaryColor >= 0) {p->tex_Texture_SecondaryColor = sampler;qglUniform1i(p->loc_Texture_SecondaryColor , sampler);sampler++;}
3979 if (p->loc_Texture_SecondaryGloss >= 0) {p->tex_Texture_SecondaryGloss = sampler;qglUniform1i(p->loc_Texture_SecondaryGloss , sampler);sampler++;}
3980 if (p->loc_Texture_SecondaryGlow >= 0) {p->tex_Texture_SecondaryGlow = sampler;qglUniform1i(p->loc_Texture_SecondaryGlow , sampler);sampler++;}
3981 if (p->loc_Texture_Pants >= 0) {p->tex_Texture_Pants = sampler;qglUniform1i(p->loc_Texture_Pants , sampler);sampler++;}
3982 if (p->loc_Texture_Shirt >= 0) {p->tex_Texture_Shirt = sampler;qglUniform1i(p->loc_Texture_Shirt , sampler);sampler++;}
3983 if (p->loc_Texture_FogHeightTexture>= 0) {p->tex_Texture_FogHeightTexture = sampler;qglUniform1i(p->loc_Texture_FogHeightTexture, sampler);sampler++;}
3984 if (p->loc_Texture_FogMask >= 0) {p->tex_Texture_FogMask = sampler;qglUniform1i(p->loc_Texture_FogMask , sampler);sampler++;}
3985 if (p->loc_Texture_Lightmap >= 0) {p->tex_Texture_Lightmap = sampler;qglUniform1i(p->loc_Texture_Lightmap , sampler);sampler++;}
3986 if (p->loc_Texture_Deluxemap >= 0) {p->tex_Texture_Deluxemap = sampler;qglUniform1i(p->loc_Texture_Deluxemap , sampler);sampler++;}
3987 if (p->loc_Texture_Attenuation >= 0) {p->tex_Texture_Attenuation = sampler;qglUniform1i(p->loc_Texture_Attenuation , sampler);sampler++;}
3988 if (p->loc_Texture_Cube >= 0) {p->tex_Texture_Cube = sampler;qglUniform1i(p->loc_Texture_Cube , sampler);sampler++;}
3989 if (p->loc_Texture_Refraction >= 0) {p->tex_Texture_Refraction = sampler;qglUniform1i(p->loc_Texture_Refraction , sampler);sampler++;}
3990 if (p->loc_Texture_Reflection >= 0) {p->tex_Texture_Reflection = sampler;qglUniform1i(p->loc_Texture_Reflection , sampler);sampler++;}
3991 if (p->loc_Texture_ShadowMap2D >= 0) {p->tex_Texture_ShadowMap2D = sampler;qglUniform1i(p->loc_Texture_ShadowMap2D , sampler);sampler++;}
3992 if (p->loc_Texture_CubeProjection >= 0) {p->tex_Texture_CubeProjection = sampler;qglUniform1i(p->loc_Texture_CubeProjection , sampler);sampler++;}
3993 if (p->loc_Texture_ScreenDepth >= 0) {p->tex_Texture_ScreenDepth = sampler;qglUniform1i(p->loc_Texture_ScreenDepth , sampler);sampler++;}
3994 if (p->loc_Texture_ScreenNormalMap >= 0) {p->tex_Texture_ScreenNormalMap = sampler;qglUniform1i(p->loc_Texture_ScreenNormalMap , sampler);sampler++;}
3995 if (p->loc_Texture_ScreenDiffuse >= 0) {p->tex_Texture_ScreenDiffuse = sampler;qglUniform1i(p->loc_Texture_ScreenDiffuse , sampler);sampler++;}
3996 if (p->loc_Texture_ScreenSpecular >= 0) {p->tex_Texture_ScreenSpecular = sampler;qglUniform1i(p->loc_Texture_ScreenSpecular , sampler);sampler++;}
3997 if (p->loc_Texture_ReflectMask >= 0) {p->tex_Texture_ReflectMask = sampler;qglUniform1i(p->loc_Texture_ReflectMask , sampler);sampler++;}
3998 if (p->loc_Texture_ReflectCube >= 0) {p->tex_Texture_ReflectCube = sampler;qglUniform1i(p->loc_Texture_ReflectCube , sampler);sampler++;}
3999 if (p->loc_Texture_BounceGrid >= 0) {p->tex_Texture_BounceGrid = sampler;qglUniform1i(p->loc_Texture_BounceGrid , sampler);sampler++;}
4001 Con_DPrintf("^5GLSL shader %s compiled (%i textures).\n", permutationname, sampler);
4004 Con_Printf("^1GLSL shader %s failed! some features may not work properly.\n", permutationname);
4008 Mem_Free(vertexstring);
4010 Mem_Free(geometrystring);
4012 Mem_Free(fragmentstring);
4015 void R_SetupShader_SetPermutationGLSL(unsigned int mode, unsigned int permutation)
4017 r_glsl_permutation_t *perm = R_GLSL_FindPermutation(mode, permutation);
4018 if (r_glsl_permutation != perm)
4020 r_glsl_permutation = perm;
4021 if (!r_glsl_permutation->program)
4023 if (!r_glsl_permutation->compiled)
4024 R_GLSL_CompilePermutation(perm, mode, permutation);
4025 if (!r_glsl_permutation->program)
4027 // remove features until we find a valid permutation
4029 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4031 // reduce i more quickly whenever it would not remove any bits
4032 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4033 if (!(permutation & j))
4036 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4037 if (!r_glsl_permutation->compiled)
4038 R_GLSL_CompilePermutation(perm, mode, permutation);
4039 if (r_glsl_permutation->program)
4042 if (i >= SHADERPERMUTATION_COUNT)
4044 //Con_Printf("Could not find a working OpenGL 2.0 shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4045 r_glsl_permutation = R_GLSL_FindPermutation(mode, permutation);
4046 qglUseProgram(0);CHECKGLERROR
4047 return; // no bit left to clear, entire mode is broken
4052 qglUseProgram(r_glsl_permutation->program);CHECKGLERROR
4054 if (r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
4055 if (r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
4056 if (r_glsl_permutation->loc_ClientTime >= 0) qglUniform1f(r_glsl_permutation->loc_ClientTime, cl.time);
4063 extern LPDIRECT3DDEVICE9 vid_d3d9dev;
4064 extern D3DCAPS9 vid_d3d9caps;
4067 struct r_hlsl_permutation_s;
4068 typedef struct r_hlsl_permutation_s
4070 /// hash lookup data
4071 struct r_hlsl_permutation_s *hashnext;
4073 unsigned int permutation;
4075 /// indicates if we have tried compiling this permutation already
4077 /// NULL if compilation failed
4078 IDirect3DVertexShader9 *vertexshader;
4079 IDirect3DPixelShader9 *pixelshader;
4081 r_hlsl_permutation_t;
4083 typedef enum D3DVSREGISTER_e
4085 D3DVSREGISTER_TexMatrix = 0, // float4x4
4086 D3DVSREGISTER_BackgroundTexMatrix = 4, // float4x4
4087 D3DVSREGISTER_ModelViewProjectionMatrix = 8, // float4x4
4088 D3DVSREGISTER_ModelViewMatrix = 12, // float4x4
4089 D3DVSREGISTER_ShadowMapMatrix = 16, // float4x4
4090 D3DVSREGISTER_ModelToLight = 20, // float4x4
4091 D3DVSREGISTER_EyePosition = 24,
4092 D3DVSREGISTER_FogPlane = 25,
4093 D3DVSREGISTER_LightDir = 26,
4094 D3DVSREGISTER_LightPosition = 27,
4098 typedef enum D3DPSREGISTER_e
4100 D3DPSREGISTER_Alpha = 0,
4101 D3DPSREGISTER_BloomBlur_Parameters = 1,
4102 D3DPSREGISTER_ClientTime = 2,
4103 D3DPSREGISTER_Color_Ambient = 3,
4104 D3DPSREGISTER_Color_Diffuse = 4,
4105 D3DPSREGISTER_Color_Specular = 5,
4106 D3DPSREGISTER_Color_Glow = 6,
4107 D3DPSREGISTER_Color_Pants = 7,
4108 D3DPSREGISTER_Color_Shirt = 8,
4109 D3DPSREGISTER_DeferredColor_Ambient = 9,
4110 D3DPSREGISTER_DeferredColor_Diffuse = 10,
4111 D3DPSREGISTER_DeferredColor_Specular = 11,
4112 D3DPSREGISTER_DeferredMod_Diffuse = 12,
4113 D3DPSREGISTER_DeferredMod_Specular = 13,
4114 D3DPSREGISTER_DistortScaleRefractReflect = 14,
4115 D3DPSREGISTER_EyePosition = 15, // unused
4116 D3DPSREGISTER_FogColor = 16,
4117 D3DPSREGISTER_FogHeightFade = 17,
4118 D3DPSREGISTER_FogPlane = 18,
4119 D3DPSREGISTER_FogPlaneViewDist = 19,
4120 D3DPSREGISTER_FogRangeRecip = 20,
4121 D3DPSREGISTER_LightColor = 21,
4122 D3DPSREGISTER_LightDir = 22, // unused
4123 D3DPSREGISTER_LightPosition = 23,
4124 D3DPSREGISTER_OffsetMapping_Scale = 24,
4125 D3DPSREGISTER_PixelSize = 25,
4126 D3DPSREGISTER_ReflectColor = 26,
4127 D3DPSREGISTER_ReflectFactor = 27,
4128 D3DPSREGISTER_ReflectOffset = 28,
4129 D3DPSREGISTER_RefractColor = 29,
4130 D3DPSREGISTER_Saturation = 30,
4131 D3DPSREGISTER_ScreenCenterRefractReflect = 31,
4132 D3DPSREGISTER_ScreenScaleRefractReflect = 32,
4133 D3DPSREGISTER_ScreenToDepth = 33,
4134 D3DPSREGISTER_ShadowMap_Parameters = 34,
4135 D3DPSREGISTER_ShadowMap_TextureScale = 35,
4136 D3DPSREGISTER_SpecularPower = 36,
4137 D3DPSREGISTER_UserVec1 = 37,
4138 D3DPSREGISTER_UserVec2 = 38,
4139 D3DPSREGISTER_UserVec3 = 39,
4140 D3DPSREGISTER_UserVec4 = 40,
4141 D3DPSREGISTER_ViewTintColor = 41,
4142 D3DPSREGISTER_PixelToScreenTexCoord = 42,
4143 D3DPSREGISTER_BloomColorSubtract = 43,
4144 D3DPSREGISTER_ViewToLight = 44, // float4x4
4145 D3DPSREGISTER_ModelToReflectCube = 48, // float4x4
4146 D3DPSREGISTER_NormalmapScrollBlend = 52,
4151 /// information about each possible shader permutation
4152 r_hlsl_permutation_t *r_hlsl_permutationhash[SHADERMODE_COUNT][SHADERPERMUTATION_HASHSIZE];
4153 /// currently selected permutation
4154 r_hlsl_permutation_t *r_hlsl_permutation;
4155 /// storage for permutations linked in the hash table
4156 memexpandablearray_t r_hlsl_permutationarray;
4158 static r_hlsl_permutation_t *R_HLSL_FindPermutation(unsigned int mode, unsigned int permutation)
4160 //unsigned int hashdepth = 0;
4161 unsigned int hashindex = (permutation * 0x1021) & (SHADERPERMUTATION_HASHSIZE - 1);
4162 r_hlsl_permutation_t *p;
4163 for (p = r_hlsl_permutationhash[mode][hashindex];p;p = p->hashnext)
4165 if (p->mode == mode && p->permutation == permutation)
4167 //if (hashdepth > 10)
4168 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4173 p = (r_hlsl_permutation_t*)Mem_ExpandableArray_AllocRecord(&r_hlsl_permutationarray);
4175 p->permutation = permutation;
4176 p->hashnext = r_hlsl_permutationhash[mode][hashindex];
4177 r_hlsl_permutationhash[mode][hashindex] = p;
4178 //if (hashdepth > 10)
4179 // Con_Printf("R_HLSL_FindPermutation: Warning: %i:%i has hashdepth %i\n", mode, permutation, hashdepth);
4183 static char *R_HLSL_GetText(const char *filename, qboolean printfromdisknotice)
4186 if (!filename || !filename[0])
4188 if (!strcmp(filename, "hlsl/default.hlsl"))
4190 if (!hlslshaderstring)
4192 hlslshaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4193 if (hlslshaderstring)
4194 Con_DPrintf("Loading shaders from file %s...\n", filename);
4196 hlslshaderstring = (char *)builtinhlslshaderstring;
4198 shaderstring = (char *) Mem_Alloc(r_main_mempool, strlen(hlslshaderstring) + 1);
4199 memcpy(shaderstring, hlslshaderstring, strlen(hlslshaderstring) + 1);
4200 return shaderstring;
4202 shaderstring = (char *)FS_LoadFile(filename, r_main_mempool, false, NULL);
4205 if (printfromdisknotice)
4206 Con_DPrintf("from disk %s... ", filename);
4207 return shaderstring;
4209 return shaderstring;
4213 //#include <d3dx9shader.h>
4214 //#include <d3dx9mesh.h>
4216 static void R_HLSL_CacheShader(r_hlsl_permutation_t *p, const char *cachename, const char *vertstring, const char *fragstring)
4218 DWORD *vsbin = NULL;
4219 DWORD *psbin = NULL;
4220 fs_offset_t vsbinsize;
4221 fs_offset_t psbinsize;
4222 // IDirect3DVertexShader9 *vs = NULL;
4223 // IDirect3DPixelShader9 *ps = NULL;
4224 ID3DXBuffer *vslog = NULL;
4225 ID3DXBuffer *vsbuffer = NULL;
4226 ID3DXConstantTable *vsconstanttable = NULL;
4227 ID3DXBuffer *pslog = NULL;
4228 ID3DXBuffer *psbuffer = NULL;
4229 ID3DXConstantTable *psconstanttable = NULL;
4232 char temp[MAX_INPUTLINE];
4233 const char *vsversion = "vs_3_0", *psversion = "ps_3_0";
4234 qboolean debugshader = gl_paranoid.integer != 0;
4235 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4236 if (p->permutation & SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING) {vsversion = "vs_3_0";psversion = "ps_3_0";}
4239 vsbin = (DWORD *)FS_LoadFile(va("%s.vsbin", cachename), r_main_mempool, true, &vsbinsize);
4240 psbin = (DWORD *)FS_LoadFile(va("%s.psbin", cachename), r_main_mempool, true, &psbinsize);
4242 if ((!vsbin && vertstring) || (!psbin && fragstring))
4244 const char* dllnames_d3dx9 [] =
4268 dllhandle_t d3dx9_dll = NULL;
4269 HRESULT (WINAPI *qD3DXCompileShaderFromFileA)(LPCSTR pSrcFile, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4270 HRESULT (WINAPI *qD3DXPreprocessShader)(LPCSTR pSrcData, UINT SrcDataSize, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPD3DXBUFFER* ppShaderText, LPD3DXBUFFER* ppErrorMsgs);
4271 HRESULT (WINAPI *qD3DXCompileShader)(LPCSTR pSrcData, UINT SrcDataLen, CONST D3DXMACRO* pDefines, LPD3DXINCLUDE pInclude, LPCSTR pFunctionName, LPCSTR pProfile, DWORD Flags, LPD3DXBUFFER* ppShader, LPD3DXBUFFER* ppErrorMsgs, LPD3DXCONSTANTTABLE* ppConstantTable);
4272 dllfunction_t d3dx9_dllfuncs[] =
4274 {"D3DXCompileShaderFromFileA", (void **) &qD3DXCompileShaderFromFileA},
4275 {"D3DXPreprocessShader", (void **) &qD3DXPreprocessShader},
4276 {"D3DXCompileShader", (void **) &qD3DXCompileShader},
4279 if (Sys_LoadLibrary(dllnames_d3dx9, &d3dx9_dll, d3dx9_dllfuncs))
4281 DWORD shaderflags = 0;
4283 shaderflags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION;
4284 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4285 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4286 if (vertstring && vertstring[0])
4290 // vsresult = qD3DXPreprocessShader(vertstring, strlen(vertstring), NULL, NULL, &vsbuffer, &vslog);
4291 // FS_WriteFile(va("%s_vs.fx", cachename), vsbuffer->GetBufferPointer(), vsbuffer->GetBufferSize());
4292 FS_WriteFile(va("%s_vs.fx", cachename), vertstring, strlen(vertstring));
4293 vsresult = qD3DXCompileShaderFromFileA(va("%s/%s_vs.fx", fs_gamedir, cachename), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4296 vsresult = qD3DXCompileShader(vertstring, strlen(vertstring), NULL, NULL, "main", vsversion, shaderflags, &vsbuffer, &vslog, &vsconstanttable);
4299 vsbinsize = vsbuffer->GetBufferSize();
4300 vsbin = (DWORD *)Mem_Alloc(tempmempool, vsbinsize);
4301 memcpy(vsbin, vsbuffer->GetBufferPointer(), vsbinsize);
4302 vsbuffer->Release();
4306 strlcpy(temp, (const char *)vslog->GetBufferPointer(), min(sizeof(temp), vslog->GetBufferSize()));
4307 Con_Printf("HLSL vertex shader compile output for %s follows:\n%s\n", cachename, temp);
4311 if (fragstring && fragstring[0])
4315 // psresult = qD3DXPreprocessShader(fragstring, strlen(fragstring), NULL, NULL, &psbuffer, &pslog);
4316 // FS_WriteFile(va("%s_ps.fx", cachename), psbuffer->GetBufferPointer(), psbuffer->GetBufferSize());
4317 FS_WriteFile(va("%s_ps.fx", cachename), fragstring, strlen(fragstring));
4318 psresult = qD3DXCompileShaderFromFileA(va("%s/%s_ps.fx", fs_gamedir, cachename), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4321 psresult = qD3DXCompileShader(fragstring, strlen(fragstring), NULL, NULL, "main", psversion, shaderflags, &psbuffer, &pslog, &psconstanttable);
4324 psbinsize = psbuffer->GetBufferSize();
4325 psbin = (DWORD *)Mem_Alloc(tempmempool, psbinsize);
4326 memcpy(psbin, psbuffer->GetBufferPointer(), psbinsize);
4327 psbuffer->Release();
4331 strlcpy(temp, (const char *)pslog->GetBufferPointer(), min(sizeof(temp), pslog->GetBufferSize()));
4332 Con_Printf("HLSL pixel shader compile output for %s follows:\n%s\n", cachename, temp);
4336 Sys_UnloadLibrary(&d3dx9_dll);
4339 Con_Printf("Unable to compile shader - D3DXCompileShader function not found\n");
4343 vsresult = IDirect3DDevice9_CreateVertexShader(vid_d3d9dev, vsbin, &p->vertexshader);
4344 if (FAILED(vsresult))
4345 Con_Printf("HLSL CreateVertexShader failed for %s (hresult = %8x)\n", cachename, vsresult);
4346 psresult = IDirect3DDevice9_CreatePixelShader(vid_d3d9dev, psbin, &p->pixelshader);
4347 if (FAILED(psresult))
4348 Con_Printf("HLSL CreatePixelShader failed for %s (hresult = %8x)\n", cachename, psresult);
4350 // free the shader data
4351 vsbin = (DWORD *)Mem_Realloc(tempmempool, vsbin, 0);
4352 psbin = (DWORD *)Mem_Realloc(tempmempool, psbin, 0);
4355 static void R_HLSL_CompilePermutation(r_hlsl_permutation_t *p, unsigned int mode, unsigned int permutation)
4358 shadermodeinfo_t *modeinfo = hlslshadermodeinfo + mode;
4359 int vertstring_length = 0;
4360 int geomstring_length = 0;
4361 int fragstring_length = 0;
4363 char *vertexstring, *geometrystring, *fragmentstring;
4364 char *vertstring, *geomstring, *fragstring;
4365 char permutationname[256];
4366 char cachename[256];
4367 int vertstrings_count = 0;
4368 int geomstrings_count = 0;
4369 int fragstrings_count = 0;
4370 const char *vertstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4371 const char *geomstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4372 const char *fragstrings_list[32+3+SHADERSTATICPARMS_COUNT+1];
4377 p->vertexshader = NULL;
4378 p->pixelshader = NULL;
4380 permutationname[0] = 0;
4382 vertexstring = R_HLSL_GetText(modeinfo->vertexfilename, true);
4383 geometrystring = R_HLSL_GetText(modeinfo->geometryfilename, false);
4384 fragmentstring = R_HLSL_GetText(modeinfo->fragmentfilename, false);
4386 strlcat(permutationname, modeinfo->vertexfilename, sizeof(permutationname));
4387 strlcat(cachename, "hlsl/", sizeof(cachename));
4389 // define HLSL so that the shader can tell apart the HLSL compiler and the Cg compiler
4390 vertstrings_count = 0;
4391 geomstrings_count = 0;
4392 fragstrings_count = 0;
4393 vertstrings_list[vertstrings_count++] = "#define HLSL\n";
4394 geomstrings_list[geomstrings_count++] = "#define HLSL\n";
4395 fragstrings_list[fragstrings_count++] = "#define HLSL\n";
4397 // the first pretext is which type of shader to compile as
4398 // (later these will all be bound together as a program object)
4399 vertstrings_list[vertstrings_count++] = "#define VERTEX_SHADER\n";
4400 geomstrings_list[geomstrings_count++] = "#define GEOMETRY_SHADER\n";
4401 fragstrings_list[fragstrings_count++] = "#define FRAGMENT_SHADER\n";
4403 // the second pretext is the mode (for example a light source)
4404 vertstrings_list[vertstrings_count++] = modeinfo->pretext;
4405 geomstrings_list[geomstrings_count++] = modeinfo->pretext;
4406 fragstrings_list[fragstrings_count++] = modeinfo->pretext;
4407 strlcat(permutationname, modeinfo->name, sizeof(permutationname));
4408 strlcat(cachename, modeinfo->name, sizeof(cachename));
4410 // now add all the permutation pretexts
4411 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4413 if (permutation & (1<<i))
4415 vertstrings_list[vertstrings_count++] = shaderpermutationinfo[i].pretext;
4416 geomstrings_list[geomstrings_count++] = shaderpermutationinfo[i].pretext;
4417 fragstrings_list[fragstrings_count++] = shaderpermutationinfo[i].pretext;
4418 strlcat(permutationname, shaderpermutationinfo[i].name, sizeof(permutationname));
4419 strlcat(cachename, shaderpermutationinfo[i].name, sizeof(cachename));
4423 // keep line numbers correct
4424 vertstrings_list[vertstrings_count++] = "\n";
4425 geomstrings_list[geomstrings_count++] = "\n";
4426 fragstrings_list[fragstrings_count++] = "\n";
4431 R_CompileShader_AddStaticParms(mode, permutation);
4432 memcpy(vertstrings_list + vertstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4433 vertstrings_count += shaderstaticparms_count;
4434 memcpy(geomstrings_list + geomstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4435 geomstrings_count += shaderstaticparms_count;
4436 memcpy(fragstrings_list + fragstrings_count, shaderstaticparmstrings_list, sizeof(*vertstrings_list) * shaderstaticparms_count);
4437 fragstrings_count += shaderstaticparms_count;
4439 // replace spaces in the cachename with _ characters
4440 for (i = 0;cachename[i];i++)
4441 if (cachename[i] == ' ')
4444 // now append the shader text itself
4445 vertstrings_list[vertstrings_count++] = vertexstring;
4446 geomstrings_list[geomstrings_count++] = geometrystring;
4447 fragstrings_list[fragstrings_count++] = fragmentstring;
4449 // if any sources were NULL, clear the respective list
4451 vertstrings_count = 0;
4452 if (!geometrystring)
4453 geomstrings_count = 0;
4454 if (!fragmentstring)
4455 fragstrings_count = 0;
4457 vertstring_length = 0;
4458 for (i = 0;i < vertstrings_count;i++)
4459 vertstring_length += strlen(vertstrings_list[i]);
4460 vertstring = t = (char *)Mem_Alloc(tempmempool, vertstring_length + 1);
4461 for (i = 0;i < vertstrings_count;t += strlen(vertstrings_list[i]), i++)
4462 memcpy(t, vertstrings_list[i], strlen(vertstrings_list[i]));
4464 geomstring_length = 0;
4465 for (i = 0;i < geomstrings_count;i++)
4466 geomstring_length += strlen(geomstrings_list[i]);
4467 geomstring = t = (char *)Mem_Alloc(tempmempool, geomstring_length + 1);
4468 for (i = 0;i < geomstrings_count;t += strlen(geomstrings_list[i]), i++)
4469 memcpy(t, geomstrings_list[i], strlen(geomstrings_list[i]));
4471 fragstring_length = 0;
4472 for (i = 0;i < fragstrings_count;i++)
4473 fragstring_length += strlen(fragstrings_list[i]);
4474 fragstring = t = (char *)Mem_Alloc(tempmempool, fragstring_length + 1);
4475 for (i = 0;i < fragstrings_count;t += strlen(fragstrings_list[i]), i++)
4476 memcpy(t, fragstrings_list[i], strlen(fragstrings_list[i]));
4478 // try to load the cached shader, or generate one
4479 R_HLSL_CacheShader(p, cachename, vertstring, fragstring);
4481 if ((p->vertexshader || !vertstring[0]) && (p->pixelshader || !fragstring[0]))
4482 Con_DPrintf("^5HLSL shader %s compiled.\n", permutationname);
4484 Con_Printf("^1HLSL shader %s failed! some features may not work properly.\n", permutationname);
4488 Mem_Free(vertstring);
4490 Mem_Free(geomstring);
4492 Mem_Free(fragstring);
4494 Mem_Free(vertexstring);
4496 Mem_Free(geometrystring);
4498 Mem_Free(fragmentstring);
4501 static inline void hlslVSSetParameter16f(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 4);}
4502 static inline void hlslVSSetParameter4fv(D3DVSREGISTER_t r, const float *a) {IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, a, 1);}
4503 static inline void hlslVSSetParameter4f(D3DVSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4504 static inline void hlslVSSetParameter3f(D3DVSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4505 static inline void hlslVSSetParameter2f(D3DVSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4506 static inline void hlslVSSetParameter1f(D3DVSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetVertexShaderConstantF(vid_d3d9dev, r, temp, 1);}
4508 static inline void hlslPSSetParameter16f(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 4);}
4509 static inline void hlslPSSetParameter4fv(D3DPSREGISTER_t r, const float *a) {IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, a, 1);}
4510 static inline void hlslPSSetParameter4f(D3DPSREGISTER_t r, float x, float y, float z, float w) {float temp[4];Vector4Set(temp, x, y, z, w);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4511 static inline void hlslPSSetParameter3f(D3DPSREGISTER_t r, float x, float y, float z) {float temp[4];Vector4Set(temp, x, y, z, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4512 static inline void hlslPSSetParameter2f(D3DPSREGISTER_t r, float x, float y) {float temp[4];Vector4Set(temp, x, y, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4513 static inline void hlslPSSetParameter1f(D3DPSREGISTER_t r, float x) {float temp[4];Vector4Set(temp, x, 0, 0, 0);IDirect3DDevice9_SetPixelShaderConstantF(vid_d3d9dev, r, temp, 1);}
4515 void R_SetupShader_SetPermutationHLSL(unsigned int mode, unsigned int permutation)
4517 r_hlsl_permutation_t *perm = R_HLSL_FindPermutation(mode, permutation);
4518 if (r_hlsl_permutation != perm)
4520 r_hlsl_permutation = perm;
4521 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4523 if (!r_hlsl_permutation->compiled)
4524 R_HLSL_CompilePermutation(perm, mode, permutation);
4525 if (!r_hlsl_permutation->vertexshader && !r_hlsl_permutation->pixelshader)
4527 // remove features until we find a valid permutation
4529 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4531 // reduce i more quickly whenever it would not remove any bits
4532 int j = 1<<(SHADERPERMUTATION_COUNT-1-i);
4533 if (!(permutation & j))
4536 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4537 if (!r_hlsl_permutation->compiled)
4538 R_HLSL_CompilePermutation(perm, mode, permutation);
4539 if (r_hlsl_permutation->vertexshader || r_hlsl_permutation->pixelshader)
4542 if (i >= SHADERPERMUTATION_COUNT)
4544 //Con_Printf("Could not find a working HLSL shader for permutation %s %s\n", shadermodeinfo[mode].vertexfilename, shadermodeinfo[mode].pretext);
4545 r_hlsl_permutation = R_HLSL_FindPermutation(mode, permutation);
4546 return; // no bit left to clear, entire mode is broken
4550 IDirect3DDevice9_SetVertexShader(vid_d3d9dev, r_hlsl_permutation->vertexshader);
4551 IDirect3DDevice9_SetPixelShader(vid_d3d9dev, r_hlsl_permutation->pixelshader);
4553 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
4554 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
4555 hlslPSSetParameter1f(D3DPSREGISTER_ClientTime, cl.time);
4559 void R_SetupShader_SetPermutationSoft(unsigned int mode, unsigned int permutation)
4561 DPSOFTRAST_SetShader(mode, permutation);
4562 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
4563 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
4564 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ClientTime, cl.time);
4567 void R_GLSL_Restart_f(void)
4569 unsigned int i, limit;
4570 if (glslshaderstring && glslshaderstring != builtinshaderstring)
4571 Mem_Free(glslshaderstring);
4572 glslshaderstring = NULL;
4573 if (hlslshaderstring && hlslshaderstring != builtinhlslshaderstring)
4574 Mem_Free(hlslshaderstring);
4575 hlslshaderstring = NULL;
4576 switch(vid.renderpath)
4578 case RENDERPATH_D3D9:
4581 r_hlsl_permutation_t *p;
4582 r_hlsl_permutation = NULL;
4583 limit = Mem_ExpandableArray_IndexRange(&r_hlsl_permutationarray);
4584 for (i = 0;i < limit;i++)
4586 if ((p = (r_hlsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_hlsl_permutationarray, i)))
4588 if (p->vertexshader)
4589 IDirect3DVertexShader9_Release(p->vertexshader);
4591 IDirect3DPixelShader9_Release(p->pixelshader);
4592 Mem_ExpandableArray_FreeRecord(&r_hlsl_permutationarray, (void*)p);
4595 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
4599 case RENDERPATH_D3D10:
4600 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4602 case RENDERPATH_D3D11:
4603 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4605 case RENDERPATH_GL20:
4606 case RENDERPATH_GLES2:
4608 r_glsl_permutation_t *p;
4609 r_glsl_permutation = NULL;
4610 limit = Mem_ExpandableArray_IndexRange(&r_glsl_permutationarray);
4611 for (i = 0;i < limit;i++)
4613 if ((p = (r_glsl_permutation_t*)Mem_ExpandableArray_RecordAtIndex(&r_glsl_permutationarray, i)))
4615 GL_Backend_FreeProgram(p->program);
4616 Mem_ExpandableArray_FreeRecord(&r_glsl_permutationarray, (void*)p);
4619 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
4622 case RENDERPATH_GL13:
4623 case RENDERPATH_GL11:
4625 case RENDERPATH_SOFT:
4630 void R_GLSL_DumpShader_f(void)
4635 file = FS_OpenRealFile("glsl/default.glsl", "w", false);
4638 FS_Print(file, "/* The engine may define the following macros:\n");
4639 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4640 for (i = 0;i < SHADERMODE_COUNT;i++)
4641 FS_Print(file, glslshadermodeinfo[i].pretext);
4642 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4643 FS_Print(file, shaderpermutationinfo[i].pretext);
4644 FS_Print(file, "*/\n");
4645 FS_Print(file, builtinshaderstring);
4647 Con_Printf("glsl/default.glsl written\n");
4650 Con_Printf("failed to write to glsl/default.glsl\n");
4652 file = FS_OpenRealFile("hlsl/default.hlsl", "w", false);
4655 FS_Print(file, "/* The engine may define the following macros:\n");
4656 FS_Print(file, "#define VERTEX_SHADER\n#define GEOMETRY_SHADER\n#define FRAGMENT_SHADER\n");
4657 for (i = 0;i < SHADERMODE_COUNT;i++)
4658 FS_Print(file, hlslshadermodeinfo[i].pretext);
4659 for (i = 0;i < SHADERPERMUTATION_COUNT;i++)
4660 FS_Print(file, shaderpermutationinfo[i].pretext);
4661 FS_Print(file, "*/\n");
4662 FS_Print(file, builtinhlslshaderstring);
4664 Con_Printf("hlsl/default.hlsl written\n");
4667 Con_Printf("failed to write to hlsl/default.hlsl\n");
4670 void R_SetupShader_Generic(rtexture_t *first, rtexture_t *second, int texturemode, int rgbscale)
4673 texturemode = GL_MODULATE;
4674 switch (vid.renderpath)
4676 case RENDERPATH_D3D9:
4678 R_SetupShader_SetPermutationHLSL(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4679 R_Mesh_TexBind(GL20TU_FIRST , first );
4680 R_Mesh_TexBind(GL20TU_SECOND, second);
4683 case RENDERPATH_D3D10:
4684 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4686 case RENDERPATH_D3D11:
4687 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4689 case RENDERPATH_GL20:
4690 case RENDERPATH_GLES2:
4691 R_SetupShader_SetPermutationGLSL(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4692 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , first );
4693 R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second, second);
4695 case RENDERPATH_GL13:
4696 R_Mesh_TexBind(0, first );
4697 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
4698 R_Mesh_TexBind(1, second);
4700 R_Mesh_TexCombine(1, texturemode, texturemode, rgbscale, 1);
4702 case RENDERPATH_GL11:
4703 R_Mesh_TexBind(0, first );
4705 case RENDERPATH_SOFT:
4706 R_SetupShader_SetPermutationSoft(SHADERMODE_GENERIC, SHADERPERMUTATION_VIEWTINT | (first ? SHADERPERMUTATION_DIFFUSE : 0) | (second ? SHADERPERMUTATION_SPECULAR : 0) | (texturemode == GL_MODULATE ? SHADERPERMUTATION_COLORMAPPING : (texturemode == GL_ADD ? SHADERPERMUTATION_GLOW : (texturemode == GL_DECAL ? SHADERPERMUTATION_VERTEXTEXTUREBLEND : 0))));
4707 R_Mesh_TexBind(GL20TU_FIRST , first );
4708 R_Mesh_TexBind(GL20TU_SECOND, second);
4713 void R_SetupShader_DepthOrShadow(void)
4715 switch (vid.renderpath)
4717 case RENDERPATH_D3D9:
4719 R_SetupShader_SetPermutationHLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4722 case RENDERPATH_D3D10:
4723 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4725 case RENDERPATH_D3D11:
4726 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4728 case RENDERPATH_GL20:
4729 case RENDERPATH_GLES2:
4730 R_SetupShader_SetPermutationGLSL(SHADERMODE_DEPTH_OR_SHADOW, 0);
4732 case RENDERPATH_GL13:
4733 R_Mesh_TexBind(0, 0);
4734 R_Mesh_TexBind(1, 0);
4736 case RENDERPATH_GL11:
4737 R_Mesh_TexBind(0, 0);
4739 case RENDERPATH_SOFT:
4740 R_SetupShader_SetPermutationSoft(SHADERMODE_DEPTH_OR_SHADOW, 0);
4745 void R_SetupShader_ShowDepth(void)
4747 switch (vid.renderpath)
4749 case RENDERPATH_D3D9:
4751 R_SetupShader_SetPermutationHLSL(SHADERMODE_SHOWDEPTH, 0);
4754 case RENDERPATH_D3D10:
4755 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4757 case RENDERPATH_D3D11:
4758 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
4760 case RENDERPATH_GL20:
4761 case RENDERPATH_GLES2:
4762 R_SetupShader_SetPermutationGLSL(SHADERMODE_SHOWDEPTH, 0);
4764 case RENDERPATH_GL13:
4766 case RENDERPATH_GL11:
4768 case RENDERPATH_SOFT:
4769 R_SetupShader_SetPermutationSoft(SHADERMODE_SHOWDEPTH, 0);
4774 extern qboolean r_shadow_usingdeferredprepass;
4775 extern cvar_t r_shadow_deferred_8bitrange;
4776 extern rtexture_t *r_shadow_attenuationgradienttexture;
4777 extern rtexture_t *r_shadow_attenuation2dtexture;
4778 extern rtexture_t *r_shadow_attenuation3dtexture;
4779 extern qboolean r_shadow_usingshadowmap2d;
4780 extern qboolean r_shadow_usingshadowmaportho;
4781 extern float r_shadow_shadowmap_texturescale[2];
4782 extern float r_shadow_shadowmap_parameters[4];
4783 extern qboolean r_shadow_shadowmapvsdct;
4784 extern qboolean r_shadow_shadowmapsampler;
4785 extern int r_shadow_shadowmappcf;
4786 extern rtexture_t *r_shadow_shadowmap2dtexture;
4787 extern rtexture_t *r_shadow_shadowmap2dcolortexture;
4788 extern rtexture_t *r_shadow_shadowmapvsdcttexture;
4789 extern matrix4x4_t r_shadow_shadowmapmatrix;
4790 extern int r_shadow_shadowmaplod; // changes for each light based on distance
4791 extern int r_shadow_prepass_width;
4792 extern int r_shadow_prepass_height;
4793 extern rtexture_t *r_shadow_prepassgeometrydepthtexture;
4794 extern rtexture_t *r_shadow_prepassgeometrynormalmaptexture;
4795 extern rtexture_t *r_shadow_prepassgeometrydepthcolortexture;
4796 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
4797 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
4798 static qboolean R_BlendFuncAllowsColormod(int src, int dst)
4800 // a blendfunc allows colormod if:
4801 // a) it can never keep the destination pixel invariant, or
4802 // b) it can keep the destination pixel invariant, and still can do so if colormodded
4803 // this is to prevent unintended side effects from colormod
4806 // IF there is a (s, sa) for which for all (d, da),
4807 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4808 // THEN, for this (s, sa) and all (colormod, d, da):
4809 // s*colormod * src(s*colormod, d, sa, da) + d * dst(s*colormod, d, sa, da) == d
4810 // OBVIOUSLY, this means that
4811 // s*colormod * src(s*colormod, d, sa, da) = 0
4812 // dst(s*colormod, d, sa, da) = 1
4814 // note: not caring about GL_SRC_ALPHA_SATURATE and following here, these are unused in DP code
4816 // main condition to leave dst color invariant:
4817 // s * src(s, d, sa, da) + d * dst(s, d, sa, da) == d
4819 // s * 0 + d * dst(s, d, sa, da) == d
4820 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4821 // => colormod is a problem for GL_SRC_COLOR only
4823 // s + d * dst(s, d, sa, da) == d
4825 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4826 // => colormod is never problematic for these
4827 // src == GL_SRC_COLOR:
4828 // s*s + d * dst(s, d, sa, da) == d
4830 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4831 // => colormod is never problematic for these
4832 // src == GL_ONE_MINUS_SRC_COLOR:
4833 // s*(1-s) + d * dst(s, d, sa, da) == d
4834 // => s == 0 or s == 1
4835 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4836 // => colormod is a problem for GL_SRC_COLOR only
4837 // src == GL_DST_COLOR
4838 // s*d + d * dst(s, d, sa, da) == d
4840 // => dst == GL_ZERO/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4841 // => colormod is always a problem
4844 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4845 // => colormod is never problematic for these
4846 // => BUT, we do not know s! We must assume it is problematic
4847 // then... except in GL_ONE case, where we know all invariant
4849 // src == GL_ONE_MINUS_DST_COLOR
4850 // s*(1-d) + d * dst(s, d, sa, da) == d
4851 // => s == 0 (1-d is impossible to handle for our desired result)
4852 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4853 // => colormod is never problematic for these
4854 // src == GL_SRC_ALPHA
4855 // s*sa + d * dst(s, d, sa, da) == d
4856 // => s == 0, or sa == 0
4857 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4858 // => colormod breaks in the case GL_SRC_COLOR only
4859 // src == GL_ONE_MINUS_SRC_ALPHA
4860 // s*(1-sa) + d * dst(s, d, sa, da) == d
4861 // => s == 0, or sa == 1
4862 // => dst == GL_ONE/GL_SRC_COLOR/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4863 // => colormod breaks in the case GL_SRC_COLOR only
4864 // src == GL_DST_ALPHA
4865 // s*da + d * dst(s, d, sa, da) == d
4867 // => dst == GL_ONE/GL_ONE_MINUS_SRC_COLOR/GL_SRC_ALPHA/GL_ONE_MINUS_SRC_ALPHA
4868 // => colormod is never problematic for these
4873 case GL_ONE_MINUS_SRC_COLOR:
4875 case GL_ONE_MINUS_SRC_ALPHA:
4876 if(dst == GL_SRC_COLOR)
4881 case GL_ONE_MINUS_DST_COLOR:
4883 case GL_ONE_MINUS_DST_ALPHA:
4893 void R_SetupShader_Surface(const vec3_t lightcolorbase, qboolean modellighting, float ambientscale, float diffusescale, float specularscale, rsurfacepass_t rsurfacepass, int texturenumsurfaces, const msurface_t **texturesurfacelist, void *surfacewaterplane)
4895 // select a permutation of the lighting shader appropriate to this
4896 // combination of texture, entity, light source, and fogging, only use the
4897 // minimum features necessary to avoid wasting rendering time in the
4898 // fragment shader on features that are not being used
4899 unsigned int permutation = 0;
4900 unsigned int mode = 0;
4901 qboolean allow_colormod;
4902 static float dummy_colormod[3] = {1, 1, 1};
4903 float *colormod = rsurface.colormod;
4905 matrix4x4_t tempmatrix;
4906 r_waterstate_waterplane_t *waterplane = (r_waterstate_waterplane_t *)surfacewaterplane;
4907 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
4908 permutation |= SHADERPERMUTATION_ALPHAKILL;
4909 if (rsurfacepass == RSURFPASS_BACKGROUND)
4911 // distorted background
4912 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERSHADER)
4914 mode = SHADERMODE_WATER;
4915 if (rsurface.texture->r_water_waterscroll[0] && rsurface.texture->r_water_waterscroll[1])
4916 permutation |= SHADERPERMUTATION_NORMALMAPSCROLLBLEND;
4917 if((r_wateralpha.value < 1) && (rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA))
4919 // this is the right thing to do for wateralpha
4920 GL_BlendFunc(GL_ONE, GL_ZERO);
4921 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4925 // this is the right thing to do for entity alpha
4926 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4927 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4930 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFRACTION)
4932 mode = SHADERMODE_REFRACTION;
4933 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4934 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
4938 mode = SHADERMODE_GENERIC;
4939 permutation |= SHADERPERMUTATION_DIFFUSE;
4940 GL_BlendFunc(GL_ONE, GL_ZERO);
4941 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4944 else if (rsurfacepass == RSURFPASS_DEFERREDGEOMETRY)
4946 if (r_glsl_offsetmapping.integer)
4948 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4949 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4950 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4951 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4952 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4954 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4955 if (r_glsl_offsetmapping_reliefmapping.integer)
4956 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4959 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4960 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4961 // normalmap (deferred prepass), may use alpha test on diffuse
4962 mode = SHADERMODE_DEFERREDGEOMETRY;
4963 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4964 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4965 GL_BlendFunc(GL_ONE, GL_ZERO);
4966 allow_colormod = R_BlendFuncAllowsColormod(GL_ONE, GL_ZERO);
4968 else if (rsurfacepass == RSURFPASS_RTLIGHT)
4970 if (r_glsl_offsetmapping.integer)
4972 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
4973 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4974 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
4975 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4976 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
4978 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
4979 if (r_glsl_offsetmapping_reliefmapping.integer)
4980 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
4983 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4984 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4986 mode = SHADERMODE_LIGHTSOURCE;
4987 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
4988 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
4989 if (rsurface.rtlight->currentcubemap != r_texture_whitecube)
4990 permutation |= SHADERPERMUTATION_CUBEFILTER;
4991 if (diffusescale > 0)
4992 permutation |= SHADERPERMUTATION_DIFFUSE;
4993 if (specularscale > 0)
4994 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
4995 if (r_refdef.fogenabled)
4996 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
4997 if (rsurface.texture->colormapping)
4998 permutation |= SHADERPERMUTATION_COLORMAPPING;
4999 if (r_shadow_usingshadowmap2d)
5001 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5002 if(r_shadow_shadowmapvsdct)
5003 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5005 if (r_shadow_shadowmapsampler)
5006 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5007 if (r_shadow_shadowmappcf > 1)
5008 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5009 else if (r_shadow_shadowmappcf)
5010 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5012 if (rsurface.texture->reflectmasktexture)
5013 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5014 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
5015 allow_colormod = R_BlendFuncAllowsColormod(GL_SRC_ALPHA, GL_ONE);
5017 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
5019 if (r_glsl_offsetmapping.integer)
5021 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5022 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5023 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5024 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5025 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5027 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5028 if (r_glsl_offsetmapping_reliefmapping.integer)
5029 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5032 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5033 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5034 // unshaded geometry (fullbright or ambient model lighting)
5035 mode = SHADERMODE_FLATCOLOR;
5036 ambientscale = diffusescale = specularscale = 0;
5037 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5038 permutation |= SHADERPERMUTATION_GLOW;
5039 if (r_refdef.fogenabled)
5040 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5041 if (rsurface.texture->colormapping)
5042 permutation |= SHADERPERMUTATION_COLORMAPPING;
5043 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5045 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5046 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5048 if (r_shadow_shadowmapsampler)
5049 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5050 if (r_shadow_shadowmappcf > 1)
5051 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5052 else if (r_shadow_shadowmappcf)
5053 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5055 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5056 permutation |= SHADERPERMUTATION_REFLECTION;
5057 if (rsurface.texture->reflectmasktexture)
5058 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5059 if (r_shadow_bouncegridtexture)
5060 permutation |= SHADERPERMUTATION_BOUNCEGRID;
5061 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5062 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5064 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT_DIRECTIONAL)
5066 if (r_glsl_offsetmapping.integer)
5068 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5069 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5070 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5071 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5072 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5074 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5075 if (r_glsl_offsetmapping_reliefmapping.integer)
5076 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5079 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5080 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5081 // directional model lighting
5082 mode = SHADERMODE_LIGHTDIRECTION;
5083 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5084 permutation |= SHADERPERMUTATION_GLOW;
5085 permutation |= SHADERPERMUTATION_DIFFUSE;
5086 if (specularscale > 0)
5087 permutation |= SHADERPERMUTATION_SPECULAR;
5088 if (r_refdef.fogenabled)
5089 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5090 if (rsurface.texture->colormapping)
5091 permutation |= SHADERPERMUTATION_COLORMAPPING;
5092 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5094 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5095 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5097 if (r_shadow_shadowmapsampler)
5098 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5099 if (r_shadow_shadowmappcf > 1)
5100 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5101 else if (r_shadow_shadowmappcf)
5102 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5104 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5105 permutation |= SHADERPERMUTATION_REFLECTION;
5106 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5107 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5108 if (rsurface.texture->reflectmasktexture)
5109 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5110 if (r_shadow_bouncegridtexture)
5111 permutation |= SHADERPERMUTATION_BOUNCEGRID;
5112 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5113 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5115 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
5117 if (r_glsl_offsetmapping.integer)
5119 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5120 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5121 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5122 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5123 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5125 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5126 if (r_glsl_offsetmapping_reliefmapping.integer)
5127 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5130 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5131 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5132 // ambient model lighting
5133 mode = SHADERMODE_LIGHTDIRECTION;
5134 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5135 permutation |= SHADERPERMUTATION_GLOW;
5136 if (r_refdef.fogenabled)
5137 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5138 if (rsurface.texture->colormapping)
5139 permutation |= SHADERPERMUTATION_COLORMAPPING;
5140 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5142 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5143 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5145 if (r_shadow_shadowmapsampler)
5146 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5147 if (r_shadow_shadowmappcf > 1)
5148 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5149 else if (r_shadow_shadowmappcf)
5150 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5152 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5153 permutation |= SHADERPERMUTATION_REFLECTION;
5154 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5155 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5156 if (rsurface.texture->reflectmasktexture)
5157 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5158 if (r_shadow_bouncegridtexture)
5159 permutation |= SHADERPERMUTATION_BOUNCEGRID;
5160 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5161 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5165 if (r_glsl_offsetmapping.integer)
5167 if (rsurface.texture->offsetmapping == OFFSETMAPPING_LINEAR)
5168 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5169 else if (rsurface.texture->offsetmapping == OFFSETMAPPING_RELIEF)
5170 permutation |= SHADERPERMUTATION_OFFSETMAPPING | SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5171 else if (rsurface.texture->offsetmapping != OFFSETMAPPING_OFF)
5173 permutation |= SHADERPERMUTATION_OFFSETMAPPING;
5174 if (r_glsl_offsetmapping_reliefmapping.integer)
5175 permutation |= SHADERPERMUTATION_OFFSETMAPPING_RELIEFMAPPING;
5178 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)
5179 permutation |= SHADERPERMUTATION_VERTEXTEXTUREBLEND;
5181 if (rsurface.texture->glowtexture && r_hdr_glowintensity.value > 0 && !gl_lightmaps.integer)
5182 permutation |= SHADERPERMUTATION_GLOW;
5183 if (r_refdef.fogenabled)
5184 permutation |= r_texture_fogheighttexture ? SHADERPERMUTATION_FOGHEIGHTTEXTURE : (r_refdef.fogplaneviewabove ? SHADERPERMUTATION_FOGOUTSIDE : SHADERPERMUTATION_FOGINSIDE);
5185 if (rsurface.texture->colormapping)
5186 permutation |= SHADERPERMUTATION_COLORMAPPING;
5187 if (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW))
5189 permutation |= SHADERPERMUTATION_SHADOWMAPORTHO;
5190 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5192 if (r_shadow_shadowmapsampler)
5193 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5194 if (r_shadow_shadowmappcf > 1)
5195 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5196 else if (r_shadow_shadowmappcf)
5197 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5199 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION)
5200 permutation |= SHADERPERMUTATION_REFLECTION;
5201 if (r_shadow_usingdeferredprepass && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED))
5202 permutation |= SHADERPERMUTATION_DEFERREDLIGHTMAP;
5203 if (rsurface.texture->reflectmasktexture)
5204 permutation |= SHADERPERMUTATION_REFLECTCUBE;
5205 if (FAKELIGHT_ENABLED)
5207 // fake lightmapping (q1bsp, q3bsp, fullbright map)
5208 mode = SHADERMODE_FAKELIGHT;
5209 permutation |= SHADERPERMUTATION_DIFFUSE;
5210 if (specularscale > 0)
5211 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5213 else if (r_glsl_deluxemapping.integer >= 1 && rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping)
5215 // deluxemapping (light direction texture)
5216 if (rsurface.uselightmaptexture && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brushq3.deluxemapping && r_refdef.scene.worldmodel->brushq3.deluxemapping_modelspace)
5217 mode = SHADERMODE_LIGHTDIRECTIONMAP_MODELSPACE;
5219 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5220 permutation |= SHADERPERMUTATION_DIFFUSE;
5221 if (specularscale > 0)
5222 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5224 else if (r_glsl_deluxemapping.integer >= 2 && rsurface.uselightmaptexture)
5226 // fake deluxemapping (uniform light direction in tangentspace)
5227 mode = SHADERMODE_LIGHTDIRECTIONMAP_TANGENTSPACE;
5228 permutation |= SHADERPERMUTATION_DIFFUSE;
5229 if (specularscale > 0)
5230 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5232 else if (rsurface.uselightmaptexture)
5234 // ordinary lightmapping (q1bsp, q3bsp)
5235 mode = SHADERMODE_LIGHTMAP;
5239 // ordinary vertex coloring (q3bsp)
5240 mode = SHADERMODE_VERTEXCOLOR;
5242 if (r_shadow_bouncegridtexture)
5243 permutation |= SHADERPERMUTATION_BOUNCEGRID;
5244 GL_BlendFunc(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5245 allow_colormod = R_BlendFuncAllowsColormod(rsurface.texture->currentlayers[0].blendfunc1, rsurface.texture->currentlayers[0].blendfunc2);
5248 colormod = dummy_colormod;
5249 switch(vid.renderpath)
5251 case RENDERPATH_D3D9:
5253 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5254 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5255 R_SetupShader_SetPermutationHLSL(mode, permutation);
5256 Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);hlslPSSetParameter16f(D3DPSREGISTER_ModelToReflectCube, m16f);
5257 if (mode == SHADERMODE_LIGHTSOURCE)
5259 Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ModelToLight, m16f);
5260 hlslVSSetParameter3f(D3DVSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5264 if (mode == SHADERMODE_LIGHTDIRECTION)
5266 hlslVSSetParameter3f(D3DVSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5269 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_TexMatrix, m16f);
5270 Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_BackgroundTexMatrix, m16f);
5271 Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);hlslVSSetParameter16f(D3DVSREGISTER_ShadowMapMatrix, m16f);
5272 hlslVSSetParameter3f(D3DVSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5273 hlslVSSetParameter4f(D3DVSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5275 if (mode == SHADERMODE_LIGHTSOURCE)
5277 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5278 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5279 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5280 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5281 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5283 // additive passes are only darkened by fog, not tinted
5284 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5285 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5289 if (mode == SHADERMODE_FLATCOLOR)
5291 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5293 else if (mode == SHADERMODE_LIGHTDIRECTION)
5295 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity) * colormod[2]);
5296 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5297 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5298 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5299 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5300 hlslPSSetParameter3f(D3DPSREGISTER_LightColor, rsurface.modellight_diffuse[0], rsurface.modellight_diffuse[1], rsurface.modellight_diffuse[2]);
5301 hlslPSSetParameter3f(D3DPSREGISTER_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5305 hlslPSSetParameter3f(D3DPSREGISTER_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5306 hlslPSSetParameter3f(D3DPSREGISTER_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5307 hlslPSSetParameter3f(D3DPSREGISTER_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5308 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5309 hlslPSSetParameter3f(D3DPSREGISTER_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5311 // additive passes are only darkened by fog, not tinted
5312 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5313 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, 0, 0, 0);
5315 hlslPSSetParameter3f(D3DPSREGISTER_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5316 hlslPSSetParameter4f(D3DPSREGISTER_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
5317 hlslPSSetParameter4f(D3DPSREGISTER_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5318 hlslPSSetParameter4f(D3DPSREGISTER_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5319 hlslPSSetParameter4f(D3DPSREGISTER_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5320 hlslPSSetParameter4f(D3DPSREGISTER_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5321 hlslPSSetParameter1f(D3DPSREGISTER_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5322 hlslPSSetParameter1f(D3DPSREGISTER_ReflectOffset, rsurface.texture->reflectmin);
5323 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5324 if (mode == SHADERMODE_WATER)
5325 hlslPSSetParameter2f(D3DPSREGISTER_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5327 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5328 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5329 hlslPSSetParameter3f(D3DPSREGISTER_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5330 hlslPSSetParameter1f(D3DPSREGISTER_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5331 hlslPSSetParameter3f(D3DPSREGISTER_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5332 if (rsurface.texture->pantstexture)
5333 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5335 hlslPSSetParameter3f(D3DPSREGISTER_Color_Pants, 0, 0, 0);
5336 if (rsurface.texture->shirttexture)
5337 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5339 hlslPSSetParameter3f(D3DPSREGISTER_Color_Shirt, 0, 0, 0);
5340 hlslPSSetParameter4f(D3DPSREGISTER_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5341 hlslPSSetParameter1f(D3DPSREGISTER_FogPlaneViewDist, rsurface.fogplaneviewdist);
5342 hlslPSSetParameter1f(D3DPSREGISTER_FogRangeRecip, rsurface.fograngerecip);
5343 hlslPSSetParameter1f(D3DPSREGISTER_FogHeightFade, rsurface.fogheightfade);
5344 hlslPSSetParameter1f(D3DPSREGISTER_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value);
5345 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5346 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5348 R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5349 R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5350 R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5351 R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5352 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5353 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5354 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5355 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5356 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5357 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5358 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5359 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5360 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5361 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5362 R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5363 R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5364 if (rsurface.rtlight ) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5365 if (rsurfacepass == RSURFPASS_BACKGROUND)
5367 R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5368 if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5369 R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5373 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5375 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5376 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5377 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5378 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5379 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5381 R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
5382 if (rsurface.rtlight)
5384 if (permutation & SHADERPERMUTATION_CUBEFILTER ) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5385 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5390 case RENDERPATH_D3D10:
5391 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5393 case RENDERPATH_D3D11:
5394 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5396 case RENDERPATH_GL20:
5397 case RENDERPATH_GLES2:
5398 if (!vid.useinterleavedarrays)
5400 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5401 R_Mesh_VertexPointer( 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
5402 R_Mesh_ColorPointer( 4, GL_FLOAT, sizeof(float[4]), rsurface.batchlightmapcolor4f, rsurface.batchlightmapcolor4f_vertexbuffer, rsurface.batchlightmapcolor4f_bufferoffset);
5403 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
5404 R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchsvector3f, rsurface.batchsvector3f_vertexbuffer, rsurface.batchsvector3f_bufferoffset);
5405 R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchtvector3f, rsurface.batchtvector3f_vertexbuffer, rsurface.batchtvector3f_bufferoffset);
5406 R_Mesh_TexCoordPointer(3, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchnormal3f, rsurface.batchnormal3f_vertexbuffer, rsurface.batchnormal3f_bufferoffset);
5407 R_Mesh_TexCoordPointer(4, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
5411 RSurf_PrepareVerticesForBatch(BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_VERTEXMESH_VERTEXCOLOR : 0) | BATCHNEED_VERTEXMESH_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_VERTEXMESH_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5412 R_Mesh_PrepareVertices_Mesh(rsurface.batchnumvertices, rsurface.batchvertexmesh, rsurface.batchvertexmeshbuffer);
5414 R_SetupShader_SetPermutationGLSL(mode, permutation);
5415 if (r_glsl_permutation->loc_ModelToReflectCube >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToReflectCube, 1, false, m16f);}
5416 if (mode == SHADERMODE_LIGHTSOURCE)
5418 if (r_glsl_permutation->loc_ModelToLight >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ModelToLight, 1, false, m16f);}
5419 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3f(r_glsl_permutation->loc_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5420 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5421 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5422 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5423 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5425 // additive passes are only darkened by fog, not tinted
5426 if (r_glsl_permutation->loc_FogColor >= 0)
5427 qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5428 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5432 if (mode == SHADERMODE_FLATCOLOR)
5434 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5436 else if (mode == SHADERMODE_LIGHTDIRECTION)
5438 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
5439 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5440 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5441 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5442 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5443 if (r_glsl_permutation->loc_LightColor >= 0) qglUniform3f(r_glsl_permutation->loc_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
5444 if (r_glsl_permutation->loc_LightDir >= 0) qglUniform3f(r_glsl_permutation->loc_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5448 if (r_glsl_permutation->loc_Color_Ambient >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5449 if (r_glsl_permutation->loc_Color_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5450 if (r_glsl_permutation->loc_Color_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5451 if (r_glsl_permutation->loc_DeferredMod_Diffuse >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5452 if (r_glsl_permutation->loc_DeferredMod_Specular >= 0) qglUniform3f(r_glsl_permutation->loc_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5454 // additive passes are only darkened by fog, not tinted
5455 if (r_glsl_permutation->loc_FogColor >= 0)
5457 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5458 qglUniform3f(r_glsl_permutation->loc_FogColor, 0, 0, 0);
5460 qglUniform3f(r_glsl_permutation->loc_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5462 if (r_glsl_permutation->loc_DistortScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
5463 if (r_glsl_permutation->loc_ScreenScaleRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5464 if (r_glsl_permutation->loc_ScreenCenterRefractReflect >= 0) qglUniform4f(r_glsl_permutation->loc_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5465 if (r_glsl_permutation->loc_RefractColor >= 0) qglUniform4f(r_glsl_permutation->loc_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5466 if (r_glsl_permutation->loc_ReflectColor >= 0) qglUniform4f(r_glsl_permutation->loc_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5467 if (r_glsl_permutation->loc_ReflectFactor >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5468 if (r_glsl_permutation->loc_ReflectOffset >= 0) qglUniform1f(r_glsl_permutation->loc_ReflectOffset, rsurface.texture->reflectmin);
5469 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f(r_glsl_permutation->loc_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5470 if (r_glsl_permutation->loc_NormalmapScrollBlend >= 0) qglUniform2f(r_glsl_permutation->loc_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5472 if (r_glsl_permutation->loc_TexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_TexMatrix, 1, false, m16f);}
5473 if (r_glsl_permutation->loc_BackgroundTexMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BackgroundTexMatrix, 1, false, m16f);}
5474 if (r_glsl_permutation->loc_ShadowMapMatrix >= 0) {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_ShadowMapMatrix, 1, false, m16f);}
5475 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2f(r_glsl_permutation->loc_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5476 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4f(r_glsl_permutation->loc_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5478 if (r_glsl_permutation->loc_Color_Glow >= 0) qglUniform3f(r_glsl_permutation->loc_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5479 if (r_glsl_permutation->loc_Alpha >= 0) qglUniform1f(r_glsl_permutation->loc_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5480 if (r_glsl_permutation->loc_EyePosition >= 0) qglUniform3f(r_glsl_permutation->loc_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5481 if (r_glsl_permutation->loc_Color_Pants >= 0)
5483 if (rsurface.texture->pantstexture)
5484 qglUniform3f(r_glsl_permutation->loc_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5486 qglUniform3f(r_glsl_permutation->loc_Color_Pants, 0, 0, 0);
5488 if (r_glsl_permutation->loc_Color_Shirt >= 0)
5490 if (rsurface.texture->shirttexture)
5491 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5493 qglUniform3f(r_glsl_permutation->loc_Color_Shirt, 0, 0, 0);
5495 if (r_glsl_permutation->loc_FogPlane >= 0) qglUniform4f(r_glsl_permutation->loc_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5496 if (r_glsl_permutation->loc_FogPlaneViewDist >= 0) qglUniform1f(r_glsl_permutation->loc_FogPlaneViewDist, rsurface.fogplaneviewdist);
5497 if (r_glsl_permutation->loc_FogRangeRecip >= 0) qglUniform1f(r_glsl_permutation->loc_FogRangeRecip, rsurface.fograngerecip);
5498 if (r_glsl_permutation->loc_FogHeightFade >= 0) qglUniform1f(r_glsl_permutation->loc_FogHeightFade, rsurface.fogheightfade);
5499 if (r_glsl_permutation->loc_OffsetMapping_Scale >= 0) qglUniform1f(r_glsl_permutation->loc_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5500 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f(r_glsl_permutation->loc_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5501 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5502 if (r_glsl_permutation->loc_BounceGridMatrix >= 0) {Matrix4x4_Concat(&tempmatrix, &r_shadow_bouncegridmatrix, &rsurface.matrix);Matrix4x4_ToArrayFloatGL(&tempmatrix, m16f);qglUniformMatrix4fv(r_glsl_permutation->loc_BounceGridMatrix, 1, false, m16f);}
5503 if (r_glsl_permutation->loc_BounceGridIntensity >= 0) qglUniform1f(r_glsl_permutation->loc_BounceGridIntensity, r_shadow_bouncegridintensity);
5505 if (r_glsl_permutation->tex_Texture_First >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , r_texture_white );
5506 if (r_glsl_permutation->tex_Texture_Second >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second , r_texture_white );
5507 if (r_glsl_permutation->tex_Texture_GammaRamps >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps , r_texture_gammaramps );
5508 if (r_glsl_permutation->tex_Texture_Normal >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Normal , rsurface.texture->nmaptexture );
5509 if (r_glsl_permutation->tex_Texture_Color >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Color , rsurface.texture->basetexture );
5510 if (r_glsl_permutation->tex_Texture_Gloss >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Gloss , rsurface.texture->glosstexture );
5511 if (r_glsl_permutation->tex_Texture_Glow >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Glow , rsurface.texture->glowtexture );
5512 if (r_glsl_permutation->tex_Texture_SecondaryNormal >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryNormal , rsurface.texture->backgroundnmaptexture );
5513 if (r_glsl_permutation->tex_Texture_SecondaryColor >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryColor , rsurface.texture->backgroundbasetexture );
5514 if (r_glsl_permutation->tex_Texture_SecondaryGloss >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGloss , rsurface.texture->backgroundglosstexture );
5515 if (r_glsl_permutation->tex_Texture_SecondaryGlow >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_SecondaryGlow , rsurface.texture->backgroundglowtexture );
5516 if (r_glsl_permutation->tex_Texture_Pants >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Pants , rsurface.texture->pantstexture );
5517 if (r_glsl_permutation->tex_Texture_Shirt >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Shirt , rsurface.texture->shirttexture );
5518 if (r_glsl_permutation->tex_Texture_ReflectMask >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectMask , rsurface.texture->reflectmasktexture );
5519 if (r_glsl_permutation->tex_Texture_ReflectCube >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ReflectCube , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5520 if (r_glsl_permutation->tex_Texture_FogHeightTexture>= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogHeightTexture , r_texture_fogheighttexture );
5521 if (r_glsl_permutation->tex_Texture_FogMask >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_FogMask , r_texture_fogattenuation );
5522 if (r_glsl_permutation->tex_Texture_Lightmap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Lightmap , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5523 if (r_glsl_permutation->tex_Texture_Deluxemap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Deluxemap , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5524 if (r_glsl_permutation->tex_Texture_Attenuation >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation , r_shadow_attenuationgradienttexture );
5525 if (rsurfacepass == RSURFPASS_BACKGROUND)
5527 if (r_glsl_permutation->tex_Texture_Refraction >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Refraction , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5528 if (r_glsl_permutation->tex_Texture_First >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5529 if (r_glsl_permutation->tex_Texture_Reflection >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5533 if (r_glsl_permutation->tex_Texture_Reflection >= 0 && waterplane) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Reflection , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5535 if (r_glsl_permutation->tex_Texture_ScreenDepth >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );
5536 if (r_glsl_permutation->tex_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap , r_shadow_prepassgeometrynormalmaptexture );
5537 if (r_glsl_permutation->tex_Texture_ScreenDiffuse >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDiffuse , r_shadow_prepasslightingdiffusetexture );
5538 if (r_glsl_permutation->tex_Texture_ScreenSpecular >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenSpecular , r_shadow_prepasslightingspeculartexture );
5539 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5541 if (r_glsl_permutation->tex_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D, r_shadow_shadowmap2dtexture );
5542 if (rsurface.rtlight)
5544 if (r_glsl_permutation->tex_Texture_Cube >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube , rsurface.rtlight->currentcubemap );
5545 if (r_glsl_permutation->tex_Texture_CubeProjection >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );
5548 if (r_glsl_permutation->tex_Texture_BounceGrid >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_BounceGrid, r_shadow_bouncegridtexture);
5551 case RENDERPATH_GL13:
5552 case RENDERPATH_GL11:
5554 case RENDERPATH_SOFT:
5555 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | (rsurface.modellightmapcolor4f ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.uselightmaptexture ? BATCHNEED_ARRAY_LIGHTMAP : 0), texturenumsurfaces, texturesurfacelist);
5556 R_Mesh_PrepareVertices_Mesh_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchsvector3f, rsurface.batchtvector3f, rsurface.batchnormal3f, rsurface.batchlightmapcolor4f, rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordlightmap2f);
5557 R_SetupShader_SetPermutationSoft(mode, permutation);
5558 {Matrix4x4_ToArrayFloatGL(&rsurface.matrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToReflectCubeM1, 1, false, m16f);}
5559 if (mode == SHADERMODE_LIGHTSOURCE)
5561 {Matrix4x4_ToArrayFloatGL(&rsurface.entitytolight, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelToLightM1, 1, false, m16f);}
5562 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightPosition, rsurface.entitylightorigin[0], rsurface.entitylightorigin[1], rsurface.entitylightorigin[2]);
5563 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, lightcolorbase[0], lightcolorbase[1], lightcolorbase[2]);
5564 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0] * ambientscale, colormod[1] * ambientscale, colormod[2] * ambientscale);
5565 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, colormod[0] * diffusescale, colormod[1] * diffusescale, colormod[2] * diffusescale);
5566 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale, r_refdef.view.colorscale * specularscale);
5568 // additive passes are only darkened by fog, not tinted
5569 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
5570 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5574 if (mode == SHADERMODE_FLATCOLOR)
5576 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, colormod[0], colormod[1], colormod[2]);
5578 else if (mode == SHADERMODE_LIGHTDIRECTION)
5580 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, (r_refdef.scene.ambient + rsurface.modellight_ambient[0] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[0], (r_refdef.scene.ambient + rsurface.modellight_ambient[1] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[1], (r_refdef.scene.ambient + rsurface.modellight_ambient[2] * r_refdef.lightmapintensity * r_refdef.scene.rtlightstylevalue[0]) * colormod[2]);
5581 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, r_refdef.lightmapintensity * colormod[0], r_refdef.lightmapintensity * colormod[1], r_refdef.lightmapintensity * colormod[2]);
5582 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5583 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * r_shadow_deferred_8bitrange.value, colormod[1] * r_shadow_deferred_8bitrange.value, colormod[2] * r_shadow_deferred_8bitrange.value);
5584 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5585 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightColor, rsurface.modellight_diffuse[0] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[1] * r_refdef.scene.rtlightstylevalue[0], rsurface.modellight_diffuse[2] * r_refdef.scene.rtlightstylevalue[0]);
5586 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_LightDir, rsurface.modellight_lightdir[0], rsurface.modellight_lightdir[1], rsurface.modellight_lightdir[2]);
5590 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Ambient, r_refdef.scene.ambient * colormod[0], r_refdef.scene.ambient * colormod[1], r_refdef.scene.ambient * colormod[2]);
5591 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Diffuse, rsurface.texture->lightmapcolor[0], rsurface.texture->lightmapcolor[1], rsurface.texture->lightmapcolor[2]);
5592 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Specular, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale, r_refdef.lightmapintensity * r_refdef.view.colorscale * specularscale);
5593 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Diffuse, colormod[0] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[1] * diffusescale * r_shadow_deferred_8bitrange.value, colormod[2] * diffusescale * r_shadow_deferred_8bitrange.value);
5594 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_DeferredMod_Specular, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value, specularscale * r_shadow_deferred_8bitrange.value);
5596 // additive passes are only darkened by fog, not tinted
5597 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
5598 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, 0, 0, 0);
5600 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_FogColor, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2]);
5601 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_DistortScaleRefractReflect, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_refractdistort.value * rsurface.texture->refractfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor, r_water_reflectdistort.value * rsurface.texture->reflectfactor);
5602 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenScaleRefractReflect, r_waterstate.screenscale[0], r_waterstate.screenscale[1], r_waterstate.screenscale[0], r_waterstate.screenscale[1]);
5603 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ScreenCenterRefractReflect, r_waterstate.screencenter[0], r_waterstate.screencenter[1], r_waterstate.screencenter[0], r_waterstate.screencenter[1]);
5604 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_RefractColor, rsurface.texture->refractcolor4f[0], rsurface.texture->refractcolor4f[1], rsurface.texture->refractcolor4f[2], rsurface.texture->refractcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5605 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ReflectColor, rsurface.texture->reflectcolor4f[0], rsurface.texture->reflectcolor4f[1], rsurface.texture->reflectcolor4f[2], rsurface.texture->reflectcolor4f[3] * rsurface.texture->lightmapcolor[3]);
5606 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectFactor, rsurface.texture->reflectmax - rsurface.texture->reflectmin);
5607 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_ReflectOffset, rsurface.texture->reflectmin);
5608 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_SpecularPower, rsurface.texture->specularpower * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5609 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_NormalmapScrollBlend, rsurface.texture->r_water_waterscroll[0], rsurface.texture->r_water_waterscroll[1]);
5611 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currenttexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_TexMatrixM1, 1, false, m16f);}
5612 {Matrix4x4_ToArrayFloatGL(&rsurface.texture->currentbackgroundtexmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_BackgroundTexMatrixM1, 1, false, m16f);}
5613 {Matrix4x4_ToArrayFloatGL(&r_shadow_shadowmapmatrix, m16f);DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ShadowMapMatrixM1, 1, false, m16f);}
5614 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5615 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5617 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Glow, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2]);
5618 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Alpha, rsurface.texture->lightmapcolor[3] * ((rsurface.texture->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay) ? rsurface.texture->r_water_wateralpha : 1));
5619 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_EyePosition, rsurface.localvieworigin[0], rsurface.localvieworigin[1], rsurface.localvieworigin[2]);
5620 if (DPSOFTRAST_UNIFORM_Color_Pants >= 0)
5622 if (rsurface.texture->pantstexture)
5623 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, rsurface.colormap_pantscolor[0], rsurface.colormap_pantscolor[1], rsurface.colormap_pantscolor[2]);
5625 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Pants, 0, 0, 0);
5627 if (DPSOFTRAST_UNIFORM_Color_Shirt >= 0)
5629 if (rsurface.texture->shirttexture)
5630 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, rsurface.colormap_shirtcolor[0], rsurface.colormap_shirtcolor[1], rsurface.colormap_shirtcolor[2]);
5632 DPSOFTRAST_Uniform3f(DPSOFTRAST_UNIFORM_Color_Shirt, 0, 0, 0);
5634 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_FogPlane, rsurface.fogplane[0], rsurface.fogplane[1], rsurface.fogplane[2], rsurface.fogplane[3]);
5635 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogPlaneViewDist, rsurface.fogplaneviewdist);
5636 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogRangeRecip, rsurface.fograngerecip);
5637 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_FogHeightFade, rsurface.fogheightfade);
5638 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_OffsetMapping_Scale, r_glsl_offsetmapping_scale.value*rsurface.texture->offsetscale);
5639 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5640 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5642 R_Mesh_TexBind(GL20TU_NORMAL , rsurface.texture->nmaptexture );
5643 R_Mesh_TexBind(GL20TU_COLOR , rsurface.texture->basetexture );
5644 R_Mesh_TexBind(GL20TU_GLOSS , rsurface.texture->glosstexture );
5645 R_Mesh_TexBind(GL20TU_GLOW , rsurface.texture->glowtexture );
5646 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL , rsurface.texture->backgroundnmaptexture );
5647 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_COLOR , rsurface.texture->backgroundbasetexture );
5648 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS , rsurface.texture->backgroundglosstexture );
5649 if (permutation & SHADERPERMUTATION_VERTEXTEXTUREBLEND) R_Mesh_TexBind(GL20TU_SECONDARY_GLOW , rsurface.texture->backgroundglowtexture );
5650 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_PANTS , rsurface.texture->pantstexture );
5651 if (permutation & SHADERPERMUTATION_COLORMAPPING) R_Mesh_TexBind(GL20TU_SHIRT , rsurface.texture->shirttexture );
5652 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTMASK , rsurface.texture->reflectmasktexture );
5653 if (permutation & SHADERPERMUTATION_REFLECTCUBE) R_Mesh_TexBind(GL20TU_REFLECTCUBE , rsurface.texture->reflectcubetexture ? rsurface.texture->reflectcubetexture : r_texture_whitecube);
5654 if (permutation & SHADERPERMUTATION_FOGHEIGHTTEXTURE) R_Mesh_TexBind(GL20TU_FOGHEIGHTTEXTURE , r_texture_fogheighttexture );
5655 if (permutation & (SHADERPERMUTATION_FOGINSIDE | SHADERPERMUTATION_FOGOUTSIDE)) R_Mesh_TexBind(GL20TU_FOGMASK , r_texture_fogattenuation );
5656 R_Mesh_TexBind(GL20TU_LIGHTMAP , rsurface.lightmaptexture ? rsurface.lightmaptexture : r_texture_white);
5657 R_Mesh_TexBind(GL20TU_DELUXEMAP , rsurface.deluxemaptexture ? rsurface.deluxemaptexture : r_texture_blanknormalmap);
5658 if (rsurface.rtlight ) R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5659 if (rsurfacepass == RSURFPASS_BACKGROUND)
5661 R_Mesh_TexBind(GL20TU_REFRACTION , waterplane->texture_refraction ? waterplane->texture_refraction : r_texture_black);
5662 if(mode == SHADERMODE_GENERIC) R_Mesh_TexBind(GL20TU_FIRST , waterplane->texture_camera ? waterplane->texture_camera : r_texture_black);
5663 R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5667 if (permutation & SHADERPERMUTATION_REFLECTION ) R_Mesh_TexBind(GL20TU_REFLECTION , waterplane->texture_reflection ? waterplane->texture_reflection : r_texture_black);
5669 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5670 // if (rsurfacepass == RSURFPASS_DEFERREDLIGHT ) R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5671 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENDIFFUSE , r_shadow_prepasslightingdiffusetexture );
5672 if (permutation & SHADERPERMUTATION_DEFERREDLIGHTMAP ) R_Mesh_TexBind(GL20TU_SCREENSPECULAR , r_shadow_prepasslightingspeculartexture );
5673 if (rsurface.rtlight || (r_shadow_usingshadowmaportho && !(rsurface.ent_flags & RENDER_NOSELFSHADOW)))
5675 R_Mesh_TexBind(GL20TU_SHADOWMAP2D, r_shadow_shadowmap2dcolortexture);
5676 if (rsurface.rtlight)
5678 if (permutation & SHADERPERMUTATION_CUBEFILTER ) R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5679 if (permutation & SHADERPERMUTATION_SHADOWMAPVSDCT ) R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5686 void R_SetupShader_DeferredLight(const rtlight_t *rtlight)
5688 // select a permutation of the lighting shader appropriate to this
5689 // combination of texture, entity, light source, and fogging, only use the
5690 // minimum features necessary to avoid wasting rendering time in the
5691 // fragment shader on features that are not being used
5692 unsigned int permutation = 0;
5693 unsigned int mode = 0;
5694 const float *lightcolorbase = rtlight->currentcolor;
5695 float ambientscale = rtlight->ambientscale;
5696 float diffusescale = rtlight->diffusescale;
5697 float specularscale = rtlight->specularscale;
5698 // this is the location of the light in view space
5699 vec3_t viewlightorigin;
5700 // this transforms from view space (camera) to light space (cubemap)
5701 matrix4x4_t viewtolight;
5702 matrix4x4_t lighttoview;
5703 float viewtolight16f[16];
5704 float range = 1.0f / r_shadow_deferred_8bitrange.value;
5706 mode = SHADERMODE_DEFERREDLIGHTSOURCE;
5707 if (rtlight->currentcubemap != r_texture_whitecube)
5708 permutation |= SHADERPERMUTATION_CUBEFILTER;
5709 if (diffusescale > 0)
5710 permutation |= SHADERPERMUTATION_DIFFUSE;
5711 if (specularscale > 0)
5712 permutation |= SHADERPERMUTATION_SPECULAR | SHADERPERMUTATION_DIFFUSE;
5713 if (r_shadow_usingshadowmap2d)
5715 permutation |= SHADERPERMUTATION_SHADOWMAP2D;
5716 if (r_shadow_shadowmapvsdct)
5717 permutation |= SHADERPERMUTATION_SHADOWMAPVSDCT;
5719 if (r_shadow_shadowmapsampler)
5720 permutation |= SHADERPERMUTATION_SHADOWSAMPLER;
5721 if (r_shadow_shadowmappcf > 1)
5722 permutation |= SHADERPERMUTATION_SHADOWMAPPCF2;
5723 else if (r_shadow_shadowmappcf)
5724 permutation |= SHADERPERMUTATION_SHADOWMAPPCF;
5726 Matrix4x4_Transform(&r_refdef.view.viewport.viewmatrix, rtlight->shadoworigin, viewlightorigin);
5727 Matrix4x4_Concat(&lighttoview, &r_refdef.view.viewport.viewmatrix, &rtlight->matrix_lighttoworld);
5728 Matrix4x4_Invert_Simple(&viewtolight, &lighttoview);
5729 Matrix4x4_ToArrayFloatGL(&viewtolight, viewtolight16f);
5730 switch(vid.renderpath)
5732 case RENDERPATH_D3D9:
5734 R_SetupShader_SetPermutationHLSL(mode, permutation);
5735 hlslPSSetParameter3f(D3DPSREGISTER_LightPosition, viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5736 hlslPSSetParameter16f(D3DPSREGISTER_ViewToLight, viewtolight16f);
5737 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
5738 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
5739 hlslPSSetParameter3f(D3DPSREGISTER_DeferredColor_Specular, lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5740 hlslPSSetParameter2f(D3DPSREGISTER_ShadowMap_TextureScale, r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5741 hlslPSSetParameter4f(D3DPSREGISTER_ShadowMap_Parameters, r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5742 hlslPSSetParameter1f(D3DPSREGISTER_SpecularPower, (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5743 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5744 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5746 R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5747 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthcolortexture );
5748 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5749 R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5750 R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dcolortexture );
5751 R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5754 case RENDERPATH_D3D10:
5755 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5757 case RENDERPATH_D3D11:
5758 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5760 case RENDERPATH_GL20:
5761 case RENDERPATH_GLES2:
5762 R_SetupShader_SetPermutationGLSL(mode, permutation);
5763 if (r_glsl_permutation->loc_LightPosition >= 0) qglUniform3f( r_glsl_permutation->loc_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5764 if (r_glsl_permutation->loc_ViewToLight >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ViewToLight , 1, false, viewtolight16f);
5765 if (r_glsl_permutation->loc_DeferredColor_Ambient >= 0) qglUniform3f( r_glsl_permutation->loc_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
5766 if (r_glsl_permutation->loc_DeferredColor_Diffuse >= 0) qglUniform3f( r_glsl_permutation->loc_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
5767 if (r_glsl_permutation->loc_DeferredColor_Specular >= 0) qglUniform3f( r_glsl_permutation->loc_DeferredColor_Specular , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5768 if (r_glsl_permutation->loc_ShadowMap_TextureScale >= 0) qglUniform2f( r_glsl_permutation->loc_ShadowMap_TextureScale , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5769 if (r_glsl_permutation->loc_ShadowMap_Parameters >= 0) qglUniform4f( r_glsl_permutation->loc_ShadowMap_Parameters , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5770 if (r_glsl_permutation->loc_SpecularPower >= 0) qglUniform1f( r_glsl_permutation->loc_SpecularPower , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5771 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f( r_glsl_permutation->loc_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5772 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f( r_glsl_permutation->loc_PixelToScreenTexCoord , 1.0f/vid.width, 1.0f/vid.height);
5774 if (r_glsl_permutation->tex_Texture_Attenuation >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Attenuation , r_shadow_attenuationgradienttexture );
5775 if (r_glsl_permutation->tex_Texture_ScreenDepth >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );
5776 if (r_glsl_permutation->tex_Texture_ScreenNormalMap >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenNormalMap , r_shadow_prepassgeometrynormalmaptexture );
5777 if (r_glsl_permutation->tex_Texture_Cube >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Cube , rsurface.rtlight->currentcubemap );
5778 if (r_glsl_permutation->tex_Texture_ShadowMap2D >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ShadowMap2D , r_shadow_shadowmap2dtexture );
5779 if (r_glsl_permutation->tex_Texture_CubeProjection >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_CubeProjection , r_shadow_shadowmapvsdcttexture );
5781 case RENDERPATH_GL13:
5782 case RENDERPATH_GL11:
5784 case RENDERPATH_SOFT:
5785 R_SetupShader_SetPermutationGLSL(mode, permutation);
5786 DPSOFTRAST_Uniform3f( DPSOFTRAST_UNIFORM_LightPosition , viewlightorigin[0], viewlightorigin[1], viewlightorigin[2]);
5787 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ViewToLightM1 , 1, false, viewtolight16f);
5788 DPSOFTRAST_Uniform3f( DPSOFTRAST_UNIFORM_DeferredColor_Ambient , lightcolorbase[0] * ambientscale * range, lightcolorbase[1] * ambientscale * range, lightcolorbase[2] * ambientscale * range);
5789 DPSOFTRAST_Uniform3f( DPSOFTRAST_UNIFORM_DeferredColor_Diffuse , lightcolorbase[0] * diffusescale * range, lightcolorbase[1] * diffusescale * range, lightcolorbase[2] * diffusescale * range);
5790 DPSOFTRAST_Uniform3f( DPSOFTRAST_UNIFORM_DeferredColor_Specular , lightcolorbase[0] * specularscale * range, lightcolorbase[1] * specularscale * range, lightcolorbase[2] * specularscale * range);
5791 DPSOFTRAST_Uniform2f( DPSOFTRAST_UNIFORM_ShadowMap_TextureScale , r_shadow_shadowmap_texturescale[0], r_shadow_shadowmap_texturescale[1]);
5792 DPSOFTRAST_Uniform4f( DPSOFTRAST_UNIFORM_ShadowMap_Parameters , r_shadow_shadowmap_parameters[0], r_shadow_shadowmap_parameters[1], r_shadow_shadowmap_parameters[2], r_shadow_shadowmap_parameters[3]);
5793 DPSOFTRAST_Uniform1f( DPSOFTRAST_UNIFORM_SpecularPower , (r_shadow_gloss.integer == 2 ? r_shadow_gloss2exponent.value : r_shadow_glossexponent.value) * (r_shadow_glossexact.integer ? 0.25f : 1.0f));
5794 DPSOFTRAST_Uniform2f( DPSOFTRAST_UNIFORM_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5795 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5797 R_Mesh_TexBind(GL20TU_ATTENUATION , r_shadow_attenuationgradienttexture );
5798 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5799 R_Mesh_TexBind(GL20TU_SCREENNORMALMAP , r_shadow_prepassgeometrynormalmaptexture );
5800 R_Mesh_TexBind(GL20TU_CUBE , rsurface.rtlight->currentcubemap );
5801 R_Mesh_TexBind(GL20TU_SHADOWMAP2D , r_shadow_shadowmap2dtexture );
5802 R_Mesh_TexBind(GL20TU_CUBEPROJECTION , r_shadow_shadowmapvsdcttexture );
5807 void R_SetupShader_DeferredBounceLight(void)
5809 // array of particle lights that contribute only ambient color
5810 unsigned int permutation = 0;
5811 unsigned int mode = 0;
5812 mode = SHADERMODE_DEFERREDBOUNCELIGHT;
5813 switch(vid.renderpath)
5815 case RENDERPATH_D3D9:
5817 R_SetupShader_SetPermutationHLSL(mode, permutation);
5818 hlslPSSetParameter2f(D3DPSREGISTER_ScreenToDepth, r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5819 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
5821 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthcolortexture );
5824 case RENDERPATH_D3D10:
5825 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5827 case RENDERPATH_D3D11:
5828 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
5830 case RENDERPATH_GL20:
5831 case RENDERPATH_GLES2:
5832 R_SetupShader_SetPermutationGLSL(mode, permutation);
5833 if (r_glsl_permutation->loc_ScreenToDepth >= 0) qglUniform2f( r_glsl_permutation->loc_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5834 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f( r_glsl_permutation->loc_PixelToScreenTexCoord , 1.0f/vid.width, 1.0f/vid.height);
5836 if (r_glsl_permutation->tex_Texture_ScreenDepth >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_ScreenDepth , r_shadow_prepassgeometrydepthtexture );
5838 case RENDERPATH_GL13:
5839 case RENDERPATH_GL11:
5841 case RENDERPATH_SOFT:
5842 R_SetupShader_SetPermutationGLSL(mode, permutation);
5843 DPSOFTRAST_Uniform2f( DPSOFTRAST_UNIFORM_ScreenToDepth , r_refdef.view.viewport.screentodepth[0], r_refdef.view.viewport.screentodepth[1]);
5844 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
5846 R_Mesh_TexBind(GL20TU_SCREENDEPTH , r_shadow_prepassgeometrydepthtexture );
5851 #define SKINFRAME_HASH 1024
5855 int loadsequence; // incremented each level change
5856 memexpandablearray_t array;
5857 skinframe_t *hash[SKINFRAME_HASH];
5860 r_skinframe_t r_skinframe;
5862 void R_SkinFrame_PrepareForPurge(void)
5864 r_skinframe.loadsequence++;
5865 // wrap it without hitting zero
5866 if (r_skinframe.loadsequence >= 200)
5867 r_skinframe.loadsequence = 1;
5870 void R_SkinFrame_MarkUsed(skinframe_t *skinframe)
5874 // mark the skinframe as used for the purging code
5875 skinframe->loadsequence = r_skinframe.loadsequence;
5878 void R_SkinFrame_Purge(void)
5882 for (i = 0;i < SKINFRAME_HASH;i++)
5884 for (s = r_skinframe.hash[i];s;s = s->next)
5886 if (s->loadsequence && s->loadsequence != r_skinframe.loadsequence)
5888 if (s->merged == s->base)
5890 // FIXME: maybe pass a pointer to the pointer to R_PurgeTexture and reset it to NULL inside? [11/29/2007 Black]
5891 R_PurgeTexture(s->stain );s->stain = NULL;
5892 R_PurgeTexture(s->merged);s->merged = NULL;
5893 R_PurgeTexture(s->base );s->base = NULL;
5894 R_PurgeTexture(s->pants );s->pants = NULL;
5895 R_PurgeTexture(s->shirt );s->shirt = NULL;
5896 R_PurgeTexture(s->nmap );s->nmap = NULL;
5897 R_PurgeTexture(s->gloss );s->gloss = NULL;
5898 R_PurgeTexture(s->glow );s->glow = NULL;
5899 R_PurgeTexture(s->fog );s->fog = NULL;
5900 R_PurgeTexture(s->reflect);s->reflect = NULL;
5901 s->loadsequence = 0;
5907 skinframe_t *R_SkinFrame_FindNextByName( skinframe_t *last, const char *name ) {
5909 char basename[MAX_QPATH];
5911 Image_StripImageExtension(name, basename, sizeof(basename));
5913 if( last == NULL ) {
5915 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5916 item = r_skinframe.hash[hashindex];
5921 // linearly search through the hash bucket
5922 for( ; item ; item = item->next ) {
5923 if( !strcmp( item->basename, basename ) ) {
5930 skinframe_t *R_SkinFrame_Find(const char *name, int textureflags, int comparewidth, int compareheight, int comparecrc, qboolean add)
5934 char basename[MAX_QPATH];
5936 Image_StripImageExtension(name, basename, sizeof(basename));
5938 hashindex = CRC_Block((unsigned char *)basename, strlen(basename)) & (SKINFRAME_HASH - 1);
5939 for (item = r_skinframe.hash[hashindex];item;item = item->next)
5940 if (!strcmp(item->basename, basename) && item->textureflags == textureflags && item->comparewidth == comparewidth && item->compareheight == compareheight && item->comparecrc == comparecrc)
5944 rtexture_t *dyntexture;
5945 // check whether its a dynamic texture
5946 dyntexture = CL_GetDynTexture( basename );
5947 if (!add && !dyntexture)
5949 item = (skinframe_t *)Mem_ExpandableArray_AllocRecord(&r_skinframe.array);
5950 memset(item, 0, sizeof(*item));
5951 strlcpy(item->basename, basename, sizeof(item->basename));
5952 item->base = dyntexture; // either NULL or dyntexture handle
5953 item->textureflags = textureflags;
5954 item->comparewidth = comparewidth;
5955 item->compareheight = compareheight;
5956 item->comparecrc = comparecrc;
5957 item->next = r_skinframe.hash[hashindex];
5958 r_skinframe.hash[hashindex] = item;
5960 else if( item->base == NULL )
5962 rtexture_t *dyntexture;
5963 // check whether its a dynamic texture
5964 // this only needs to be done because Purge doesnt delete skinframes - only sets the texture pointers to NULL and we need to restore it before returing.. [11/29/2007 Black]
5965 dyntexture = CL_GetDynTexture( basename );
5966 item->base = dyntexture; // either NULL or dyntexture handle
5969 R_SkinFrame_MarkUsed(item);
5973 #define R_SKINFRAME_LOAD_AVERAGE_COLORS(cnt, getpixel) \
5975 unsigned long long avgcolor[5], wsum; \
5983 for(pix = 0; pix < cnt; ++pix) \
5986 for(comp = 0; comp < 3; ++comp) \
5988 if(w) /* ignore perfectly black pixels because that is better for model skins */ \
5991 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5993 for(comp = 0; comp < 3; ++comp) \
5994 avgcolor[comp] += getpixel * w; \
5997 /* comp = 3; -- not needed, comp is always 3 when we get here */ \
5998 avgcolor[4] += getpixel; \
6000 if(avgcolor[3] == 0) /* no pixels seen? even worse */ \
6002 skinframe->avgcolor[0] = avgcolor[2] / (255.0 * avgcolor[3]); \
6003 skinframe->avgcolor[1] = avgcolor[1] / (255.0 * avgcolor[3]); \
6004 skinframe->avgcolor[2] = avgcolor[0] / (255.0 * avgcolor[3]); \
6005 skinframe->avgcolor[3] = avgcolor[4] / (255.0 * cnt); \
6008 extern cvar_t gl_picmip;
6009 skinframe_t *R_SkinFrame_LoadExternal(const char *name, int textureflags, qboolean complain)
6012 unsigned char *pixels;
6013 unsigned char *bumppixels;
6014 unsigned char *basepixels = NULL;
6015 int basepixels_width = 0;
6016 int basepixels_height = 0;
6017 skinframe_t *skinframe;
6018 rtexture_t *ddsbase = NULL;
6019 qboolean ddshasalpha = false;
6020 float ddsavgcolor[4];
6021 char basename[MAX_QPATH];
6022 int miplevel = R_PicmipForFlags(textureflags);
6023 int savemiplevel = miplevel;
6026 if (cls.state == ca_dedicated)
6029 // return an existing skinframe if already loaded
6030 // if loading of the first image fails, don't make a new skinframe as it
6031 // would cause all future lookups of this to be missing
6032 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
6033 if (skinframe && skinframe->base)
6036 Image_StripImageExtension(name, basename, sizeof(basename));
6038 // check for DDS texture file first
6039 if (!r_loaddds || !(ddsbase = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s.dds", basename), textureflags, &ddshasalpha, ddsavgcolor, miplevel)))
6041 basepixels = loadimagepixelsbgra(name, complain, true, r_texture_convertsRGB_skin.integer != 0, &miplevel);
6042 if (basepixels == NULL)
6046 // FIXME handle miplevel
6048 if (developer_loading.integer)
6049 Con_Printf("loading skin \"%s\"\n", name);
6051 // we've got some pixels to store, so really allocate this new texture now
6053 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, true);
6054 skinframe->stain = NULL;
6055 skinframe->merged = NULL;
6056 skinframe->base = NULL;
6057 skinframe->pants = NULL;
6058 skinframe->shirt = NULL;
6059 skinframe->nmap = NULL;
6060 skinframe->gloss = NULL;
6061 skinframe->glow = NULL;
6062 skinframe->fog = NULL;
6063 skinframe->reflect = NULL;
6064 skinframe->hasalpha = false;
6068 skinframe->base = ddsbase;
6069 skinframe->hasalpha = ddshasalpha;
6070 VectorCopy(ddsavgcolor, skinframe->avgcolor);
6071 if (r_loadfog && skinframe->hasalpha)
6072 skinframe->fog = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_mask.dds", skinframe->basename), textureflags | TEXF_ALPHA, NULL, NULL, miplevel);
6073 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6077 basepixels_width = image_width;
6078 basepixels_height = image_height;
6079 skinframe->base = R_LoadTexture2D (r_main_texturepool, skinframe->basename, basepixels_width, basepixels_height, basepixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
6080 if (textureflags & TEXF_ALPHA)
6082 for (j = 3;j < basepixels_width * basepixels_height * 4;j += 4)
6084 if (basepixels[j] < 255)
6086 skinframe->hasalpha = true;
6090 if (r_loadfog && skinframe->hasalpha)
6092 // has transparent pixels
6093 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6094 for (j = 0;j < image_width * image_height * 4;j += 4)
6099 pixels[j+3] = basepixels[j+3];
6101 skinframe->fog = R_LoadTexture2D (r_main_texturepool, va("%s_mask", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), miplevel, NULL);
6105 R_SKINFRAME_LOAD_AVERAGE_COLORS(basepixels_width * basepixels_height, basepixels[4 * pix + comp]);
6106 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6107 if (r_savedds && qglGetCompressedTexImageARB && skinframe->base)
6108 R_SaveTextureDDSFile(skinframe->base, va("dds/%s.dds", skinframe->basename), true, skinframe->hasalpha);
6109 if (r_savedds && qglGetCompressedTexImageARB && skinframe->fog)
6110 R_SaveTextureDDSFile(skinframe->fog, va("dds/%s_mask.dds", skinframe->basename), true, true);
6115 mymiplevel = savemiplevel;
6116 if (r_loadnormalmap)
6117 skinframe->nmap = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_norm.dds", skinframe->basename), (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), NULL, NULL, mymiplevel);
6118 skinframe->glow = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_glow.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6120 skinframe->gloss = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_gloss.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6121 skinframe->pants = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_pants.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6122 skinframe->shirt = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_shirt.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6123 skinframe->reflect = R_LoadTextureDDSFile(r_main_texturepool, va("dds/%s_reflect.dds", skinframe->basename), textureflags, NULL, NULL, mymiplevel);
6126 // _norm is the name used by tenebrae and has been adopted as standard
6127 if (r_loadnormalmap && skinframe->nmap == NULL)
6129 mymiplevel = savemiplevel;
6130 if ((pixels = loadimagepixelsbgra(va("%s_norm", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6132 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6136 else if (r_shadow_bumpscale_bumpmap.value > 0 && (bumppixels = loadimagepixelsbgra(va("%s_bump", skinframe->basename), false, false, false, &mymiplevel)) != NULL)
6138 pixels = (unsigned char *)Mem_Alloc(tempmempool, image_width * image_height * 4);
6139 Image_HeightmapToNormalmap_BGRA(bumppixels, pixels, image_width, image_height, false, r_shadow_bumpscale_bumpmap.value);
6140 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6142 Mem_Free(bumppixels);
6144 else if (r_shadow_bumpscale_basetexture.value > 0)
6146 pixels = (unsigned char *)Mem_Alloc(tempmempool, basepixels_width * basepixels_height * 4);
6147 Image_HeightmapToNormalmap_BGRA(basepixels, pixels, basepixels_width, basepixels_height, false, r_shadow_bumpscale_basetexture.value);
6148 skinframe->nmap = R_LoadTexture2D (r_main_texturepool, va("%s_nmap", skinframe->basename), basepixels_width, basepixels_height, pixels, TEXTYPE_BGRA, (TEXF_ALPHA | textureflags) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP) & (gl_texturecompression_normal.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6151 if (r_savedds && qglGetCompressedTexImageARB && skinframe->nmap)
6152 R_SaveTextureDDSFile(skinframe->nmap, va("dds/%s_norm.dds", skinframe->basename), true, true);
6155 // _luma is supported only for tenebrae compatibility
6156 // _glow is the preferred name
6157 mymiplevel = savemiplevel;
6158 if (skinframe->glow == NULL && ((pixels = loadimagepixelsbgra(va("%s_glow", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)) || (pixels = loadimagepixelsbgra(va("%s_luma", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel))))
6160 skinframe->glow = R_LoadTexture2D (r_main_texturepool, va("%s_glow", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_glow.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6161 if (r_savedds && qglGetCompressedTexImageARB && skinframe->glow)
6162 R_SaveTextureDDSFile(skinframe->glow, va("dds/%s_glow.dds", skinframe->basename), true, true);
6163 Mem_Free(pixels);pixels = NULL;
6166 mymiplevel = savemiplevel;
6167 if (skinframe->gloss == NULL && r_loadgloss && (pixels = loadimagepixelsbgra(va("%s_gloss", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6169 skinframe->gloss = R_LoadTexture2D (r_main_texturepool, va("%s_gloss", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_gloss.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6170 if (r_savedds && qglGetCompressedTexImageARB && skinframe->gloss)
6171 R_SaveTextureDDSFile(skinframe->gloss, va("dds/%s_gloss.dds", skinframe->basename), true, true);
6176 mymiplevel = savemiplevel;
6177 if (skinframe->pants == NULL && (pixels = loadimagepixelsbgra(va("%s_pants", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6179 skinframe->pants = R_LoadTexture2D (r_main_texturepool, va("%s_pants", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6180 if (r_savedds && qglGetCompressedTexImageARB && skinframe->pants)
6181 R_SaveTextureDDSFile(skinframe->pants, va("dds/%s_pants.dds", skinframe->basename), true, false);
6186 mymiplevel = savemiplevel;
6187 if (skinframe->shirt == NULL && (pixels = loadimagepixelsbgra(va("%s_shirt", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6189 skinframe->shirt = R_LoadTexture2D (r_main_texturepool, va("%s_shirt", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_color.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6190 if (r_savedds && qglGetCompressedTexImageARB && skinframe->shirt)
6191 R_SaveTextureDDSFile(skinframe->shirt, va("dds/%s_shirt.dds", skinframe->basename), true, false);
6196 mymiplevel = savemiplevel;
6197 if (skinframe->reflect == NULL && (pixels = loadimagepixelsbgra(va("%s_reflect", skinframe->basename), false, false, r_texture_convertsRGB_skin.integer != 0, &mymiplevel)))
6199 skinframe->reflect = R_LoadTexture2D (r_main_texturepool, va("%s_reflect", skinframe->basename), image_width, image_height, pixels, TEXTYPE_BGRA, textureflags & (gl_texturecompression_reflectmask.integer ? ~0 : ~TEXF_COMPRESS), mymiplevel, NULL);
6200 if (r_savedds && qglGetCompressedTexImageARB && skinframe->reflect)
6201 R_SaveTextureDDSFile(skinframe->reflect, va("dds/%s_reflect.dds", skinframe->basename), true, true);
6207 Mem_Free(basepixels);
6212 // this is only used by .spr32 sprites, HL .spr files, HL .bsp files
6213 skinframe_t *R_SkinFrame_LoadInternalBGRA(const char *name, int textureflags, const unsigned char *skindata, int width, int height)
6216 unsigned char *temp1, *temp2;
6217 skinframe_t *skinframe;
6219 if (cls.state == ca_dedicated)
6222 // if already loaded just return it, otherwise make a new skinframe
6223 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height*4) : 0, true);
6224 if (skinframe && skinframe->base)
6227 skinframe->stain = NULL;
6228 skinframe->merged = NULL;
6229 skinframe->base = NULL;
6230 skinframe->pants = NULL;
6231 skinframe->shirt = NULL;
6232 skinframe->nmap = NULL;
6233 skinframe->gloss = NULL;
6234 skinframe->glow = NULL;
6235 skinframe->fog = NULL;
6236 skinframe->reflect = NULL;
6237 skinframe->hasalpha = false;
6239 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6243 if (developer_loading.integer)
6244 Con_Printf("loading 32bit skin \"%s\"\n", name);
6246 if (r_loadnormalmap && r_shadow_bumpscale_basetexture.value > 0)
6248 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6249 temp2 = temp1 + width * height * 4;
6250 Image_HeightmapToNormalmap_BGRA(skindata, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6251 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
6254 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_BGRA, textureflags, -1, NULL);
6255 if (textureflags & TEXF_ALPHA)
6257 for (i = 3;i < width * height * 4;i += 4)
6259 if (skindata[i] < 255)
6261 skinframe->hasalpha = true;
6265 if (r_loadfog && skinframe->hasalpha)
6267 unsigned char *fogpixels = (unsigned char *)Mem_Alloc(tempmempool, width * height * 4);
6268 memcpy(fogpixels, skindata, width * height * 4);
6269 for (i = 0;i < width * height * 4;i += 4)
6270 fogpixels[i] = fogpixels[i+1] = fogpixels[i+2] = 255;
6271 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, fogpixels, TEXTYPE_BGRA, textureflags, -1, NULL);
6272 Mem_Free(fogpixels);
6276 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, skindata[4 * pix + comp]);
6277 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6282 skinframe_t *R_SkinFrame_LoadInternalQuake(const char *name, int textureflags, int loadpantsandshirt, int loadglowtexture, const unsigned char *skindata, int width, int height)
6286 skinframe_t *skinframe;
6288 if (cls.state == ca_dedicated)
6291 // if already loaded just return it, otherwise make a new skinframe
6292 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6293 if (skinframe && skinframe->base)
6296 skinframe->stain = NULL;
6297 skinframe->merged = NULL;
6298 skinframe->base = NULL;
6299 skinframe->pants = NULL;
6300 skinframe->shirt = NULL;
6301 skinframe->nmap = NULL;
6302 skinframe->gloss = NULL;
6303 skinframe->glow = NULL;
6304 skinframe->fog = NULL;
6305 skinframe->reflect = NULL;
6306 skinframe->hasalpha = false;
6308 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6312 if (developer_loading.integer)
6313 Con_Printf("loading quake skin \"%s\"\n", name);
6315 // we actually don't upload anything until the first use, because mdl skins frequently go unused, and are almost never used in both modes (colormapped and non-colormapped)
6316 skinframe->qpixels = (unsigned char *)Mem_Alloc(r_main_mempool, width*height); // FIXME LEAK
6317 memcpy(skinframe->qpixels, skindata, width*height);
6318 skinframe->qwidth = width;
6319 skinframe->qheight = height;
6322 for (i = 0;i < width * height;i++)
6323 featuresmask |= palette_featureflags[skindata[i]];
6325 skinframe->hasalpha = false;
6326 skinframe->qhascolormapping = loadpantsandshirt && (featuresmask & (PALETTEFEATURE_PANTS | PALETTEFEATURE_SHIRT));
6327 skinframe->qgeneratenmap = r_shadow_bumpscale_basetexture.value > 0;
6328 skinframe->qgeneratemerged = true;
6329 skinframe->qgeneratebase = skinframe->qhascolormapping;
6330 skinframe->qgenerateglow = loadglowtexture && (featuresmask & PALETTEFEATURE_GLOW);
6332 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette_bgra_complete)[skindata[pix]*4 + comp]);
6333 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6338 static void R_SkinFrame_GenerateTexturesFromQPixels(skinframe_t *skinframe, qboolean colormapped)
6342 unsigned char *skindata;
6344 if (!skinframe->qpixels)
6347 if (!skinframe->qhascolormapping)
6348 colormapped = false;
6352 if (!skinframe->qgeneratebase)
6357 if (!skinframe->qgeneratemerged)
6361 width = skinframe->qwidth;
6362 height = skinframe->qheight;
6363 skindata = skinframe->qpixels;
6365 if (skinframe->qgeneratenmap)
6367 unsigned char *temp1, *temp2;
6368 skinframe->qgeneratenmap = false;
6369 temp1 = (unsigned char *)Mem_Alloc(tempmempool, width * height * 8);
6370 temp2 = temp1 + width * height * 4;
6371 // use either a custom palette or the quake palette
6372 Image_Copy8bitBGRA(skindata, temp1, width * height, palette_bgra_complete);
6373 Image_HeightmapToNormalmap_BGRA(temp1, temp2, width, height, false, r_shadow_bumpscale_basetexture.value);
6374 skinframe->nmap = R_LoadTexture2D(r_main_texturepool, va("%s_nmap", skinframe->basename), width, height, temp2, TEXTYPE_BGRA, (skinframe->textureflags | TEXF_ALPHA) & (r_mipnormalmaps.integer ? ~0 : ~TEXF_MIPMAP), -1, NULL);
6378 if (skinframe->qgenerateglow)
6380 skinframe->qgenerateglow = false;
6381 skinframe->glow = R_LoadTexture2D(r_main_texturepool, va("%s_glow", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_onlyfullbrights); // glow
6386 skinframe->qgeneratebase = false;
6387 skinframe->base = R_LoadTexture2D(r_main_texturepool, va("%s_nospecial", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nocolormapnofullbrights : palette_bgra_nocolormap);
6388 skinframe->pants = R_LoadTexture2D(r_main_texturepool, va("%s_pants", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_pantsaswhite);
6389 skinframe->shirt = R_LoadTexture2D(r_main_texturepool, va("%s_shirt", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, palette_bgra_shirtaswhite);
6393 skinframe->qgeneratemerged = false;
6394 skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, skinframe->textureflags, -1, skinframe->glow ? palette_bgra_nofullbrights : palette_bgra_complete);
6397 if (!skinframe->qgeneratemerged && !skinframe->qgeneratebase)
6399 Mem_Free(skinframe->qpixels);
6400 skinframe->qpixels = NULL;
6404 skinframe_t *R_SkinFrame_LoadInternal8bit(const char *name, int textureflags, const unsigned char *skindata, int width, int height, const unsigned int *palette, const unsigned int *alphapalette)
6407 skinframe_t *skinframe;
6409 if (cls.state == ca_dedicated)
6412 // if already loaded just return it, otherwise make a new skinframe
6413 skinframe = R_SkinFrame_Find(name, textureflags, width, height, skindata ? CRC_Block(skindata, width*height) : 0, true);
6414 if (skinframe && skinframe->base)
6417 skinframe->stain = NULL;
6418 skinframe->merged = NULL;
6419 skinframe->base = NULL;
6420 skinframe->pants = NULL;
6421 skinframe->shirt = NULL;
6422 skinframe->nmap = NULL;
6423 skinframe->gloss = NULL;
6424 skinframe->glow = NULL;
6425 skinframe->fog = NULL;
6426 skinframe->reflect = NULL;
6427 skinframe->hasalpha = false;
6429 // if no data was provided, then clearly the caller wanted to get a blank skinframe
6433 if (developer_loading.integer)
6434 Con_Printf("loading embedded 8bit image \"%s\"\n", name);
6436 skinframe->base = skinframe->merged = R_LoadTexture2D(r_main_texturepool, skinframe->basename, width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, palette);
6437 if (textureflags & TEXF_ALPHA)
6439 for (i = 0;i < width * height;i++)
6441 if (((unsigned char *)palette)[skindata[i]*4+3] < 255)
6443 skinframe->hasalpha = true;
6447 if (r_loadfog && skinframe->hasalpha)
6448 skinframe->fog = R_LoadTexture2D(r_main_texturepool, va("%s_fog", skinframe->basename), width, height, skindata, TEXTYPE_PALETTE, textureflags, -1, alphapalette);
6451 R_SKINFRAME_LOAD_AVERAGE_COLORS(width * height, ((unsigned char *)palette)[skindata[pix]*4 + comp]);
6452 //Con_Printf("Texture %s has average colors %f %f %f alpha %f\n", name, skinframe->avgcolor[0], skinframe->avgcolor[1], skinframe->avgcolor[2], skinframe->avgcolor[3]);
6457 skinframe_t *R_SkinFrame_LoadMissing(void)
6459 skinframe_t *skinframe;
6461 if (cls.state == ca_dedicated)
6464 skinframe = R_SkinFrame_Find("missing", TEXF_FORCENEAREST, 0, 0, 0, true);
6465 skinframe->stain = NULL;
6466 skinframe->merged = NULL;
6467 skinframe->base = NULL;
6468 skinframe->pants = NULL;
6469 skinframe->shirt = NULL;
6470 skinframe->nmap = NULL;
6471 skinframe->gloss = NULL;
6472 skinframe->glow = NULL;
6473 skinframe->fog = NULL;
6474 skinframe->reflect = NULL;
6475 skinframe->hasalpha = false;
6477 skinframe->avgcolor[0] = rand() / RAND_MAX;
6478 skinframe->avgcolor[1] = rand() / RAND_MAX;
6479 skinframe->avgcolor[2] = rand() / RAND_MAX;
6480 skinframe->avgcolor[3] = 1;
6485 //static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"};
6486 typedef struct suffixinfo_s
6489 qboolean flipx, flipy, flipdiagonal;
6492 static suffixinfo_t suffix[3][6] =
6495 {"px", false, false, false},
6496 {"nx", false, false, false},
6497 {"py", false, false, false},
6498 {"ny", false, false, false},
6499 {"pz", false, false, false},
6500 {"nz", false, false, false}
6503 {"posx", false, false, false},
6504 {"negx", false, false, false},
6505 {"posy", false, false, false},
6506 {"negy", false, false, false},
6507 {"posz", false, false, false},
6508 {"negz", false, false, false}
6511 {"rt", true, false, true},
6512 {"lf", false, true, true},
6513 {"ft", true, true, false},
6514 {"bk", false, false, false},
6515 {"up", true, false, true},
6516 {"dn", true, false, true}
6520 static int componentorder[4] = {0, 1, 2, 3};
6522 rtexture_t *R_LoadCubemap(const char *basename)
6524 int i, j, cubemapsize;
6525 unsigned char *cubemappixels, *image_buffer;
6526 rtexture_t *cubemaptexture;
6528 // must start 0 so the first loadimagepixels has no requested width/height
6530 cubemappixels = NULL;
6531 cubemaptexture = NULL;
6532 // keep trying different suffix groups (posx, px, rt) until one loads
6533 for (j = 0;j < 3 && !cubemappixels;j++)
6535 // load the 6 images in the suffix group
6536 for (i = 0;i < 6;i++)
6538 // generate an image name based on the base and and suffix
6539 dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix);
6541 if ((image_buffer = loadimagepixelsbgra(name, false, false, r_texture_convertsRGB_cubemap.integer != 0, NULL)))
6543 // an image loaded, make sure width and height are equal
6544 if (image_width == image_height && (!cubemappixels || image_width == cubemapsize))
6546 // if this is the first image to load successfully, allocate the cubemap memory
6547 if (!cubemappixels && image_width >= 1)
6549 cubemapsize = image_width;
6550 // note this clears to black, so unavailable sides are black
6551 cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4);
6553 // copy the image with any flipping needed by the suffix (px and posx types don't need flipping)
6555 Image_CopyMux(cubemappixels+i*cubemapsize*cubemapsize*4, image_buffer, cubemapsize, cubemapsize, suffix[j][i].flipx, suffix[j][i].flipy, suffix[j][i].flipdiagonal, 4, 4, componentorder);
6558 Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height);
6560 Mem_Free(image_buffer);
6564 // if a cubemap loaded, upload it
6567 if (developer_loading.integer)
6568 Con_Printf("loading cubemap \"%s\"\n", basename);
6570 cubemaptexture = R_LoadTextureCubeMap(r_main_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
6571 Mem_Free(cubemappixels);
6575 Con_DPrintf("failed to load cubemap \"%s\"\n", basename);
6576 if (developer_loading.integer)
6578 Con_Printf("(tried tried images ");
6579 for (j = 0;j < 3;j++)
6580 for (i = 0;i < 6;i++)
6581 Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix);
6582 Con_Print(" and was unable to find any of them).\n");
6585 return cubemaptexture;
6588 rtexture_t *R_GetCubemap(const char *basename)
6591 for (i = 0;i < r_texture_numcubemaps;i++)
6592 if (!strcasecmp(r_texture_cubemaps[i].basename, basename))
6593 return r_texture_cubemaps[i].texture ? r_texture_cubemaps[i].texture : r_texture_whitecube;
6594 if (i >= MAX_CUBEMAPS)
6595 return r_texture_whitecube;
6596 r_texture_numcubemaps++;
6597 strlcpy(r_texture_cubemaps[i].basename, basename, sizeof(r_texture_cubemaps[i].basename));
6598 r_texture_cubemaps[i].texture = R_LoadCubemap(r_texture_cubemaps[i].basename);
6599 return r_texture_cubemaps[i].texture;
6602 void R_FreeCubemaps(void)
6605 for (i = 0;i < r_texture_numcubemaps;i++)
6607 if (developer_loading.integer)
6608 Con_DPrintf("unloading cubemap \"%s\"\n", r_texture_cubemaps[i].basename);
6609 if (r_texture_cubemaps[i].texture)
6610 R_FreeTexture(r_texture_cubemaps[i].texture);
6612 r_texture_numcubemaps = 0;
6615 void R_Main_FreeViewCache(void)
6617 if (r_refdef.viewcache.entityvisible)
6618 Mem_Free(r_refdef.viewcache.entityvisible);
6619 if (r_refdef.viewcache.world_pvsbits)
6620 Mem_Free(r_refdef.viewcache.world_pvsbits);
6621 if (r_refdef.viewcache.world_leafvisible)
6622 Mem_Free(r_refdef.viewcache.world_leafvisible);
6623 if (r_refdef.viewcache.world_surfacevisible)
6624 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6625 memset(&r_refdef.viewcache, 0, sizeof(r_refdef.viewcache));
6628 void R_Main_ResizeViewCache(void)
6630 int numentities = r_refdef.scene.numentities;
6631 int numclusters = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusters : 1;
6632 int numclusterbytes = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_pvsclusterbytes : 1;
6633 int numleafs = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->brush.num_leafs : 1;
6634 int numsurfaces = r_refdef.scene.worldmodel ? r_refdef.scene.worldmodel->num_surfaces : 1;
6635 if (r_refdef.viewcache.maxentities < numentities)
6637 r_refdef.viewcache.maxentities = numentities;
6638 if (r_refdef.viewcache.entityvisible)
6639 Mem_Free(r_refdef.viewcache.entityvisible);
6640 r_refdef.viewcache.entityvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.maxentities);
6642 if (r_refdef.viewcache.world_numclusters != numclusters)
6644 r_refdef.viewcache.world_numclusters = numclusters;
6645 r_refdef.viewcache.world_numclusterbytes = numclusterbytes;
6646 if (r_refdef.viewcache.world_pvsbits)
6647 Mem_Free(r_refdef.viewcache.world_pvsbits);
6648 r_refdef.viewcache.world_pvsbits = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numclusterbytes);
6650 if (r_refdef.viewcache.world_numleafs != numleafs)
6652 r_refdef.viewcache.world_numleafs = numleafs;
6653 if (r_refdef.viewcache.world_leafvisible)
6654 Mem_Free(r_refdef.viewcache.world_leafvisible);
6655 r_refdef.viewcache.world_leafvisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numleafs);
6657 if (r_refdef.viewcache.world_numsurfaces != numsurfaces)
6659 r_refdef.viewcache.world_numsurfaces = numsurfaces;
6660 if (r_refdef.viewcache.world_surfacevisible)
6661 Mem_Free(r_refdef.viewcache.world_surfacevisible);
6662 r_refdef.viewcache.world_surfacevisible = (unsigned char *)Mem_Alloc(r_main_mempool, r_refdef.viewcache.world_numsurfaces);
6666 extern rtexture_t *loadingscreentexture;
6667 void gl_main_start(void)
6669 loadingscreentexture = NULL;
6670 r_texture_blanknormalmap = NULL;
6671 r_texture_white = NULL;
6672 r_texture_grey128 = NULL;
6673 r_texture_black = NULL;
6674 r_texture_whitecube = NULL;
6675 r_texture_normalizationcube = NULL;
6676 r_texture_fogattenuation = NULL;
6677 r_texture_fogheighttexture = NULL;
6678 r_texture_gammaramps = NULL;
6679 r_texture_numcubemaps = 0;
6681 r_loaddds = r_texture_dds_load.integer != 0;
6682 r_savedds = vid.support.arb_texture_compression && vid.support.ext_texture_compression_s3tc && r_texture_dds_save.integer;
6684 switch(vid.renderpath)
6686 case RENDERPATH_GL20:
6687 case RENDERPATH_D3D9:
6688 case RENDERPATH_D3D10:
6689 case RENDERPATH_D3D11:
6690 case RENDERPATH_SOFT:
6691 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6692 Cvar_SetValueQuick(&gl_combine, 1);
6693 Cvar_SetValueQuick(&r_glsl, 1);
6694 r_loadnormalmap = true;
6698 case RENDERPATH_GL13:
6699 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6700 Cvar_SetValueQuick(&gl_combine, 1);
6701 Cvar_SetValueQuick(&r_glsl, 0);
6702 r_loadnormalmap = false;
6703 r_loadgloss = false;
6706 case RENDERPATH_GL11:
6707 Cvar_SetValueQuick(&r_textureunits, vid.texunits);
6708 Cvar_SetValueQuick(&gl_combine, 0);
6709 Cvar_SetValueQuick(&r_glsl, 0);
6710 r_loadnormalmap = false;
6711 r_loadgloss = false;
6714 case RENDERPATH_GLES2:
6715 Cvar_SetValueQuick(&r_textureunits, 1);
6716 Cvar_SetValueQuick(&gl_combine, 1);
6717 Cvar_SetValueQuick(&r_glsl, 1);
6718 r_loadnormalmap = true;
6719 r_loadgloss = false;
6725 R_FrameData_Reset();
6729 memset(r_queries, 0, sizeof(r_queries));
6731 r_qwskincache = NULL;
6732 r_qwskincache_size = 0;
6734 // set up r_skinframe loading system for textures
6735 memset(&r_skinframe, 0, sizeof(r_skinframe));
6736 r_skinframe.loadsequence = 1;
6737 Mem_ExpandableArray_NewArray(&r_skinframe.array, r_main_mempool, sizeof(skinframe_t), 256);
6739 r_main_texturepool = R_AllocTexturePool();
6740 R_BuildBlankTextures();
6742 if (vid.support.arb_texture_cube_map)
6745 R_BuildNormalizationCube();
6747 r_texture_fogattenuation = NULL;
6748 r_texture_fogheighttexture = NULL;
6749 r_texture_gammaramps = NULL;
6750 //r_texture_fogintensity = NULL;
6751 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6752 memset(&r_waterstate, 0, sizeof(r_waterstate));
6753 r_glsl_permutation = NULL;
6754 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6755 Mem_ExpandableArray_NewArray(&r_glsl_permutationarray, r_main_mempool, sizeof(r_glsl_permutation_t), 256);
6756 glslshaderstring = NULL;
6758 r_hlsl_permutation = NULL;
6759 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
6760 Mem_ExpandableArray_NewArray(&r_hlsl_permutationarray, r_main_mempool, sizeof(r_hlsl_permutation_t), 256);
6762 hlslshaderstring = NULL;
6763 memset(&r_svbsp, 0, sizeof (r_svbsp));
6765 r_refdef.fogmasktable_density = 0;
6768 void gl_main_shutdown(void)
6771 R_FrameData_Reset();
6773 R_Main_FreeViewCache();
6775 switch(vid.renderpath)
6777 case RENDERPATH_GL11:
6778 case RENDERPATH_GL13:
6779 case RENDERPATH_GL20:
6780 case RENDERPATH_GLES2:
6782 qglDeleteQueriesARB(r_maxqueries, r_queries);
6784 case RENDERPATH_D3D9:
6785 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6787 case RENDERPATH_D3D10:
6788 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6790 case RENDERPATH_D3D11:
6791 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
6793 case RENDERPATH_SOFT:
6799 memset(r_queries, 0, sizeof(r_queries));
6801 r_qwskincache = NULL;
6802 r_qwskincache_size = 0;
6804 // clear out the r_skinframe state
6805 Mem_ExpandableArray_FreeArray(&r_skinframe.array);
6806 memset(&r_skinframe, 0, sizeof(r_skinframe));
6809 Mem_Free(r_svbsp.nodes);
6810 memset(&r_svbsp, 0, sizeof (r_svbsp));
6811 R_FreeTexturePool(&r_main_texturepool);
6812 loadingscreentexture = NULL;
6813 r_texture_blanknormalmap = NULL;
6814 r_texture_white = NULL;
6815 r_texture_grey128 = NULL;
6816 r_texture_black = NULL;
6817 r_texture_whitecube = NULL;
6818 r_texture_normalizationcube = NULL;
6819 r_texture_fogattenuation = NULL;
6820 r_texture_fogheighttexture = NULL;
6821 r_texture_gammaramps = NULL;
6822 r_texture_numcubemaps = 0;
6823 //r_texture_fogintensity = NULL;
6824 memset(&r_bloomstate, 0, sizeof(r_bloomstate));
6825 memset(&r_waterstate, 0, sizeof(r_waterstate));
6828 r_glsl_permutation = NULL;
6829 memset(r_glsl_permutationhash, 0, sizeof(r_glsl_permutationhash));
6830 Mem_ExpandableArray_FreeArray(&r_glsl_permutationarray);
6831 glslshaderstring = NULL;
6833 r_hlsl_permutation = NULL;
6834 memset(r_hlsl_permutationhash, 0, sizeof(r_hlsl_permutationhash));
6835 Mem_ExpandableArray_FreeArray(&r_hlsl_permutationarray);
6837 hlslshaderstring = NULL;
6840 extern void CL_ParseEntityLump(char *entitystring);
6841 void gl_main_newmap(void)
6843 // FIXME: move this code to client
6844 char *entities, entname[MAX_QPATH];
6846 Mem_Free(r_qwskincache);
6847 r_qwskincache = NULL;
6848 r_qwskincache_size = 0;
6851 dpsnprintf(entname, sizeof(entname), "%s.ent", cl.worldnamenoextension);
6852 if ((entities = (char *)FS_LoadFile(entname, tempmempool, true, NULL)))
6854 CL_ParseEntityLump(entities);
6858 if (cl.worldmodel->brush.entities)
6859 CL_ParseEntityLump(cl.worldmodel->brush.entities);
6861 R_Main_FreeViewCache();
6863 R_FrameData_Reset();
6866 void GL_Main_Init(void)
6868 r_main_mempool = Mem_AllocPool("Renderer", 0, NULL);
6870 Cmd_AddCommand("r_glsl_restart", R_GLSL_Restart_f, "unloads GLSL shaders, they will then be reloaded as needed");
6871 Cmd_AddCommand("r_glsl_dumpshader", R_GLSL_DumpShader_f, "dumps the engine internal default.glsl shader into glsl/default.glsl");
6872 // FIXME: the client should set up r_refdef.fog stuff including the fogmasktable
6873 if (gamemode == GAME_NEHAHRA)
6875 Cvar_RegisterVariable (&gl_fogenable);
6876 Cvar_RegisterVariable (&gl_fogdensity);
6877 Cvar_RegisterVariable (&gl_fogred);
6878 Cvar_RegisterVariable (&gl_foggreen);
6879 Cvar_RegisterVariable (&gl_fogblue);
6880 Cvar_RegisterVariable (&gl_fogstart);
6881 Cvar_RegisterVariable (&gl_fogend);
6882 Cvar_RegisterVariable (&gl_skyclip);
6884 Cvar_RegisterVariable(&r_motionblur);
6885 Cvar_RegisterVariable(&r_motionblur_maxblur);
6886 Cvar_RegisterVariable(&r_motionblur_bmin);
6887 Cvar_RegisterVariable(&r_motionblur_vmin);
6888 Cvar_RegisterVariable(&r_motionblur_vmax);
6889 Cvar_RegisterVariable(&r_motionblur_vcoeff);
6890 Cvar_RegisterVariable(&r_motionblur_randomize);
6891 Cvar_RegisterVariable(&r_damageblur);
6892 Cvar_RegisterVariable(&r_equalize_entities_fullbright);
6893 Cvar_RegisterVariable(&r_equalize_entities_minambient);
6894 Cvar_RegisterVariable(&r_equalize_entities_by);
6895 Cvar_RegisterVariable(&r_equalize_entities_to);
6896 Cvar_RegisterVariable(&r_depthfirst);
6897 Cvar_RegisterVariable(&r_useinfinitefarclip);
6898 Cvar_RegisterVariable(&r_farclip_base);
6899 Cvar_RegisterVariable(&r_farclip_world);
6900 Cvar_RegisterVariable(&r_nearclip);
6901 Cvar_RegisterVariable(&r_showbboxes);
6902 Cvar_RegisterVariable(&r_showsurfaces);
6903 Cvar_RegisterVariable(&r_showtris);
6904 Cvar_RegisterVariable(&r_shownormals);
6905 Cvar_RegisterVariable(&r_showlighting);
6906 Cvar_RegisterVariable(&r_showshadowvolumes);
6907 Cvar_RegisterVariable(&r_showcollisionbrushes);
6908 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonfactor);
6909 Cvar_RegisterVariable(&r_showcollisionbrushes_polygonoffset);
6910 Cvar_RegisterVariable(&r_showdisabledepthtest);
6911 Cvar_RegisterVariable(&r_drawportals);
6912 Cvar_RegisterVariable(&r_drawentities);
6913 Cvar_RegisterVariable(&r_draw2d);
6914 Cvar_RegisterVariable(&r_drawworld);
6915 Cvar_RegisterVariable(&r_cullentities_trace);
6916 Cvar_RegisterVariable(&r_cullentities_trace_samples);
6917 Cvar_RegisterVariable(&r_cullentities_trace_tempentitysamples);
6918 Cvar_RegisterVariable(&r_cullentities_trace_enlarge);
6919 Cvar_RegisterVariable(&r_cullentities_trace_delay);
6920 Cvar_RegisterVariable(&r_drawviewmodel);
6921 Cvar_RegisterVariable(&r_drawexteriormodel);
6922 Cvar_RegisterVariable(&r_speeds);
6923 Cvar_RegisterVariable(&r_fullbrights);
6924 Cvar_RegisterVariable(&r_wateralpha);
6925 Cvar_RegisterVariable(&r_dynamic);
6926 Cvar_RegisterVariable(&r_fakelight);
6927 Cvar_RegisterVariable(&r_fakelight_intensity);
6928 Cvar_RegisterVariable(&r_fullbright);
6929 Cvar_RegisterVariable(&r_shadows);
6930 Cvar_RegisterVariable(&r_shadows_darken);
6931 Cvar_RegisterVariable(&r_shadows_drawafterrtlighting);
6932 Cvar_RegisterVariable(&r_shadows_castfrombmodels);
6933 Cvar_RegisterVariable(&r_shadows_throwdistance);
6934 Cvar_RegisterVariable(&r_shadows_throwdirection);
6935 Cvar_RegisterVariable(&r_shadows_focus);
6936 Cvar_RegisterVariable(&r_shadows_shadowmapscale);
6937 Cvar_RegisterVariable(&r_q1bsp_skymasking);
6938 Cvar_RegisterVariable(&r_polygonoffset_submodel_factor);
6939 Cvar_RegisterVariable(&r_polygonoffset_submodel_offset);
6940 Cvar_RegisterVariable(&r_polygonoffset_decals_factor);
6941 Cvar_RegisterVariable(&r_polygonoffset_decals_offset);
6942 Cvar_RegisterVariable(&r_fog_exp2);
6943 Cvar_RegisterVariable(&r_drawfog);
6944 Cvar_RegisterVariable(&r_transparentdepthmasking);
6945 Cvar_RegisterVariable(&r_texture_dds_load);
6946 Cvar_RegisterVariable(&r_texture_dds_save);
6947 Cvar_RegisterVariable(&r_texture_convertsRGB_2d);
6948 Cvar_RegisterVariable(&r_texture_convertsRGB_skin);
6949 Cvar_RegisterVariable(&r_texture_convertsRGB_cubemap);
6950 Cvar_RegisterVariable(&r_texture_convertsRGB_skybox);
6951 Cvar_RegisterVariable(&r_texture_convertsRGB_particles);
6952 Cvar_RegisterVariable(&r_textureunits);
6953 Cvar_RegisterVariable(&gl_combine);
6954 Cvar_RegisterVariable(&r_glsl);
6955 Cvar_RegisterVariable(&r_glsl_deluxemapping);
6956 Cvar_RegisterVariable(&r_glsl_offsetmapping);
6957 Cvar_RegisterVariable(&r_glsl_offsetmapping_reliefmapping);
6958 Cvar_RegisterVariable(&r_glsl_offsetmapping_scale);
6959 Cvar_RegisterVariable(&r_glsl_postprocess);
6960 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1);
6961 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2);
6962 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3);
6963 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4);
6964 Cvar_RegisterVariable(&r_glsl_postprocess_uservec1_enable);
6965 Cvar_RegisterVariable(&r_glsl_postprocess_uservec2_enable);
6966 Cvar_RegisterVariable(&r_glsl_postprocess_uservec3_enable);
6967 Cvar_RegisterVariable(&r_glsl_postprocess_uservec4_enable);
6969 Cvar_RegisterVariable(&r_water);
6970 Cvar_RegisterVariable(&r_water_resolutionmultiplier);
6971 Cvar_RegisterVariable(&r_water_clippingplanebias);
6972 Cvar_RegisterVariable(&r_water_refractdistort);
6973 Cvar_RegisterVariable(&r_water_reflectdistort);
6974 Cvar_RegisterVariable(&r_water_scissormode);
6975 Cvar_RegisterVariable(&r_lerpsprites);
6976 Cvar_RegisterVariable(&r_lerpmodels);
6977 Cvar_RegisterVariable(&r_lerplightstyles);
6978 Cvar_RegisterVariable(&r_waterscroll);
6979 Cvar_RegisterVariable(&r_bloom);
6980 Cvar_RegisterVariable(&r_bloom_colorscale);
6981 Cvar_RegisterVariable(&r_bloom_brighten);
6982 Cvar_RegisterVariable(&r_bloom_blur);
6983 Cvar_RegisterVariable(&r_bloom_resolution);
6984 Cvar_RegisterVariable(&r_bloom_colorexponent);
6985 Cvar_RegisterVariable(&r_bloom_colorsubtract);
6986 Cvar_RegisterVariable(&r_hdr);
6987 Cvar_RegisterVariable(&r_hdr_scenebrightness);
6988 Cvar_RegisterVariable(&r_hdr_glowintensity);
6989 Cvar_RegisterVariable(&r_hdr_range);
6990 Cvar_RegisterVariable(&r_hdr_irisadaptation);
6991 Cvar_RegisterVariable(&r_hdr_irisadaptation_multiplier);
6992 Cvar_RegisterVariable(&r_hdr_irisadaptation_minvalue);
6993 Cvar_RegisterVariable(&r_hdr_irisadaptation_maxvalue);
6994 Cvar_RegisterVariable(&r_hdr_irisadaptation_value);
6995 Cvar_RegisterVariable(&r_hdr_irisadaptation_fade);
6996 Cvar_RegisterVariable(&r_smoothnormals_areaweighting);
6997 Cvar_RegisterVariable(&developer_texturelogging);
6998 Cvar_RegisterVariable(&gl_lightmaps);
6999 Cvar_RegisterVariable(&r_test);
7000 Cvar_RegisterVariable(&r_glsl_saturation);
7001 Cvar_RegisterVariable(&r_glsl_saturation_redcompensate);
7002 Cvar_RegisterVariable(&r_framedatasize);
7003 if (gamemode == GAME_NEHAHRA || gamemode == GAME_TENEBRAE)
7004 Cvar_SetValue("r_fullbrights", 0);
7005 R_RegisterModule("GL_Main", gl_main_start, gl_main_shutdown, gl_main_newmap, NULL, NULL);
7007 Cvar_RegisterVariable(&r_track_sprites);
7008 Cvar_RegisterVariable(&r_track_sprites_flags);
7009 Cvar_RegisterVariable(&r_track_sprites_scalew);
7010 Cvar_RegisterVariable(&r_track_sprites_scaleh);
7011 Cvar_RegisterVariable(&r_overheadsprites_perspective);
7012 Cvar_RegisterVariable(&r_overheadsprites_pushback);
7013 Cvar_RegisterVariable(&r_overheadsprites_scalex);
7014 Cvar_RegisterVariable(&r_overheadsprites_scaley);
7017 extern void R_Textures_Init(void);
7018 extern void GL_Draw_Init(void);
7019 extern void GL_Main_Init(void);
7020 extern void R_Shadow_Init(void);
7021 extern void R_Sky_Init(void);
7022 extern void GL_Surf_Init(void);
7023 extern void R_Particles_Init(void);
7024 extern void R_Explosion_Init(void);
7025 extern void gl_backend_init(void);
7026 extern void Sbar_Init(void);
7027 extern void R_LightningBeams_Init(void);
7028 extern void Mod_RenderInit(void);
7029 extern void Font_Init(void);
7031 void Render_Init(void)
7044 R_LightningBeams_Init();
7053 extern char *ENGINE_EXTENSIONS;
7056 gl_renderer = (const char *)qglGetString(GL_RENDERER);
7057 gl_vendor = (const char *)qglGetString(GL_VENDOR);
7058 gl_version = (const char *)qglGetString(GL_VERSION);
7059 gl_extensions = (const char *)qglGetString(GL_EXTENSIONS);
7063 if (!gl_platformextensions)
7064 gl_platformextensions = "";
7066 Con_Printf("GL_VENDOR: %s\n", gl_vendor);
7067 Con_Printf("GL_RENDERER: %s\n", gl_renderer);
7068 Con_Printf("GL_VERSION: %s\n", gl_version);
7069 Con_DPrintf("GL_EXTENSIONS: %s\n", gl_extensions);
7070 Con_DPrintf("%s_EXTENSIONS: %s\n", gl_platform, gl_platformextensions);
7072 VID_CheckExtensions();
7074 // LordHavoc: report supported extensions
7075 Con_DPrintf("\nQuakeC extensions for server and client: %s\nQuakeC extensions for menu: %s\n", vm_sv_extensions, vm_m_extensions );
7077 // clear to black (loading plaque will be seen over this)
7078 GL_Clear(GL_COLOR_BUFFER_BIT, NULL, 1.0f, 128);
7081 int R_CullBox(const vec3_t mins, const vec3_t maxs)
7085 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7087 // skip nearclip plane, it often culls portals when you are very close, and is almost never useful
7090 p = r_refdef.view.frustum + i;
7095 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7099 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7103 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7107 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7111 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7115 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7119 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7123 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7131 int R_CullBoxCustomPlanes(const vec3_t mins, const vec3_t maxs, int numplanes, const mplane_t *planes)
7135 for (i = 0;i < numplanes;i++)
7142 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7146 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*maxs[2] < p->dist)
7150 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7154 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*maxs[2] < p->dist)
7158 if (p->normal[0]*maxs[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7162 if (p->normal[0]*mins[0] + p->normal[1]*maxs[1] + p->normal[2]*mins[2] < p->dist)
7166 if (p->normal[0]*maxs[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7170 if (p->normal[0]*mins[0] + p->normal[1]*mins[1] + p->normal[2]*mins[2] < p->dist)
7178 //==================================================================================
7180 // LordHavoc: this stores temporary data used within the same frame
7182 typedef struct r_framedata_mem_s
7184 struct r_framedata_mem_s *purge; // older mem block to free on next frame
7185 size_t size; // how much usable space
7186 size_t current; // how much space in use
7187 size_t mark; // last "mark" location, temporary memory can be freed by returning to this
7188 size_t wantedsize; // how much space was allocated
7189 unsigned char *data; // start of real data (16byte aligned)
7193 static r_framedata_mem_t *r_framedata_mem;
7195 void R_FrameData_Reset(void)
7197 while (r_framedata_mem)
7199 r_framedata_mem_t *next = r_framedata_mem->purge;
7200 Mem_Free(r_framedata_mem);
7201 r_framedata_mem = next;
7205 void R_FrameData_Resize(void)
7208 wantedsize = (size_t)(r_framedatasize.value * 1024*1024);
7209 wantedsize = bound(65536, wantedsize, 1000*1024*1024);
7210 if (!r_framedata_mem || r_framedata_mem->wantedsize != wantedsize)
7212 r_framedata_mem_t *newmem = (r_framedata_mem_t *)Mem_Alloc(r_main_mempool, wantedsize);
7213 newmem->wantedsize = wantedsize;
7214 newmem->data = (unsigned char *)(((size_t)(newmem+1) + 15) & ~15);
7215 newmem->size = (unsigned char *)newmem + wantedsize - newmem->data;
7216 newmem->current = 0;
7218 newmem->purge = r_framedata_mem;
7219 r_framedata_mem = newmem;
7223 void R_FrameData_NewFrame(void)
7225 R_FrameData_Resize();
7226 if (!r_framedata_mem)
7228 // if we ran out of space on the last frame, free the old memory now
7229 while (r_framedata_mem->purge)
7231 // repeatedly remove the second item in the list, leaving only head
7232 r_framedata_mem_t *next = r_framedata_mem->purge->purge;
7233 Mem_Free(r_framedata_mem->purge);
7234 r_framedata_mem->purge = next;
7236 // reset the current mem pointer
7237 r_framedata_mem->current = 0;
7238 r_framedata_mem->mark = 0;
7241 void *R_FrameData_Alloc(size_t size)
7245 // align to 16 byte boundary - the data pointer is already aligned, so we
7246 // only need to ensure the size of every allocation is also aligned
7247 size = (size + 15) & ~15;
7249 while (!r_framedata_mem || r_framedata_mem->current + size > r_framedata_mem->size)
7251 // emergency - we ran out of space, allocate more memory
7252 Cvar_SetValueQuick(&r_framedatasize, bound(0.25f, r_framedatasize.value * 2.0f, 128.0f));
7253 R_FrameData_Resize();
7256 data = r_framedata_mem->data + r_framedata_mem->current;
7257 r_framedata_mem->current += size;
7259 // count the usage for stats
7260 r_refdef.stats.framedatacurrent = max(r_refdef.stats.framedatacurrent, (int)r_framedata_mem->current);
7261 r_refdef.stats.framedatasize = max(r_refdef.stats.framedatasize, (int)r_framedata_mem->size);
7263 return (void *)data;
7266 void *R_FrameData_Store(size_t size, void *data)
7268 void *d = R_FrameData_Alloc(size);
7270 memcpy(d, data, size);
7274 void R_FrameData_SetMark(void)
7276 if (!r_framedata_mem)
7278 r_framedata_mem->mark = r_framedata_mem->current;
7281 void R_FrameData_ReturnToMark(void)
7283 if (!r_framedata_mem)
7285 r_framedata_mem->current = r_framedata_mem->mark;
7288 //==================================================================================
7290 // LordHavoc: animcache originally written by Echon, rewritten since then
7293 * Animation cache prevents re-generating mesh data for an animated model
7294 * multiple times in one frame for lighting, shadowing, reflections, etc.
7297 void R_AnimCache_Free(void)
7301 void R_AnimCache_ClearCache(void)
7304 entity_render_t *ent;
7306 for (i = 0;i < r_refdef.scene.numentities;i++)
7308 ent = r_refdef.scene.entities[i];
7309 ent->animcache_vertex3f = NULL;
7310 ent->animcache_normal3f = NULL;
7311 ent->animcache_svector3f = NULL;
7312 ent->animcache_tvector3f = NULL;
7313 ent->animcache_vertexmesh = NULL;
7314 ent->animcache_vertex3fbuffer = NULL;
7315 ent->animcache_vertexmeshbuffer = NULL;
7319 void R_AnimCache_UpdateEntityMeshBuffers(entity_render_t *ent, int numvertices)
7323 // check if we need the meshbuffers
7324 if (!vid.useinterleavedarrays)
7327 if (!ent->animcache_vertexmesh && ent->animcache_normal3f)
7328 ent->animcache_vertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(sizeof(r_vertexmesh_t)*numvertices);
7329 // TODO: upload vertex3f buffer?
7330 if (ent->animcache_vertexmesh)
7332 memcpy(ent->animcache_vertexmesh, ent->model->surfmesh.vertexmesh, sizeof(r_vertexmesh_t)*numvertices);
7333 for (i = 0;i < numvertices;i++)
7334 memcpy(ent->animcache_vertexmesh[i].vertex3f, ent->animcache_vertex3f + 3*i, sizeof(float[3]));
7335 if (ent->animcache_svector3f)
7336 for (i = 0;i < numvertices;i++)
7337 memcpy(ent->animcache_vertexmesh[i].svector3f, ent->animcache_svector3f + 3*i, sizeof(float[3]));
7338 if (ent->animcache_tvector3f)
7339 for (i = 0;i < numvertices;i++)
7340 memcpy(ent->animcache_vertexmesh[i].tvector3f, ent->animcache_tvector3f + 3*i, sizeof(float[3]));
7341 if (ent->animcache_normal3f)
7342 for (i = 0;i < numvertices;i++)
7343 memcpy(ent->animcache_vertexmesh[i].normal3f, ent->animcache_normal3f + 3*i, sizeof(float[3]));
7344 // TODO: upload vertexmeshbuffer?
7348 qboolean R_AnimCache_GetEntity(entity_render_t *ent, qboolean wantnormals, qboolean wanttangents)
7350 dp_model_t *model = ent->model;
7352 // see if it's already cached this frame
7353 if (ent->animcache_vertex3f)
7355 // add normals/tangents if needed (this only happens with multiple views, reflections, cameras, etc)
7356 if (wantnormals || wanttangents)
7358 if (ent->animcache_normal3f)
7359 wantnormals = false;
7360 if (ent->animcache_svector3f)
7361 wanttangents = false;
7362 if (wantnormals || wanttangents)
7364 numvertices = model->surfmesh.num_vertices;
7366 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7369 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7370 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7372 model->AnimateVertices(model, ent->frameblend, ent->skeleton, NULL, wantnormals ? ent->animcache_normal3f : NULL, wanttangents ? ent->animcache_svector3f : NULL, wanttangents ? ent->animcache_tvector3f : NULL);
7373 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7379 // see if this ent is worth caching
7380 if (!model || !model->Draw || !model->surfmesh.isanimated || !model->AnimateVertices || (ent->frameblend[0].lerp == 1 && ent->frameblend[0].subframe == 0 && !ent->skeleton))
7382 // get some memory for this entity and generate mesh data
7383 numvertices = model->surfmesh.num_vertices;
7384 ent->animcache_vertex3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7386 ent->animcache_normal3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7389 ent->animcache_svector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7390 ent->animcache_tvector3f = (float *)R_FrameData_Alloc(sizeof(float[3])*numvertices);
7392 model->AnimateVertices(model, ent->frameblend, ent->skeleton, ent->animcache_vertex3f, ent->animcache_normal3f, ent->animcache_svector3f, ent->animcache_tvector3f);
7393 R_AnimCache_UpdateEntityMeshBuffers(ent, model->surfmesh.num_vertices);
7398 void R_AnimCache_CacheVisibleEntities(void)
7401 qboolean wantnormals = true;
7402 qboolean wanttangents = !r_showsurfaces.integer;
7404 switch(vid.renderpath)
7406 case RENDERPATH_GL20:
7407 case RENDERPATH_D3D9:
7408 case RENDERPATH_D3D10:
7409 case RENDERPATH_D3D11:
7410 case RENDERPATH_GLES2:
7412 case RENDERPATH_GL13:
7413 case RENDERPATH_GL11:
7414 wanttangents = false;
7416 case RENDERPATH_SOFT:
7420 if (r_shownormals.integer)
7421 wanttangents = wantnormals = true;
7423 // TODO: thread this
7424 // NOTE: R_PrepareRTLights() also caches entities
7426 for (i = 0;i < r_refdef.scene.numentities;i++)
7427 if (r_refdef.viewcache.entityvisible[i])
7428 R_AnimCache_GetEntity(r_refdef.scene.entities[i], wantnormals, wanttangents);
7431 //==================================================================================
7433 static void R_View_UpdateEntityLighting (void)
7436 entity_render_t *ent;
7437 vec3_t tempdiffusenormal, avg;
7438 vec_t f, fa, fd, fdd;
7439 qboolean skipunseen = r_shadows.integer != 1; //|| R_Shadow_ShadowMappingEnabled();
7441 for (i = 0;i < r_refdef.scene.numentities;i++)
7443 ent = r_refdef.scene.entities[i];
7445 // skip unseen models
7446 if (!r_refdef.viewcache.entityvisible[i] && skipunseen)
7450 if (ent->model && ent->model->brush.num_leafs)
7452 // TODO: use modellight for r_ambient settings on world?
7453 VectorSet(ent->modellight_ambient, 0, 0, 0);
7454 VectorSet(ent->modellight_diffuse, 0, 0, 0);
7455 VectorSet(ent->modellight_lightdir, 0, 0, 1);
7459 // fetch the lighting from the worldmodel data
7460 VectorClear(ent->modellight_ambient);
7461 VectorClear(ent->modellight_diffuse);
7462 VectorClear(tempdiffusenormal);
7463 if ((ent->flags & RENDER_LIGHT) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint)
7466 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
7468 // complete lightning for lit sprites
7469 // todo: make a EF_ field so small ents could be lit purely by modellight and skipping real rtlight pass (like EF_NORTLIGHT)?
7470 if (ent->model->type == mod_sprite && !(ent->model->data_textures[0].basematerialflags & MATERIALFLAG_FULLBRIGHT))
7472 if (ent->model->sprite.sprnum_type == SPR_OVERHEAD) // apply offset for overhead sprites
7473 org[2] = org[2] + r_overheadsprites_pushback.value;
7474 R_CompleteLightPoint(ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal, org, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
7477 R_CompleteLightPoint(ent->modellight_ambient, ent->modellight_diffuse, tempdiffusenormal, org, LP_LIGHTMAP);
7479 if(ent->flags & RENDER_EQUALIZE)
7481 // first fix up ambient lighting...
7482 if(r_equalize_entities_minambient.value > 0)
7484 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7487 fa = (0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2]);
7488 if(fa < r_equalize_entities_minambient.value * fd)
7491 // fa'/fd' = minambient
7492 // fa'+0.25*fd' = fa+0.25*fd
7494 // fa' = fd' * minambient
7495 // fd'*(0.25+minambient) = fa+0.25*fd
7497 // fd' = (fa+0.25*fd) * 1 / (0.25+minambient)
7498 // fa' = (fa+0.25*fd) * minambient / (0.25+minambient)
7500 fdd = (fa + 0.25f * fd) / (0.25f + r_equalize_entities_minambient.value);
7501 f = fdd / fd; // f>0 because all this is additive; f<1 because fdd<fd because this follows from fa < r_equalize_entities_minambient.value * fd
7502 VectorMA(ent->modellight_ambient, (1-f)*0.25f, ent->modellight_diffuse, ent->modellight_ambient);
7503 VectorScale(ent->modellight_diffuse, f, ent->modellight_diffuse);
7508 if(r_equalize_entities_to.value > 0 && r_equalize_entities_by.value != 0)
7510 fa = 0.299f * ent->modellight_ambient[0] + 0.587f * ent->modellight_ambient[1] + 0.114f * ent->modellight_ambient[2];
7511 fd = 0.299f * ent->modellight_diffuse[0] + 0.587f * ent->modellight_diffuse[1] + 0.114f * ent->modellight_diffuse[2];
7515 // adjust brightness and saturation to target
7516 avg[0] = avg[1] = avg[2] = fa / f;
7517 VectorLerp(ent->modellight_ambient, r_equalize_entities_by.value, avg, ent->modellight_ambient);
7518 avg[0] = avg[1] = avg[2] = fd / f;
7519 VectorLerp(ent->modellight_diffuse, r_equalize_entities_by.value, avg, ent->modellight_diffuse);
7525 VectorSet(ent->modellight_ambient, 1, 1, 1);
7527 // move the light direction into modelspace coordinates for lighting code
7528 Matrix4x4_Transform3x3(&ent->inversematrix, tempdiffusenormal, ent->modellight_lightdir);
7529 if(VectorLength2(ent->modellight_lightdir) == 0)
7530 VectorSet(ent->modellight_lightdir, 0, 0, 1); // have to set SOME valid vector here
7531 VectorNormalize(ent->modellight_lightdir);
7535 #define MAX_LINEOFSIGHTTRACES 64
7537 static qboolean R_CanSeeBox(int numsamples, vec_t enlarge, vec3_t eye, vec3_t entboxmins, vec3_t entboxmaxs)
7540 vec3_t boxmins, boxmaxs;
7543 dp_model_t *model = r_refdef.scene.worldmodel;
7545 if (!model || !model->brush.TraceLineOfSight)
7548 // expand the box a little
7549 boxmins[0] = (enlarge+1) * entboxmins[0] - enlarge * entboxmaxs[0];
7550 boxmaxs[0] = (enlarge+1) * entboxmaxs[0] - enlarge * entboxmins[0];
7551 boxmins[1] = (enlarge+1) * entboxmins[1] - enlarge * entboxmaxs[1];
7552 boxmaxs[1] = (enlarge+1) * entboxmaxs[1] - enlarge * entboxmins[1];
7553 boxmins[2] = (enlarge+1) * entboxmins[2] - enlarge * entboxmaxs[2];
7554 boxmaxs[2] = (enlarge+1) * entboxmaxs[2] - enlarge * entboxmins[2];
7556 // return true if eye is inside enlarged box
7557 if (BoxesOverlap(boxmins, boxmaxs, eye, eye))
7561 VectorCopy(eye, start);
7562 VectorMAM(0.5f, boxmins, 0.5f, boxmaxs, end);
7563 if (model->brush.TraceLineOfSight(model, start, end))
7566 // try various random positions
7567 for (i = 0;i < numsamples;i++)
7569 VectorSet(end, lhrandom(boxmins[0], boxmaxs[0]), lhrandom(boxmins[1], boxmaxs[1]), lhrandom(boxmins[2], boxmaxs[2]));
7570 if (model->brush.TraceLineOfSight(model, start, end))
7578 static void R_View_UpdateEntityVisible (void)
7583 entity_render_t *ent;
7585 renderimask = r_refdef.envmap ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7586 : r_waterstate.renderingrefraction ? (RENDER_EXTERIORMODEL | RENDER_VIEWMODEL)
7587 : (chase_active.integer || r_waterstate.renderingscene) ? RENDER_VIEWMODEL
7588 : RENDER_EXTERIORMODEL;
7589 if (!r_drawviewmodel.integer)
7590 renderimask |= RENDER_VIEWMODEL;
7591 if (!r_drawexteriormodel.integer)
7592 renderimask |= RENDER_EXTERIORMODEL;
7593 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs)
7595 // worldmodel can check visibility
7596 memset(r_refdef.viewcache.entityvisible, 0, r_refdef.scene.numentities);
7597 for (i = 0;i < r_refdef.scene.numentities;i++)
7599 ent = r_refdef.scene.entities[i];
7600 if (!(ent->flags & renderimask))
7601 if (!R_CullBox(ent->mins, ent->maxs) || (ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)))
7602 if ((ent->flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL)) || r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, ent->mins, ent->maxs))
7603 r_refdef.viewcache.entityvisible[i] = true;
7605 if(r_cullentities_trace.integer && r_refdef.scene.worldmodel->brush.TraceLineOfSight && !r_refdef.view.useclipplane)
7606 // sorry, this check doesn't work for portal/reflection/refraction renders as the view origin is not useful for culling
7608 for (i = 0;i < r_refdef.scene.numentities;i++)
7610 ent = r_refdef.scene.entities[i];
7611 if(r_refdef.viewcache.entityvisible[i] && !(ent->flags & (RENDER_VIEWMODEL | RENDER_NOCULL | RENDER_NODEPTHTEST)) && !(ent->model && (ent->model->name[0] == '*')))
7613 samples = ent->entitynumber ? r_cullentities_trace_samples.integer : r_cullentities_trace_tempentitysamples.integer;
7615 continue; // temp entities do pvs only
7616 if(R_CanSeeBox(samples, r_cullentities_trace_enlarge.value, r_refdef.view.origin, ent->mins, ent->maxs))
7617 ent->last_trace_visibility = realtime;
7618 if(ent->last_trace_visibility < realtime - r_cullentities_trace_delay.value)
7619 r_refdef.viewcache.entityvisible[i] = 0;
7626 // no worldmodel or it can't check visibility
7627 for (i = 0;i < r_refdef.scene.numentities;i++)
7629 ent = r_refdef.scene.entities[i];
7630 r_refdef.viewcache.entityvisible[i] = !(ent->flags & renderimask) && ((ent->model && ent->model->type == mod_sprite && (ent->model->sprite.sprnum_type == SPR_LABEL || ent->model->sprite.sprnum_type == SPR_LABEL_SCALE)) || !R_CullBox(ent->mins, ent->maxs));
7635 /// only used if skyrendermasked, and normally returns false
7636 int R_DrawBrushModelsSky (void)
7639 entity_render_t *ent;
7642 for (i = 0;i < r_refdef.scene.numentities;i++)
7644 if (!r_refdef.viewcache.entityvisible[i])
7646 ent = r_refdef.scene.entities[i];
7647 if (!ent->model || !ent->model->DrawSky)
7649 ent->model->DrawSky(ent);
7655 static void R_DrawNoModel(entity_render_t *ent);
7656 static void R_DrawModels(void)
7659 entity_render_t *ent;
7661 for (i = 0;i < r_refdef.scene.numentities;i++)
7663 if (!r_refdef.viewcache.entityvisible[i])
7665 ent = r_refdef.scene.entities[i];
7666 r_refdef.stats.entities++;
7667 if (ent->model && ent->model->Draw != NULL)
7668 ent->model->Draw(ent);
7674 static void R_DrawModelsDepth(void)
7677 entity_render_t *ent;
7679 for (i = 0;i < r_refdef.scene.numentities;i++)
7681 if (!r_refdef.viewcache.entityvisible[i])
7683 ent = r_refdef.scene.entities[i];
7684 if (ent->model && ent->model->DrawDepth != NULL)
7685 ent->model->DrawDepth(ent);
7689 static void R_DrawModelsDebug(void)
7692 entity_render_t *ent;
7694 for (i = 0;i < r_refdef.scene.numentities;i++)
7696 if (!r_refdef.viewcache.entityvisible[i])
7698 ent = r_refdef.scene.entities[i];
7699 if (ent->model && ent->model->DrawDebug != NULL)
7700 ent->model->DrawDebug(ent);
7704 static void R_DrawModelsAddWaterPlanes(void)
7707 entity_render_t *ent;
7709 for (i = 0;i < r_refdef.scene.numentities;i++)
7711 if (!r_refdef.viewcache.entityvisible[i])
7713 ent = r_refdef.scene.entities[i];
7714 if (ent->model && ent->model->DrawAddWaterPlanes != NULL)
7715 ent->model->DrawAddWaterPlanes(ent);
7719 void R_HDR_UpdateIrisAdaptation(const vec3_t point)
7721 if (r_hdr_irisadaptation.integer)
7725 vec3_t diffusenormal;
7730 R_CompleteLightPoint(ambient, diffuse, diffusenormal, point, LP_LIGHTMAP | LP_RTWORLD | LP_DYNLIGHT);
7731 brightness = (ambient[0] + ambient[1] + ambient[2] + diffuse[0] + diffuse[1] + diffuse[2]) * (1.0f / 3.0f);
7732 brightness = max(0.0000001f, brightness);
7733 goal = r_hdr_irisadaptation_multiplier.value / brightness;
7734 goal = bound(r_hdr_irisadaptation_minvalue.value, goal, r_hdr_irisadaptation_maxvalue.value);
7735 adjust = r_hdr_irisadaptation_fade.value * cl.realframetime;
7736 current = r_hdr_irisadaptation_value.value;
7738 current = min(current + adjust, goal);
7739 else if (current > goal)
7740 current = max(current - adjust, goal);
7741 if (fabs(r_hdr_irisadaptation_value.value - current) > 0.0001f)
7742 Cvar_SetValueQuick(&r_hdr_irisadaptation_value, current);
7744 else if (r_hdr_irisadaptation_value.value != 1.0f)
7745 Cvar_SetValueQuick(&r_hdr_irisadaptation_value, 1.0f);
7748 static void R_View_SetFrustum(const int *scissor)
7751 double fpx = +1, fnx = -1, fpy = +1, fny = -1;
7752 vec3_t forward, left, up, origin, v;
7756 // flipped x coordinates (because x points left here)
7757 fpx = 1.0 - 2.0 * (scissor[0] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7758 fnx = 1.0 - 2.0 * (scissor[0] + scissor[2] - r_refdef.view.viewport.x) / (double) (r_refdef.view.viewport.width);
7760 // D3D Y coordinate is top to bottom, OpenGL is bottom to top, fix the D3D one
7761 switch(vid.renderpath)
7763 case RENDERPATH_D3D9:
7764 case RENDERPATH_D3D10:
7765 case RENDERPATH_D3D11:
7766 case RENDERPATH_SOFT:
7767 // non-flipped y coordinates
7768 fny = -1.0 + 2.0 * (vid.height - scissor[1] - scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7769 fpy = -1.0 + 2.0 * (vid.height - scissor[1] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7771 case RENDERPATH_GL11:
7772 case RENDERPATH_GL13:
7773 case RENDERPATH_GL20:
7774 case RENDERPATH_GLES2:
7775 // non-flipped y coordinates
7776 fny = -1.0 + 2.0 * (scissor[1] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7777 fpy = -1.0 + 2.0 * (scissor[1] + scissor[3] - r_refdef.view.viewport.y) / (double) (r_refdef.view.viewport.height);
7782 // we can't trust r_refdef.view.forward and friends in reflected scenes
7783 Matrix4x4_ToVectors(&r_refdef.view.matrix, forward, left, up, origin);
7786 r_refdef.view.frustum[0].normal[0] = 0 - 1.0 / r_refdef.view.frustum_x;
7787 r_refdef.view.frustum[0].normal[1] = 0 - 0;
7788 r_refdef.view.frustum[0].normal[2] = -1 - 0;
7789 r_refdef.view.frustum[1].normal[0] = 0 + 1.0 / r_refdef.view.frustum_x;
7790 r_refdef.view.frustum[1].normal[1] = 0 + 0;
7791 r_refdef.view.frustum[1].normal[2] = -1 + 0;
7792 r_refdef.view.frustum[2].normal[0] = 0 - 0;
7793 r_refdef.view.frustum[2].normal[1] = 0 - 1.0 / r_refdef.view.frustum_y;
7794 r_refdef.view.frustum[2].normal[2] = -1 - 0;
7795 r_refdef.view.frustum[3].normal[0] = 0 + 0;
7796 r_refdef.view.frustum[3].normal[1] = 0 + 1.0 / r_refdef.view.frustum_y;
7797 r_refdef.view.frustum[3].normal[2] = -1 + 0;
7801 zNear = r_refdef.nearclip;
7802 nudge = 1.0 - 1.0 / (1<<23);
7803 r_refdef.view.frustum[4].normal[0] = 0 - 0;
7804 r_refdef.view.frustum[4].normal[1] = 0 - 0;
7805 r_refdef.view.frustum[4].normal[2] = -1 - -nudge;
7806 r_refdef.view.frustum[4].dist = 0 - -2 * zNear * nudge;
7807 r_refdef.view.frustum[5].normal[0] = 0 + 0;
7808 r_refdef.view.frustum[5].normal[1] = 0 + 0;
7809 r_refdef.view.frustum[5].normal[2] = -1 + -nudge;
7810 r_refdef.view.frustum[5].dist = 0 + -2 * zNear * nudge;
7816 r_refdef.view.frustum[0].normal[0] = m[3] - m[0];
7817 r_refdef.view.frustum[0].normal[1] = m[7] - m[4];
7818 r_refdef.view.frustum[0].normal[2] = m[11] - m[8];
7819 r_refdef.view.frustum[0].dist = m[15] - m[12];
7821 r_refdef.view.frustum[1].normal[0] = m[3] + m[0];
7822 r_refdef.view.frustum[1].normal[1] = m[7] + m[4];
7823 r_refdef.view.frustum[1].normal[2] = m[11] + m[8];
7824 r_refdef.view.frustum[1].dist = m[15] + m[12];
7826 r_refdef.view.frustum[2].normal[0] = m[3] - m[1];
7827 r_refdef.view.frustum[2].normal[1] = m[7] - m[5];
7828 r_refdef.view.frustum[2].normal[2] = m[11] - m[9];
7829 r_refdef.view.frustum[2].dist = m[15] - m[13];
7831 r_refdef.view.frustum[3].normal[0] = m[3] + m[1];
7832 r_refdef.view.frustum[3].normal[1] = m[7] + m[5];
7833 r_refdef.view.frustum[3].normal[2] = m[11] + m[9];
7834 r_refdef.view.frustum[3].dist = m[15] + m[13];
7836 r_refdef.view.frustum[4].normal[0] = m[3] - m[2];
7837 r_refdef.view.frustum[4].normal[1] = m[7] - m[6];
7838 r_refdef.view.frustum[4].normal[2] = m[11] - m[10];
7839 r_refdef.view.frustum[4].dist = m[15] - m[14];
7841 r_refdef.view.frustum[5].normal[0] = m[3] + m[2];
7842 r_refdef.view.frustum[5].normal[1] = m[7] + m[6];
7843 r_refdef.view.frustum[5].normal[2] = m[11] + m[10];
7844 r_refdef.view.frustum[5].dist = m[15] + m[14];
7847 if (r_refdef.view.useperspective)
7849 // calculate frustum corners, which are used to calculate deformed frustum planes for shadow caster culling
7850 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[0]);
7851 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fny * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[1]);
7852 VectorMAMAM(1024, forward, fnx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[2]);
7853 VectorMAMAM(1024, forward, fpx * 1024.0 * r_refdef.view.frustum_x, left, fpy * 1024.0 * r_refdef.view.frustum_y, up, r_refdef.view.frustumcorner[3]);
7855 // then the normals from the corners relative to origin
7856 CrossProduct(r_refdef.view.frustumcorner[2], r_refdef.view.frustumcorner[0], r_refdef.view.frustum[0].normal);
7857 CrossProduct(r_refdef.view.frustumcorner[1], r_refdef.view.frustumcorner[3], r_refdef.view.frustum[1].normal);
7858 CrossProduct(r_refdef.view.frustumcorner[0], r_refdef.view.frustumcorner[1], r_refdef.view.frustum[2].normal);
7859 CrossProduct(r_refdef.view.frustumcorner[3], r_refdef.view.frustumcorner[2], r_refdef.view.frustum[3].normal);
7861 // in a NORMAL view, forward cross left == up
7862 // in a REFLECTED view, forward cross left == down
7863 // so our cross products above need to be adjusted for a left handed coordinate system
7864 CrossProduct(forward, left, v);
7865 if(DotProduct(v, up) < 0)
7867 VectorNegate(r_refdef.view.frustum[0].normal, r_refdef.view.frustum[0].normal);
7868 VectorNegate(r_refdef.view.frustum[1].normal, r_refdef.view.frustum[1].normal);
7869 VectorNegate(r_refdef.view.frustum[2].normal, r_refdef.view.frustum[2].normal);
7870 VectorNegate(r_refdef.view.frustum[3].normal, r_refdef.view.frustum[3].normal);
7873 // Leaving those out was a mistake, those were in the old code, and they
7874 // fix a reproducable bug in this one: frustum culling got fucked up when viewmatrix was an identity matrix
7875 // I couldn't reproduce it after adding those normalizations. --blub
7876 VectorNormalize(r_refdef.view.frustum[0].normal);
7877 VectorNormalize(r_refdef.view.frustum[1].normal);
7878 VectorNormalize(r_refdef.view.frustum[2].normal);
7879 VectorNormalize(r_refdef.view.frustum[3].normal);
7881 // make the corners absolute
7882 VectorAdd(r_refdef.view.frustumcorner[0], r_refdef.view.origin, r_refdef.view.frustumcorner[0]);
7883 VectorAdd(r_refdef.view.frustumcorner[1], r_refdef.view.origin, r_refdef.view.frustumcorner[1]);
7884 VectorAdd(r_refdef.view.frustumcorner[2], r_refdef.view.origin, r_refdef.view.frustumcorner[2]);
7885 VectorAdd(r_refdef.view.frustumcorner[3], r_refdef.view.origin, r_refdef.view.frustumcorner[3]);
7888 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7890 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal);
7891 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal);
7892 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal);
7893 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal);
7894 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7898 VectorScale(left, -r_refdef.view.ortho_x, r_refdef.view.frustum[0].normal);
7899 VectorScale(left, r_refdef.view.ortho_x, r_refdef.view.frustum[1].normal);
7900 VectorScale(up, -r_refdef.view.ortho_y, r_refdef.view.frustum[2].normal);
7901 VectorScale(up, r_refdef.view.ortho_y, r_refdef.view.frustum[3].normal);
7902 VectorCopy(forward, r_refdef.view.frustum[4].normal);
7903 r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[0].normal) + r_refdef.view.ortho_x;
7904 r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[1].normal) + r_refdef.view.ortho_x;
7905 r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[2].normal) + r_refdef.view.ortho_y;
7906 r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[3].normal) + r_refdef.view.ortho_y;
7907 r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, r_refdef.view.frustum[4].normal) + r_refdef.nearclip;
7909 r_refdef.view.numfrustumplanes = 5;
7911 if (r_refdef.view.useclipplane)
7913 r_refdef.view.numfrustumplanes = 6;
7914 r_refdef.view.frustum[5] = r_refdef.view.clipplane;
7917 for (i = 0;i < r_refdef.view.numfrustumplanes;i++)
7918 PlaneClassify(r_refdef.view.frustum + i);
7920 // LordHavoc: note to all quake engine coders, Quake had a special case
7921 // for 90 degrees which assumed a square view (wrong), so I removed it,
7922 // Quake2 has it disabled as well.
7924 // rotate R_VIEWFORWARD right by FOV_X/2 degrees
7925 //RotatePointAroundVector( r_refdef.view.frustum[0].normal, up, forward, -(90 - r_refdef.fov_x / 2));
7926 //r_refdef.view.frustum[0].dist = DotProduct (r_refdef.view.origin, frustum[0].normal);
7927 //PlaneClassify(&frustum[0]);
7929 // rotate R_VIEWFORWARD left by FOV_X/2 degrees
7930 //RotatePointAroundVector( r_refdef.view.frustum[1].normal, up, forward, (90 - r_refdef.fov_x / 2));
7931 //r_refdef.view.frustum[1].dist = DotProduct (r_refdef.view.origin, frustum[1].normal);
7932 //PlaneClassify(&frustum[1]);
7934 // rotate R_VIEWFORWARD up by FOV_X/2 degrees
7935 //RotatePointAroundVector( r_refdef.view.frustum[2].normal, left, forward, -(90 - r_refdef.fov_y / 2));
7936 //r_refdef.view.frustum[2].dist = DotProduct (r_refdef.view.origin, frustum[2].normal);
7937 //PlaneClassify(&frustum[2]);
7939 // rotate R_VIEWFORWARD down by FOV_X/2 degrees
7940 //RotatePointAroundVector( r_refdef.view.frustum[3].normal, left, forward, (90 - r_refdef.fov_y / 2));
7941 //r_refdef.view.frustum[3].dist = DotProduct (r_refdef.view.origin, frustum[3].normal);
7942 //PlaneClassify(&frustum[3]);
7945 //VectorCopy(forward, r_refdef.view.frustum[4].normal);
7946 //r_refdef.view.frustum[4].dist = DotProduct (r_refdef.view.origin, frustum[4].normal) + r_nearclip.value;
7947 //PlaneClassify(&frustum[4]);
7950 void R_View_UpdateWithScissor(const int *myscissor)
7952 R_Main_ResizeViewCache();
7953 R_View_SetFrustum(myscissor);
7954 R_View_WorldVisibility(r_refdef.view.useclipplane);
7955 R_View_UpdateEntityVisible();
7956 R_View_UpdateEntityLighting();
7959 void R_View_Update(void)
7961 R_Main_ResizeViewCache();
7962 R_View_SetFrustum(NULL);
7963 R_View_WorldVisibility(r_refdef.view.useclipplane);
7964 R_View_UpdateEntityVisible();
7965 R_View_UpdateEntityLighting();
7968 void R_SetupView(qboolean allowwaterclippingplane)
7970 const float *customclipplane = NULL;
7972 if (r_refdef.view.useclipplane && allowwaterclippingplane)
7974 // LordHavoc: couldn't figure out how to make this approach the
7975 vec_t dist = r_refdef.view.clipplane.dist - r_water_clippingplanebias.value;
7976 vec_t viewdist = DotProduct(r_refdef.view.origin, r_refdef.view.clipplane.normal);
7977 if (viewdist < r_refdef.view.clipplane.dist + r_water_clippingplanebias.value)
7978 dist = r_refdef.view.clipplane.dist;
7979 plane[0] = r_refdef.view.clipplane.normal[0];
7980 plane[1] = r_refdef.view.clipplane.normal[1];
7981 plane[2] = r_refdef.view.clipplane.normal[2];
7983 customclipplane = plane;
7986 if (!r_refdef.view.useperspective)
7987 R_Viewport_InitOrtho(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, -r_refdef.view.ortho_x, -r_refdef.view.ortho_y, r_refdef.view.ortho_x, r_refdef.view.ortho_y, -r_refdef.farclip, r_refdef.farclip, customclipplane);
7988 else if (vid.stencil && r_useinfinitefarclip.integer)
7989 R_Viewport_InitPerspectiveInfinite(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, customclipplane);
7991 R_Viewport_InitPerspective(&r_refdef.view.viewport, &r_refdef.view.matrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, r_refdef.view.frustum_x, r_refdef.view.frustum_y, r_refdef.nearclip, r_refdef.farclip, customclipplane);
7992 R_SetViewport(&r_refdef.view.viewport);
7995 void R_EntityMatrix(const matrix4x4_t *matrix)
7997 if (gl_modelmatrixchanged || memcmp(matrix, &gl_modelmatrix, sizeof(matrix4x4_t)))
7999 gl_modelmatrixchanged = false;
8000 gl_modelmatrix = *matrix;
8001 Matrix4x4_Concat(&gl_modelviewmatrix, &gl_viewmatrix, &gl_modelmatrix);
8002 Matrix4x4_Concat(&gl_modelviewprojectionmatrix, &gl_projectionmatrix, &gl_modelviewmatrix);
8003 Matrix4x4_ToArrayFloatGL(&gl_modelviewmatrix, gl_modelview16f);
8004 Matrix4x4_ToArrayFloatGL(&gl_modelviewprojectionmatrix, gl_modelviewprojection16f);
8006 switch(vid.renderpath)
8008 case RENDERPATH_D3D9:
8010 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewProjectionMatrix, gl_modelviewprojection16f);
8011 hlslVSSetParameter16f(D3DVSREGISTER_ModelViewMatrix, gl_modelview16f);
8014 case RENDERPATH_D3D10:
8015 Con_DPrintf("FIXME D3D10 shader %s:%i\n", __FILE__, __LINE__);
8017 case RENDERPATH_D3D11:
8018 Con_DPrintf("FIXME D3D11 shader %s:%i\n", __FILE__, __LINE__);
8020 case RENDERPATH_GL13:
8021 case RENDERPATH_GL11:
8022 qglLoadMatrixf(gl_modelview16f);CHECKGLERROR
8024 case RENDERPATH_SOFT:
8025 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewProjectionMatrixM1, 1, false, gl_modelviewprojection16f);
8026 DPSOFTRAST_UniformMatrix4fv(DPSOFTRAST_UNIFORM_ModelViewMatrixM1, 1, false, gl_modelview16f);
8028 case RENDERPATH_GL20:
8029 case RENDERPATH_GLES2:
8030 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewProjectionMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewProjectionMatrix, 1, false, gl_modelviewprojection16f);
8031 if (r_glsl_permutation && r_glsl_permutation->loc_ModelViewMatrix >= 0) qglUniformMatrix4fv(r_glsl_permutation->loc_ModelViewMatrix, 1, false, gl_modelview16f);
8037 void R_ResetViewRendering2D(void)
8039 r_viewport_t viewport;
8042 // GL is weird because it's bottom to top, r_refdef.view.y is top to bottom
8043 R_Viewport_InitOrtho(&viewport, &identitymatrix, r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height, 0, 0, 1, 1, -10, 100, NULL);
8044 R_SetViewport(&viewport);
8045 GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height);
8046 GL_Color(1, 1, 1, 1);
8047 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8048 GL_BlendFunc(GL_ONE, GL_ZERO);
8049 GL_ScissorTest(false);
8050 GL_DepthMask(false);
8051 GL_DepthRange(0, 1);
8052 GL_DepthTest(false);
8053 GL_DepthFunc(GL_LEQUAL);
8054 R_EntityMatrix(&identitymatrix);
8055 R_Mesh_ResetTextureState();
8056 GL_PolygonOffset(0, 0);
8057 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8058 switch(vid.renderpath)
8060 case RENDERPATH_GL11:
8061 case RENDERPATH_GL13:
8062 case RENDERPATH_GL20:
8063 case RENDERPATH_GLES2:
8064 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8066 case RENDERPATH_D3D9:
8067 case RENDERPATH_D3D10:
8068 case RENDERPATH_D3D11:
8069 case RENDERPATH_SOFT:
8072 GL_CullFace(GL_NONE);
8075 void R_ResetViewRendering3D(void)
8080 GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8081 GL_Color(1, 1, 1, 1);
8082 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
8083 GL_BlendFunc(GL_ONE, GL_ZERO);
8084 GL_ScissorTest(true);
8086 GL_DepthRange(0, 1);
8088 GL_DepthFunc(GL_LEQUAL);
8089 R_EntityMatrix(&identitymatrix);
8090 R_Mesh_ResetTextureState();
8091 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
8092 R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255);
8093 switch(vid.renderpath)
8095 case RENDERPATH_GL11:
8096 case RENDERPATH_GL13:
8097 case RENDERPATH_GL20:
8098 case RENDERPATH_GLES2:
8099 qglEnable(GL_POLYGON_OFFSET_FILL);CHECKGLERROR
8101 case RENDERPATH_D3D9:
8102 case RENDERPATH_D3D10:
8103 case RENDERPATH_D3D11:
8104 case RENDERPATH_SOFT:
8107 GL_CullFace(r_refdef.view.cullface_back);
8112 R_RenderView_UpdateViewVectors
8115 static void R_RenderView_UpdateViewVectors(void)
8117 // break apart the view matrix into vectors for various purposes
8118 // it is important that this occurs outside the RenderScene function because that can be called from reflection renders, where the vectors come out wrong
8119 // however the r_refdef.view.origin IS updated in RenderScene intentionally - otherwise the sky renders at the wrong origin, etc
8120 Matrix4x4_ToVectors(&r_refdef.view.matrix, r_refdef.view.forward, r_refdef.view.left, r_refdef.view.up, r_refdef.view.origin);
8121 VectorNegate(r_refdef.view.left, r_refdef.view.right);
8122 // make an inverted copy of the view matrix for tracking sprites
8123 Matrix4x4_Invert_Simple(&r_refdef.view.inverse_matrix, &r_refdef.view.matrix);
8126 void R_RenderScene(void);
8127 void R_RenderWaterPlanes(void);
8129 static void R_Water_StartFrame(void)
8132 int waterwidth, waterheight, texturewidth, textureheight, camerawidth, cameraheight;
8133 r_waterstate_waterplane_t *p;
8135 if (vid.width > (int)vid.maxtexturesize_2d || vid.height > (int)vid.maxtexturesize_2d)
8138 switch(vid.renderpath)
8140 case RENDERPATH_GL20:
8141 case RENDERPATH_D3D9:
8142 case RENDERPATH_D3D10:
8143 case RENDERPATH_D3D11:
8144 case RENDERPATH_SOFT:
8145 case RENDERPATH_GLES2:
8147 case RENDERPATH_GL13:
8148 case RENDERPATH_GL11:
8152 // set waterwidth and waterheight to the water resolution that will be
8153 // used (often less than the screen resolution for faster rendering)
8154 waterwidth = (int)bound(1, vid.width * r_water_resolutionmultiplier.value, vid.width);
8155 waterheight = (int)bound(1, vid.height * r_water_resolutionmultiplier.value, vid.height);
8157 // calculate desired texture sizes
8158 // can't use water if the card does not support the texture size
8159 if (!r_water.integer || r_showsurfaces.integer)
8160 texturewidth = textureheight = waterwidth = waterheight = camerawidth = cameraheight = 0;
8161 else if (vid.support.arb_texture_non_power_of_two)
8163 texturewidth = waterwidth;
8164 textureheight = waterheight;
8165 camerawidth = waterwidth;
8166 cameraheight = waterheight;
8170 for (texturewidth = 1;texturewidth < waterwidth ;texturewidth *= 2);
8171 for (textureheight = 1;textureheight < waterheight;textureheight *= 2);
8172 for (camerawidth = 1;camerawidth <= waterwidth; camerawidth *= 2); camerawidth /= 2;
8173 for (cameraheight = 1;cameraheight <= waterheight;cameraheight *= 2); cameraheight /= 2;
8176 // allocate textures as needed
8177 if (r_waterstate.texturewidth != texturewidth || r_waterstate.textureheight != textureheight || r_waterstate.camerawidth != camerawidth || r_waterstate.cameraheight != cameraheight)
8179 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8180 for (i = 0, p = r_waterstate.waterplanes;i < r_waterstate.maxwaterplanes;i++, p++)
8182 if (p->texture_refraction)
8183 R_FreeTexture(p->texture_refraction);
8184 p->texture_refraction = NULL;
8185 if (p->texture_reflection)
8186 R_FreeTexture(p->texture_reflection);
8187 p->texture_reflection = NULL;
8188 if (p->texture_camera)
8189 R_FreeTexture(p->texture_camera);
8190 p->texture_camera = NULL;
8192 memset(&r_waterstate, 0, sizeof(r_waterstate));
8193 r_waterstate.texturewidth = texturewidth;
8194 r_waterstate.textureheight = textureheight;
8195 r_waterstate.camerawidth = camerawidth;
8196 r_waterstate.cameraheight = cameraheight;
8199 if (r_waterstate.texturewidth)
8201 r_waterstate.enabled = true;
8203 // when doing a reduced render (HDR) we want to use a smaller area
8204 r_waterstate.waterwidth = (int)bound(1, r_refdef.view.width * r_water_resolutionmultiplier.value, r_refdef.view.width);
8205 r_waterstate.waterheight = (int)bound(1, r_refdef.view.height * r_water_resolutionmultiplier.value, r_refdef.view.height);
8207 // set up variables that will be used in shader setup
8208 r_waterstate.screenscale[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8209 r_waterstate.screenscale[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8210 r_waterstate.screencenter[0] = 0.5f * (float)r_waterstate.waterwidth / (float)r_waterstate.texturewidth;
8211 r_waterstate.screencenter[1] = 0.5f * (float)r_waterstate.waterheight / (float)r_waterstate.textureheight;
8214 r_waterstate.maxwaterplanes = MAX_WATERPLANES;
8215 r_waterstate.numwaterplanes = 0;
8218 void R_Water_AddWaterPlane(msurface_t *surface, int entno)
8220 int triangleindex, planeindex;
8226 r_waterstate_waterplane_t *p;
8227 texture_t *t = R_GetCurrentTexture(surface->texture);
8229 // just use the first triangle with a valid normal for any decisions
8230 VectorClear(normal);
8231 for (triangleindex = 0, e = rsurface.modelelement3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
8233 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[0]*3, vert[0]);
8234 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[1]*3, vert[1]);
8235 Matrix4x4_Transform(&rsurface.matrix, rsurface.modelvertex3f + e[2]*3, vert[2]);
8236 TriangleNormal(vert[0], vert[1], vert[2], normal);
8237 if (VectorLength2(normal) >= 0.001)
8241 VectorCopy(normal, plane.normal);
8242 VectorNormalize(plane.normal);
8243 plane.dist = DotProduct(vert[0], plane.normal);
8244 PlaneClassify(&plane);
8245 if (PlaneDiff(r_refdef.view.origin, &plane) < 0)
8247 // skip backfaces (except if nocullface is set)
8248 if (!(t->currentmaterialflags & MATERIALFLAG_NOCULLFACE))
8250 VectorNegate(plane.normal, plane.normal);
8252 PlaneClassify(&plane);
8256 // find a matching plane if there is one
8257 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8258 if(p->camera_entity == t->camera_entity)
8259 if (fabs(PlaneDiff(vert[0], &p->plane)) < 1 && fabs(PlaneDiff(vert[1], &p->plane)) < 1 && fabs(PlaneDiff(vert[2], &p->plane)) < 1)
8261 if (planeindex >= r_waterstate.maxwaterplanes)
8262 return; // nothing we can do, out of planes
8264 // if this triangle does not fit any known plane rendered this frame, add one
8265 if (planeindex >= r_waterstate.numwaterplanes)
8267 // store the new plane
8268 r_waterstate.numwaterplanes++;
8270 // clear materialflags and pvs
8271 p->materialflags = 0;
8272 p->pvsvalid = false;
8273 p->camera_entity = t->camera_entity;
8274 VectorCopy(surface->mins, p->mins);
8275 VectorCopy(surface->maxs, p->maxs);
8280 p->mins[0] = min(p->mins[0], surface->mins[0]);
8281 p->mins[1] = min(p->mins[1], surface->mins[1]);
8282 p->mins[2] = min(p->mins[2], surface->mins[2]);
8283 p->maxs[0] = max(p->maxs[0], surface->maxs[0]);
8284 p->maxs[1] = max(p->maxs[1], surface->maxs[1]);
8285 p->maxs[2] = max(p->maxs[2], surface->maxs[2]);
8287 // merge this surface's materialflags into the waterplane
8288 p->materialflags |= t->currentmaterialflags;
8289 if(!(p->materialflags & MATERIALFLAG_CAMERA))
8291 // merge this surface's PVS into the waterplane
8292 VectorMAM(0.5f, surface->mins, 0.5f, surface->maxs, center);
8293 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS
8294 && r_refdef.scene.worldmodel->brush.PointInLeaf && r_refdef.scene.worldmodel->brush.PointInLeaf(r_refdef.scene.worldmodel, center)->clusterindex >= 0)
8296 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, center, 2, p->pvsbits, sizeof(p->pvsbits), p->pvsvalid);
8302 static void R_Water_ProcessPlanes(void)
8305 r_refdef_view_t originalview;
8306 r_refdef_view_t myview;
8308 r_waterstate_waterplane_t *p;
8311 originalview = r_refdef.view;
8313 // make sure enough textures are allocated
8314 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8316 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8318 if (!p->texture_refraction)
8319 p->texture_refraction = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_refraction", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8320 if (!p->texture_refraction)
8323 else if (p->materialflags & MATERIALFLAG_CAMERA)
8325 if (!p->texture_camera)
8326 p->texture_camera = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_camera", planeindex), r_waterstate.camerawidth, r_waterstate.cameraheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR, -1, NULL);
8327 if (!p->texture_camera)
8331 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8333 if (!p->texture_reflection)
8334 p->texture_reflection = R_LoadTexture2D(r_main_texturepool, va("waterplane%i_reflection", planeindex), r_waterstate.texturewidth, r_waterstate.textureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8335 if (!p->texture_reflection)
8341 r_refdef.view = originalview;
8342 r_refdef.view.showdebug = false;
8343 r_refdef.view.width = r_waterstate.waterwidth;
8344 r_refdef.view.height = r_waterstate.waterheight;
8345 r_refdef.view.useclipplane = true;
8346 myview = r_refdef.view;
8347 r_waterstate.renderingscene = true;
8348 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
8350 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION))
8352 r_refdef.view = myview;
8353 if(r_water_scissormode.integer)
8356 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8357 continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8360 // render reflected scene and copy into texture
8361 Matrix4x4_Reflect(&r_refdef.view.matrix, p->plane.normal[0], p->plane.normal[1], p->plane.normal[2], p->plane.dist, -2);
8362 // update the r_refdef.view.origin because otherwise the sky renders at the wrong location (amongst other problems)
8363 Matrix4x4_OriginFromMatrix(&r_refdef.view.matrix, r_refdef.view.origin);
8364 r_refdef.view.clipplane = p->plane;
8366 // reverse the cullface settings for this render
8367 r_refdef.view.cullface_front = GL_FRONT;
8368 r_refdef.view.cullface_back = GL_BACK;
8369 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.num_pvsclusterbytes)
8371 r_refdef.view.usecustompvs = true;
8373 memcpy(r_refdef.viewcache.world_pvsbits, p->pvsbits, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8375 memset(r_refdef.viewcache.world_pvsbits, 0xFF, r_refdef.scene.worldmodel->brush.num_pvsclusterbytes);
8378 R_ResetViewRendering3D();
8379 R_ClearScreen(r_refdef.fogenabled);
8380 if(r_water_scissormode.integer & 2)
8381 R_View_UpdateWithScissor(myscissor);
8384 if(r_water_scissormode.integer & 1)
8385 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8388 R_Mesh_CopyToTexture(p->texture_reflection, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8391 // render the normal view scene and copy into texture
8392 // (except that a clipping plane should be used to hide everything on one side of the water, and the viewer's weapon model should be omitted)
8393 if (p->materialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
8395 r_refdef.view = myview;
8396 if(r_water_scissormode.integer)
8399 if(R_ScissorForBBox(p->mins, p->maxs, myscissor))
8400 continue; // FIXME the plane then still may get rendered but with broken texture, but it sure won't be visible
8403 r_waterstate.renderingrefraction = true;
8405 r_refdef.view.clipplane = p->plane;
8406 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8407 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8409 if((p->materialflags & MATERIALFLAG_CAMERA) && p->camera_entity)
8411 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8412 r_waterstate.renderingrefraction = false; // we don't want to hide the player model from these ones
8413 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8414 R_RenderView_UpdateViewVectors();
8415 if(r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8417 r_refdef.view.usecustompvs = true;
8418 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
8422 PlaneClassify(&r_refdef.view.clipplane);
8424 R_ResetViewRendering3D();
8425 R_ClearScreen(r_refdef.fogenabled);
8426 if(r_water_scissormode.integer & 2)
8427 R_View_UpdateWithScissor(myscissor);
8430 if(r_water_scissormode.integer & 1)
8431 GL_Scissor(myscissor[0], myscissor[1], myscissor[2], myscissor[3]);
8434 R_Mesh_CopyToTexture(p->texture_refraction, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8435 r_waterstate.renderingrefraction = false;
8437 else if (p->materialflags & MATERIALFLAG_CAMERA)
8439 r_refdef.view = myview;
8441 r_refdef.view.clipplane = p->plane;
8442 VectorNegate(r_refdef.view.clipplane.normal, r_refdef.view.clipplane.normal);
8443 r_refdef.view.clipplane.dist = -r_refdef.view.clipplane.dist;
8445 r_refdef.view.width = r_waterstate.camerawidth;
8446 r_refdef.view.height = r_waterstate.cameraheight;
8447 r_refdef.view.frustum_x = 1; // tan(45 * M_PI / 180.0);
8448 r_refdef.view.frustum_y = 1; // tan(45 * M_PI / 180.0);
8450 if(p->camera_entity)
8452 // we need to perform a matrix transform to render the view... so let's get the transformation matrix
8453 CL_VM_TransformView(p->camera_entity - MAX_EDICTS, &r_refdef.view.matrix, &r_refdef.view.clipplane, visorigin);
8456 // note: all of the view is used for displaying... so
8457 // there is no use in scissoring
8459 // reverse the cullface settings for this render
8460 r_refdef.view.cullface_front = GL_FRONT;
8461 r_refdef.view.cullface_back = GL_BACK;
8462 // also reverse the view matrix
8463 Matrix4x4_ConcatScale3(&r_refdef.view.matrix, 1, 1, -1); // this serves to invert texcoords in the result, as the copied texture is mapped the wrong way round
8464 R_RenderView_UpdateViewVectors();
8465 if(p->camera_entity && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.FatPVS)
8467 r_refdef.view.usecustompvs = true;
8468 r_refdef.scene.worldmodel->brush.FatPVS(r_refdef.scene.worldmodel, visorigin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
8471 // camera needs no clipplane
8472 r_refdef.view.useclipplane = false;
8474 PlaneClassify(&r_refdef.view.clipplane);
8476 R_ResetViewRendering3D();
8477 R_ClearScreen(r_refdef.fogenabled);
8481 R_Mesh_CopyToTexture(p->texture_camera, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8482 r_waterstate.renderingrefraction = false;
8486 r_waterstate.renderingscene = false;
8487 r_refdef.view = originalview;
8488 R_ResetViewRendering3D();
8489 R_ClearScreen(r_refdef.fogenabled);
8493 r_refdef.view = originalview;
8494 r_waterstate.renderingscene = false;
8495 Cvar_SetValueQuick(&r_water, 0);
8496 Con_Printf("R_Water_ProcessPlanes: Error: texture creation failed! Turned off r_water.\n");
8500 void R_Bloom_StartFrame(void)
8502 int bloomtexturewidth, bloomtextureheight, screentexturewidth, screentextureheight;
8504 switch(vid.renderpath)
8506 case RENDERPATH_GL20:
8507 case RENDERPATH_D3D9:
8508 case RENDERPATH_D3D10:
8509 case RENDERPATH_D3D11:
8510 case RENDERPATH_SOFT:
8511 case RENDERPATH_GLES2:
8513 case RENDERPATH_GL13:
8514 case RENDERPATH_GL11:
8518 // set bloomwidth and bloomheight to the bloom resolution that will be
8519 // used (often less than the screen resolution for faster rendering)
8520 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, vid.height);
8521 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * vid.height / vid.width;
8522 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, vid.height);
8523 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, (int)vid.maxtexturesize_2d);
8524 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, (int)vid.maxtexturesize_2d);
8526 // calculate desired texture sizes
8527 if (vid.support.arb_texture_non_power_of_two)
8529 screentexturewidth = r_refdef.view.width;
8530 screentextureheight = r_refdef.view.height;
8531 bloomtexturewidth = r_bloomstate.bloomwidth;
8532 bloomtextureheight = r_bloomstate.bloomheight;
8536 for (screentexturewidth = 1;screentexturewidth < vid.width ;screentexturewidth *= 2);
8537 for (screentextureheight = 1;screentextureheight < vid.height ;screentextureheight *= 2);
8538 for (bloomtexturewidth = 1;bloomtexturewidth < r_bloomstate.bloomwidth ;bloomtexturewidth *= 2);
8539 for (bloomtextureheight = 1;bloomtextureheight < r_bloomstate.bloomheight;bloomtextureheight *= 2);
8542 if ((r_hdr.integer || r_bloom.integer || (!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))) && ((r_bloom_resolution.integer < 4 || r_bloom_blur.value < 1 || r_bloom_blur.value >= 512) || r_refdef.view.width > (int)vid.maxtexturesize_2d || r_refdef.view.height > (int)vid.maxtexturesize_2d))
8544 Cvar_SetValueQuick(&r_hdr, 0);
8545 Cvar_SetValueQuick(&r_bloom, 0);
8546 Cvar_SetValueQuick(&r_motionblur, 0);
8547 Cvar_SetValueQuick(&r_damageblur, 0);
8550 if (!(r_glsl_postprocess.integer || (!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) || (v_glslgamma.integer && !vid_gammatables_trivial)) && !r_bloom.integer && !r_hdr.integer && (R_Stereo_Active() || (r_motionblur.value <= 0 && r_damageblur.value <= 0)))
8551 screentexturewidth = screentextureheight = 0;
8552 if (!r_hdr.integer && !r_bloom.integer)
8553 bloomtexturewidth = bloomtextureheight = 0;
8555 // allocate textures as needed
8556 if (r_bloomstate.screentexturewidth != screentexturewidth || r_bloomstate.screentextureheight != screentextureheight)
8558 if (r_bloomstate.texture_screen)
8559 R_FreeTexture(r_bloomstate.texture_screen);
8560 r_bloomstate.texture_screen = NULL;
8561 r_bloomstate.screentexturewidth = screentexturewidth;
8562 r_bloomstate.screentextureheight = screentextureheight;
8563 if (r_bloomstate.screentexturewidth && r_bloomstate.screentextureheight)
8564 r_bloomstate.texture_screen = R_LoadTexture2D(r_main_texturepool, "screen", r_bloomstate.screentexturewidth, r_bloomstate.screentextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP, -1, NULL);
8566 if (r_bloomstate.bloomtexturewidth != bloomtexturewidth || r_bloomstate.bloomtextureheight != bloomtextureheight)
8568 if (r_bloomstate.texture_bloom)
8569 R_FreeTexture(r_bloomstate.texture_bloom);
8570 r_bloomstate.texture_bloom = NULL;
8571 r_bloomstate.bloomtexturewidth = bloomtexturewidth;
8572 r_bloomstate.bloomtextureheight = bloomtextureheight;
8573 if (r_bloomstate.bloomtexturewidth && r_bloomstate.bloomtextureheight)
8574 r_bloomstate.texture_bloom = R_LoadTexture2D(r_main_texturepool, "bloom", r_bloomstate.bloomtexturewidth, r_bloomstate.bloomtextureheight, NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCELINEAR | TEXF_CLAMP, -1, NULL);
8577 // when doing a reduced render (HDR) we want to use a smaller area
8578 r_bloomstate.bloomwidth = bound(1, r_bloom_resolution.integer, r_refdef.view.height);
8579 r_bloomstate.bloomheight = r_bloomstate.bloomwidth * r_refdef.view.height / r_refdef.view.width;
8580 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_refdef.view.height);
8581 r_bloomstate.bloomwidth = bound(1, r_bloomstate.bloomwidth, r_bloomstate.bloomtexturewidth);
8582 r_bloomstate.bloomheight = bound(1, r_bloomstate.bloomheight, r_bloomstate.bloomtextureheight);
8584 // set up a texcoord array for the full resolution screen image
8585 // (we have to keep this around to copy back during final render)
8586 r_bloomstate.screentexcoord2f[0] = 0;
8587 r_bloomstate.screentexcoord2f[1] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8588 r_bloomstate.screentexcoord2f[2] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8589 r_bloomstate.screentexcoord2f[3] = (float)r_refdef.view.height / (float)r_bloomstate.screentextureheight;
8590 r_bloomstate.screentexcoord2f[4] = (float)r_refdef.view.width / (float)r_bloomstate.screentexturewidth;
8591 r_bloomstate.screentexcoord2f[5] = 0;
8592 r_bloomstate.screentexcoord2f[6] = 0;
8593 r_bloomstate.screentexcoord2f[7] = 0;
8595 // set up a texcoord array for the reduced resolution bloom image
8596 // (which will be additive blended over the screen image)
8597 r_bloomstate.bloomtexcoord2f[0] = 0;
8598 r_bloomstate.bloomtexcoord2f[1] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8599 r_bloomstate.bloomtexcoord2f[2] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8600 r_bloomstate.bloomtexcoord2f[3] = (float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8601 r_bloomstate.bloomtexcoord2f[4] = (float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8602 r_bloomstate.bloomtexcoord2f[5] = 0;
8603 r_bloomstate.bloomtexcoord2f[6] = 0;
8604 r_bloomstate.bloomtexcoord2f[7] = 0;
8606 switch(vid.renderpath)
8608 case RENDERPATH_GL11:
8609 case RENDERPATH_GL13:
8610 case RENDERPATH_GL20:
8611 case RENDERPATH_SOFT:
8612 case RENDERPATH_GLES2:
8614 case RENDERPATH_D3D9:
8615 case RENDERPATH_D3D10:
8616 case RENDERPATH_D3D11:
8619 for (i = 0;i < 4;i++)
8621 r_bloomstate.screentexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.screentexturewidth;
8622 r_bloomstate.screentexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.screentextureheight;
8623 r_bloomstate.bloomtexcoord2f[i*2+0] += 0.5f / (float)r_bloomstate.bloomtexturewidth;
8624 r_bloomstate.bloomtexcoord2f[i*2+1] += 0.5f / (float)r_bloomstate.bloomtextureheight;
8630 if (r_hdr.integer || r_bloom.integer)
8632 r_bloomstate.enabled = true;
8633 r_bloomstate.hdr = r_hdr.integer != 0;
8636 R_Viewport_InitOrtho(&r_bloomstate.viewport, &identitymatrix, r_refdef.view.x, vid.height - r_bloomstate.bloomheight - r_refdef.view.y, r_bloomstate.bloomwidth, r_bloomstate.bloomheight, 0, 0, 1, 1, -10, 100, NULL);
8639 void R_Bloom_CopyBloomTexture(float colorscale)
8641 r_refdef.stats.bloom++;
8643 // scale down screen texture to the bloom texture size
8645 R_SetViewport(&r_bloomstate.viewport);
8646 GL_BlendFunc(GL_ONE, GL_ZERO);
8647 GL_Color(colorscale, colorscale, colorscale, 1);
8648 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8649 switch(vid.renderpath)
8651 case RENDERPATH_GL11:
8652 case RENDERPATH_GL13:
8653 case RENDERPATH_GL20:
8654 case RENDERPATH_SOFT:
8655 case RENDERPATH_GLES2:
8656 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8658 case RENDERPATH_D3D9:
8659 case RENDERPATH_D3D10:
8660 case RENDERPATH_D3D11:
8661 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8664 // TODO: do boxfilter scale-down in shader?
8665 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8666 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8667 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8669 // we now have a bloom image in the framebuffer
8670 // copy it into the bloom image texture for later processing
8671 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8672 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8675 void R_Bloom_CopyHDRTexture(void)
8677 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8678 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8681 void R_Bloom_MakeTexture(void)
8684 float xoffset, yoffset, r, brighten;
8686 r_refdef.stats.bloom++;
8688 R_ResetViewRendering2D();
8690 // we have a bloom image in the framebuffer
8692 R_SetViewport(&r_bloomstate.viewport);
8694 for (x = 1;x < min(r_bloom_colorexponent.value, 32);)
8697 r = bound(0, r_bloom_colorexponent.value / x, 1);
8698 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
8700 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.bloomtexcoord2f);
8701 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8702 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8703 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8705 // copy the vertically blurred bloom view to a texture
8706 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8707 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8710 range = r_bloom_blur.integer * r_bloomstate.bloomwidth / 320;
8711 brighten = r_bloom_brighten.value;
8713 brighten *= r_hdr_range.value;
8714 brighten = sqrt(brighten);
8716 brighten *= (3 * range) / (2 * range - 1); // compensate for the "dot particle"
8717 R_SetupShader_Generic(r_bloomstate.texture_bloom, NULL, GL_MODULATE, 1);
8719 for (dir = 0;dir < 2;dir++)
8721 // blend on at multiple vertical offsets to achieve a vertical blur
8722 // TODO: do offset blends using GLSL
8723 // TODO instead of changing the texcoords, change the target positions to prevent artifacts at edges
8724 GL_BlendFunc(GL_ONE, GL_ZERO);
8725 for (x = -range;x <= range;x++)
8727 if (!dir){xoffset = 0;yoffset = x;}
8728 else {xoffset = x;yoffset = 0;}
8729 xoffset /= (float)r_bloomstate.bloomtexturewidth;
8730 yoffset /= (float)r_bloomstate.bloomtextureheight;
8731 // compute a texcoord array with the specified x and y offset
8732 r_bloomstate.offsettexcoord2f[0] = xoffset+0;
8733 r_bloomstate.offsettexcoord2f[1] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8734 r_bloomstate.offsettexcoord2f[2] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8735 r_bloomstate.offsettexcoord2f[3] = yoffset+(float)r_bloomstate.bloomheight / (float)r_bloomstate.bloomtextureheight;
8736 r_bloomstate.offsettexcoord2f[4] = xoffset+(float)r_bloomstate.bloomwidth / (float)r_bloomstate.bloomtexturewidth;
8737 r_bloomstate.offsettexcoord2f[5] = yoffset+0;
8738 r_bloomstate.offsettexcoord2f[6] = xoffset+0;
8739 r_bloomstate.offsettexcoord2f[7] = yoffset+0;
8740 // this r value looks like a 'dot' particle, fading sharply to
8741 // black at the edges
8742 // (probably not realistic but looks good enough)
8743 //r = ((range*range+1)/((float)(x*x+1)))/(range*2+1);
8744 //r = brighten/(range*2+1);
8745 r = brighten / (range * 2 + 1);
8747 r *= (1 - x*x/(float)(range*range));
8748 GL_Color(r, r, r, 1);
8749 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.offsettexcoord2f);
8750 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8751 r_refdef.stats.bloom_drawpixels += r_bloomstate.bloomwidth * r_bloomstate.bloomheight;
8752 GL_BlendFunc(GL_ONE, GL_ONE);
8755 // copy the vertically blurred bloom view to a texture
8756 R_Mesh_CopyToTexture(r_bloomstate.texture_bloom, 0, 0, r_bloomstate.viewport.x, r_bloomstate.viewport.y, r_bloomstate.viewport.width, r_bloomstate.viewport.height);
8757 r_refdef.stats.bloom_copypixels += r_bloomstate.viewport.width * r_bloomstate.viewport.height;
8761 void R_HDR_RenderBloomTexture(void)
8763 int oldwidth, oldheight;
8764 float oldcolorscale;
8765 qboolean oldwaterstate;
8767 oldwaterstate = r_waterstate.enabled;
8768 oldcolorscale = r_refdef.view.colorscale;
8769 oldwidth = r_refdef.view.width;
8770 oldheight = r_refdef.view.height;
8771 r_refdef.view.width = r_bloomstate.bloomwidth;
8772 r_refdef.view.height = r_bloomstate.bloomheight;
8774 if(r_hdr.integer < 2)
8775 r_waterstate.enabled = false;
8777 // TODO: support GL_EXT_framebuffer_object rather than reusing the framebuffer? it might improve SLI performance.
8778 // TODO: add exposure compensation features
8779 // TODO: add fp16 framebuffer support (using GL_EXT_framebuffer_object)
8781 r_refdef.view.showdebug = false;
8782 r_refdef.view.colorscale *= r_bloom_colorscale.value / bound(1, r_hdr_range.value, 16);
8784 R_ResetViewRendering3D();
8786 R_ClearScreen(r_refdef.fogenabled);
8787 if (r_timereport_active)
8788 R_TimeReport("HDRclear");
8791 if (r_timereport_active)
8792 R_TimeReport("visibility");
8794 // only do secondary renders with HDR if r_hdr is 2 or higher
8795 r_waterstate.numwaterplanes = 0;
8796 if (r_waterstate.enabled)
8797 R_RenderWaterPlanes();
8799 r_refdef.view.showdebug = true;
8801 r_waterstate.numwaterplanes = 0;
8803 R_ResetViewRendering2D();
8805 R_Bloom_CopyHDRTexture();
8806 R_Bloom_MakeTexture();
8808 // restore the view settings
8809 r_waterstate.enabled = oldwaterstate;
8810 r_refdef.view.width = oldwidth;
8811 r_refdef.view.height = oldheight;
8812 r_refdef.view.colorscale = oldcolorscale;
8814 R_ResetViewRendering3D();
8816 R_ClearScreen(r_refdef.fogenabled);
8817 if (r_timereport_active)
8818 R_TimeReport("viewclear");
8821 static void R_BlendView(void)
8823 unsigned int permutation;
8824 float uservecs[4][4];
8826 switch (vid.renderpath)
8828 case RENDERPATH_GL20:
8829 case RENDERPATH_D3D9:
8830 case RENDERPATH_D3D10:
8831 case RENDERPATH_D3D11:
8832 case RENDERPATH_SOFT:
8833 case RENDERPATH_GLES2:
8835 (r_bloomstate.texture_bloom ? SHADERPERMUTATION_BLOOM : 0)
8836 | (r_refdef.viewblend[3] > 0 ? SHADERPERMUTATION_VIEWTINT : 0)
8837 | ((v_glslgamma.value && !vid_gammatables_trivial) ? SHADERPERMUTATION_GAMMARAMPS : 0)
8838 | (r_glsl_postprocess.integer ? SHADERPERMUTATION_POSTPROCESSING : 0)
8839 | ((!R_Stereo_ColorMasking() && r_glsl_saturation.value != 1) ? SHADERPERMUTATION_SATURATION : 0);
8841 if (r_bloomstate.texture_screen)
8843 // make sure the buffer is available
8844 if (r_bloom_blur.value < 1) { Cvar_SetValueQuick(&r_bloom_blur, 1); }
8846 R_ResetViewRendering2D();
8848 if(!R_Stereo_Active() && (r_motionblur.value > 0 || r_damageblur.value > 0))
8850 // declare variables
8852 static float avgspeed;
8854 speed = VectorLength(cl.movement_velocity);
8856 cl.motionbluralpha = bound(0, (cl.time - cl.oldtime) / max(0.001, r_motionblur_vcoeff.value), 1);
8857 avgspeed = avgspeed * (1 - cl.motionbluralpha) + speed * cl.motionbluralpha;
8859 speed = (avgspeed - r_motionblur_vmin.value) / max(1, r_motionblur_vmax.value - r_motionblur_vmin.value);
8860 speed = bound(0, speed, 1);
8861 speed = speed * (1 - r_motionblur_bmin.value) + r_motionblur_bmin.value;
8863 // calculate values into a standard alpha
8864 cl.motionbluralpha = 1 - exp(-
8866 (r_motionblur.value * speed / 80)
8868 (r_damageblur.value * (cl.cshifts[CSHIFT_DAMAGE].percent / 1600))
8871 max(0.0001, cl.time - cl.oldtime) // fps independent
8874 cl.motionbluralpha *= lhrandom(1 - r_motionblur_randomize.value, 1 + r_motionblur_randomize.value);
8875 cl.motionbluralpha = bound(0, cl.motionbluralpha, r_motionblur_maxblur.value);
8877 if (cl.motionbluralpha > 0 && !r_refdef.envmap)
8879 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8880 GL_Color(1, 1, 1, cl.motionbluralpha);
8881 switch(vid.renderpath)
8883 case RENDERPATH_GL11:
8884 case RENDERPATH_GL13:
8885 case RENDERPATH_GL20:
8886 case RENDERPATH_SOFT:
8887 case RENDERPATH_GLES2:
8888 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8890 case RENDERPATH_D3D9:
8891 case RENDERPATH_D3D10:
8892 case RENDERPATH_D3D11:
8893 R_Mesh_PrepareVertices_Generic_Arrays(4, r_d3dscreenvertex3f, NULL, r_bloomstate.screentexcoord2f);
8896 R_SetupShader_Generic(r_bloomstate.texture_screen, NULL, GL_MODULATE, 1);
8897 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8898 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8902 // copy view into the screen texture
8903 R_Mesh_CopyToTexture(r_bloomstate.texture_screen, 0, 0, r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height);
8904 r_refdef.stats.bloom_copypixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
8906 else if (!r_bloomstate.texture_bloom)
8908 // we may still have to do view tint...
8909 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
8911 // apply a color tint to the whole view
8912 R_ResetViewRendering2D();
8913 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8914 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
8915 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
8916 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
8917 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
8919 break; // no screen processing, no bloom, skip it
8922 if (r_bloomstate.texture_bloom && !r_bloomstate.hdr)
8924 // render simple bloom effect
8925 // copy the screen and shrink it and darken it for the bloom process
8926 R_Bloom_CopyBloomTexture(r_bloom_colorscale.value);
8927 // make the bloom texture
8928 R_Bloom_MakeTexture();
8931 #if _MSC_VER >= 1400
8932 #define sscanf sscanf_s
8934 memset(uservecs, 0, sizeof(uservecs));
8935 if (r_glsl_postprocess_uservec1_enable.integer)
8936 sscanf(r_glsl_postprocess_uservec1.string, "%f %f %f %f", &uservecs[0][0], &uservecs[0][1], &uservecs[0][2], &uservecs[0][3]);
8937 if (r_glsl_postprocess_uservec2_enable.integer)
8938 sscanf(r_glsl_postprocess_uservec2.string, "%f %f %f %f", &uservecs[1][0], &uservecs[1][1], &uservecs[1][2], &uservecs[1][3]);
8939 if (r_glsl_postprocess_uservec3_enable.integer)
8940 sscanf(r_glsl_postprocess_uservec3.string, "%f %f %f %f", &uservecs[2][0], &uservecs[2][1], &uservecs[2][2], &uservecs[2][3]);
8941 if (r_glsl_postprocess_uservec4_enable.integer)
8942 sscanf(r_glsl_postprocess_uservec4.string, "%f %f %f %f", &uservecs[3][0], &uservecs[3][1], &uservecs[3][2], &uservecs[3][3]);
8944 R_ResetViewRendering2D();
8945 GL_Color(1, 1, 1, 1);
8946 GL_BlendFunc(GL_ONE, GL_ZERO);
8948 switch(vid.renderpath)
8950 case RENDERPATH_GL20:
8951 case RENDERPATH_GLES2:
8952 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8953 R_SetupShader_SetPermutationGLSL(SHADERMODE_POSTPROCESS, permutation);
8954 if (r_glsl_permutation->tex_Texture_First >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_First , r_bloomstate.texture_screen);
8955 if (r_glsl_permutation->tex_Texture_Second >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_Second , r_bloomstate.texture_bloom );
8956 if (r_glsl_permutation->tex_Texture_GammaRamps >= 0) R_Mesh_TexBind(r_glsl_permutation->tex_Texture_GammaRamps, r_texture_gammaramps );
8957 if (r_glsl_permutation->loc_ViewTintColor >= 0) qglUniform4f(r_glsl_permutation->loc_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8958 if (r_glsl_permutation->loc_PixelSize >= 0) qglUniform2f(r_glsl_permutation->loc_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8959 if (r_glsl_permutation->loc_UserVec1 >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8960 if (r_glsl_permutation->loc_UserVec2 >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8961 if (r_glsl_permutation->loc_UserVec3 >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8962 if (r_glsl_permutation->loc_UserVec4 >= 0) qglUniform4f(r_glsl_permutation->loc_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8963 if (r_glsl_permutation->loc_Saturation >= 0) qglUniform1f(r_glsl_permutation->loc_Saturation , r_glsl_saturation.value);
8964 if (r_glsl_permutation->loc_PixelToScreenTexCoord >= 0) qglUniform2f(r_glsl_permutation->loc_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
8965 if (r_glsl_permutation->loc_BloomColorSubtract >= 0) qglUniform4f(r_glsl_permutation->loc_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
8967 case RENDERPATH_D3D9:
8969 // D3D has upside down Y coords, the easiest way to flip this is to flip the screen vertices rather than the texcoords, so we just use a different array for that...
8970 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_d3dscreenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8971 R_SetupShader_SetPermutationHLSL(SHADERMODE_POSTPROCESS, permutation);
8972 R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8973 R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8974 R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8975 hlslPSSetParameter4f(D3DPSREGISTER_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8976 hlslPSSetParameter2f(D3DPSREGISTER_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
8977 hlslPSSetParameter4f(D3DPSREGISTER_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
8978 hlslPSSetParameter4f(D3DPSREGISTER_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
8979 hlslPSSetParameter4f(D3DPSREGISTER_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
8980 hlslPSSetParameter4f(D3DPSREGISTER_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
8981 hlslPSSetParameter1f(D3DPSREGISTER_Saturation , r_glsl_saturation.value);
8982 hlslPSSetParameter2f(D3DPSREGISTER_PixelToScreenTexCoord, 1.0f/vid.width, 1.0/vid.height);
8983 hlslPSSetParameter4f(D3DPSREGISTER_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
8986 case RENDERPATH_D3D10:
8987 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
8989 case RENDERPATH_D3D11:
8990 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
8992 case RENDERPATH_SOFT:
8993 R_Mesh_PrepareVertices_Mesh_Arrays(4, r_screenvertex3f, NULL, NULL, NULL, NULL, r_bloomstate.screentexcoord2f, r_bloomstate.bloomtexcoord2f);
8994 R_SetupShader_SetPermutationSoft(SHADERMODE_POSTPROCESS, permutation);
8995 R_Mesh_TexBind(GL20TU_FIRST , r_bloomstate.texture_screen);
8996 R_Mesh_TexBind(GL20TU_SECOND , r_bloomstate.texture_bloom );
8997 R_Mesh_TexBind(GL20TU_GAMMARAMPS, r_texture_gammaramps );
8998 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_ViewTintColor , r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
8999 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelSize , 1.0/r_bloomstate.screentexturewidth, 1.0/r_bloomstate.screentextureheight);
9000 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec1 , uservecs[0][0], uservecs[0][1], uservecs[0][2], uservecs[0][3]);
9001 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec2 , uservecs[1][0], uservecs[1][1], uservecs[1][2], uservecs[1][3]);
9002 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec3 , uservecs[2][0], uservecs[2][1], uservecs[2][2], uservecs[2][3]);
9003 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_UserVec4 , uservecs[3][0], uservecs[3][1], uservecs[3][2], uservecs[3][3]);
9004 DPSOFTRAST_Uniform1f(DPSOFTRAST_UNIFORM_Saturation , r_glsl_saturation.value);
9005 DPSOFTRAST_Uniform2f(DPSOFTRAST_UNIFORM_PixelToScreenTexCoord, 1.0f/vid.width, 1.0f/vid.height);
9006 DPSOFTRAST_Uniform4f(DPSOFTRAST_UNIFORM_BloomColorSubtract , r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, r_bloom_colorsubtract.value, 0.0f);
9011 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9012 r_refdef.stats.bloom_drawpixels += r_refdef.view.viewport.width * r_refdef.view.viewport.height;
9014 case RENDERPATH_GL13:
9015 case RENDERPATH_GL11:
9016 if (r_refdef.viewblend[3] >= (1.0f / 256.0f))
9018 // apply a color tint to the whole view
9019 R_ResetViewRendering2D();
9020 GL_Color(r_refdef.viewblend[0], r_refdef.viewblend[1], r_refdef.viewblend[2], r_refdef.viewblend[3]);
9021 R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL);
9022 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9023 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9024 R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
9030 matrix4x4_t r_waterscrollmatrix;
9032 void R_UpdateFogColor(void) // needs to be called before HDR subrender too, as that changes colorscale!
9034 if (r_refdef.fog_density)
9036 r_refdef.fogcolor[0] = r_refdef.fog_red;
9037 r_refdef.fogcolor[1] = r_refdef.fog_green;
9038 r_refdef.fogcolor[2] = r_refdef.fog_blue;
9040 Vector4Set(r_refdef.fogplane, 0, 0, 1, -r_refdef.fog_height);
9041 r_refdef.fogplaneviewdist = DotProduct(r_refdef.fogplane, r_refdef.view.origin) + r_refdef.fogplane[3];
9042 r_refdef.fogplaneviewabove = r_refdef.fogplaneviewdist >= 0;
9043 r_refdef.fogheightfade = -0.5f/max(0.125f, r_refdef.fog_fadedepth);
9047 VectorCopy(r_refdef.fogcolor, fogvec);
9048 // color.rgb *= ContrastBoost * SceneBrightness;
9049 VectorScale(fogvec, r_refdef.view.colorscale, fogvec);
9050 r_refdef.fogcolor[0] = bound(0.0f, fogvec[0], 1.0f);
9051 r_refdef.fogcolor[1] = bound(0.0f, fogvec[1], 1.0f);
9052 r_refdef.fogcolor[2] = bound(0.0f, fogvec[2], 1.0f);
9057 void R_UpdateVariables(void)
9061 r_refdef.scene.ambient = r_ambient.value * (1.0f / 64.0f);
9063 r_refdef.farclip = r_farclip_base.value;
9064 if (r_refdef.scene.worldmodel)
9065 r_refdef.farclip += r_refdef.scene.worldmodel->radius * r_farclip_world.value * 2;
9066 r_refdef.nearclip = bound (0.001f, r_nearclip.value, r_refdef.farclip - 1.0f);
9068 if (r_shadow_frontsidecasting.integer < 0 || r_shadow_frontsidecasting.integer > 1)
9069 Cvar_SetValueQuick(&r_shadow_frontsidecasting, 1);
9070 r_refdef.polygonfactor = 0;
9071 r_refdef.polygonoffset = 0;
9072 r_refdef.shadowpolygonfactor = r_refdef.polygonfactor + r_shadow_polygonfactor.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9073 r_refdef.shadowpolygonoffset = r_refdef.polygonoffset + r_shadow_polygonoffset.value * (r_shadow_frontsidecasting.integer ? 1 : -1);
9075 r_refdef.scene.rtworld = r_shadow_realtime_world.integer != 0;
9076 r_refdef.scene.rtworldshadows = r_shadow_realtime_world_shadows.integer && vid.stencil;
9077 r_refdef.scene.rtdlight = r_shadow_realtime_dlight.integer != 0 && !gl_flashblend.integer && r_dynamic.integer;
9078 r_refdef.scene.rtdlightshadows = r_refdef.scene.rtdlight && r_shadow_realtime_dlight_shadows.integer && vid.stencil;
9079 r_refdef.lightmapintensity = r_refdef.scene.rtworld ? r_shadow_realtime_world_lightmaps.value : 1;
9080 if (FAKELIGHT_ENABLED)
9082 r_refdef.lightmapintensity *= r_fakelight_intensity.value;
9084 if (r_showsurfaces.integer)
9086 r_refdef.scene.rtworld = false;
9087 r_refdef.scene.rtworldshadows = false;
9088 r_refdef.scene.rtdlight = false;
9089 r_refdef.scene.rtdlightshadows = false;
9090 r_refdef.lightmapintensity = 0;
9093 if (gamemode == GAME_NEHAHRA)
9095 if (gl_fogenable.integer)
9097 r_refdef.oldgl_fogenable = true;
9098 r_refdef.fog_density = gl_fogdensity.value;
9099 r_refdef.fog_red = gl_fogred.value;
9100 r_refdef.fog_green = gl_foggreen.value;
9101 r_refdef.fog_blue = gl_fogblue.value;
9102 r_refdef.fog_alpha = 1;
9103 r_refdef.fog_start = 0;
9104 r_refdef.fog_end = gl_skyclip.value;
9105 r_refdef.fog_height = 1<<30;
9106 r_refdef.fog_fadedepth = 128;
9108 else if (r_refdef.oldgl_fogenable)
9110 r_refdef.oldgl_fogenable = false;
9111 r_refdef.fog_density = 0;
9112 r_refdef.fog_red = 0;
9113 r_refdef.fog_green = 0;
9114 r_refdef.fog_blue = 0;
9115 r_refdef.fog_alpha = 0;
9116 r_refdef.fog_start = 0;
9117 r_refdef.fog_end = 0;
9118 r_refdef.fog_height = 1<<30;
9119 r_refdef.fog_fadedepth = 128;
9123 r_refdef.fog_alpha = bound(0, r_refdef.fog_alpha, 1);
9124 r_refdef.fog_start = max(0, r_refdef.fog_start);
9125 r_refdef.fog_end = max(r_refdef.fog_start + 0.01, r_refdef.fog_end);
9127 // R_UpdateFogColor(); // why? R_RenderScene does it anyway
9129 if (r_refdef.fog_density && r_drawfog.integer)
9131 r_refdef.fogenabled = true;
9132 // this is the point where the fog reaches 0.9986 alpha, which we
9133 // consider a good enough cutoff point for the texture
9134 // (0.9986 * 256 == 255.6)
9135 if (r_fog_exp2.integer)
9136 r_refdef.fogrange = 32 / (r_refdef.fog_density * r_refdef.fog_density) + r_refdef.fog_start;
9138 r_refdef.fogrange = 2048 / r_refdef.fog_density + r_refdef.fog_start;
9139 r_refdef.fogrange = bound(r_refdef.fog_start, r_refdef.fogrange, r_refdef.fog_end);
9140 r_refdef.fograngerecip = 1.0f / r_refdef.fogrange;
9141 r_refdef.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * r_refdef.fograngerecip;
9142 if (strcmp(r_refdef.fogheighttexturename, r_refdef.fog_height_texturename))
9143 R_BuildFogHeightTexture();
9144 // fog color was already set
9145 // update the fog texture
9146 if (r_refdef.fogmasktable_start != r_refdef.fog_start || r_refdef.fogmasktable_alpha != r_refdef.fog_alpha || r_refdef.fogmasktable_density != r_refdef.fog_density || r_refdef.fogmasktable_range != r_refdef.fogrange)
9147 R_BuildFogTexture();
9148 r_refdef.fog_height_texcoordscale = 1.0f / max(0.125f, r_refdef.fog_fadedepth);
9149 r_refdef.fog_height_tablescale = r_refdef.fog_height_tablesize * r_refdef.fog_height_texcoordscale;
9152 r_refdef.fogenabled = false;
9154 switch(vid.renderpath)
9156 case RENDERPATH_GL20:
9157 case RENDERPATH_D3D9:
9158 case RENDERPATH_D3D10:
9159 case RENDERPATH_D3D11:
9160 case RENDERPATH_SOFT:
9161 case RENDERPATH_GLES2:
9162 if(v_glslgamma.integer && !vid_gammatables_trivial)
9164 if(!r_texture_gammaramps || vid_gammatables_serial != r_texture_gammaramps_serial)
9166 // build GLSL gamma texture
9167 #define RAMPWIDTH 256
9168 unsigned short ramp[RAMPWIDTH * 3];
9169 unsigned char rampbgr[RAMPWIDTH][4];
9172 r_texture_gammaramps_serial = vid_gammatables_serial;
9174 VID_BuildGammaTables(&ramp[0], RAMPWIDTH);
9175 for(i = 0; i < RAMPWIDTH; ++i)
9177 rampbgr[i][0] = (unsigned char) (ramp[i + 2 * RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9178 rampbgr[i][1] = (unsigned char) (ramp[i + RAMPWIDTH] * 255.0 / 65535.0 + 0.5);
9179 rampbgr[i][2] = (unsigned char) (ramp[i] * 255.0 / 65535.0 + 0.5);
9182 if (r_texture_gammaramps)
9184 R_UpdateTexture(r_texture_gammaramps, &rampbgr[0][0], 0, 0, 0, RAMPWIDTH, 1, 1);
9188 r_texture_gammaramps = R_LoadTexture2D(r_main_texturepool, "gammaramps", RAMPWIDTH, 1, &rampbgr[0][0], TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_CLAMP | TEXF_PERSISTENT, -1, NULL);
9194 // remove GLSL gamma texture
9197 case RENDERPATH_GL13:
9198 case RENDERPATH_GL11:
9203 static r_refdef_scene_type_t r_currentscenetype = RST_CLIENT;
9204 static r_refdef_scene_t r_scenes_store[ RST_COUNT ];
9210 void R_SelectScene( r_refdef_scene_type_t scenetype ) {
9211 if( scenetype != r_currentscenetype ) {
9212 // store the old scenetype
9213 r_scenes_store[ r_currentscenetype ] = r_refdef.scene;
9214 r_currentscenetype = scenetype;
9215 // move in the new scene
9216 r_refdef.scene = r_scenes_store[ r_currentscenetype ];
9225 r_refdef_scene_t * R_GetScenePointer( r_refdef_scene_type_t scenetype )
9227 // of course, we could also add a qboolean that provides a lock state and a ReleaseScenePointer function..
9228 if( scenetype == r_currentscenetype ) {
9229 return &r_refdef.scene;
9231 return &r_scenes_store[ scenetype ];
9240 int dpsoftrast_test;
9241 void R_RenderView(void)
9243 matrix4x4_t originalmatrix = r_refdef.view.matrix, offsetmatrix;
9245 dpsoftrast_test = r_test.integer;
9247 if (r_timereport_active)
9248 R_TimeReport("start");
9249 r_textureframe++; // used only by R_GetCurrentTexture
9250 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
9252 if(R_CompileShader_CheckStaticParms())
9255 if (!r_drawentities.integer)
9256 r_refdef.scene.numentities = 0;
9258 R_AnimCache_ClearCache();
9259 R_FrameData_NewFrame();
9261 /* adjust for stereo display */
9262 if(R_Stereo_Active())
9264 Matrix4x4_CreateFromQuakeEntity(&offsetmatrix, 0, r_stereo_separation.value * (0.5f - r_stereo_side), 0, 0, r_stereo_angle.value * (0.5f - r_stereo_side), 0, 1);
9265 Matrix4x4_Concat(&r_refdef.view.matrix, &originalmatrix, &offsetmatrix);
9268 if (r_refdef.view.isoverlay)
9270 // TODO: FIXME: move this into its own backend function maybe? [2/5/2008 Andreas]
9271 GL_Clear(GL_DEPTH_BUFFER_BIT, NULL, 1.0f, 0);
9272 R_TimeReport("depthclear");
9274 r_refdef.view.showdebug = false;
9276 r_waterstate.enabled = false;
9277 r_waterstate.numwaterplanes = 0;
9281 r_refdef.view.matrix = originalmatrix;
9287 if (!r_refdef.scene.entities || r_refdef.view.width * r_refdef.view.height == 0 || !r_renderview.integer || cl_videoplaying/* || !r_refdef.scene.worldmodel*/)
9289 r_refdef.view.matrix = originalmatrix;
9290 return; //Host_Error ("R_RenderView: NULL worldmodel");
9293 r_refdef.view.colorscale = r_hdr_scenebrightness.value * r_hdr_irisadaptation_value.value;
9295 R_RenderView_UpdateViewVectors();
9297 R_Shadow_UpdateWorldLightSelection();
9299 R_Bloom_StartFrame();
9300 R_Water_StartFrame();
9303 if (r_timereport_active)
9304 R_TimeReport("viewsetup");
9306 R_ResetViewRendering3D();
9308 if (r_refdef.view.clear || r_refdef.fogenabled)
9310 R_ClearScreen(r_refdef.fogenabled);
9311 if (r_timereport_active)
9312 R_TimeReport("viewclear");
9314 r_refdef.view.clear = true;
9316 // this produces a bloom texture to be used in R_BlendView() later
9317 if (r_hdr.integer && r_bloomstate.bloomwidth)
9319 R_HDR_RenderBloomTexture();
9320 // we have to bump the texture frame again because r_refdef.view.colorscale is cached in the textures
9321 r_textureframe++; // used only by R_GetCurrentTexture
9324 r_refdef.view.showdebug = true;
9327 if (r_timereport_active)
9328 R_TimeReport("visibility");
9330 r_waterstate.numwaterplanes = 0;
9331 if (r_waterstate.enabled)
9332 R_RenderWaterPlanes();
9335 r_waterstate.numwaterplanes = 0;
9338 if (r_timereport_active)
9339 R_TimeReport("blendview");
9341 GL_Scissor(0, 0, vid.width, vid.height);
9342 GL_ScissorTest(false);
9344 r_refdef.view.matrix = originalmatrix;
9349 void R_RenderWaterPlanes(void)
9351 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawAddWaterPlanes)
9353 r_refdef.scene.worldmodel->DrawAddWaterPlanes(r_refdef.scene.worldentity);
9354 if (r_timereport_active)
9355 R_TimeReport("waterworld");
9358 // don't let sound skip if going slow
9359 if (r_refdef.scene.extraupdate)
9362 R_DrawModelsAddWaterPlanes();
9363 if (r_timereport_active)
9364 R_TimeReport("watermodels");
9366 if (r_waterstate.numwaterplanes)
9368 R_Water_ProcessPlanes();
9369 if (r_timereport_active)
9370 R_TimeReport("waterscenes");
9374 extern void R_DrawLightningBeams (void);
9375 extern void VM_CL_AddPolygonsToMeshQueue (void);
9376 extern void R_DrawPortals (void);
9377 extern cvar_t cl_locs_show;
9378 static void R_DrawLocs(void);
9379 static void R_DrawEntityBBoxes(void);
9380 static void R_DrawModelDecals(void);
9381 extern void R_DrawModelShadows(void);
9382 extern void R_DrawModelShadowMaps(void);
9383 extern cvar_t cl_decals_newsystem;
9384 extern qboolean r_shadow_usingdeferredprepass;
9385 void R_RenderScene(void)
9387 qboolean shadowmapping = false;
9389 if (r_timereport_active)
9390 R_TimeReport("beginscene");
9392 r_refdef.stats.renders++;
9396 // don't let sound skip if going slow
9397 if (r_refdef.scene.extraupdate)
9400 R_MeshQueue_BeginScene();
9404 Matrix4x4_CreateTranslate(&r_waterscrollmatrix, sin(r_refdef.scene.time) * 0.025 * r_waterscroll.value, sin(r_refdef.scene.time * 0.8f) * 0.025 * r_waterscroll.value, 0);
9406 if (r_timereport_active)
9407 R_TimeReport("skystartframe");
9409 if (cl.csqc_vidvars.drawworld)
9411 // don't let sound skip if going slow
9412 if (r_refdef.scene.extraupdate)
9415 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawSky)
9417 r_refdef.scene.worldmodel->DrawSky(r_refdef.scene.worldentity);
9418 if (r_timereport_active)
9419 R_TimeReport("worldsky");
9422 if (R_DrawBrushModelsSky() && r_timereport_active)
9423 R_TimeReport("bmodelsky");
9425 if (skyrendermasked && skyrenderlater)
9427 // we have to force off the water clipping plane while rendering sky
9431 if (r_timereport_active)
9432 R_TimeReport("sky");
9436 R_AnimCache_CacheVisibleEntities();
9437 if (r_timereport_active)
9438 R_TimeReport("animation");
9440 R_Shadow_PrepareLights();
9441 if (r_shadows.integer > 0 && r_refdef.lightmapintensity > 0)
9442 R_Shadow_PrepareModelShadows();
9443 if (r_timereport_active)
9444 R_TimeReport("preparelights");
9446 if (R_Shadow_ShadowMappingEnabled())
9447 shadowmapping = true;
9449 if (r_shadow_usingdeferredprepass)
9450 R_Shadow_DrawPrepass();
9452 if (r_depthfirst.integer >= 1 && cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDepth)
9454 r_refdef.scene.worldmodel->DrawDepth(r_refdef.scene.worldentity);
9455 if (r_timereport_active)
9456 R_TimeReport("worlddepth");
9458 if (r_depthfirst.integer >= 2)
9460 R_DrawModelsDepth();
9461 if (r_timereport_active)
9462 R_TimeReport("modeldepth");
9465 if (r_shadows.integer >= 2 && shadowmapping && r_refdef.lightmapintensity > 0)
9467 R_DrawModelShadowMaps();
9468 R_ResetViewRendering3D();
9469 // don't let sound skip if going slow
9470 if (r_refdef.scene.extraupdate)
9474 if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->Draw)
9476 r_refdef.scene.worldmodel->Draw(r_refdef.scene.worldentity);
9477 if (r_timereport_active)
9478 R_TimeReport("world");
9481 // don't let sound skip if going slow
9482 if (r_refdef.scene.extraupdate)
9486 if (r_timereport_active)
9487 R_TimeReport("models");
9489 // don't let sound skip if going slow
9490 if (r_refdef.scene.extraupdate)
9493 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && !r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9495 R_DrawModelShadows();
9496 R_ResetViewRendering3D();
9497 // don't let sound skip if going slow
9498 if (r_refdef.scene.extraupdate)
9502 if (!r_shadow_usingdeferredprepass)
9504 R_Shadow_DrawLights();
9505 if (r_timereport_active)
9506 R_TimeReport("rtlights");
9509 // don't let sound skip if going slow
9510 if (r_refdef.scene.extraupdate)
9513 if ((r_shadows.integer == 1 || (r_shadows.integer > 0 && !shadowmapping)) && r_shadows_drawafterrtlighting.integer && r_refdef.lightmapintensity > 0)
9515 R_DrawModelShadows();
9516 R_ResetViewRendering3D();
9517 // don't let sound skip if going slow
9518 if (r_refdef.scene.extraupdate)
9522 if (cl.csqc_vidvars.drawworld)
9524 if (cl_decals_newsystem.integer)
9526 R_DrawModelDecals();
9527 if (r_timereport_active)
9528 R_TimeReport("modeldecals");
9533 if (r_timereport_active)
9534 R_TimeReport("decals");
9538 if (r_timereport_active)
9539 R_TimeReport("particles");
9542 if (r_timereport_active)
9543 R_TimeReport("explosions");
9545 R_DrawLightningBeams();
9546 if (r_timereport_active)
9547 R_TimeReport("lightning");
9550 VM_CL_AddPolygonsToMeshQueue();
9552 if (r_refdef.view.showdebug)
9554 if (cl_locs_show.integer)
9557 if (r_timereport_active)
9558 R_TimeReport("showlocs");
9561 if (r_drawportals.integer)
9564 if (r_timereport_active)
9565 R_TimeReport("portals");
9568 if (r_showbboxes.value > 0)
9570 R_DrawEntityBBoxes();
9571 if (r_timereport_active)
9572 R_TimeReport("bboxes");
9576 R_MeshQueue_RenderTransparent();
9577 if (r_timereport_active)
9578 R_TimeReport("drawtrans");
9580 if (r_refdef.view.showdebug && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawDebug && (r_showtris.value > 0 || r_shownormals.value != 0 || r_showcollisionbrushes.value > 0))
9582 r_refdef.scene.worldmodel->DrawDebug(r_refdef.scene.worldentity);
9583 if (r_timereport_active)
9584 R_TimeReport("worlddebug");
9585 R_DrawModelsDebug();
9586 if (r_timereport_active)
9587 R_TimeReport("modeldebug");
9590 if (cl.csqc_vidvars.drawworld)
9592 R_Shadow_DrawCoronas();
9593 if (r_timereport_active)
9594 R_TimeReport("coronas");
9599 GL_DepthTest(false);
9600 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
9601 GL_Color(1, 1, 1, 1);
9602 qglBegin(GL_POLYGON);
9603 qglVertex3f(r_refdef.view.frustumcorner[0][0], r_refdef.view.frustumcorner[0][1], r_refdef.view.frustumcorner[0][2]);
9604 qglVertex3f(r_refdef.view.frustumcorner[1][0], r_refdef.view.frustumcorner[1][1], r_refdef.view.frustumcorner[1][2]);
9605 qglVertex3f(r_refdef.view.frustumcorner[3][0], r_refdef.view.frustumcorner[3][1], r_refdef.view.frustumcorner[3][2]);
9606 qglVertex3f(r_refdef.view.frustumcorner[2][0], r_refdef.view.frustumcorner[2][1], r_refdef.view.frustumcorner[2][2]);
9608 qglBegin(GL_POLYGON);
9609 qglVertex3f(r_refdef.view.frustumcorner[0][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[0][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[0][2] + 1000 * r_refdef.view.forward[2]);
9610 qglVertex3f(r_refdef.view.frustumcorner[1][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[1][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[1][2] + 1000 * r_refdef.view.forward[2]);
9611 qglVertex3f(r_refdef.view.frustumcorner[3][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[3][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[3][2] + 1000 * r_refdef.view.forward[2]);
9612 qglVertex3f(r_refdef.view.frustumcorner[2][0] + 1000 * r_refdef.view.forward[0], r_refdef.view.frustumcorner[2][1] + 1000 * r_refdef.view.forward[1], r_refdef.view.frustumcorner[2][2] + 1000 * r_refdef.view.forward[2]);
9614 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
9618 // don't let sound skip if going slow
9619 if (r_refdef.scene.extraupdate)
9622 R_ResetViewRendering2D();
9625 static const unsigned short bboxelements[36] =
9635 void R_DrawBBoxMesh(vec3_t mins, vec3_t maxs, float cr, float cg, float cb, float ca)
9638 float *v, *c, f1, f2, vertex3f[8*3], color4f[8*4];
9640 RSurf_ActiveWorldEntity();
9642 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9643 GL_DepthMask(false);
9644 GL_DepthRange(0, 1);
9645 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
9646 // R_Mesh_ResetTextureState();
9648 vertex3f[ 0] = mins[0];vertex3f[ 1] = mins[1];vertex3f[ 2] = mins[2]; //
9649 vertex3f[ 3] = maxs[0];vertex3f[ 4] = mins[1];vertex3f[ 5] = mins[2];
9650 vertex3f[ 6] = mins[0];vertex3f[ 7] = maxs[1];vertex3f[ 8] = mins[2];
9651 vertex3f[ 9] = maxs[0];vertex3f[10] = maxs[1];vertex3f[11] = mins[2];
9652 vertex3f[12] = mins[0];vertex3f[13] = mins[1];vertex3f[14] = maxs[2];
9653 vertex3f[15] = maxs[0];vertex3f[16] = mins[1];vertex3f[17] = maxs[2];
9654 vertex3f[18] = mins[0];vertex3f[19] = maxs[1];vertex3f[20] = maxs[2];
9655 vertex3f[21] = maxs[0];vertex3f[22] = maxs[1];vertex3f[23] = maxs[2];
9656 R_FillColors(color4f, 8, cr, cg, cb, ca);
9657 if (r_refdef.fogenabled)
9659 for (i = 0, v = vertex3f, c = color4f;i < 8;i++, v += 3, c += 4)
9661 f1 = RSurf_FogVertex(v);
9663 c[0] = c[0] * f1 + r_refdef.fogcolor[0] * f2;
9664 c[1] = c[1] * f1 + r_refdef.fogcolor[1] * f2;
9665 c[2] = c[2] * f1 + r_refdef.fogcolor[2] * f2;
9668 R_Mesh_PrepareVertices_Generic_Arrays(8, vertex3f, color4f, NULL);
9669 R_Mesh_ResetTextureState();
9670 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9671 R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0);
9674 static void R_DrawEntityBBoxes_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9678 prvm_edict_t *edict;
9679 prvm_prog_t *prog_save = prog;
9681 // this function draws bounding boxes of server entities
9685 GL_CullFace(GL_NONE);
9686 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9690 for (i = 0;i < numsurfaces;i++)
9692 edict = PRVM_EDICT_NUM(surfacelist[i]);
9693 switch ((int)edict->fields.server->solid)
9695 case SOLID_NOT: Vector4Set(color, 1, 1, 1, 0.05);break;
9696 case SOLID_TRIGGER: Vector4Set(color, 1, 0, 1, 0.10);break;
9697 case SOLID_BBOX: Vector4Set(color, 0, 1, 0, 0.10);break;
9698 case SOLID_SLIDEBOX: Vector4Set(color, 1, 0, 0, 0.10);break;
9699 case SOLID_BSP: Vector4Set(color, 0, 0, 1, 0.05);break;
9700 default: Vector4Set(color, 0, 0, 0, 0.50);break;
9702 color[3] *= r_showbboxes.value;
9703 color[3] = bound(0, color[3], 1);
9704 GL_DepthTest(!r_showdisabledepthtest.integer);
9705 GL_CullFace(r_refdef.view.cullface_front);
9706 R_DrawBBoxMesh(edict->priv.server->areamins, edict->priv.server->areamaxs, color[0], color[1], color[2], color[3]);
9712 static void R_DrawEntityBBoxes(void)
9715 prvm_edict_t *edict;
9717 prvm_prog_t *prog_save = prog;
9719 // this function draws bounding boxes of server entities
9725 for (i = 0;i < prog->num_edicts;i++)
9727 edict = PRVM_EDICT_NUM(i);
9728 if (edict->priv.server->free)
9730 // exclude the following for now, as they don't live in world coordinate space and can't be solid:
9731 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.tag_entity)->edict != 0)
9733 if(PRVM_EDICTFIELDVALUE(edict, prog->fieldoffsets.viewmodelforclient)->edict != 0)
9735 VectorLerp(edict->priv.server->areamins, 0.5f, edict->priv.server->areamaxs, center);
9736 R_MeshQueue_AddTransparent(center, R_DrawEntityBBoxes_Callback, (entity_render_t *)NULL, i, (rtlight_t *)NULL);
9742 static const int nomodelelement3i[24] =
9754 static const unsigned short nomodelelement3s[24] =
9766 static const float nomodelvertex3f[6*3] =
9776 static const float nomodelcolor4f[6*4] =
9778 0.0f, 0.0f, 0.5f, 1.0f,
9779 0.0f, 0.0f, 0.5f, 1.0f,
9780 0.0f, 0.5f, 0.0f, 1.0f,
9781 0.0f, 0.5f, 0.0f, 1.0f,
9782 0.5f, 0.0f, 0.0f, 1.0f,
9783 0.5f, 0.0f, 0.0f, 1.0f
9786 void R_DrawNoModel_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
9792 RSurf_ActiveCustomEntity(&ent->matrix, &ent->inversematrix, ent->flags, ent->shadertime, ent->colormod[0], ent->colormod[1], ent->colormod[2], ent->alpha, 6, nomodelvertex3f, NULL, NULL, NULL, NULL, nomodelcolor4f, 8, nomodelelement3i, nomodelelement3s, false, false);
9794 // this is only called once per entity so numsurfaces is always 1, and
9795 // surfacelist is always {0}, so this code does not handle batches
9797 if (rsurface.ent_flags & RENDER_ADDITIVE)
9799 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
9800 GL_DepthMask(false);
9802 else if (rsurface.colormod[3] < 1)
9804 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
9805 GL_DepthMask(false);
9809 GL_BlendFunc(GL_ONE, GL_ZERO);
9812 GL_DepthRange(0, (rsurface.ent_flags & RENDER_VIEWMODEL) ? 0.0625 : 1);
9813 GL_PolygonOffset(rsurface.basepolygonfactor, rsurface.basepolygonoffset);
9814 GL_DepthTest(!(rsurface.ent_flags & RENDER_NODEPTHTEST));
9815 GL_CullFace((rsurface.ent_flags & RENDER_DOUBLESIDED) ? GL_NONE : r_refdef.view.cullface_back);
9816 memcpy(color4f, nomodelcolor4f, sizeof(float[6*4]));
9817 for (i = 0, c = color4f;i < 6;i++, c += 4)
9819 c[0] *= rsurface.colormod[0];
9820 c[1] *= rsurface.colormod[1];
9821 c[2] *= rsurface.colormod[2];
9822 c[3] *= rsurface.colormod[3];
9824 if (r_refdef.fogenabled)
9826 for (i = 0, c = color4f;i < 6;i++, c += 4)
9828 f1 = RSurf_FogVertex(nomodelvertex3f + 3*i);
9830 c[0] = (c[0] * f1 + r_refdef.fogcolor[0] * f2);
9831 c[1] = (c[1] * f1 + r_refdef.fogcolor[1] * f2);
9832 c[2] = (c[2] * f1 + r_refdef.fogcolor[2] * f2);
9835 // R_Mesh_ResetTextureState();
9836 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
9837 R_Mesh_PrepareVertices_Generic_Arrays(6, nomodelvertex3f, color4f, NULL);
9838 R_Mesh_Draw(0, 6, 0, 8, nomodelelement3i, NULL, 0, nomodelelement3s, NULL, 0);
9841 void R_DrawNoModel(entity_render_t *ent)
9844 Matrix4x4_OriginFromMatrix(&ent->matrix, org);
9845 if ((ent->flags & RENDER_ADDITIVE) || (ent->alpha < 1))
9846 R_MeshQueue_AddTransparent(ent->flags & RENDER_NODEPTHTEST ? r_refdef.view.origin : org, R_DrawNoModel_TransparentCallback, ent, 0, rsurface.rtlight);
9848 R_DrawNoModel_TransparentCallback(ent, rsurface.rtlight, 0, NULL);
9851 void R_CalcBeam_Vertex3f (float *vert, const vec3_t org1, const vec3_t org2, float width)
9853 vec3_t right1, right2, diff, normal;
9855 VectorSubtract (org2, org1, normal);
9857 // calculate 'right' vector for start
9858 VectorSubtract (r_refdef.view.origin, org1, diff);
9859 CrossProduct (normal, diff, right1);
9860 VectorNormalize (right1);
9862 // calculate 'right' vector for end
9863 VectorSubtract (r_refdef.view.origin, org2, diff);
9864 CrossProduct (normal, diff, right2);
9865 VectorNormalize (right2);
9867 vert[ 0] = org1[0] + width * right1[0];
9868 vert[ 1] = org1[1] + width * right1[1];
9869 vert[ 2] = org1[2] + width * right1[2];
9870 vert[ 3] = org1[0] - width * right1[0];
9871 vert[ 4] = org1[1] - width * right1[1];
9872 vert[ 5] = org1[2] - width * right1[2];
9873 vert[ 6] = org2[0] - width * right2[0];
9874 vert[ 7] = org2[1] - width * right2[1];
9875 vert[ 8] = org2[2] - width * right2[2];
9876 vert[ 9] = org2[0] + width * right2[0];
9877 vert[10] = org2[1] + width * right2[1];
9878 vert[11] = org2[2] + width * right2[2];
9881 void R_CalcSprite_Vertex3f(float *vertex3f, const vec3_t origin, const vec3_t left, const vec3_t up, float scalex1, float scalex2, float scaley1, float scaley2)
9883 vertex3f[ 0] = origin[0] + left[0] * scalex2 + up[0] * scaley1;
9884 vertex3f[ 1] = origin[1] + left[1] * scalex2 + up[1] * scaley1;
9885 vertex3f[ 2] = origin[2] + left[2] * scalex2 + up[2] * scaley1;
9886 vertex3f[ 3] = origin[0] + left[0] * scalex2 + up[0] * scaley2;
9887 vertex3f[ 4] = origin[1] + left[1] * scalex2 + up[1] * scaley2;
9888 vertex3f[ 5] = origin[2] + left[2] * scalex2 + up[2] * scaley2;
9889 vertex3f[ 6] = origin[0] + left[0] * scalex1 + up[0] * scaley2;
9890 vertex3f[ 7] = origin[1] + left[1] * scalex1 + up[1] * scaley2;
9891 vertex3f[ 8] = origin[2] + left[2] * scalex1 + up[2] * scaley2;
9892 vertex3f[ 9] = origin[0] + left[0] * scalex1 + up[0] * scaley1;
9893 vertex3f[10] = origin[1] + left[1] * scalex1 + up[1] * scaley1;
9894 vertex3f[11] = origin[2] + left[2] * scalex1 + up[2] * scaley1;
9897 int R_Mesh_AddVertex(rmesh_t *mesh, float x, float y, float z)
9902 VectorSet(v, x, y, z);
9903 for (i = 0, vertex3f = mesh->vertex3f;i < mesh->numvertices;i++, vertex3f += 3)
9904 if (VectorDistance2(v, vertex3f) < mesh->epsilon2)
9906 if (i == mesh->numvertices)
9908 if (mesh->numvertices < mesh->maxvertices)
9910 VectorCopy(v, vertex3f);
9911 mesh->numvertices++;
9913 return mesh->numvertices;
9919 void R_Mesh_AddPolygon3f(rmesh_t *mesh, int numvertices, float *vertex3f)
9923 element[0] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9924 element[1] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);vertex3f += 3;
9925 e = mesh->element3i + mesh->numtriangles * 3;
9926 for (i = 0;i < numvertices - 2;i++, vertex3f += 3)
9928 element[2] = R_Mesh_AddVertex(mesh, vertex3f[0], vertex3f[1], vertex3f[2]);
9929 if (mesh->numtriangles < mesh->maxtriangles)
9934 mesh->numtriangles++;
9936 element[1] = element[2];
9940 void R_Mesh_AddPolygon3d(rmesh_t *mesh, int numvertices, double *vertex3d)
9944 element[0] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9945 element[1] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);vertex3d += 3;
9946 e = mesh->element3i + mesh->numtriangles * 3;
9947 for (i = 0;i < numvertices - 2;i++, vertex3d += 3)
9949 element[2] = R_Mesh_AddVertex(mesh, vertex3d[0], vertex3d[1], vertex3d[2]);
9950 if (mesh->numtriangles < mesh->maxtriangles)
9955 mesh->numtriangles++;
9957 element[1] = element[2];
9961 #define R_MESH_PLANE_DIST_EPSILON (1.0 / 32.0)
9962 void R_Mesh_AddBrushMeshFromPlanes(rmesh_t *mesh, int numplanes, mplane_t *planes)
9964 int planenum, planenum2;
9967 mplane_t *plane, *plane2;
9969 double temppoints[2][256*3];
9970 // figure out how large a bounding box we need to properly compute this brush
9972 for (w = 0;w < numplanes;w++)
9973 maxdist = max(maxdist, fabs(planes[w].dist));
9974 // now make it large enough to enclose the entire brush, and round it off to a reasonable multiple of 1024
9975 maxdist = floor(maxdist * (4.0 / 1024.0) + 1) * 1024.0;
9976 for (planenum = 0, plane = planes;planenum < numplanes;planenum++, plane++)
9980 PolygonD_QuadForPlane(temppoints[w], plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, maxdist);
9981 for (planenum2 = 0, plane2 = planes;planenum2 < numplanes && tempnumpoints >= 3;planenum2++, plane2++)
9983 if (planenum2 == planenum)
9985 PolygonD_Divide(tempnumpoints, temppoints[w], plane2->normal[0], plane2->normal[1], plane2->normal[2], plane2->dist, R_MESH_PLANE_DIST_EPSILON, 0, NULL, NULL, 256, temppoints[!w], &tempnumpoints, NULL);
9988 if (tempnumpoints < 3)
9990 // generate elements forming a triangle fan for this polygon
9991 R_Mesh_AddPolygon3d(mesh, tempnumpoints, temppoints[w]);
9995 static void R_Texture_AddLayer(texture_t *t, qboolean depthmask, int blendfunc1, int blendfunc2, texturelayertype_t type, rtexture_t *texture, const matrix4x4_t *matrix, float r, float g, float b, float a)
9997 texturelayer_t *layer;
9998 layer = t->currentlayers + t->currentnumlayers++;
10000 layer->depthmask = depthmask;
10001 layer->blendfunc1 = blendfunc1;
10002 layer->blendfunc2 = blendfunc2;
10003 layer->texture = texture;
10004 layer->texmatrix = *matrix;
10005 layer->color[0] = r;
10006 layer->color[1] = g;
10007 layer->color[2] = b;
10008 layer->color[3] = a;
10011 static qboolean R_TestQ3WaveFunc(q3wavefunc_t func, const float *parms)
10013 if(parms[0] == 0 && parms[1] == 0)
10015 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10016 if(rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)] == 0)
10021 static float R_EvaluateQ3WaveFunc(q3wavefunc_t func, const float *parms)
10024 index = parms[2] + r_refdef.scene.time * parms[3];
10025 index -= floor(index);
10026 switch (func & ((1 << Q3WAVEFUNC_USER_SHIFT) - 1))
10029 case Q3WAVEFUNC_NONE:
10030 case Q3WAVEFUNC_NOISE:
10031 case Q3WAVEFUNC_COUNT:
10034 case Q3WAVEFUNC_SIN: f = sin(index * M_PI * 2);break;
10035 case Q3WAVEFUNC_SQUARE: f = index < 0.5 ? 1 : -1;break;
10036 case Q3WAVEFUNC_SAWTOOTH: f = index;break;
10037 case Q3WAVEFUNC_INVERSESAWTOOTH: f = 1 - index;break;
10038 case Q3WAVEFUNC_TRIANGLE:
10040 f = index - floor(index);
10043 else if (index < 2)
10045 else if (index < 3)
10051 f = parms[0] + parms[1] * f;
10052 if(func >> Q3WAVEFUNC_USER_SHIFT) // assumes rsurface to be set!
10053 f *= rsurface.userwavefunc_param[bound(0, (func >> Q3WAVEFUNC_USER_SHIFT) - 1, Q3WAVEFUNC_USER_COUNT)];
10057 void R_tcMod_ApplyToMatrix(matrix4x4_t *texmatrix, q3shaderinfo_layer_tcmod_t *tcmod, int currentmaterialflags)
10062 matrix4x4_t matrix, temp;
10063 switch(tcmod->tcmod)
10065 case Q3TCMOD_COUNT:
10067 if (currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10068 matrix = r_waterscrollmatrix;
10070 matrix = identitymatrix;
10072 case Q3TCMOD_ENTITYTRANSLATE:
10073 // this is used in Q3 to allow the gamecode to control texcoord
10074 // scrolling on the entity, which is not supported in darkplaces yet.
10075 Matrix4x4_CreateTranslate(&matrix, 0, 0, 0);
10077 case Q3TCMOD_ROTATE:
10078 Matrix4x4_CreateTranslate(&matrix, 0.5, 0.5, 0);
10079 Matrix4x4_ConcatRotate(&matrix, tcmod->parms[0] * r_refdef.scene.time, 0, 0, 1);
10080 Matrix4x4_ConcatTranslate(&matrix, -0.5, -0.5, 0);
10082 case Q3TCMOD_SCALE:
10083 Matrix4x4_CreateScale3(&matrix, tcmod->parms[0], tcmod->parms[1], 1);
10085 case Q3TCMOD_SCROLL:
10086 Matrix4x4_CreateTranslate(&matrix, tcmod->parms[0] * r_refdef.scene.time, tcmod->parms[1] * r_refdef.scene.time, 0);
10088 case Q3TCMOD_PAGE: // poor man's animmap (to store animations into a single file, useful for HTTP downloaded textures)
10089 w = (int) tcmod->parms[0];
10090 h = (int) tcmod->parms[1];
10091 f = r_refdef.scene.time / (tcmod->parms[2] * w * h);
10093 idx = (int) floor(f * w * h);
10094 Matrix4x4_CreateTranslate(&matrix, (idx % w) / tcmod->parms[0], (idx / w) / tcmod->parms[1], 0);
10096 case Q3TCMOD_STRETCH:
10097 f = 1.0f / R_EvaluateQ3WaveFunc(tcmod->wavefunc, tcmod->waveparms);
10098 Matrix4x4_CreateFromQuakeEntity(&matrix, 0.5f * (1 - f), 0.5 * (1 - f), 0, 0, 0, 0, f);
10100 case Q3TCMOD_TRANSFORM:
10101 VectorSet(tcmat + 0, tcmod->parms[0], tcmod->parms[1], 0);
10102 VectorSet(tcmat + 3, tcmod->parms[2], tcmod->parms[3], 0);
10103 VectorSet(tcmat + 6, 0 , 0 , 1);
10104 VectorSet(tcmat + 9, tcmod->parms[4], tcmod->parms[5], 0);
10105 Matrix4x4_FromArray12FloatGL(&matrix, tcmat);
10107 case Q3TCMOD_TURBULENT:
10108 // this is handled in the RSurf_PrepareVertices function
10109 matrix = identitymatrix;
10113 Matrix4x4_Concat(texmatrix, &matrix, &temp);
10116 void R_LoadQWSkin(r_qwskincache_t *cache, const char *skinname)
10118 int textureflags = (r_mipskins.integer ? TEXF_MIPMAP : 0) | TEXF_PICMIP | TEXF_COMPRESS;
10119 char name[MAX_QPATH];
10120 skinframe_t *skinframe;
10121 unsigned char pixels[296*194];
10122 strlcpy(cache->name, skinname, sizeof(cache->name));
10123 dpsnprintf(name, sizeof(name), "skins/%s.pcx", cache->name);
10124 if (developer_loading.integer)
10125 Con_Printf("loading %s\n", name);
10126 skinframe = R_SkinFrame_Find(name, textureflags, 0, 0, 0, false);
10127 if (!skinframe || !skinframe->base)
10130 fs_offset_t filesize;
10132 f = FS_LoadFile(name, tempmempool, true, &filesize);
10135 if (LoadPCX_QWSkin(f, (int)filesize, pixels, 296, 194))
10136 skinframe = R_SkinFrame_LoadInternalQuake(name, textureflags, true, r_fullbrights.integer, pixels, image_width, image_height);
10140 cache->skinframe = skinframe;
10143 texture_t *R_GetCurrentTexture(texture_t *t)
10146 const entity_render_t *ent = rsurface.entity;
10147 dp_model_t *model = ent->model;
10148 q3shaderinfo_layer_tcmod_t *tcmod;
10150 if (t->update_lastrenderframe == r_textureframe && t->update_lastrenderentity == (void *)ent)
10151 return t->currentframe;
10152 t->update_lastrenderframe = r_textureframe;
10153 t->update_lastrenderentity = (void *)ent;
10155 if(ent && ent->entitynumber >= MAX_EDICTS && ent->entitynumber < 2 * MAX_EDICTS)
10156 t->camera_entity = ent->entitynumber;
10158 t->camera_entity = 0;
10160 // switch to an alternate material if this is a q1bsp animated material
10162 texture_t *texture = t;
10163 int s = rsurface.ent_skinnum;
10164 if ((unsigned int)s >= (unsigned int)model->numskins)
10166 if (model->skinscenes)
10168 if (model->skinscenes[s].framecount > 1)
10169 s = model->skinscenes[s].firstframe + (unsigned int) (r_refdef.scene.time * model->skinscenes[s].framerate) % model->skinscenes[s].framecount;
10171 s = model->skinscenes[s].firstframe;
10174 t = t + s * model->num_surfaces;
10177 // use an alternate animation if the entity's frame is not 0,
10178 // and only if the texture has an alternate animation
10179 if (rsurface.ent_alttextures && t->anim_total[1])
10180 t = t->anim_frames[1][(t->anim_total[1] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[1]) : 0];
10182 t = t->anim_frames[0][(t->anim_total[0] >= 2) ? ((int)(r_refdef.scene.time * 5.0f) % t->anim_total[0]) : 0];
10184 texture->currentframe = t;
10187 // update currentskinframe to be a qw skin or animation frame
10188 if (rsurface.ent_qwskin >= 0)
10190 i = rsurface.ent_qwskin;
10191 if (!r_qwskincache || r_qwskincache_size != cl.maxclients)
10193 r_qwskincache_size = cl.maxclients;
10195 Mem_Free(r_qwskincache);
10196 r_qwskincache = (r_qwskincache_t *)Mem_Alloc(r_main_mempool, sizeof(*r_qwskincache) * r_qwskincache_size);
10198 if (strcmp(r_qwskincache[i].name, cl.scores[i].qw_skin))
10199 R_LoadQWSkin(&r_qwskincache[i], cl.scores[i].qw_skin);
10200 t->currentskinframe = r_qwskincache[i].skinframe;
10201 if (t->currentskinframe == NULL)
10202 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10204 else if (t->numskinframes >= 2)
10205 t->currentskinframe = t->skinframes[(unsigned int)(t->skinframerate * (cl.time - rsurface.ent_shadertime)) % t->numskinframes];
10206 if (t->backgroundnumskinframes >= 2)
10207 t->backgroundcurrentskinframe = t->backgroundskinframes[(unsigned int)(t->backgroundskinframerate * (cl.time - rsurface.ent_shadertime)) % t->backgroundnumskinframes];
10209 t->currentmaterialflags = t->basematerialflags;
10210 t->currentalpha = rsurface.colormod[3];
10211 if (t->basematerialflags & MATERIALFLAG_WATERALPHA && (model->brush.supportwateralpha || r_novis.integer))
10212 t->currentalpha *= r_wateralpha.value;
10213 if(t->basematerialflags & MATERIALFLAG_WATERSHADER && r_waterstate.enabled && !r_refdef.view.isoverlay)
10214 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW; // we apply wateralpha later
10215 if(!r_waterstate.enabled || r_refdef.view.isoverlay)
10216 t->currentmaterialflags &= ~(MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA);
10217 if (!(rsurface.ent_flags & RENDER_LIGHT))
10218 t->currentmaterialflags |= MATERIALFLAG_FULLBRIGHT;
10219 else if (FAKELIGHT_ENABLED)
10221 // no modellight if using fakelight for the map
10223 else if (rsurface.modeltexcoordlightmap2f == NULL && !(t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT))
10225 // pick a model lighting mode
10226 if (VectorLength2(rsurface.modellight_diffuse) >= (1.0f / 256.0f))
10227 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL;
10229 t->currentmaterialflags |= MATERIALFLAG_MODELLIGHT;
10231 if (rsurface.ent_flags & RENDER_ADDITIVE)
10232 t->currentmaterialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10233 else if (t->currentalpha < 1)
10234 t->currentmaterialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
10235 if (rsurface.ent_flags & RENDER_DOUBLESIDED)
10236 t->currentmaterialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
10237 if (rsurface.ent_flags & (RENDER_NODEPTHTEST | RENDER_VIEWMODEL))
10238 t->currentmaterialflags |= MATERIALFLAG_SHORTDEPTHRANGE;
10239 if (t->backgroundnumskinframes)
10240 t->currentmaterialflags |= MATERIALFLAG_VERTEXTEXTUREBLEND;
10241 if (t->currentmaterialflags & MATERIALFLAG_BLENDED)
10243 if (t->currentmaterialflags & (MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA))
10244 t->currentmaterialflags &= ~MATERIALFLAG_BLENDED;
10247 t->currentmaterialflags &= ~(MATERIALFLAG_REFRACTION | MATERIALFLAG_WATERSHADER | MATERIALFLAG_CAMERA);
10248 if ((t->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST)) == MATERIALFLAG_BLENDED && r_transparentdepthmasking.integer && !(t->basematerialflags & MATERIALFLAG_BLENDED))
10249 t->currentmaterialflags |= MATERIALFLAG_TRANSDEPTH;
10251 // there is no tcmod
10252 if (t->currentmaterialflags & MATERIALFLAG_WATERSCROLL)
10254 t->currenttexmatrix = r_waterscrollmatrix;
10255 t->currentbackgroundtexmatrix = r_waterscrollmatrix;
10257 else if (!(t->currentmaterialflags & MATERIALFLAG_CUSTOMSURFACE))
10259 Matrix4x4_CreateIdentity(&t->currenttexmatrix);
10260 Matrix4x4_CreateIdentity(&t->currentbackgroundtexmatrix);
10263 for (i = 0, tcmod = t->tcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10264 R_tcMod_ApplyToMatrix(&t->currenttexmatrix, tcmod, t->currentmaterialflags);
10265 for (i = 0, tcmod = t->backgroundtcmods;i < Q3MAXTCMODS && tcmod->tcmod;i++, tcmod++)
10266 R_tcMod_ApplyToMatrix(&t->currentbackgroundtexmatrix, tcmod, t->currentmaterialflags);
10268 t->colormapping = VectorLength2(rsurface.colormap_pantscolor) + VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f);
10269 if (t->currentskinframe->qpixels)
10270 R_SkinFrame_GenerateTexturesFromQPixels(t->currentskinframe, t->colormapping);
10271 t->basetexture = (!t->colormapping && t->currentskinframe->merged) ? t->currentskinframe->merged : t->currentskinframe->base;
10272 if (!t->basetexture)
10273 t->basetexture = r_texture_notexture;
10274 t->pantstexture = t->colormapping ? t->currentskinframe->pants : NULL;
10275 t->shirttexture = t->colormapping ? t->currentskinframe->shirt : NULL;
10276 t->nmaptexture = t->currentskinframe->nmap;
10277 if (!t->nmaptexture)
10278 t->nmaptexture = r_texture_blanknormalmap;
10279 t->glosstexture = r_texture_black;
10280 t->glowtexture = t->currentskinframe->glow;
10281 t->fogtexture = t->currentskinframe->fog;
10282 t->reflectmasktexture = t->currentskinframe->reflect;
10283 if (t->backgroundnumskinframes)
10285 t->backgroundbasetexture = (!t->colormapping && t->backgroundcurrentskinframe->merged) ? t->backgroundcurrentskinframe->merged : t->backgroundcurrentskinframe->base;
10286 t->backgroundnmaptexture = t->backgroundcurrentskinframe->nmap;
10287 t->backgroundglosstexture = r_texture_black;
10288 t->backgroundglowtexture = t->backgroundcurrentskinframe->glow;
10289 if (!t->backgroundnmaptexture)
10290 t->backgroundnmaptexture = r_texture_blanknormalmap;
10294 t->backgroundbasetexture = r_texture_white;
10295 t->backgroundnmaptexture = r_texture_blanknormalmap;
10296 t->backgroundglosstexture = r_texture_black;
10297 t->backgroundglowtexture = NULL;
10299 t->specularpower = r_shadow_glossexponent.value;
10300 // TODO: store reference values for these in the texture?
10301 t->specularscale = 0;
10302 if (r_shadow_gloss.integer > 0)
10304 if (t->currentskinframe->gloss || (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss))
10306 if (r_shadow_glossintensity.value > 0)
10308 t->glosstexture = t->currentskinframe->gloss ? t->currentskinframe->gloss : r_texture_white;
10309 t->backgroundglosstexture = (t->backgroundcurrentskinframe && t->backgroundcurrentskinframe->gloss) ? t->backgroundcurrentskinframe->gloss : r_texture_white;
10310 t->specularscale = r_shadow_glossintensity.value;
10313 else if (r_shadow_gloss.integer >= 2 && r_shadow_gloss2intensity.value > 0)
10315 t->glosstexture = r_texture_white;
10316 t->backgroundglosstexture = r_texture_white;
10317 t->specularscale = r_shadow_gloss2intensity.value;
10318 t->specularpower = r_shadow_gloss2exponent.value;
10321 t->specularscale *= t->specularscalemod;
10322 t->specularpower *= t->specularpowermod;
10324 // lightmaps mode looks bad with dlights using actual texturing, so turn
10325 // off the colormap and glossmap, but leave the normalmap on as it still
10326 // accurately represents the shading involved
10327 if (gl_lightmaps.integer)
10329 t->basetexture = r_texture_grey128;
10330 t->pantstexture = r_texture_black;
10331 t->shirttexture = r_texture_black;
10332 t->nmaptexture = r_texture_blanknormalmap;
10333 t->glosstexture = r_texture_black;
10334 t->glowtexture = NULL;
10335 t->fogtexture = NULL;
10336 t->reflectmasktexture = NULL;
10337 t->backgroundbasetexture = NULL;
10338 t->backgroundnmaptexture = r_texture_blanknormalmap;
10339 t->backgroundglosstexture = r_texture_black;
10340 t->backgroundglowtexture = NULL;
10341 t->specularscale = 0;
10342 t->currentmaterialflags = MATERIALFLAG_WALL | (t->currentmaterialflags & (MATERIALFLAG_NOCULLFACE | MATERIALFLAG_MODELLIGHT | MATERIALFLAG_MODELLIGHT_DIRECTIONAL | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SHORTDEPTHRANGE));
10345 Vector4Set(t->lightmapcolor, rsurface.colormod[0], rsurface.colormod[1], rsurface.colormod[2], t->currentalpha);
10346 VectorClear(t->dlightcolor);
10347 t->currentnumlayers = 0;
10348 if (t->currentmaterialflags & MATERIALFLAG_WALL)
10350 int blendfunc1, blendfunc2;
10351 qboolean depthmask;
10352 if (t->currentmaterialflags & MATERIALFLAG_ADD)
10354 blendfunc1 = GL_SRC_ALPHA;
10355 blendfunc2 = GL_ONE;
10357 else if (t->currentmaterialflags & MATERIALFLAG_ALPHA)
10359 blendfunc1 = GL_SRC_ALPHA;
10360 blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
10362 else if (t->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
10364 blendfunc1 = t->customblendfunc[0];
10365 blendfunc2 = t->customblendfunc[1];
10369 blendfunc1 = GL_ONE;
10370 blendfunc2 = GL_ZERO;
10372 // don't colormod evilblend textures
10373 if(!R_BlendFuncAllowsColormod(blendfunc1, blendfunc2))
10374 VectorSet(t->lightmapcolor, 1, 1, 1);
10375 depthmask = !(t->currentmaterialflags & MATERIALFLAG_BLENDED);
10376 if (t->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
10378 // fullbright is not affected by r_refdef.lightmapintensity
10379 R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
10380 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10381 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10382 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10383 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10387 vec3_t ambientcolor;
10389 // set the color tint used for lights affecting this surface
10390 VectorSet(t->dlightcolor, t->lightmapcolor[0] * t->lightmapcolor[3], t->lightmapcolor[1] * t->lightmapcolor[3], t->lightmapcolor[2] * t->lightmapcolor[3]);
10392 // q3bsp has no lightmap updates, so the lightstylevalue that
10393 // would normally be baked into the lightmap must be
10394 // applied to the color
10395 // FIXME: r_glsl 1 rendering doesn't support overbright lightstyles with this (the default light style is not overbright)
10396 if (model->type == mod_brushq3)
10397 colorscale *= r_refdef.scene.rtlightstylevalue[0];
10398 colorscale *= r_refdef.lightmapintensity;
10399 VectorScale(t->lightmapcolor, r_refdef.scene.ambient, ambientcolor);
10400 VectorScale(t->lightmapcolor, colorscale, t->lightmapcolor);
10401 // basic lit geometry
10402 R_Texture_AddLayer(t, depthmask, blendfunc1, blendfunc2, TEXTURELAYERTYPE_LITTEXTURE, t->basetexture, &t->currenttexmatrix, t->lightmapcolor[0], t->lightmapcolor[1], t->lightmapcolor[2], t->lightmapcolor[3]);
10403 // add pants/shirt if needed
10404 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10405 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * t->lightmapcolor[0], rsurface.colormap_pantscolor[1] * t->lightmapcolor[1], rsurface.colormap_pantscolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10406 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10407 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_LITTEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * t->lightmapcolor[0], rsurface.colormap_shirtcolor[1] * t->lightmapcolor[1], rsurface.colormap_shirtcolor[2] * t->lightmapcolor[2], t->lightmapcolor[3]);
10408 // now add ambient passes if needed
10409 if (VectorLength2(ambientcolor) >= (1.0f/1048576.0f))
10411 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->basetexture, &t->currenttexmatrix, ambientcolor[0], ambientcolor[1], ambientcolor[2], t->lightmapcolor[3]);
10412 if (VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f) && t->pantstexture)
10413 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->pantstexture, &t->currenttexmatrix, rsurface.colormap_pantscolor[0] * ambientcolor[0], rsurface.colormap_pantscolor[1] * ambientcolor[1], rsurface.colormap_pantscolor[2] * ambientcolor[2], t->lightmapcolor[3]);
10414 if (VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f) && t->shirttexture)
10415 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->shirttexture, &t->currenttexmatrix, rsurface.colormap_shirtcolor[0] * ambientcolor[0], rsurface.colormap_shirtcolor[1] * ambientcolor[1], rsurface.colormap_shirtcolor[2] * ambientcolor[2], t->lightmapcolor[3]);
10418 if (t->glowtexture != NULL && !gl_lightmaps.integer)
10419 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, GL_ONE, TEXTURELAYERTYPE_TEXTURE, t->glowtexture, &t->currenttexmatrix, rsurface.glowmod[0], rsurface.glowmod[1], rsurface.glowmod[2], t->lightmapcolor[3]);
10420 if (r_refdef.fogenabled && !(t->currentmaterialflags & MATERIALFLAG_ADD))
10422 // if this is opaque use alpha blend which will darken the earlier
10425 // if this is an alpha blended material, all the earlier passes
10426 // were darkened by fog already, so we only need to add the fog
10427 // color ontop through the fog mask texture
10429 // if this is an additive blended material, all the earlier passes
10430 // were darkened by fog already, and we should not add fog color
10431 // (because the background was not darkened, there is no fog color
10432 // that was lost behind it).
10433 R_Texture_AddLayer(t, false, GL_SRC_ALPHA, (t->currentmaterialflags & MATERIALFLAG_BLENDED) ? GL_ONE : GL_ONE_MINUS_SRC_ALPHA, TEXTURELAYERTYPE_FOG, t->fogtexture, &t->currenttexmatrix, r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], t->lightmapcolor[3]);
10437 return t->currentframe;
10440 rsurfacestate_t rsurface;
10442 void RSurf_ActiveWorldEntity(void)
10444 dp_model_t *model = r_refdef.scene.worldmodel;
10445 //if (rsurface.entity == r_refdef.scene.worldentity)
10447 rsurface.entity = r_refdef.scene.worldentity;
10448 rsurface.skeleton = NULL;
10449 memset(rsurface.userwavefunc_param, 0, sizeof(rsurface.userwavefunc_param));
10450 rsurface.ent_skinnum = 0;
10451 rsurface.ent_qwskin = -1;
10452 rsurface.ent_shadertime = 0;
10453 rsurface.ent_flags = r_refdef.scene.worldentity->flags;
10454 rsurface.matrix = identitymatrix;
10455 rsurface.inversematrix = identitymatrix;
10456 rsurface.matrixscale = 1;
10457 rsurface.inversematrixscale = 1;
10458 R_EntityMatrix(&identitymatrix);
10459 VectorCopy(r_refdef.view.origin, rsurface.localvieworigin);
10460 Vector4Copy(r_refdef.fogplane, rsurface.fogplane);
10461 rsurface.fograngerecip = r_refdef.fograngerecip;
10462 rsurface.fogheightfade = r_refdef.fogheightfade;
10463 rsurface.fogplaneviewdist = r_refdef.fogplaneviewdist;
10464 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10465 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10466 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10467 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10468 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10469 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10470 VectorSet(rsurface.colormod, r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale);
10471 rsurface.colormod[3] = 1;
10472 VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
10473 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10474 rsurface.frameblend[0].lerp = 1;
10475 rsurface.ent_alttextures = false;
10476 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10477 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10478 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10479 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10480 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10481 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10482 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10483 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10484 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10485 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10486 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10487 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10488 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10489 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10490 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10491 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10492 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10493 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10494 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10495 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10496 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10497 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10498 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10499 rsurface.modelelement3i = model->surfmesh.data_element3i;
10500 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10501 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10502 rsurface.modelelement3s = model->surfmesh.data_element3s;
10503 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10504 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10505 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10506 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10507 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10508 rsurface.modelsurfaces = model->data_surfaces;
10509 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10510 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10511 rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
10512 rsurface.modelgeneratedvertex = false;
10513 rsurface.batchgeneratedvertex = false;
10514 rsurface.batchfirstvertex = 0;
10515 rsurface.batchnumvertices = 0;
10516 rsurface.batchfirsttriangle = 0;
10517 rsurface.batchnumtriangles = 0;
10518 rsurface.batchvertex3f = NULL;
10519 rsurface.batchvertex3f_vertexbuffer = NULL;
10520 rsurface.batchvertex3f_bufferoffset = 0;
10521 rsurface.batchsvector3f = NULL;
10522 rsurface.batchsvector3f_vertexbuffer = NULL;
10523 rsurface.batchsvector3f_bufferoffset = 0;
10524 rsurface.batchtvector3f = NULL;
10525 rsurface.batchtvector3f_vertexbuffer = NULL;
10526 rsurface.batchtvector3f_bufferoffset = 0;
10527 rsurface.batchnormal3f = NULL;
10528 rsurface.batchnormal3f_vertexbuffer = NULL;
10529 rsurface.batchnormal3f_bufferoffset = 0;
10530 rsurface.batchlightmapcolor4f = NULL;
10531 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10532 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10533 rsurface.batchtexcoordtexture2f = NULL;
10534 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10535 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10536 rsurface.batchtexcoordlightmap2f = NULL;
10537 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10538 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10539 rsurface.batchvertexmesh = NULL;
10540 rsurface.batchvertexmeshbuffer = NULL;
10541 rsurface.batchvertex3fbuffer = NULL;
10542 rsurface.batchelement3i = NULL;
10543 rsurface.batchelement3i_indexbuffer = NULL;
10544 rsurface.batchelement3i_bufferoffset = 0;
10545 rsurface.batchelement3s = NULL;
10546 rsurface.batchelement3s_indexbuffer = NULL;
10547 rsurface.batchelement3s_bufferoffset = 0;
10548 rsurface.passcolor4f = NULL;
10549 rsurface.passcolor4f_vertexbuffer = NULL;
10550 rsurface.passcolor4f_bufferoffset = 0;
10553 void RSurf_ActiveModelEntity(const entity_render_t *ent, qboolean wantnormals, qboolean wanttangents, qboolean prepass)
10555 dp_model_t *model = ent->model;
10556 //if (rsurface.entity == ent && (!model->surfmesh.isanimated || (!wantnormals && !wanttangents)))
10558 rsurface.entity = (entity_render_t *)ent;
10559 rsurface.skeleton = ent->skeleton;
10560 memcpy(rsurface.userwavefunc_param, ent->userwavefunc_param, sizeof(rsurface.userwavefunc_param));
10561 rsurface.ent_skinnum = ent->skinnum;
10562 rsurface.ent_qwskin = (ent->entitynumber <= cl.maxclients && ent->entitynumber >= 1 && cls.protocol == PROTOCOL_QUAKEWORLD && cl.scores[ent->entitynumber - 1].qw_skin[0] && !strcmp(ent->model->name, "progs/player.mdl")) ? (ent->entitynumber - 1) : -1;
10563 rsurface.ent_shadertime = ent->shadertime;
10564 rsurface.ent_flags = ent->flags;
10565 rsurface.matrix = ent->matrix;
10566 rsurface.inversematrix = ent->inversematrix;
10567 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10568 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10569 R_EntityMatrix(&rsurface.matrix);
10570 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10571 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10572 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10573 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10574 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10575 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10576 VectorCopy(ent->modellight_ambient, rsurface.modellight_ambient);
10577 VectorCopy(ent->modellight_diffuse, rsurface.modellight_diffuse);
10578 VectorCopy(ent->modellight_lightdir, rsurface.modellight_lightdir);
10579 VectorCopy(ent->colormap_pantscolor, rsurface.colormap_pantscolor);
10580 VectorCopy(ent->colormap_shirtcolor, rsurface.colormap_shirtcolor);
10581 VectorScale(ent->colormod, r_refdef.view.colorscale, rsurface.colormod);
10582 rsurface.colormod[3] = ent->alpha;
10583 VectorScale(ent->glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, rsurface.glowmod);
10584 memcpy(rsurface.frameblend, ent->frameblend, sizeof(ent->frameblend));
10585 rsurface.ent_alttextures = ent->framegroupblend[0].frame != 0;
10586 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10587 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10588 if (ent->model->brush.submodel && !prepass)
10590 rsurface.basepolygonfactor += r_polygonoffset_submodel_factor.value;
10591 rsurface.basepolygonoffset += r_polygonoffset_submodel_offset.value;
10593 if (model->surfmesh.isanimated && model->AnimateVertices && (rsurface.frameblend[0].lerp != 1 || rsurface.frameblend[0].subframe != 0))
10595 if (ent->animcache_vertex3f)
10597 rsurface.modelvertex3f = ent->animcache_vertex3f;
10598 rsurface.modelsvector3f = wanttangents ? ent->animcache_svector3f : NULL;
10599 rsurface.modeltvector3f = wanttangents ? ent->animcache_tvector3f : NULL;
10600 rsurface.modelnormal3f = wantnormals ? ent->animcache_normal3f : NULL;
10601 rsurface.modelvertexmesh = ent->animcache_vertexmesh;
10602 rsurface.modelvertexmeshbuffer = ent->animcache_vertexmeshbuffer;
10603 rsurface.modelvertex3fbuffer = ent->animcache_vertex3fbuffer;
10605 else if (wanttangents)
10607 rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10608 rsurface.modelsvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10609 rsurface.modeltvector3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10610 rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10611 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, rsurface.modelsvector3f, rsurface.modeltvector3f);
10612 rsurface.modelvertexmesh = NULL;
10613 rsurface.modelvertexmeshbuffer = NULL;
10614 rsurface.modelvertex3fbuffer = NULL;
10616 else if (wantnormals)
10618 rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10619 rsurface.modelsvector3f = NULL;
10620 rsurface.modeltvector3f = NULL;
10621 rsurface.modelnormal3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10622 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, rsurface.modelnormal3f, NULL, NULL);
10623 rsurface.modelvertexmesh = NULL;
10624 rsurface.modelvertexmeshbuffer = NULL;
10625 rsurface.modelvertex3fbuffer = NULL;
10629 rsurface.modelvertex3f = (float *)R_FrameData_Alloc(model->surfmesh.num_vertices * sizeof(float[3]));
10630 rsurface.modelsvector3f = NULL;
10631 rsurface.modeltvector3f = NULL;
10632 rsurface.modelnormal3f = NULL;
10633 model->AnimateVertices(model, rsurface.frameblend, rsurface.skeleton, rsurface.modelvertex3f, NULL, NULL, NULL);
10634 rsurface.modelvertexmesh = NULL;
10635 rsurface.modelvertexmeshbuffer = NULL;
10636 rsurface.modelvertex3fbuffer = NULL;
10638 rsurface.modelvertex3f_vertexbuffer = 0;
10639 rsurface.modelvertex3f_bufferoffset = 0;
10640 rsurface.modelsvector3f_vertexbuffer = 0;
10641 rsurface.modelsvector3f_bufferoffset = 0;
10642 rsurface.modeltvector3f_vertexbuffer = 0;
10643 rsurface.modeltvector3f_bufferoffset = 0;
10644 rsurface.modelnormal3f_vertexbuffer = 0;
10645 rsurface.modelnormal3f_bufferoffset = 0;
10646 rsurface.modelgeneratedvertex = true;
10650 rsurface.modelvertex3f = model->surfmesh.data_vertex3f;
10651 rsurface.modelvertex3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10652 rsurface.modelvertex3f_bufferoffset = model->surfmesh.vbooffset_vertex3f;
10653 rsurface.modelsvector3f = model->surfmesh.data_svector3f;
10654 rsurface.modelsvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10655 rsurface.modelsvector3f_bufferoffset = model->surfmesh.vbooffset_svector3f;
10656 rsurface.modeltvector3f = model->surfmesh.data_tvector3f;
10657 rsurface.modeltvector3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10658 rsurface.modeltvector3f_bufferoffset = model->surfmesh.vbooffset_tvector3f;
10659 rsurface.modelnormal3f = model->surfmesh.data_normal3f;
10660 rsurface.modelnormal3f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10661 rsurface.modelnormal3f_bufferoffset = model->surfmesh.vbooffset_normal3f;
10662 rsurface.modelvertexmesh = model->surfmesh.vertexmesh;
10663 rsurface.modelvertexmeshbuffer = model->surfmesh.vertexmeshbuffer;
10664 rsurface.modelvertex3fbuffer = model->surfmesh.vertex3fbuffer;
10665 rsurface.modelgeneratedvertex = false;
10667 rsurface.modellightmapcolor4f = model->surfmesh.data_lightmapcolor4f;
10668 rsurface.modellightmapcolor4f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10669 rsurface.modellightmapcolor4f_bufferoffset = model->surfmesh.vbooffset_lightmapcolor4f;
10670 rsurface.modeltexcoordtexture2f = model->surfmesh.data_texcoordtexture2f;
10671 rsurface.modeltexcoordtexture2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10672 rsurface.modeltexcoordtexture2f_bufferoffset = model->surfmesh.vbooffset_texcoordtexture2f;
10673 rsurface.modeltexcoordlightmap2f = model->surfmesh.data_texcoordlightmap2f;
10674 rsurface.modeltexcoordlightmap2f_vertexbuffer = model->surfmesh.vbo_vertexbuffer;
10675 rsurface.modeltexcoordlightmap2f_bufferoffset = model->surfmesh.vbooffset_texcoordlightmap2f;
10676 rsurface.modelelement3i = model->surfmesh.data_element3i;
10677 rsurface.modelelement3i_indexbuffer = model->surfmesh.data_element3i_indexbuffer;
10678 rsurface.modelelement3i_bufferoffset = model->surfmesh.data_element3i_bufferoffset;
10679 rsurface.modelelement3s = model->surfmesh.data_element3s;
10680 rsurface.modelelement3s_indexbuffer = model->surfmesh.data_element3s_indexbuffer;
10681 rsurface.modelelement3s_bufferoffset = model->surfmesh.data_element3s_bufferoffset;
10682 rsurface.modellightmapoffsets = model->surfmesh.data_lightmapoffsets;
10683 rsurface.modelnumvertices = model->surfmesh.num_vertices;
10684 rsurface.modelnumtriangles = model->surfmesh.num_triangles;
10685 rsurface.modelsurfaces = model->data_surfaces;
10686 rsurface.batchgeneratedvertex = false;
10687 rsurface.batchfirstvertex = 0;
10688 rsurface.batchnumvertices = 0;
10689 rsurface.batchfirsttriangle = 0;
10690 rsurface.batchnumtriangles = 0;
10691 rsurface.batchvertex3f = NULL;
10692 rsurface.batchvertex3f_vertexbuffer = NULL;
10693 rsurface.batchvertex3f_bufferoffset = 0;
10694 rsurface.batchsvector3f = NULL;
10695 rsurface.batchsvector3f_vertexbuffer = NULL;
10696 rsurface.batchsvector3f_bufferoffset = 0;
10697 rsurface.batchtvector3f = NULL;
10698 rsurface.batchtvector3f_vertexbuffer = NULL;
10699 rsurface.batchtvector3f_bufferoffset = 0;
10700 rsurface.batchnormal3f = NULL;
10701 rsurface.batchnormal3f_vertexbuffer = NULL;
10702 rsurface.batchnormal3f_bufferoffset = 0;
10703 rsurface.batchlightmapcolor4f = NULL;
10704 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10705 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10706 rsurface.batchtexcoordtexture2f = NULL;
10707 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10708 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10709 rsurface.batchtexcoordlightmap2f = NULL;
10710 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10711 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10712 rsurface.batchvertexmesh = NULL;
10713 rsurface.batchvertexmeshbuffer = NULL;
10714 rsurface.batchvertex3fbuffer = NULL;
10715 rsurface.batchelement3i = NULL;
10716 rsurface.batchelement3i_indexbuffer = NULL;
10717 rsurface.batchelement3i_bufferoffset = 0;
10718 rsurface.batchelement3s = NULL;
10719 rsurface.batchelement3s_indexbuffer = NULL;
10720 rsurface.batchelement3s_bufferoffset = 0;
10721 rsurface.passcolor4f = NULL;
10722 rsurface.passcolor4f_vertexbuffer = NULL;
10723 rsurface.passcolor4f_bufferoffset = 0;
10726 void RSurf_ActiveCustomEntity(const matrix4x4_t *matrix, const matrix4x4_t *inversematrix, int entflags, double shadertime, float r, float g, float b, float a, int numvertices, const float *vertex3f, const float *texcoord2f, const float *normal3f, const float *svector3f, const float *tvector3f, const float *color4f, int numtriangles, const int *element3i, const unsigned short *element3s, qboolean wantnormals, qboolean wanttangents)
10728 rsurface.entity = r_refdef.scene.worldentity;
10729 rsurface.skeleton = NULL;
10730 rsurface.ent_skinnum = 0;
10731 rsurface.ent_qwskin = -1;
10732 rsurface.ent_shadertime = shadertime;
10733 rsurface.ent_flags = entflags;
10734 rsurface.modelnumvertices = numvertices;
10735 rsurface.modelnumtriangles = numtriangles;
10736 rsurface.matrix = *matrix;
10737 rsurface.inversematrix = *inversematrix;
10738 rsurface.matrixscale = Matrix4x4_ScaleFromMatrix(&rsurface.matrix);
10739 rsurface.inversematrixscale = 1.0f / rsurface.matrixscale;
10740 R_EntityMatrix(&rsurface.matrix);
10741 Matrix4x4_Transform(&rsurface.inversematrix, r_refdef.view.origin, rsurface.localvieworigin);
10742 Matrix4x4_TransformStandardPlane(&rsurface.inversematrix, r_refdef.fogplane[0], r_refdef.fogplane[1], r_refdef.fogplane[2], r_refdef.fogplane[3], rsurface.fogplane);
10743 rsurface.fogplaneviewdist *= rsurface.inversematrixscale;
10744 rsurface.fograngerecip = r_refdef.fograngerecip * rsurface.matrixscale;
10745 rsurface.fogheightfade = r_refdef.fogheightfade * rsurface.matrixscale;
10746 rsurface.fogmasktabledistmultiplier = FOGMASKTABLEWIDTH * rsurface.fograngerecip;
10747 VectorSet(rsurface.modellight_ambient, 0, 0, 0);
10748 VectorSet(rsurface.modellight_diffuse, 0, 0, 0);
10749 VectorSet(rsurface.modellight_lightdir, 0, 0, 1);
10750 VectorSet(rsurface.colormap_pantscolor, 0, 0, 0);
10751 VectorSet(rsurface.colormap_shirtcolor, 0, 0, 0);
10752 Vector4Set(rsurface.colormod, r * r_refdef.view.colorscale, g * r_refdef.view.colorscale, b * r_refdef.view.colorscale, a);
10753 VectorSet(rsurface.glowmod, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value, r_refdef.view.colorscale * r_hdr_glowintensity.value);
10754 memset(rsurface.frameblend, 0, sizeof(rsurface.frameblend));
10755 rsurface.frameblend[0].lerp = 1;
10756 rsurface.ent_alttextures = false;
10757 rsurface.basepolygonfactor = r_refdef.polygonfactor;
10758 rsurface.basepolygonoffset = r_refdef.polygonoffset;
10761 rsurface.modelvertex3f = (float *)vertex3f;
10762 rsurface.modelsvector3f = svector3f ? (float *)svector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10763 rsurface.modeltvector3f = tvector3f ? (float *)tvector3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10764 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10766 else if (wantnormals)
10768 rsurface.modelvertex3f = (float *)vertex3f;
10769 rsurface.modelsvector3f = NULL;
10770 rsurface.modeltvector3f = NULL;
10771 rsurface.modelnormal3f = normal3f ? (float *)normal3f : (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10775 rsurface.modelvertex3f = (float *)vertex3f;
10776 rsurface.modelsvector3f = NULL;
10777 rsurface.modeltvector3f = NULL;
10778 rsurface.modelnormal3f = NULL;
10780 rsurface.modelvertexmesh = NULL;
10781 rsurface.modelvertexmeshbuffer = NULL;
10782 rsurface.modelvertex3fbuffer = NULL;
10783 rsurface.modelvertex3f_vertexbuffer = 0;
10784 rsurface.modelvertex3f_bufferoffset = 0;
10785 rsurface.modelsvector3f_vertexbuffer = 0;
10786 rsurface.modelsvector3f_bufferoffset = 0;
10787 rsurface.modeltvector3f_vertexbuffer = 0;
10788 rsurface.modeltvector3f_bufferoffset = 0;
10789 rsurface.modelnormal3f_vertexbuffer = 0;
10790 rsurface.modelnormal3f_bufferoffset = 0;
10791 rsurface.modelgeneratedvertex = true;
10792 rsurface.modellightmapcolor4f = (float *)color4f;
10793 rsurface.modellightmapcolor4f_vertexbuffer = 0;
10794 rsurface.modellightmapcolor4f_bufferoffset = 0;
10795 rsurface.modeltexcoordtexture2f = (float *)texcoord2f;
10796 rsurface.modeltexcoordtexture2f_vertexbuffer = 0;
10797 rsurface.modeltexcoordtexture2f_bufferoffset = 0;
10798 rsurface.modeltexcoordlightmap2f = NULL;
10799 rsurface.modeltexcoordlightmap2f_vertexbuffer = 0;
10800 rsurface.modeltexcoordlightmap2f_bufferoffset = 0;
10801 rsurface.modelelement3i = (int *)element3i;
10802 rsurface.modelelement3i_indexbuffer = NULL;
10803 rsurface.modelelement3i_bufferoffset = 0;
10804 rsurface.modelelement3s = (unsigned short *)element3s;
10805 rsurface.modelelement3s_indexbuffer = NULL;
10806 rsurface.modelelement3s_bufferoffset = 0;
10807 rsurface.modellightmapoffsets = NULL;
10808 rsurface.modelsurfaces = NULL;
10809 rsurface.batchgeneratedvertex = false;
10810 rsurface.batchfirstvertex = 0;
10811 rsurface.batchnumvertices = 0;
10812 rsurface.batchfirsttriangle = 0;
10813 rsurface.batchnumtriangles = 0;
10814 rsurface.batchvertex3f = NULL;
10815 rsurface.batchvertex3f_vertexbuffer = NULL;
10816 rsurface.batchvertex3f_bufferoffset = 0;
10817 rsurface.batchsvector3f = NULL;
10818 rsurface.batchsvector3f_vertexbuffer = NULL;
10819 rsurface.batchsvector3f_bufferoffset = 0;
10820 rsurface.batchtvector3f = NULL;
10821 rsurface.batchtvector3f_vertexbuffer = NULL;
10822 rsurface.batchtvector3f_bufferoffset = 0;
10823 rsurface.batchnormal3f = NULL;
10824 rsurface.batchnormal3f_vertexbuffer = NULL;
10825 rsurface.batchnormal3f_bufferoffset = 0;
10826 rsurface.batchlightmapcolor4f = NULL;
10827 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
10828 rsurface.batchlightmapcolor4f_bufferoffset = 0;
10829 rsurface.batchtexcoordtexture2f = NULL;
10830 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
10831 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
10832 rsurface.batchtexcoordlightmap2f = NULL;
10833 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
10834 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
10835 rsurface.batchvertexmesh = NULL;
10836 rsurface.batchvertexmeshbuffer = NULL;
10837 rsurface.batchvertex3fbuffer = NULL;
10838 rsurface.batchelement3i = NULL;
10839 rsurface.batchelement3i_indexbuffer = NULL;
10840 rsurface.batchelement3i_bufferoffset = 0;
10841 rsurface.batchelement3s = NULL;
10842 rsurface.batchelement3s_indexbuffer = NULL;
10843 rsurface.batchelement3s_bufferoffset = 0;
10844 rsurface.passcolor4f = NULL;
10845 rsurface.passcolor4f_vertexbuffer = NULL;
10846 rsurface.passcolor4f_bufferoffset = 0;
10848 if (rsurface.modelnumvertices && rsurface.modelelement3i)
10850 if ((wantnormals || wanttangents) && !normal3f)
10852 rsurface.modelnormal3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10853 Mod_BuildNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modelelement3i, rsurface.modelnormal3f, r_smoothnormals_areaweighting.integer != 0);
10855 if (wanttangents && !svector3f)
10857 rsurface.modelsvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10858 rsurface.modeltvector3f = (float *)R_FrameData_Alloc(rsurface.modelnumvertices * sizeof(float[3]));
10859 Mod_BuildTextureVectorsFromNormals(0, rsurface.modelnumvertices, rsurface.modelnumtriangles, rsurface.modelvertex3f, rsurface.modeltexcoordtexture2f, rsurface.modelnormal3f, rsurface.modelelement3i, rsurface.modelsvector3f, rsurface.modeltvector3f, r_smoothnormals_areaweighting.integer != 0);
10864 float RSurf_FogPoint(const float *v)
10866 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10867 float FogPlaneViewDist = r_refdef.fogplaneviewdist;
10868 float FogPlaneVertexDist = DotProduct(r_refdef.fogplane, v) + r_refdef.fogplane[3];
10869 float FogHeightFade = r_refdef.fogheightfade;
10871 unsigned int fogmasktableindex;
10872 if (r_refdef.fogplaneviewabove)
10873 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10875 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10876 fogmasktableindex = (unsigned int)(VectorDistance(r_refdef.view.origin, v) * fogfrac * r_refdef.fogmasktabledistmultiplier);
10877 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10880 float RSurf_FogVertex(const float *v)
10882 // this code is identical to the USEFOGINSIDE/USEFOGOUTSIDE code in the shader
10883 float FogPlaneViewDist = rsurface.fogplaneviewdist;
10884 float FogPlaneVertexDist = DotProduct(rsurface.fogplane, v) + rsurface.fogplane[3];
10885 float FogHeightFade = rsurface.fogheightfade;
10887 unsigned int fogmasktableindex;
10888 if (r_refdef.fogplaneviewabove)
10889 fogfrac = min(0.0f, FogPlaneVertexDist) / (FogPlaneVertexDist - FogPlaneViewDist) * min(1.0f, min(0.0f, FogPlaneVertexDist) * FogHeightFade);
10891 fogfrac = FogPlaneViewDist / (FogPlaneViewDist - max(0.0f, FogPlaneVertexDist)) * min(1.0f, (min(0.0f, FogPlaneVertexDist) + FogPlaneViewDist) * FogHeightFade);
10892 fogmasktableindex = (unsigned int)(VectorDistance(rsurface.localvieworigin, v) * fogfrac * rsurface.fogmasktabledistmultiplier);
10893 return r_refdef.fogmasktable[min(fogmasktableindex, FOGMASKTABLEWIDTH - 1)];
10896 void RSurf_RenumberElements(const int *inelement3i, int *outelement3i, int numelements, int adjust)
10899 for (i = 0;i < numelements;i++)
10900 outelement3i[i] = inelement3i[i] + adjust;
10903 static const int quadedges[6][2] = {{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}};
10904 extern cvar_t gl_vbo;
10905 void RSurf_PrepareVerticesForBatch(int batchneed, int texturenumsurfaces, const msurface_t **texturesurfacelist)
10913 int surfacefirsttriangle;
10914 int surfacenumtriangles;
10915 int surfacefirstvertex;
10916 int surfaceendvertex;
10917 int surfacenumvertices;
10918 int batchnumvertices;
10919 int batchnumtriangles;
10923 qboolean dynamicvertex;
10927 float center[3], forward[3], right[3], up[3], v[3], newforward[3], newright[3], newup[3];
10928 float waveparms[4];
10929 q3shaderinfo_deform_t *deform;
10930 const msurface_t *surface, *firstsurface;
10931 r_vertexmesh_t *vertexmesh;
10932 if (!texturenumsurfaces)
10934 // find vertex range of this surface batch
10936 firstsurface = texturesurfacelist[0];
10937 firsttriangle = firstsurface->num_firsttriangle;
10938 batchnumvertices = 0;
10939 batchnumtriangles = 0;
10940 firstvertex = endvertex = firstsurface->num_firstvertex;
10941 for (i = 0;i < texturenumsurfaces;i++)
10943 surface = texturesurfacelist[i];
10944 if (surface != firstsurface + i)
10946 surfacefirstvertex = surface->num_firstvertex;
10947 surfaceendvertex = surfacefirstvertex + surface->num_vertices;
10948 surfacenumvertices = surface->num_vertices;
10949 surfacenumtriangles = surface->num_triangles;
10950 if (firstvertex > surfacefirstvertex)
10951 firstvertex = surfacefirstvertex;
10952 if (endvertex < surfaceendvertex)
10953 endvertex = surfaceendvertex;
10954 batchnumvertices += surfacenumvertices;
10955 batchnumtriangles += surfacenumtriangles;
10958 // we now know the vertex range used, and if there are any gaps in it
10959 rsurface.batchfirstvertex = firstvertex;
10960 rsurface.batchnumvertices = endvertex - firstvertex;
10961 rsurface.batchfirsttriangle = firsttriangle;
10962 rsurface.batchnumtriangles = batchnumtriangles;
10964 // this variable holds flags for which properties have been updated that
10965 // may require regenerating vertexmesh array...
10968 // check if any dynamic vertex processing must occur
10969 dynamicvertex = false;
10971 // if there is a chance of animated vertex colors, it's a dynamic batch
10972 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
10974 dynamicvertex = true;
10975 batchneed |= BATCHNEED_NOGAPS;
10976 needsupdate |= BATCHNEED_VERTEXMESH_VERTEXCOLOR;
10979 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
10981 switch (deform->deform)
10984 case Q3DEFORM_PROJECTIONSHADOW:
10985 case Q3DEFORM_TEXT0:
10986 case Q3DEFORM_TEXT1:
10987 case Q3DEFORM_TEXT2:
10988 case Q3DEFORM_TEXT3:
10989 case Q3DEFORM_TEXT4:
10990 case Q3DEFORM_TEXT5:
10991 case Q3DEFORM_TEXT6:
10992 case Q3DEFORM_TEXT7:
10993 case Q3DEFORM_NONE:
10995 case Q3DEFORM_AUTOSPRITE:
10996 dynamicvertex = true;
10997 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
10998 needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11000 case Q3DEFORM_AUTOSPRITE2:
11001 dynamicvertex = true;
11002 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11003 needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11005 case Q3DEFORM_NORMAL:
11006 dynamicvertex = true;
11007 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11008 needsupdate |= BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11010 case Q3DEFORM_WAVE:
11011 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11012 break; // if wavefunc is a nop, ignore this transform
11013 dynamicvertex = true;
11014 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11015 needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11017 case Q3DEFORM_BULGE:
11018 dynamicvertex = true;
11019 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11020 needsupdate |= BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR;
11022 case Q3DEFORM_MOVE:
11023 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11024 break; // if wavefunc is a nop, ignore this transform
11025 dynamicvertex = true;
11026 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11027 needsupdate |= BATCHNEED_VERTEXMESH_VERTEX;
11031 switch(rsurface.texture->tcgen.tcgen)
11034 case Q3TCGEN_TEXTURE:
11036 case Q3TCGEN_LIGHTMAP:
11037 dynamicvertex = true;
11038 batchneed |= BATCHNEED_ARRAY_LIGHTMAP | BATCHNEED_NOGAPS;
11039 needsupdate |= BATCHNEED_VERTEXMESH_LIGHTMAP;
11041 case Q3TCGEN_VECTOR:
11042 dynamicvertex = true;
11043 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS;
11044 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11046 case Q3TCGEN_ENVIRONMENT:
11047 dynamicvertex = true;
11048 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS;
11049 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11052 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11054 dynamicvertex = true;
11055 batchneed |= BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS;
11056 needsupdate |= BATCHNEED_VERTEXMESH_TEXCOORD;
11059 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11061 dynamicvertex = true;
11062 batchneed |= BATCHNEED_NOGAPS;
11063 needsupdate |= (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP));
11066 if (dynamicvertex || gaps || rsurface.batchfirstvertex)
11068 // when copying, we need to consider the regeneration of vertexmesh, any dependencies it may have must be set...
11069 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX) batchneed |= BATCHNEED_ARRAY_VERTEX;
11070 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL) batchneed |= BATCHNEED_ARRAY_NORMAL;
11071 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR) batchneed |= BATCHNEED_ARRAY_VECTOR;
11072 if (batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) batchneed |= BATCHNEED_ARRAY_VERTEXCOLOR;
11073 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD) batchneed |= BATCHNEED_ARRAY_TEXCOORD;
11074 if (batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) batchneed |= BATCHNEED_ARRAY_LIGHTMAP;
11077 // when the model data has no vertex buffer (dynamic mesh), we need to
11079 if (vid.useinterleavedarrays ? !rsurface.modelvertexmeshbuffer : !rsurface.modelvertex3f_vertexbuffer)
11080 batchneed |= BATCHNEED_NOGAPS;
11082 // if needsupdate, we have to do a dynamic vertex batch for sure
11083 if (needsupdate & batchneed)
11084 dynamicvertex = true;
11086 // see if we need to build vertexmesh from arrays
11087 if (!rsurface.modelvertexmesh && (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)))
11088 dynamicvertex = true;
11090 // if gaps are unacceptable, and there are gaps, it's a dynamic batch...
11091 // also some drivers strongly dislike firstvertex
11092 if ((batchneed & BATCHNEED_NOGAPS) && (gaps || firstvertex))
11093 dynamicvertex = true;
11095 rsurface.batchvertex3f = rsurface.modelvertex3f;
11096 rsurface.batchvertex3f_vertexbuffer = rsurface.modelvertex3f_vertexbuffer;
11097 rsurface.batchvertex3f_bufferoffset = rsurface.modelvertex3f_bufferoffset;
11098 rsurface.batchsvector3f = rsurface.modelsvector3f;
11099 rsurface.batchsvector3f_vertexbuffer = rsurface.modelsvector3f_vertexbuffer;
11100 rsurface.batchsvector3f_bufferoffset = rsurface.modelsvector3f_bufferoffset;
11101 rsurface.batchtvector3f = rsurface.modeltvector3f;
11102 rsurface.batchtvector3f_vertexbuffer = rsurface.modeltvector3f_vertexbuffer;
11103 rsurface.batchtvector3f_bufferoffset = rsurface.modeltvector3f_bufferoffset;
11104 rsurface.batchnormal3f = rsurface.modelnormal3f;
11105 rsurface.batchnormal3f_vertexbuffer = rsurface.modelnormal3f_vertexbuffer;
11106 rsurface.batchnormal3f_bufferoffset = rsurface.modelnormal3f_bufferoffset;
11107 rsurface.batchlightmapcolor4f = rsurface.modellightmapcolor4f;
11108 rsurface.batchlightmapcolor4f_vertexbuffer = rsurface.modellightmapcolor4f_vertexbuffer;
11109 rsurface.batchlightmapcolor4f_bufferoffset = rsurface.modellightmapcolor4f_bufferoffset;
11110 rsurface.batchtexcoordtexture2f = rsurface.modeltexcoordtexture2f;
11111 rsurface.batchtexcoordtexture2f_vertexbuffer = rsurface.modeltexcoordtexture2f_vertexbuffer;
11112 rsurface.batchtexcoordtexture2f_bufferoffset = rsurface.modeltexcoordtexture2f_bufferoffset;
11113 rsurface.batchtexcoordlightmap2f = rsurface.modeltexcoordlightmap2f;
11114 rsurface.batchtexcoordlightmap2f_vertexbuffer = rsurface.modeltexcoordlightmap2f_vertexbuffer;
11115 rsurface.batchtexcoordlightmap2f_bufferoffset = rsurface.modeltexcoordlightmap2f_bufferoffset;
11116 rsurface.batchvertex3fbuffer = rsurface.modelvertex3fbuffer;
11117 rsurface.batchvertexmesh = rsurface.modelvertexmesh;
11118 rsurface.batchvertexmeshbuffer = rsurface.modelvertexmeshbuffer;
11119 rsurface.batchelement3i = rsurface.modelelement3i;
11120 rsurface.batchelement3i_indexbuffer = rsurface.modelelement3i_indexbuffer;
11121 rsurface.batchelement3i_bufferoffset = rsurface.modelelement3i_bufferoffset;
11122 rsurface.batchelement3s = rsurface.modelelement3s;
11123 rsurface.batchelement3s_indexbuffer = rsurface.modelelement3s_indexbuffer;
11124 rsurface.batchelement3s_bufferoffset = rsurface.modelelement3s_bufferoffset;
11126 // if any dynamic vertex processing has to occur in software, we copy the
11127 // entire surface list together before processing to rebase the vertices
11128 // to start at 0 (otherwise we waste a lot of room in a vertex buffer).
11130 // if any gaps exist and we do not have a static vertex buffer, we have to
11131 // copy the surface list together to avoid wasting upload bandwidth on the
11132 // vertices in the gaps.
11134 // if gaps exist and we have a static vertex buffer, we still have to
11135 // combine the index buffer ranges into one dynamic index buffer.
11137 // in all cases we end up with data that can be drawn in one call.
11139 if (!dynamicvertex)
11141 // static vertex data, just set pointers...
11142 rsurface.batchgeneratedvertex = false;
11143 // if there are gaps, we want to build a combined index buffer,
11144 // otherwise use the original static buffer with an appropriate offset
11147 // build a new triangle elements array for this batch
11148 rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
11149 rsurface.batchfirsttriangle = 0;
11151 for (i = 0;i < texturenumsurfaces;i++)
11153 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11154 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11155 memcpy(rsurface.batchelement3i + 3*numtriangles, rsurface.modelelement3i + 3*surfacefirsttriangle, surfacenumtriangles*sizeof(int[3]));
11156 numtriangles += surfacenumtriangles;
11158 rsurface.batchelement3i_indexbuffer = NULL;
11159 rsurface.batchelement3i_bufferoffset = 0;
11160 rsurface.batchelement3s = NULL;
11161 rsurface.batchelement3s_indexbuffer = NULL;
11162 rsurface.batchelement3s_bufferoffset = 0;
11163 if (endvertex <= 65536)
11165 // make a 16bit (unsigned short) index array if possible
11166 rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
11167 for (i = 0;i < numtriangles*3;i++)
11168 rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
11174 // something needs software processing, do it for real...
11175 // we only directly handle separate array data in this case and then
11176 // generate interleaved data if needed...
11177 rsurface.batchgeneratedvertex = true;
11179 // now copy the vertex data into a combined array and make an index array
11180 // (this is what Quake3 does all the time)
11181 //if (gaps || rsurface.batchfirstvertex)
11183 rsurface.batchvertex3fbuffer = NULL;
11184 rsurface.batchvertexmesh = NULL;
11185 rsurface.batchvertexmeshbuffer = NULL;
11186 rsurface.batchvertex3f = NULL;
11187 rsurface.batchvertex3f_vertexbuffer = NULL;
11188 rsurface.batchvertex3f_bufferoffset = 0;
11189 rsurface.batchsvector3f = NULL;
11190 rsurface.batchsvector3f_vertexbuffer = NULL;
11191 rsurface.batchsvector3f_bufferoffset = 0;
11192 rsurface.batchtvector3f = NULL;
11193 rsurface.batchtvector3f_vertexbuffer = NULL;
11194 rsurface.batchtvector3f_bufferoffset = 0;
11195 rsurface.batchnormal3f = NULL;
11196 rsurface.batchnormal3f_vertexbuffer = NULL;
11197 rsurface.batchnormal3f_bufferoffset = 0;
11198 rsurface.batchlightmapcolor4f = NULL;
11199 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11200 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11201 rsurface.batchtexcoordtexture2f = NULL;
11202 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11203 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11204 rsurface.batchtexcoordlightmap2f = NULL;
11205 rsurface.batchtexcoordlightmap2f_vertexbuffer = NULL;
11206 rsurface.batchtexcoordlightmap2f_bufferoffset = 0;
11207 rsurface.batchelement3i = (int *)R_FrameData_Alloc(batchnumtriangles * sizeof(int[3]));
11208 rsurface.batchelement3i_indexbuffer = NULL;
11209 rsurface.batchelement3i_bufferoffset = 0;
11210 rsurface.batchelement3s = NULL;
11211 rsurface.batchelement3s_indexbuffer = NULL;
11212 rsurface.batchelement3s_bufferoffset = 0;
11213 // we'll only be setting up certain arrays as needed
11214 if (batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11215 rsurface.batchvertexmesh = (r_vertexmesh_t *)R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
11216 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11217 rsurface.batchvertex3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11218 if (batchneed & BATCHNEED_ARRAY_NORMAL)
11219 rsurface.batchnormal3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11220 if (batchneed & BATCHNEED_ARRAY_VECTOR)
11222 rsurface.batchsvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11223 rsurface.batchtvector3f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11225 if (batchneed & BATCHNEED_ARRAY_VERTEXCOLOR)
11226 rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
11227 if (batchneed & BATCHNEED_ARRAY_TEXCOORD)
11228 rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11229 if (batchneed & BATCHNEED_ARRAY_LIGHTMAP)
11230 rsurface.batchtexcoordlightmap2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11233 for (i = 0;i < texturenumsurfaces;i++)
11235 surfacefirstvertex = texturesurfacelist[i]->num_firstvertex;
11236 surfacenumvertices = texturesurfacelist[i]->num_vertices;
11237 surfacefirsttriangle = texturesurfacelist[i]->num_firsttriangle;
11238 surfacenumtriangles = texturesurfacelist[i]->num_triangles;
11239 // copy only the data requested
11240 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP)) && rsurface.modelvertexmesh)
11241 memcpy(rsurface.batchvertexmesh + numvertices, rsurface.modelvertexmesh + surfacefirstvertex, surfacenumvertices * sizeof(rsurface.batchvertexmesh[0]));
11242 if (batchneed & (BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_ARRAY_LIGHTMAP))
11244 if (batchneed & BATCHNEED_ARRAY_VERTEX)
11245 memcpy(rsurface.batchvertex3f + 3*numvertices, rsurface.modelvertex3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11246 if ((batchneed & BATCHNEED_ARRAY_NORMAL) && rsurface.modelnormal3f)
11247 memcpy(rsurface.batchnormal3f + 3*numvertices, rsurface.modelnormal3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11248 if ((batchneed & BATCHNEED_ARRAY_VECTOR) && rsurface.modelsvector3f)
11250 memcpy(rsurface.batchsvector3f + 3*numvertices, rsurface.modelsvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11251 memcpy(rsurface.batchtvector3f + 3*numvertices, rsurface.modeltvector3f + 3*surfacefirstvertex, surfacenumvertices * sizeof(float[3]));
11253 if ((batchneed & BATCHNEED_ARRAY_VERTEXCOLOR) && rsurface.modellightmapcolor4f)
11254 memcpy(rsurface.batchlightmapcolor4f + 4*numvertices, rsurface.modellightmapcolor4f + 4*surfacefirstvertex, surfacenumvertices * sizeof(float[4]));
11255 if ((batchneed & BATCHNEED_ARRAY_TEXCOORD) && rsurface.modeltexcoordtexture2f)
11256 memcpy(rsurface.batchtexcoordtexture2f + 2*numvertices, rsurface.modeltexcoordtexture2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11257 if ((batchneed & BATCHNEED_ARRAY_LIGHTMAP) && rsurface.modeltexcoordlightmap2f)
11258 memcpy(rsurface.batchtexcoordlightmap2f + 2*numvertices, rsurface.modeltexcoordlightmap2f + 2*surfacefirstvertex, surfacenumvertices * sizeof(float[2]));
11260 RSurf_RenumberElements(rsurface.modelelement3i + 3*surfacefirsttriangle, rsurface.batchelement3i + 3*numtriangles, 3*surfacenumtriangles, numvertices - surfacefirstvertex);
11261 numvertices += surfacenumvertices;
11262 numtriangles += surfacenumtriangles;
11265 // generate a 16bit index array as well if possible
11266 // (in general, dynamic batches fit)
11267 if (numvertices <= 65536)
11269 rsurface.batchelement3s = (unsigned short *)R_FrameData_Alloc(batchnumtriangles * sizeof(unsigned short[3]));
11270 for (i = 0;i < numtriangles*3;i++)
11271 rsurface.batchelement3s[i] = rsurface.batchelement3i[i];
11274 // since we've copied everything, the batch now starts at 0
11275 rsurface.batchfirstvertex = 0;
11276 rsurface.batchnumvertices = batchnumvertices;
11277 rsurface.batchfirsttriangle = 0;
11278 rsurface.batchnumtriangles = batchnumtriangles;
11281 // q1bsp surfaces rendered in vertex color mode have to have colors
11282 // calculated based on lightstyles
11283 if ((batchneed & (BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_ARRAY_VERTEXCOLOR)) && texturesurfacelist[0]->lightmapinfo)
11285 // generate color arrays for the surfaces in this list
11289 const int *offsets;
11290 const unsigned char *lm;
11291 rsurface.batchlightmapcolor4f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[4]));
11292 rsurface.batchlightmapcolor4f_vertexbuffer = NULL;
11293 rsurface.batchlightmapcolor4f_bufferoffset = 0;
11295 for (i = 0;i < texturenumsurfaces;i++)
11297 surface = texturesurfacelist[i];
11298 offsets = rsurface.modellightmapoffsets + surface->num_firstvertex;
11299 surfacenumvertices = surface->num_vertices;
11300 if (surface->lightmapinfo->samples)
11302 for (j = 0;j < surfacenumvertices;j++)
11304 lm = surface->lightmapinfo->samples + offsets[j];
11305 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[0]];
11306 VectorScale(lm, scale, c);
11307 if (surface->lightmapinfo->styles[1] != 255)
11309 size3 = ((surface->lightmapinfo->extents[0]>>4)+1)*((surface->lightmapinfo->extents[1]>>4)+1)*3;
11311 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[1]];
11312 VectorMA(c, scale, lm, c);
11313 if (surface->lightmapinfo->styles[2] != 255)
11316 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[2]];
11317 VectorMA(c, scale, lm, c);
11318 if (surface->lightmapinfo->styles[3] != 255)
11321 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[3]];
11322 VectorMA(c, scale, lm, c);
11329 Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, min(c[0], 255) * (1.0f / 255.0f), min(c[1], 255) * (1.0f / 255.0f), min(c[2], 255) * (1.0f / 255.0f), 1);
11335 for (j = 0;j < surfacenumvertices;j++)
11337 Vector4Set(rsurface.batchlightmapcolor4f + 4*numvertices, 0, 0, 0, 1);
11344 // if vertices are deformed (sprite flares and things in maps, possibly
11345 // water waves, bulges and other deformations), modify the copied vertices
11347 for (deformindex = 0, deform = rsurface.texture->deforms;deformindex < Q3MAXDEFORMS && deform->deform;deformindex++, deform++)
11349 switch (deform->deform)
11352 case Q3DEFORM_PROJECTIONSHADOW:
11353 case Q3DEFORM_TEXT0:
11354 case Q3DEFORM_TEXT1:
11355 case Q3DEFORM_TEXT2:
11356 case Q3DEFORM_TEXT3:
11357 case Q3DEFORM_TEXT4:
11358 case Q3DEFORM_TEXT5:
11359 case Q3DEFORM_TEXT6:
11360 case Q3DEFORM_TEXT7:
11361 case Q3DEFORM_NONE:
11363 case Q3DEFORM_AUTOSPRITE:
11364 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11365 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11366 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11367 VectorNormalize(newforward);
11368 VectorNormalize(newright);
11369 VectorNormalize(newup);
11370 // rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11371 // rsurface.batchvertex3f_vertexbuffer = NULL;
11372 // rsurface.batchvertex3f_bufferoffset = 0;
11373 // rsurface.batchsvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchsvector3f);
11374 // rsurface.batchsvector3f_vertexbuffer = NULL;
11375 // rsurface.batchsvector3f_bufferoffset = 0;
11376 // rsurface.batchtvector3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchtvector3f);
11377 // rsurface.batchtvector3f_vertexbuffer = NULL;
11378 // rsurface.batchtvector3f_bufferoffset = 0;
11379 // rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11380 // rsurface.batchnormal3f_vertexbuffer = NULL;
11381 // rsurface.batchnormal3f_bufferoffset = 0;
11382 // a single autosprite surface can contain multiple sprites...
11383 for (j = 0;j < batchnumvertices - 3;j += 4)
11385 VectorClear(center);
11386 for (i = 0;i < 4;i++)
11387 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11388 VectorScale(center, 0.25f, center);
11389 VectorCopy(rsurface.batchnormal3f + 3*j, forward);
11390 VectorCopy(rsurface.batchsvector3f + 3*j, right);
11391 VectorCopy(rsurface.batchtvector3f + 3*j, up);
11392 for (i = 0;i < 4;i++)
11394 VectorSubtract(rsurface.batchvertex3f + 3*(j+i), center, v);
11395 VectorMAMAMAM(1, center, DotProduct(forward, v), newforward, DotProduct(right, v), newright, DotProduct(up, v), newup, rsurface.batchvertex3f + 3*(j+i));
11398 // if we get here, BATCHNEED_ARRAY_NORMAL and BATCHNEED_ARRAY_VECTOR are in batchneed, so no need to check
11399 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11400 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11402 case Q3DEFORM_AUTOSPRITE2:
11403 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, newforward);
11404 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.right, newright);
11405 Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.up, newup);
11406 VectorNormalize(newforward);
11407 VectorNormalize(newright);
11408 VectorNormalize(newup);
11409 // rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11410 // rsurface.batchvertex3f_vertexbuffer = NULL;
11411 // rsurface.batchvertex3f_bufferoffset = 0;
11413 const float *v1, *v2;
11423 memset(shortest, 0, sizeof(shortest));
11424 // a single autosprite surface can contain multiple sprites...
11425 for (j = 0;j < batchnumvertices - 3;j += 4)
11427 VectorClear(center);
11428 for (i = 0;i < 4;i++)
11429 VectorAdd(center, rsurface.batchvertex3f + 3*(j+i), center);
11430 VectorScale(center, 0.25f, center);
11431 // find the two shortest edges, then use them to define the
11432 // axis vectors for rotating around the central axis
11433 for (i = 0;i < 6;i++)
11435 v1 = rsurface.batchvertex3f + 3*(j+quadedges[i][0]);
11436 v2 = rsurface.batchvertex3f + 3*(j+quadedges[i][1]);
11437 l = VectorDistance2(v1, v2);
11438 // this length bias tries to make sense of square polygons, assuming they are meant to be upright
11439 if (v1[2] != v2[2])
11440 l += (1.0f / 1024.0f);
11441 if (shortest[0].length2 > l || i == 0)
11443 shortest[1] = shortest[0];
11444 shortest[0].length2 = l;
11445 shortest[0].v1 = v1;
11446 shortest[0].v2 = v2;
11448 else if (shortest[1].length2 > l || i == 1)
11450 shortest[1].length2 = l;
11451 shortest[1].v1 = v1;
11452 shortest[1].v2 = v2;
11455 VectorLerp(shortest[0].v1, 0.5f, shortest[0].v2, start);
11456 VectorLerp(shortest[1].v1, 0.5f, shortest[1].v2, end);
11457 // this calculates the right vector from the shortest edge
11458 // and the up vector from the edge midpoints
11459 VectorSubtract(shortest[0].v1, shortest[0].v2, right);
11460 VectorNormalize(right);
11461 VectorSubtract(end, start, up);
11462 VectorNormalize(up);
11463 // calculate a forward vector to use instead of the original plane normal (this is how we get a new right vector)
11464 VectorSubtract(rsurface.localvieworigin, center, forward);
11465 //Matrix4x4_Transform3x3(&rsurface.inversematrix, r_refdef.view.forward, forward);
11466 VectorNegate(forward, forward);
11467 VectorReflect(forward, 0, up, forward);
11468 VectorNormalize(forward);
11469 CrossProduct(up, forward, newright);
11470 VectorNormalize(newright);
11471 // rotate the quad around the up axis vector, this is made
11472 // especially easy by the fact we know the quad is flat,
11473 // so we only have to subtract the center position and
11474 // measure distance along the right vector, and then
11475 // multiply that by the newright vector and add back the
11477 // we also need to subtract the old position to undo the
11478 // displacement from the center, which we do with a
11479 // DotProduct, the subtraction/addition of center is also
11480 // optimized into DotProducts here
11481 l = DotProduct(right, center);
11482 for (i = 0;i < 4;i++)
11484 v1 = rsurface.batchvertex3f + 3*(j+i);
11485 f = DotProduct(right, v1) - l;
11486 VectorMAMAM(1, v1, -f, right, f, newright, rsurface.batchvertex3f + 3*(j+i));
11490 if(batchneed & (BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR)) // otherwise these can stay NULL
11492 // rsurface.batchnormal3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11493 // rsurface.batchnormal3f_vertexbuffer = NULL;
11494 // rsurface.batchnormal3f_bufferoffset = 0;
11495 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11497 if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11499 // rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11500 // rsurface.batchsvector3f_vertexbuffer = NULL;
11501 // rsurface.batchsvector3f_bufferoffset = 0;
11502 // rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11503 // rsurface.batchtvector3f_vertexbuffer = NULL;
11504 // rsurface.batchtvector3f_bufferoffset = 0;
11505 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11508 case Q3DEFORM_NORMAL:
11509 // deform the normals to make reflections wavey
11510 rsurface.batchnormal3f = (float *)R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11511 rsurface.batchnormal3f_vertexbuffer = NULL;
11512 rsurface.batchnormal3f_bufferoffset = 0;
11513 for (j = 0;j < batchnumvertices;j++)
11516 float *normal = rsurface.batchnormal3f + 3*j;
11517 VectorScale(rsurface.batchvertex3f + 3*j, 0.98f, vertex);
11518 normal[0] = rsurface.batchnormal3f[j*3+0] + deform->parms[0] * noise4f( vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11519 normal[1] = rsurface.batchnormal3f[j*3+1] + deform->parms[0] * noise4f( 98 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11520 normal[2] = rsurface.batchnormal3f[j*3+2] + deform->parms[0] * noise4f(196 + vertex[0], vertex[1], vertex[2], r_refdef.scene.time * deform->parms[1]);
11521 VectorNormalize(normal);
11523 if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11525 // rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11526 // rsurface.batchsvector3f_vertexbuffer = NULL;
11527 // rsurface.batchsvector3f_bufferoffset = 0;
11528 // rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11529 // rsurface.batchtvector3f_vertexbuffer = NULL;
11530 // rsurface.batchtvector3f_bufferoffset = 0;
11531 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11534 case Q3DEFORM_WAVE:
11535 // deform vertex array to make wavey water and flags and such
11536 waveparms[0] = deform->waveparms[0];
11537 waveparms[1] = deform->waveparms[1];
11538 waveparms[2] = deform->waveparms[2];
11539 waveparms[3] = deform->waveparms[3];
11540 if(!R_TestQ3WaveFunc(deform->wavefunc, waveparms))
11541 break; // if wavefunc is a nop, don't make a dynamic vertex array
11542 // this is how a divisor of vertex influence on deformation
11543 animpos = deform->parms[0] ? 1.0f / deform->parms[0] : 100.0f;
11544 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11545 // rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11546 // rsurface.batchvertex3f_vertexbuffer = NULL;
11547 // rsurface.batchvertex3f_bufferoffset = 0;
11548 // rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11549 // rsurface.batchnormal3f_vertexbuffer = NULL;
11550 // rsurface.batchnormal3f_bufferoffset = 0;
11551 for (j = 0;j < batchnumvertices;j++)
11553 // if the wavefunc depends on time, evaluate it per-vertex
11556 waveparms[2] = deform->waveparms[2] + (rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+1] + rsurface.batchvertex3f[j*3+2]) * animpos;
11557 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, waveparms);
11559 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
11561 // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11562 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11563 if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11565 // rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11566 // rsurface.batchsvector3f_vertexbuffer = NULL;
11567 // rsurface.batchsvector3f_bufferoffset = 0;
11568 // rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11569 // rsurface.batchtvector3f_vertexbuffer = NULL;
11570 // rsurface.batchtvector3f_bufferoffset = 0;
11571 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11574 case Q3DEFORM_BULGE:
11575 // deform vertex array to make the surface have moving bulges
11576 // rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11577 // rsurface.batchvertex3f_vertexbuffer = NULL;
11578 // rsurface.batchvertex3f_bufferoffset = 0;
11579 // rsurface.batchnormal3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchnormal3f);
11580 // rsurface.batchnormal3f_vertexbuffer = NULL;
11581 // rsurface.batchnormal3f_bufferoffset = 0;
11582 for (j = 0;j < batchnumvertices;j++)
11584 scale = sin(rsurface.batchtexcoordtexture2f[j*2+0] * deform->parms[0] + r_refdef.scene.time * deform->parms[2]) * deform->parms[1];
11585 VectorMA(rsurface.batchvertex3f + 3*j, scale, rsurface.batchnormal3f + 3*j, rsurface.batchvertex3f + 3*j);
11587 // if we get here, BATCHNEED_ARRAY_NORMAL is in batchneed, so no need to check
11588 Mod_BuildNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchnormal3f, r_smoothnormals_areaweighting.integer != 0);
11589 if(batchneed & BATCHNEED_ARRAY_VECTOR) // otherwise these can stay NULL
11591 // rsurface.batchsvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11592 // rsurface.batchsvector3f_vertexbuffer = NULL;
11593 // rsurface.batchsvector3f_bufferoffset = 0;
11594 // rsurface.batchtvector3f = R_FrameData_Alloc(batchnumvertices * sizeof(float[3]));
11595 // rsurface.batchtvector3f_vertexbuffer = NULL;
11596 // rsurface.batchtvector3f_bufferoffset = 0;
11597 Mod_BuildTextureVectorsFromNormals(rsurface.batchfirstvertex, batchnumvertices, batchnumtriangles, rsurface.batchvertex3f, rsurface.batchtexcoordtexture2f, rsurface.batchnormal3f, rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle, rsurface.batchsvector3f, rsurface.batchtvector3f, r_smoothnormals_areaweighting.integer != 0);
11600 case Q3DEFORM_MOVE:
11601 // deform vertex array
11602 if(!R_TestQ3WaveFunc(deform->wavefunc, deform->waveparms))
11603 break; // if wavefunc is a nop, don't make a dynamic vertex array
11604 scale = R_EvaluateQ3WaveFunc(deform->wavefunc, deform->waveparms);
11605 VectorScale(deform->parms, scale, waveparms);
11606 // rsurface.batchvertex3f = R_FrameData_Store(batchnumvertices * sizeof(float[3]), rsurface.batchvertex3f);
11607 // rsurface.batchvertex3f_vertexbuffer = NULL;
11608 // rsurface.batchvertex3f_bufferoffset = 0;
11609 for (j = 0;j < batchnumvertices;j++)
11610 VectorAdd(rsurface.batchvertex3f + 3*j, waveparms, rsurface.batchvertex3f + 3*j);
11615 // generate texcoords based on the chosen texcoord source
11616 switch(rsurface.texture->tcgen.tcgen)
11619 case Q3TCGEN_TEXTURE:
11621 case Q3TCGEN_LIGHTMAP:
11622 // rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11623 // rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11624 // rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11625 if (rsurface.batchtexcoordlightmap2f)
11626 memcpy(rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordtexture2f, batchnumvertices * sizeof(float[2]));
11628 case Q3TCGEN_VECTOR:
11629 // rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11630 // rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11631 // rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11632 for (j = 0;j < batchnumvertices;j++)
11634 rsurface.batchtexcoordtexture2f[j*2+0] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms);
11635 rsurface.batchtexcoordtexture2f[j*2+1] = DotProduct(rsurface.batchvertex3f + 3*j, rsurface.texture->tcgen.parms + 3);
11638 case Q3TCGEN_ENVIRONMENT:
11639 // make environment reflections using a spheremap
11640 rsurface.batchtexcoordtexture2f = (float *)R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11641 rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11642 rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11643 for (j = 0;j < batchnumvertices;j++)
11645 // identical to Q3A's method, but executed in worldspace so
11646 // carried models can be shiny too
11648 float viewer[3], d, reflected[3], worldreflected[3];
11650 VectorSubtract(rsurface.localvieworigin, rsurface.batchvertex3f + 3*j, viewer);
11651 // VectorNormalize(viewer);
11653 d = DotProduct(rsurface.batchnormal3f + 3*j, viewer);
11655 reflected[0] = rsurface.batchnormal3f[j*3+0]*2*d - viewer[0];
11656 reflected[1] = rsurface.batchnormal3f[j*3+1]*2*d - viewer[1];
11657 reflected[2] = rsurface.batchnormal3f[j*3+2]*2*d - viewer[2];
11658 // note: this is proportinal to viewer, so we can normalize later
11660 Matrix4x4_Transform3x3(&rsurface.matrix, reflected, worldreflected);
11661 VectorNormalize(worldreflected);
11663 // note: this sphere map only uses world x and z!
11664 // so positive and negative y will LOOK THE SAME.
11665 rsurface.batchtexcoordtexture2f[j*2+0] = 0.5 + 0.5 * worldreflected[1];
11666 rsurface.batchtexcoordtexture2f[j*2+1] = 0.5 - 0.5 * worldreflected[2];
11670 // the only tcmod that needs software vertex processing is turbulent, so
11671 // check for it here and apply the changes if needed
11672 // and we only support that as the first one
11673 // (handling a mixture of turbulent and other tcmods would be problematic
11674 // without punting it entirely to a software path)
11675 if (rsurface.texture->tcmods[0].tcmod == Q3TCMOD_TURBULENT)
11677 amplitude = rsurface.texture->tcmods[0].parms[1];
11678 animpos = rsurface.texture->tcmods[0].parms[2] + r_refdef.scene.time * rsurface.texture->tcmods[0].parms[3];
11679 // rsurface.batchtexcoordtexture2f = R_FrameData_Alloc(batchnumvertices * sizeof(float[2]));
11680 // rsurface.batchtexcoordtexture2f_vertexbuffer = NULL;
11681 // rsurface.batchtexcoordtexture2f_bufferoffset = 0;
11682 for (j = 0;j < batchnumvertices;j++)
11684 rsurface.batchtexcoordtexture2f[j*2+0] += amplitude * sin(((rsurface.batchvertex3f[j*3+0] + rsurface.batchvertex3f[j*3+2]) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11685 rsurface.batchtexcoordtexture2f[j*2+1] += amplitude * sin(((rsurface.batchvertex3f[j*3+1] ) * 1.0 / 1024.0f + animpos) * M_PI * 2);
11689 if (needsupdate & batchneed & (BATCHNEED_VERTEXMESH_VERTEX | BATCHNEED_VERTEXMESH_NORMAL | BATCHNEED_VERTEXMESH_VECTOR | BATCHNEED_VERTEXMESH_VERTEXCOLOR | BATCHNEED_VERTEXMESH_TEXCOORD | BATCHNEED_VERTEXMESH_LIGHTMAP))
11691 // convert the modified arrays to vertex structs
11692 // rsurface.batchvertexmesh = R_FrameData_Alloc(batchnumvertices * sizeof(r_vertexmesh_t));
11693 // rsurface.batchvertexmeshbuffer = NULL;
11694 if (batchneed & BATCHNEED_VERTEXMESH_VERTEX)
11695 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11696 VectorCopy(rsurface.batchvertex3f + 3*j, vertexmesh->vertex3f);
11697 if (batchneed & BATCHNEED_VERTEXMESH_NORMAL)
11698 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11699 VectorCopy(rsurface.batchnormal3f + 3*j, vertexmesh->normal3f);
11700 if (batchneed & BATCHNEED_VERTEXMESH_VECTOR)
11702 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11704 VectorCopy(rsurface.batchsvector3f + 3*j, vertexmesh->svector3f);
11705 VectorCopy(rsurface.batchtvector3f + 3*j, vertexmesh->tvector3f);
11708 if ((batchneed & BATCHNEED_VERTEXMESH_VERTEXCOLOR) && rsurface.batchlightmapcolor4f)
11709 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11710 Vector4Scale(rsurface.batchlightmapcolor4f + 4*j, 255.0f, vertexmesh->color4ub);
11711 if (batchneed & BATCHNEED_VERTEXMESH_TEXCOORD)
11712 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11713 Vector2Copy(rsurface.batchtexcoordtexture2f + 2*j, vertexmesh->texcoordtexture2f);
11714 if ((batchneed & BATCHNEED_VERTEXMESH_LIGHTMAP) && rsurface.batchtexcoordlightmap2f)
11715 for (j = 0, vertexmesh = rsurface.batchvertexmesh;j < batchnumvertices;j++, vertexmesh++)
11716 Vector2Copy(rsurface.batchtexcoordlightmap2f + 2*j, vertexmesh->texcoordlightmap2f);
11720 void RSurf_DrawBatch(void)
11722 // sometimes a zero triangle surface (usually a degenerate patch) makes it
11723 // through the pipeline, killing it earlier in the pipeline would have
11724 // per-surface overhead rather than per-batch overhead, so it's best to
11725 // reject it here, before it hits glDraw.
11726 if (rsurface.batchnumtriangles == 0)
11729 // batch debugging code
11730 if (r_test.integer && rsurface.entity == r_refdef.scene.worldentity && rsurface.batchvertex3f == r_refdef.scene.worldentity->model->surfmesh.data_vertex3f)
11736 e = rsurface.batchelement3i + rsurface.batchfirsttriangle*3;
11737 for (i = 0;i < rsurface.batchnumtriangles*3;i++)
11740 for (j = 0;j < rsurface.entity->model->num_surfaces;j++)
11742 if (c >= rsurface.modelsurfaces[j].num_firstvertex && c < (rsurface.modelsurfaces[j].num_firstvertex + rsurface.modelsurfaces[j].num_vertices))
11744 if (rsurface.modelsurfaces[j].texture != rsurface.texture)
11745 Sys_Error("RSurf_DrawBatch: index %i uses different texture (%s) than surface %i which it belongs to (which uses %s)\n", c, rsurface.texture->name, j, rsurface.modelsurfaces[j].texture->name);
11752 R_Mesh_Draw(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchfirsttriangle, rsurface.batchnumtriangles, rsurface.batchelement3i, rsurface.batchelement3i_indexbuffer, rsurface.batchelement3i_bufferoffset, rsurface.batchelement3s, rsurface.batchelement3s_indexbuffer, rsurface.batchelement3s_bufferoffset);
11755 static int RSurf_FindWaterPlaneForSurface(const msurface_t *surface)
11757 // pick the closest matching water plane
11758 int planeindex, vertexindex, bestplaneindex = -1;
11762 r_waterstate_waterplane_t *p;
11763 qboolean prepared = false;
11765 for (planeindex = 0, p = r_waterstate.waterplanes;planeindex < r_waterstate.numwaterplanes;planeindex++, p++)
11767 if(p->camera_entity != rsurface.texture->camera_entity)
11772 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, 1, &surface);
11774 if(rsurface.batchnumvertices == 0)
11777 for (vertexindex = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3;vertexindex < rsurface.batchnumvertices;vertexindex++, v += 3)
11779 Matrix4x4_Transform(&rsurface.matrix, v, vert);
11780 d += fabs(PlaneDiff(vert, &p->plane));
11782 if (bestd > d || bestplaneindex < 0)
11785 bestplaneindex = planeindex;
11788 return bestplaneindex;
11789 // NOTE: this MAY return a totally unrelated water plane; we can ignore
11790 // this situation though, as it might be better to render single larger
11791 // batches with useless stuff (backface culled for example) than to
11792 // render multiple smaller batches
11795 static void RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray(void)
11798 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11799 rsurface.passcolor4f_vertexbuffer = 0;
11800 rsurface.passcolor4f_bufferoffset = 0;
11801 for (i = 0;i < rsurface.batchnumvertices;i++)
11802 Vector4Set(rsurface.passcolor4f + 4*i, 0.5f, 0.5f, 0.5f, 1.0f);
11805 static void RSurf_DrawBatch_GL11_ApplyFog(void)
11812 if (rsurface.passcolor4f)
11814 // generate color arrays
11815 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11816 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11817 rsurface.passcolor4f_vertexbuffer = 0;
11818 rsurface.passcolor4f_bufferoffset = 0;
11819 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11821 f = RSurf_FogVertex(v);
11830 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11831 rsurface.passcolor4f_vertexbuffer = 0;
11832 rsurface.passcolor4f_bufferoffset = 0;
11833 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c2 += 4)
11835 f = RSurf_FogVertex(v);
11844 static void RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors(void)
11851 if (!rsurface.passcolor4f)
11853 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11854 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11855 rsurface.passcolor4f_vertexbuffer = 0;
11856 rsurface.passcolor4f_bufferoffset = 0;
11857 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4, c2 += 4)
11859 f = RSurf_FogVertex(v);
11860 c2[0] = c[0] * f + r_refdef.fogcolor[0] * (1 - f);
11861 c2[1] = c[1] * f + r_refdef.fogcolor[1] * (1 - f);
11862 c2[2] = c[2] * f + r_refdef.fogcolor[2] * (1 - f);
11867 static void RSurf_DrawBatch_GL11_ApplyColor(float r, float g, float b, float a)
11872 if (!rsurface.passcolor4f)
11874 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11875 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11876 rsurface.passcolor4f_vertexbuffer = 0;
11877 rsurface.passcolor4f_bufferoffset = 0;
11878 for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11887 static void RSurf_DrawBatch_GL11_ApplyAmbient(void)
11892 if (!rsurface.passcolor4f)
11894 c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;
11895 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11896 rsurface.passcolor4f_vertexbuffer = 0;
11897 rsurface.passcolor4f_bufferoffset = 0;
11898 for (i = 0, c2 = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, c += 4, c2 += 4)
11900 c2[0] = c[0] + r_refdef.scene.ambient;
11901 c2[1] = c[1] + r_refdef.scene.ambient;
11902 c2[2] = c[2] + r_refdef.scene.ambient;
11907 static void RSurf_DrawBatch_GL11_Lightmap(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11910 rsurface.passcolor4f = NULL;
11911 rsurface.passcolor4f_vertexbuffer = 0;
11912 rsurface.passcolor4f_bufferoffset = 0;
11913 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11914 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11915 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11916 GL_Color(r, g, b, a);
11917 R_Mesh_TexBind(0, rsurface.lightmaptexture);
11921 static void RSurf_DrawBatch_GL11_Unlit(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11923 // TODO: optimize applyfog && applycolor case
11924 // just apply fog if necessary, and tint the fog color array if necessary
11925 rsurface.passcolor4f = NULL;
11926 rsurface.passcolor4f_vertexbuffer = 0;
11927 rsurface.passcolor4f_bufferoffset = 0;
11928 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11929 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11930 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11931 GL_Color(r, g, b, a);
11935 static void RSurf_DrawBatch_GL11_VertexColor(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11938 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
11939 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
11940 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
11941 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11942 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11943 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11944 GL_Color(r, g, b, a);
11948 static void RSurf_DrawBatch_GL11_ClampColor(void)
11953 if (!rsurface.passcolor4f)
11955 for (i = 0, c1 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex, c2 = rsurface.passcolor4f + 4*rsurface.batchfirstvertex;i < rsurface.batchnumvertices;i++, c1 += 4, c2 += 4)
11957 c2[0] = bound(0.0f, c1[0], 1.0f);
11958 c2[1] = bound(0.0f, c1[1], 1.0f);
11959 c2[2] = bound(0.0f, c1[2], 1.0f);
11960 c2[3] = bound(0.0f, c1[3], 1.0f);
11964 static void RSurf_DrawBatch_GL11_ApplyFakeLight(void)
11974 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
11975 rsurface.passcolor4f_vertexbuffer = 0;
11976 rsurface.passcolor4f_bufferoffset = 0;
11977 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
11979 f = -DotProduct(r_refdef.view.forward, n);
11981 f = f * 0.85 + 0.15; // work around so stuff won't get black
11982 f *= r_refdef.lightmapintensity;
11983 Vector4Set(c, f, f, f, 1);
11987 static void RSurf_DrawBatch_GL11_FakeLight(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
11989 RSurf_DrawBatch_GL11_ApplyFakeLight();
11990 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
11991 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
11992 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
11993 GL_Color(r, g, b, a);
11997 static void RSurf_DrawBatch_GL11_ApplyVertexShade(float *r, float *g, float *b, float *a, qboolean *applycolor)
12005 vec3_t ambientcolor;
12006 vec3_t diffusecolor;
12010 VectorCopy(rsurface.modellight_lightdir, lightdir);
12011 f = 0.5f * r_refdef.lightmapintensity;
12012 ambientcolor[0] = rsurface.modellight_ambient[0] * *r * f;
12013 ambientcolor[1] = rsurface.modellight_ambient[1] * *g * f;
12014 ambientcolor[2] = rsurface.modellight_ambient[2] * *b * f;
12015 diffusecolor[0] = rsurface.modellight_diffuse[0] * *r * f;
12016 diffusecolor[1] = rsurface.modellight_diffuse[1] * *g * f;
12017 diffusecolor[2] = rsurface.modellight_diffuse[2] * *b * f;
12019 if (VectorLength2(diffusecolor) > 0)
12021 // q3-style directional shading
12022 rsurface.passcolor4f = (float *)R_FrameData_Alloc(rsurface.batchnumvertices * sizeof(float[4]));
12023 rsurface.passcolor4f_vertexbuffer = 0;
12024 rsurface.passcolor4f_bufferoffset = 0;
12025 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, n = rsurface.batchnormal3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, n += 3, c += 4)
12027 if ((f = DotProduct(n, lightdir)) > 0)
12028 VectorMA(ambientcolor, f, diffusecolor, c);
12030 VectorCopy(ambientcolor, c);
12037 *applycolor = false;
12041 *r = ambientcolor[0];
12042 *g = ambientcolor[1];
12043 *b = ambientcolor[2];
12044 rsurface.passcolor4f = NULL;
12045 rsurface.passcolor4f_vertexbuffer = 0;
12046 rsurface.passcolor4f_bufferoffset = 0;
12050 static void RSurf_DrawBatch_GL11_VertexShade(float r, float g, float b, float a, qboolean applycolor, qboolean applyfog)
12052 RSurf_DrawBatch_GL11_ApplyVertexShade(&r, &g, &b, &a, &applycolor);
12053 if (applyfog) RSurf_DrawBatch_GL11_ApplyFog();
12054 if (applycolor) RSurf_DrawBatch_GL11_ApplyColor(r, g, b, a);
12055 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, rsurface.passcolor4f_vertexbuffer, rsurface.passcolor4f_bufferoffset);
12056 GL_Color(r, g, b, a);
12060 static void RSurf_DrawBatch_GL11_MakeFogColor(float r, float g, float b, float a)
12066 for (i = 0, v = rsurface.batchvertex3f + rsurface.batchfirstvertex * 3, c = rsurface.passcolor4f + rsurface.batchfirstvertex * 4;i < rsurface.batchnumvertices;i++, v += 3, c += 4)
12068 f = 1 - RSurf_FogVertex(v);
12076 void RSurf_SetupDepthAndCulling(void)
12078 // submodels are biased to avoid z-fighting with world surfaces that they
12079 // may be exactly overlapping (avoids z-fighting artifacts on certain
12080 // doors and things in Quake maps)
12081 GL_DepthRange(0, (rsurface.texture->currentmaterialflags & MATERIALFLAG_SHORTDEPTHRANGE) ? 0.0625 : 1);
12082 GL_PolygonOffset(rsurface.basepolygonfactor + rsurface.texture->biaspolygonfactor, rsurface.basepolygonoffset + rsurface.texture->biaspolygonoffset);
12083 GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST));
12084 GL_CullFace((rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE) ? GL_NONE : r_refdef.view.cullface_back);
12087 static void R_DrawTextureSurfaceList_Sky(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12089 // transparent sky would be ridiculous
12090 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12092 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12093 skyrenderlater = true;
12094 RSurf_SetupDepthAndCulling();
12095 GL_DepthMask(true);
12096 // LordHavoc: HalfLife maps have freaky skypolys so don't use
12097 // skymasking on them, and Quake3 never did sky masking (unlike
12098 // software Quake and software Quake2), so disable the sky masking
12099 // in Quake3 maps as it causes problems with q3map2 sky tricks,
12100 // and skymasking also looks very bad when noclipping outside the
12101 // level, so don't use it then either.
12102 if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->type == mod_brushq1 && r_q1bsp_skymasking.integer && !r_refdef.viewcache.world_novis)
12104 R_Mesh_ResetTextureState();
12105 if (skyrendermasked)
12107 R_SetupShader_DepthOrShadow();
12108 // depth-only (masking)
12109 GL_ColorMask(0,0,0,0);
12110 // just to make sure that braindead drivers don't draw
12111 // anything despite that colormask...
12112 GL_BlendFunc(GL_ZERO, GL_ONE);
12113 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12114 if (rsurface.batchvertex3fbuffer)
12115 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12117 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12121 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12123 GL_BlendFunc(GL_ONE, GL_ZERO);
12124 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12125 GL_Color(r_refdef.fogcolor[0], r_refdef.fogcolor[1], r_refdef.fogcolor[2], 1);
12126 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
12129 if (skyrendermasked)
12130 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12132 R_Mesh_ResetTextureState();
12133 GL_Color(1, 1, 1, 1);
12136 extern rtexture_t *r_shadow_prepasslightingdiffusetexture;
12137 extern rtexture_t *r_shadow_prepasslightingspeculartexture;
12138 static void R_DrawTextureSurfaceList_GL20(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12140 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
12144 // render screenspace normalmap to texture
12145 GL_DepthMask(true);
12146 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_DEFERREDGEOMETRY, texturenumsurfaces, texturesurfacelist, NULL);
12151 // bind lightmap texture
12153 // water/refraction/reflection/camera surfaces have to be handled specially
12154 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA | MATERIALFLAG_REFLECTION)))
12156 int start, end, startplaneindex;
12157 for (start = 0;start < texturenumsurfaces;start = end)
12159 startplaneindex = RSurf_FindWaterPlaneForSurface(texturesurfacelist[start]);
12160 if(startplaneindex < 0)
12162 // this happens if the plane e.g. got backface culled and thus didn't get a water plane. We can just ignore this.
12163 // Con_Printf("No matching water plane for surface with material flags 0x%08x - PLEASE DEBUG THIS\n", rsurface.texture->currentmaterialflags);
12167 for (end = start + 1;end < texturenumsurfaces && startplaneindex == RSurf_FindWaterPlaneForSurface(texturesurfacelist[end]);end++)
12169 // now that we have a batch using the same planeindex, render it
12170 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_CAMERA)))
12172 // render water or distortion background
12173 GL_DepthMask(true);
12174 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BACKGROUND, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12176 // blend surface on top
12177 GL_DepthMask(false);
12178 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, NULL);
12181 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_REFLECTION))
12183 // render surface with reflection texture as input
12184 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12185 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, end-start, texturesurfacelist + start, (void *)(r_waterstate.waterplanes + startplaneindex));
12192 // render surface batch normally
12193 GL_DepthMask(writedepth && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED));
12194 R_SetupShader_Surface(vec3_origin, (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT) != 0, 1, 1, rsurface.texture->specularscale, RSURFPASS_BASE, texturenumsurfaces, texturesurfacelist, NULL);
12198 static void R_DrawTextureSurfaceList_GL13(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12200 // OpenGL 1.3 path - anything not completely ancient
12201 qboolean applycolor;
12204 const texturelayer_t *layer;
12205 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12206 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12208 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12211 int layertexrgbscale;
12212 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12214 if (layerindex == 0)
12215 GL_AlphaTest(true);
12218 GL_AlphaTest(false);
12219 GL_DepthFunc(GL_EQUAL);
12222 GL_DepthMask(layer->depthmask && writedepth);
12223 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12224 if (layer->color[0] > 2 || layer->color[1] > 2 || layer->color[2] > 2)
12226 layertexrgbscale = 4;
12227 VectorScale(layer->color, 0.25f, layercolor);
12229 else if (layer->color[0] > 1 || layer->color[1] > 1 || layer->color[2] > 1)
12231 layertexrgbscale = 2;
12232 VectorScale(layer->color, 0.5f, layercolor);
12236 layertexrgbscale = 1;
12237 VectorScale(layer->color, 1.0f, layercolor);
12239 layercolor[3] = layer->color[3];
12240 applycolor = layercolor[0] != 1 || layercolor[1] != 1 || layercolor[2] != 1 || layercolor[3] != 1;
12241 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12242 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12243 switch (layer->type)
12245 case TEXTURELAYERTYPE_LITTEXTURE:
12246 // single-pass lightmapped texture with 2x rgbscale
12247 R_Mesh_TexBind(0, r_texture_white);
12248 R_Mesh_TexMatrix(0, NULL);
12249 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12250 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12251 R_Mesh_TexBind(1, layer->texture);
12252 R_Mesh_TexMatrix(1, &layer->texmatrix);
12253 R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12254 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12255 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12256 RSurf_DrawBatch_GL11_VertexShade(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12257 else if (FAKELIGHT_ENABLED)
12258 RSurf_DrawBatch_GL11_FakeLight(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12259 else if (rsurface.uselightmaptexture)
12260 RSurf_DrawBatch_GL11_Lightmap(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12262 RSurf_DrawBatch_GL11_VertexColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12264 case TEXTURELAYERTYPE_TEXTURE:
12265 // singletexture unlit texture with transparency support
12266 R_Mesh_TexBind(0, layer->texture);
12267 R_Mesh_TexMatrix(0, &layer->texmatrix);
12268 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12269 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12270 R_Mesh_TexBind(1, 0);
12271 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12272 RSurf_DrawBatch_GL11_Unlit(layercolor[0], layercolor[1], layercolor[2], layercolor[3], applycolor, applyfog);
12274 case TEXTURELAYERTYPE_FOG:
12275 // singletexture fogging
12276 if (layer->texture)
12278 R_Mesh_TexBind(0, layer->texture);
12279 R_Mesh_TexMatrix(0, &layer->texmatrix);
12280 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, layertexrgbscale, 1);
12281 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12285 R_Mesh_TexBind(0, 0);
12286 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12288 R_Mesh_TexBind(1, 0);
12289 R_Mesh_TexCoordPointer(1, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12290 // generate a color array for the fog pass
12291 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
12292 RSurf_DrawBatch_GL11_MakeFogColor(layercolor[0], layercolor[1], layercolor[2], layercolor[3]);
12296 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12299 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12301 GL_DepthFunc(GL_LEQUAL);
12302 GL_AlphaTest(false);
12306 static void R_DrawTextureSurfaceList_GL11(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12308 // OpenGL 1.1 - crusty old voodoo path
12311 const texturelayer_t *layer;
12312 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | ((!rsurface.uselightmaptexture && !(rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)) ? BATCHNEED_ARRAY_VERTEXCOLOR : 0) | BATCHNEED_ARRAY_TEXCOORD | (rsurface.modeltexcoordlightmap2f ? BATCHNEED_ARRAY_LIGHTMAP : 0) | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12313 R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
12315 for (layerindex = 0, layer = rsurface.texture->currentlayers;layerindex < rsurface.texture->currentnumlayers;layerindex++, layer++)
12317 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12319 if (layerindex == 0)
12320 GL_AlphaTest(true);
12323 GL_AlphaTest(false);
12324 GL_DepthFunc(GL_EQUAL);
12327 GL_DepthMask(layer->depthmask && writedepth);
12328 GL_BlendFunc(layer->blendfunc1, layer->blendfunc2);
12329 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL, 0, 0);
12330 applyfog = r_refdef.fogenabled && (rsurface.texture->currentmaterialflags & MATERIALFLAG_BLENDED);
12331 switch (layer->type)
12333 case TEXTURELAYERTYPE_LITTEXTURE:
12334 if (layer->blendfunc1 == GL_ONE && layer->blendfunc2 == GL_ZERO)
12336 // two-pass lit texture with 2x rgbscale
12337 // first the lightmap pass
12338 R_Mesh_TexBind(0, r_texture_white);
12339 R_Mesh_TexMatrix(0, NULL);
12340 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12341 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordlightmap2f, rsurface.batchtexcoordlightmap2f_vertexbuffer, rsurface.batchtexcoordlightmap2f_bufferoffset);
12342 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12343 RSurf_DrawBatch_GL11_VertexShade(1, 1, 1, 1, false, false);
12344 else if (FAKELIGHT_ENABLED)
12345 RSurf_DrawBatch_GL11_FakeLight(1, 1, 1, 1, false, false);
12346 else if (rsurface.uselightmaptexture)
12347 RSurf_DrawBatch_GL11_Lightmap(1, 1, 1, 1, false, false);
12349 RSurf_DrawBatch_GL11_VertexColor(1, 1, 1, 1, false, false);
12350 // then apply the texture to it
12351 GL_BlendFunc(GL_DST_COLOR, GL_SRC_COLOR);
12352 R_Mesh_TexBind(0, layer->texture);
12353 R_Mesh_TexMatrix(0, &layer->texmatrix);
12354 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12355 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12356 RSurf_DrawBatch_GL11_Unlit(layer->color[0] * 0.5f, layer->color[1] * 0.5f, layer->color[2] * 0.5f, layer->color[3], layer->color[0] != 2 || layer->color[1] != 2 || layer->color[2] != 2 || layer->color[3] != 1, false);
12360 // single pass vertex-lighting-only texture with 1x rgbscale and transparency support
12361 R_Mesh_TexBind(0, layer->texture);
12362 R_Mesh_TexMatrix(0, &layer->texmatrix);
12363 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12364 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12365 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12366 RSurf_DrawBatch_GL11_VertexShade(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
12368 RSurf_DrawBatch_GL11_VertexColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
12371 case TEXTURELAYERTYPE_TEXTURE:
12372 // singletexture unlit texture with transparency support
12373 R_Mesh_TexBind(0, layer->texture);
12374 R_Mesh_TexMatrix(0, &layer->texmatrix);
12375 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12376 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12377 RSurf_DrawBatch_GL11_Unlit(layer->color[0], layer->color[1], layer->color[2], layer->color[3], layer->color[0] != 1 || layer->color[1] != 1 || layer->color[2] != 1 || layer->color[3] != 1, applyfog);
12379 case TEXTURELAYERTYPE_FOG:
12380 // singletexture fogging
12381 if (layer->texture)
12383 R_Mesh_TexBind(0, layer->texture);
12384 R_Mesh_TexMatrix(0, &layer->texmatrix);
12385 R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1);
12386 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset);
12390 R_Mesh_TexBind(0, 0);
12391 R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), NULL, 0, 0);
12393 // generate a color array for the fog pass
12394 R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0);
12395 RSurf_DrawBatch_GL11_MakeFogColor(layer->color[0], layer->color[1], layer->color[2], layer->color[3]);
12399 Con_Printf("R_DrawTextureSurfaceList: unknown layer type %i\n", layer->type);
12402 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12404 GL_DepthFunc(GL_LEQUAL);
12405 GL_AlphaTest(false);
12409 static void R_DrawTextureSurfaceList_ShowSurfaces(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth)
12413 r_vertexgeneric_t *batchvertex;
12416 // R_Mesh_ResetTextureState();
12417 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12419 if(rsurface.texture && rsurface.texture->currentskinframe)
12421 memcpy(c, rsurface.texture->currentskinframe->avgcolor, sizeof(c));
12422 c[3] *= rsurface.texture->currentalpha;
12432 if (rsurface.texture->pantstexture || rsurface.texture->shirttexture)
12434 c[0] = 0.5 * (rsurface.colormap_pantscolor[0] * 0.3 + rsurface.colormap_shirtcolor[0] * 0.7);
12435 c[1] = 0.5 * (rsurface.colormap_pantscolor[1] * 0.3 + rsurface.colormap_shirtcolor[1] * 0.7);
12436 c[2] = 0.5 * (rsurface.colormap_pantscolor[2] * 0.3 + rsurface.colormap_shirtcolor[2] * 0.7);
12439 // brighten it up (as texture value 127 means "unlit")
12440 c[0] *= 2 * r_refdef.view.colorscale;
12441 c[1] *= 2 * r_refdef.view.colorscale;
12442 c[2] *= 2 * r_refdef.view.colorscale;
12444 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_WATERALPHA)
12445 c[3] *= r_wateralpha.value;
12447 if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHA && c[3] != 1)
12449 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
12450 GL_DepthMask(false);
12452 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ADD)
12454 GL_BlendFunc(GL_ONE, GL_ONE);
12455 GL_DepthMask(false);
12457 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST)
12459 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // can't do alpha test without texture, so let's blend instead
12460 GL_DepthMask(false);
12462 else if(rsurface.texture->currentmaterialflags & MATERIALFLAG_CUSTOMBLEND)
12464 GL_BlendFunc(rsurface.texture->customblendfunc[0], rsurface.texture->customblendfunc[1]);
12465 GL_DepthMask(false);
12469 GL_BlendFunc(GL_ONE, GL_ZERO);
12470 GL_DepthMask(writedepth);
12473 if (r_showsurfaces.integer == 3)
12475 rsurface.passcolor4f = NULL;
12477 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_FULLBRIGHT)
12479 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12481 rsurface.passcolor4f = NULL;
12482 rsurface.passcolor4f_vertexbuffer = 0;
12483 rsurface.passcolor4f_bufferoffset = 0;
12485 else if (rsurface.texture->currentmaterialflags & MATERIALFLAG_MODELLIGHT)
12487 qboolean applycolor = true;
12490 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12492 r_refdef.lightmapintensity = 1;
12493 RSurf_DrawBatch_GL11_ApplyVertexShade(&one, &one, &one, &one, &applycolor);
12494 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12496 else if (FAKELIGHT_ENABLED)
12498 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12500 r_refdef.lightmapintensity = r_fakelight_intensity.value;
12501 RSurf_DrawBatch_GL11_ApplyFakeLight();
12502 r_refdef.lightmapintensity = 0; // we're in showsurfaces, after all
12506 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_VERTEXCOLOR | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12508 rsurface.passcolor4f = rsurface.batchlightmapcolor4f;
12509 rsurface.passcolor4f_vertexbuffer = rsurface.batchlightmapcolor4f_vertexbuffer;
12510 rsurface.passcolor4f_bufferoffset = rsurface.batchlightmapcolor4f_bufferoffset;
12513 if(!rsurface.passcolor4f)
12514 RSurf_DrawBatch_GL11_MakeFullbrightLightmapColorArray();
12516 RSurf_DrawBatch_GL11_ApplyAmbient();
12517 RSurf_DrawBatch_GL11_ApplyColor(c[0], c[1], c[2], c[3]);
12518 if(r_refdef.fogenabled)
12519 RSurf_DrawBatch_GL11_ApplyFogToFinishedVertexColors();
12520 RSurf_DrawBatch_GL11_ClampColor();
12522 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.passcolor4f, NULL);
12523 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
12526 else if (!r_refdef.view.showdebug)
12528 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12529 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12530 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12532 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12533 Vector4Set(batchvertex[vi].color4ub, 0, 0, 0, 255);
12535 R_Mesh_PrepareVertices_Generic_Unlock();
12538 else if (r_showsurfaces.integer == 4)
12540 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12541 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchnumvertices);
12542 for (j = 0, vi = rsurface.batchfirstvertex;j < rsurface.batchnumvertices;j++, vi++)
12544 unsigned char c = vi << 3;
12545 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12546 Vector4Set(batchvertex[vi].color4ub, c, c, c, 255);
12548 R_Mesh_PrepareVertices_Generic_Unlock();
12551 else if (r_showsurfaces.integer == 2)
12554 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12555 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(3*rsurface.batchnumtriangles);
12556 for (j = 0, e = rsurface.batchelement3i + 3 * rsurface.batchfirsttriangle;j < rsurface.batchnumtriangles;j++, e += 3)
12558 unsigned char c = (j + rsurface.batchfirsttriangle) << 3;
12559 VectorCopy(rsurface.batchvertex3f + 3*e[0], batchvertex[j*3+0].vertex3f);
12560 VectorCopy(rsurface.batchvertex3f + 3*e[1], batchvertex[j*3+1].vertex3f);
12561 VectorCopy(rsurface.batchvertex3f + 3*e[2], batchvertex[j*3+2].vertex3f);
12562 Vector4Set(batchvertex[j*3+0].color4ub, c, c, c, 255);
12563 Vector4Set(batchvertex[j*3+1].color4ub, c, c, c, 255);
12564 Vector4Set(batchvertex[j*3+2].color4ub, c, c, c, 255);
12566 R_Mesh_PrepareVertices_Generic_Unlock();
12567 R_Mesh_Draw(0, rsurface.batchnumtriangles*3, 0, rsurface.batchnumtriangles, NULL, NULL, 0, NULL, NULL, 0);
12571 int texturesurfaceindex;
12573 const msurface_t *surface;
12574 unsigned char surfacecolor4ub[4];
12575 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist);
12576 batchvertex = R_Mesh_PrepareVertices_Generic_Lock(rsurface.batchfirstvertex + rsurface.batchnumvertices);
12578 for (texturesurfaceindex = 0;texturesurfaceindex < texturenumsurfaces;texturesurfaceindex++)
12580 surface = texturesurfacelist[texturesurfaceindex];
12581 k = (int)(((size_t)surface) / sizeof(msurface_t));
12582 Vector4Set(surfacecolor4ub, (k & 0xF) << 4, (k & 0xF0), (k & 0xF00) >> 4, 255);
12583 for (j = 0;j < surface->num_vertices;j++)
12585 VectorCopy(rsurface.batchvertex3f + 3*vi, batchvertex[vi].vertex3f);
12586 Vector4Copy(surfacecolor4ub, batchvertex[vi].color4ub);
12590 R_Mesh_PrepareVertices_Generic_Unlock();
12595 static void R_DrawWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12598 RSurf_SetupDepthAndCulling();
12599 if (r_showsurfaces.integer)
12601 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12604 switch (vid.renderpath)
12606 case RENDERPATH_GL20:
12607 case RENDERPATH_D3D9:
12608 case RENDERPATH_D3D10:
12609 case RENDERPATH_D3D11:
12610 case RENDERPATH_SOFT:
12611 case RENDERPATH_GLES2:
12612 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12614 case RENDERPATH_GL13:
12615 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12617 case RENDERPATH_GL11:
12618 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12624 static void R_DrawModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean prepass)
12627 RSurf_SetupDepthAndCulling();
12628 if (r_showsurfaces.integer)
12630 R_DrawTextureSurfaceList_ShowSurfaces(texturenumsurfaces, texturesurfacelist, writedepth);
12633 switch (vid.renderpath)
12635 case RENDERPATH_GL20:
12636 case RENDERPATH_D3D9:
12637 case RENDERPATH_D3D10:
12638 case RENDERPATH_D3D11:
12639 case RENDERPATH_SOFT:
12640 case RENDERPATH_GLES2:
12641 R_DrawTextureSurfaceList_GL20(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12643 case RENDERPATH_GL13:
12644 R_DrawTextureSurfaceList_GL13(texturenumsurfaces, texturesurfacelist, writedepth);
12646 case RENDERPATH_GL11:
12647 R_DrawTextureSurfaceList_GL11(texturenumsurfaces, texturesurfacelist, writedepth);
12653 static void R_DrawSurface_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
12656 int texturenumsurfaces, endsurface;
12657 texture_t *texture;
12658 const msurface_t *surface;
12659 #define MAXBATCH_TRANSPARENTSURFACES 256
12660 const msurface_t *texturesurfacelist[MAXBATCH_TRANSPARENTSURFACES];
12662 // if the model is static it doesn't matter what value we give for
12663 // wantnormals and wanttangents, so this logic uses only rules applicable
12664 // to a model, knowing that they are meaningless otherwise
12665 if (ent == r_refdef.scene.worldentity)
12666 RSurf_ActiveWorldEntity();
12667 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
12668 RSurf_ActiveModelEntity(ent, false, false, false);
12671 switch (vid.renderpath)
12673 case RENDERPATH_GL20:
12674 case RENDERPATH_D3D9:
12675 case RENDERPATH_D3D10:
12676 case RENDERPATH_D3D11:
12677 case RENDERPATH_SOFT:
12678 case RENDERPATH_GLES2:
12679 RSurf_ActiveModelEntity(ent, true, true, false);
12681 case RENDERPATH_GL13:
12682 case RENDERPATH_GL11:
12683 RSurf_ActiveModelEntity(ent, true, false, false);
12688 if (r_transparentdepthmasking.integer)
12690 qboolean setup = false;
12691 for (i = 0;i < numsurfaces;i = j)
12694 surface = rsurface.modelsurfaces + surfacelist[i];
12695 texture = surface->texture;
12696 rsurface.texture = R_GetCurrentTexture(texture);
12697 rsurface.lightmaptexture = NULL;
12698 rsurface.deluxemaptexture = NULL;
12699 rsurface.uselightmaptexture = false;
12700 // scan ahead until we find a different texture
12701 endsurface = min(i + 1024, numsurfaces);
12702 texturenumsurfaces = 0;
12703 texturesurfacelist[texturenumsurfaces++] = surface;
12704 for (;j < endsurface;j++)
12706 surface = rsurface.modelsurfaces + surfacelist[j];
12707 if (texture != surface->texture)
12709 texturesurfacelist[texturenumsurfaces++] = surface;
12711 if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_TRANSDEPTH))
12713 // render the range of surfaces as depth
12717 GL_ColorMask(0,0,0,0);
12719 GL_DepthTest(true);
12720 GL_BlendFunc(GL_ONE, GL_ZERO);
12721 GL_DepthMask(true);
12722 // R_Mesh_ResetTextureState();
12723 R_SetupShader_DepthOrShadow();
12725 RSurf_SetupDepthAndCulling();
12726 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12727 if (rsurface.batchvertex3fbuffer)
12728 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12730 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12734 GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
12737 for (i = 0;i < numsurfaces;i = j)
12740 surface = rsurface.modelsurfaces + surfacelist[i];
12741 texture = surface->texture;
12742 rsurface.texture = R_GetCurrentTexture(texture);
12743 // scan ahead until we find a different texture
12744 endsurface = min(i + MAXBATCH_TRANSPARENTSURFACES, numsurfaces);
12745 texturenumsurfaces = 0;
12746 texturesurfacelist[texturenumsurfaces++] = surface;
12747 if(FAKELIGHT_ENABLED)
12749 rsurface.lightmaptexture = NULL;
12750 rsurface.deluxemaptexture = NULL;
12751 rsurface.uselightmaptexture = false;
12752 for (;j < endsurface;j++)
12754 surface = rsurface.modelsurfaces + surfacelist[j];
12755 if (texture != surface->texture)
12757 texturesurfacelist[texturenumsurfaces++] = surface;
12762 rsurface.lightmaptexture = surface->lightmaptexture;
12763 rsurface.deluxemaptexture = surface->deluxemaptexture;
12764 rsurface.uselightmaptexture = surface->lightmaptexture != NULL;
12765 for (;j < endsurface;j++)
12767 surface = rsurface.modelsurfaces + surfacelist[j];
12768 if (texture != surface->texture || rsurface.lightmaptexture != surface->lightmaptexture)
12770 texturesurfacelist[texturenumsurfaces++] = surface;
12773 // render the range of surfaces
12774 if (ent == r_refdef.scene.worldentity)
12775 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12777 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, false, false);
12779 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
12782 static void R_ProcessTransparentTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, const entity_render_t *queueentity)
12784 // transparent surfaces get pushed off into the transparent queue
12785 int surfacelistindex;
12786 const msurface_t *surface;
12787 vec3_t tempcenter, center;
12788 for (surfacelistindex = 0;surfacelistindex < texturenumsurfaces;surfacelistindex++)
12790 surface = texturesurfacelist[surfacelistindex];
12791 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
12792 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
12793 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
12794 Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
12795 if (queueentity->transparent_offset) // transparent offset
12797 center[0] += r_refdef.view.forward[0]*queueentity->transparent_offset;
12798 center[1] += r_refdef.view.forward[1]*queueentity->transparent_offset;
12799 center[2] += r_refdef.view.forward[2]*queueentity->transparent_offset;
12801 R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_DrawSurface_TransparentCallback, queueentity, surface - rsurface.modelsurfaces, rsurface.rtlight);
12805 static void R_DrawTextureSurfaceList_DepthOnly(int texturenumsurfaces, const msurface_t **texturesurfacelist)
12807 if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_BLENDED | MATERIALFLAG_ALPHATEST)))
12809 if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFLECTION)))
12811 RSurf_SetupDepthAndCulling();
12812 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX, texturenumsurfaces, texturesurfacelist);
12813 if (rsurface.batchvertex3fbuffer)
12814 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3fbuffer);
12816 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer);
12820 static void R_ProcessWorldTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, qboolean prepass)
12822 const entity_render_t *queueentity = r_refdef.scene.worldentity;
12825 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12828 if (!rsurface.texture->currentnumlayers)
12830 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12831 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12833 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12835 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12836 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12837 else if (!rsurface.texture->currentnumlayers)
12839 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12841 // in the deferred case, transparent surfaces were queued during prepass
12842 if (!r_shadow_usingdeferredprepass)
12843 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12847 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12848 R_DrawWorldTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12853 void R_QueueWorldSurfaceList(int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12856 texture_t *texture;
12857 R_FrameData_SetMark();
12858 // break the surface list down into batches by texture and use of lightmapping
12859 for (i = 0;i < numsurfaces;i = j)
12862 // texture is the base texture pointer, rsurface.texture is the
12863 // current frame/skin the texture is directing us to use (for example
12864 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12865 // use skin 1 instead)
12866 texture = surfacelist[i]->texture;
12867 rsurface.texture = R_GetCurrentTexture(texture);
12868 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12870 // if this texture is not the kind we want, skip ahead to the next one
12871 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12875 if(FAKELIGHT_ENABLED || depthonly || prepass)
12877 rsurface.lightmaptexture = NULL;
12878 rsurface.deluxemaptexture = NULL;
12879 rsurface.uselightmaptexture = false;
12880 // simply scan ahead until we find a different texture or lightmap state
12881 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12886 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12887 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12888 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12889 // simply scan ahead until we find a different texture or lightmap state
12890 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12893 // render the range of surfaces
12894 R_ProcessWorldTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, prepass);
12896 R_FrameData_ReturnToMark();
12899 static void R_ProcessModelTextureSurfaceList(int texturenumsurfaces, const msurface_t **texturesurfacelist, qboolean writedepth, qboolean depthonly, const entity_render_t *queueentity, qboolean prepass)
12903 R_DrawTextureSurfaceList_DepthOnly(texturenumsurfaces, texturesurfacelist);
12906 if (!rsurface.texture->currentnumlayers)
12908 if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
12909 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12911 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth, prepass);
12913 else if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_SKY) && !r_showsurfaces.integer)
12914 R_DrawTextureSurfaceList_Sky(texturenumsurfaces, texturesurfacelist);
12915 else if (!rsurface.texture->currentnumlayers)
12917 else if (((rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED) || (r_showsurfaces.integer == 3 && (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST))) && queueentity)
12919 // in the deferred case, transparent surfaces were queued during prepass
12920 if (!r_shadow_usingdeferredprepass)
12921 R_ProcessTransparentTextureSurfaceList(texturenumsurfaces, texturesurfacelist, queueentity);
12925 // the alphatest check is to make sure we write depth for anything we skipped on the depth-only pass earlier
12926 R_DrawModelTextureSurfaceList(texturenumsurfaces, texturesurfacelist, writedepth || (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST), prepass);
12931 void R_QueueModelSurfaceList(entity_render_t *ent, int numsurfaces, const msurface_t **surfacelist, int flagsmask, qboolean writedepth, qboolean depthonly, qboolean prepass)
12934 texture_t *texture;
12935 R_FrameData_SetMark();
12936 // break the surface list down into batches by texture and use of lightmapping
12937 for (i = 0;i < numsurfaces;i = j)
12940 // texture is the base texture pointer, rsurface.texture is the
12941 // current frame/skin the texture is directing us to use (for example
12942 // if a model has 2 skins and it is on skin 1, then skin 0 tells us to
12943 // use skin 1 instead)
12944 texture = surfacelist[i]->texture;
12945 rsurface.texture = R_GetCurrentTexture(texture);
12946 if (!(rsurface.texture->currentmaterialflags & flagsmask) || (rsurface.texture->currentmaterialflags & MATERIALFLAG_NODRAW))
12948 // if this texture is not the kind we want, skip ahead to the next one
12949 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12953 if(FAKELIGHT_ENABLED || depthonly || prepass)
12955 rsurface.lightmaptexture = NULL;
12956 rsurface.deluxemaptexture = NULL;
12957 rsurface.uselightmaptexture = false;
12958 // simply scan ahead until we find a different texture or lightmap state
12959 for (;j < numsurfaces && texture == surfacelist[j]->texture;j++)
12964 rsurface.lightmaptexture = surfacelist[i]->lightmaptexture;
12965 rsurface.deluxemaptexture = surfacelist[i]->deluxemaptexture;
12966 rsurface.uselightmaptexture = surfacelist[i]->lightmaptexture != NULL;
12967 // simply scan ahead until we find a different texture or lightmap state
12968 for (;j < numsurfaces && texture == surfacelist[j]->texture && rsurface.lightmaptexture == surfacelist[j]->lightmaptexture;j++)
12971 // render the range of surfaces
12972 R_ProcessModelTextureSurfaceList(j - i, surfacelist + i, writedepth, depthonly, ent, prepass);
12974 R_FrameData_ReturnToMark();
12977 float locboxvertex3f[6*4*3] =
12979 1,0,1, 1,0,0, 1,1,0, 1,1,1,
12980 0,1,1, 0,1,0, 0,0,0, 0,0,1,
12981 1,1,1, 1,1,0, 0,1,0, 0,1,1,
12982 0,0,1, 0,0,0, 1,0,0, 1,0,1,
12983 0,0,1, 1,0,1, 1,1,1, 0,1,1,
12984 1,0,0, 0,0,0, 0,1,0, 1,1,0
12987 unsigned short locboxelements[6*2*3] =
12992 12,13,14, 12,14,15,
12993 16,17,18, 16,18,19,
12997 void R_DrawLoc_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
13000 cl_locnode_t *loc = (cl_locnode_t *)ent;
13002 float vertex3f[6*4*3];
13004 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13005 GL_DepthMask(false);
13006 GL_DepthRange(0, 1);
13007 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13008 GL_DepthTest(true);
13009 GL_CullFace(GL_NONE);
13010 R_EntityMatrix(&identitymatrix);
13012 // R_Mesh_ResetTextureState();
13014 i = surfacelist[0];
13015 GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13016 ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13017 ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
13018 surfacelist[0] < 0 ? 0.5f : 0.125f);
13020 if (VectorCompare(loc->mins, loc->maxs))
13022 VectorSet(size, 2, 2, 2);
13023 VectorMA(loc->mins, -0.5f, size, mins);
13027 VectorCopy(loc->mins, mins);
13028 VectorSubtract(loc->maxs, loc->mins, size);
13031 for (i = 0;i < 6*4*3;)
13032 for (j = 0;j < 3;j++, i++)
13033 vertex3f[i] = mins[j] + size[j] * locboxvertex3f[i];
13035 R_Mesh_PrepareVertices_Generic_Arrays(6*4, vertex3f, NULL, NULL);
13036 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13037 R_Mesh_Draw(0, 6*4, 0, 6*2, NULL, NULL, 0, locboxelements, NULL, 0);
13040 void R_DrawLocs(void)
13043 cl_locnode_t *loc, *nearestloc;
13045 nearestloc = CL_Locs_FindNearest(cl.movement_origin);
13046 for (loc = cl.locnodes, index = 0;loc;loc = loc->next, index++)
13048 VectorLerp(loc->mins, 0.5f, loc->maxs, center);
13049 R_MeshQueue_AddTransparent(center, R_DrawLoc_Callback, (entity_render_t *)loc, loc == nearestloc ? -1 : index, NULL);
13053 void R_DecalSystem_Reset(decalsystem_t *decalsystem)
13055 if (decalsystem->decals)
13056 Mem_Free(decalsystem->decals);
13057 memset(decalsystem, 0, sizeof(*decalsystem));
13060 static void R_DecalSystem_SpawnTriangle(decalsystem_t *decalsystem, const float *v0, const float *v1, const float *v2, const float *t0, const float *t1, const float *t2, const float *c0, const float *c1, const float *c2, int triangleindex, int surfaceindex, int decalsequence)
13063 tridecal_t *decals;
13066 // expand or initialize the system
13067 if (decalsystem->maxdecals <= decalsystem->numdecals)
13069 decalsystem_t old = *decalsystem;
13070 qboolean useshortelements;
13071 decalsystem->maxdecals = max(16, decalsystem->maxdecals * 2);
13072 useshortelements = decalsystem->maxdecals * 3 <= 65536;
13073 decalsystem->decals = (tridecal_t *)Mem_Alloc(cls.levelmempool, decalsystem->maxdecals * (sizeof(tridecal_t) + sizeof(float[3][3]) + sizeof(float[3][2]) + sizeof(float[3][4]) + sizeof(int[3]) + (useshortelements ? sizeof(unsigned short[3]) : 0)));
13074 decalsystem->color4f = (float *)(decalsystem->decals + decalsystem->maxdecals);
13075 decalsystem->texcoord2f = (float *)(decalsystem->color4f + decalsystem->maxdecals*12);
13076 decalsystem->vertex3f = (float *)(decalsystem->texcoord2f + decalsystem->maxdecals*6);
13077 decalsystem->element3i = (int *)(decalsystem->vertex3f + decalsystem->maxdecals*9);
13078 decalsystem->element3s = (useshortelements ? ((unsigned short *)(decalsystem->element3i + decalsystem->maxdecals*3)) : NULL);
13079 if (decalsystem->numdecals)
13080 memcpy(decalsystem->decals, old.decals, decalsystem->numdecals * sizeof(tridecal_t));
13082 Mem_Free(old.decals);
13083 for (i = 0;i < decalsystem->maxdecals*3;i++)
13084 decalsystem->element3i[i] = i;
13085 if (useshortelements)
13086 for (i = 0;i < decalsystem->maxdecals*3;i++)
13087 decalsystem->element3s[i] = i;
13090 // grab a decal and search for another free slot for the next one
13091 decals = decalsystem->decals;
13092 decal = decalsystem->decals + (i = decalsystem->freedecal++);
13093 for (i = decalsystem->freedecal;i < decalsystem->numdecals && decals[i].color4ub[0][3];i++)
13095 decalsystem->freedecal = i;
13096 if (decalsystem->numdecals <= i)
13097 decalsystem->numdecals = i + 1;
13099 // initialize the decal
13101 decal->triangleindex = triangleindex;
13102 decal->surfaceindex = surfaceindex;
13103 decal->decalsequence = decalsequence;
13104 decal->color4ub[0][0] = (unsigned char)(c0[0]*255.0f);
13105 decal->color4ub[0][1] = (unsigned char)(c0[1]*255.0f);
13106 decal->color4ub[0][2] = (unsigned char)(c0[2]*255.0f);
13107 decal->color4ub[0][3] = 255;
13108 decal->color4ub[1][0] = (unsigned char)(c1[0]*255.0f);
13109 decal->color4ub[1][1] = (unsigned char)(c1[1]*255.0f);
13110 decal->color4ub[1][2] = (unsigned char)(c1[2]*255.0f);
13111 decal->color4ub[1][3] = 255;
13112 decal->color4ub[2][0] = (unsigned char)(c2[0]*255.0f);
13113 decal->color4ub[2][1] = (unsigned char)(c2[1]*255.0f);
13114 decal->color4ub[2][2] = (unsigned char)(c2[2]*255.0f);
13115 decal->color4ub[2][3] = 255;
13116 decal->vertex3f[0][0] = v0[0];
13117 decal->vertex3f[0][1] = v0[1];
13118 decal->vertex3f[0][2] = v0[2];
13119 decal->vertex3f[1][0] = v1[0];
13120 decal->vertex3f[1][1] = v1[1];
13121 decal->vertex3f[1][2] = v1[2];
13122 decal->vertex3f[2][0] = v2[0];
13123 decal->vertex3f[2][1] = v2[1];
13124 decal->vertex3f[2][2] = v2[2];
13125 decal->texcoord2f[0][0] = t0[0];
13126 decal->texcoord2f[0][1] = t0[1];
13127 decal->texcoord2f[1][0] = t1[0];
13128 decal->texcoord2f[1][1] = t1[1];
13129 decal->texcoord2f[2][0] = t2[0];
13130 decal->texcoord2f[2][1] = t2[1];
13133 extern cvar_t cl_decals_bias;
13134 extern cvar_t cl_decals_models;
13135 extern cvar_t cl_decals_newsystem_intensitymultiplier;
13136 // baseparms, parms, temps
13137 static void R_DecalSystem_SplatTriangle(decalsystem_t *decalsystem, float r, float g, float b, float a, float s1, float t1, float s2, float t2, int decalsequence, qboolean dynamic, float (*planes)[4], matrix4x4_t *projection, int triangleindex, int surfaceindex)
13142 const float *vertex3f;
13144 float points[2][9][3];
13151 e = rsurface.modelelement3i + 3*triangleindex;
13153 vertex3f = rsurface.modelvertex3f;
13155 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13157 index = 3*e[cornerindex];
13158 VectorCopy(vertex3f + index, v[cornerindex]);
13161 //TriangleNormal(v[0], v[1], v[2], normal);
13162 //if (DotProduct(normal, localnormal) < 0.0f)
13164 // clip by each of the box planes formed from the projection matrix
13165 // if anything survives, we emit the decal
13166 numpoints = PolygonF_Clip(3 , v[0] , planes[0][0], planes[0][1], planes[0][2], planes[0][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13169 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[1][0], planes[1][1], planes[1][2], planes[1][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
13172 numpoints = PolygonF_Clip(numpoints, points[0][0], planes[2][0], planes[2][1], planes[2][2], planes[2][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13175 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[3][0], planes[3][1], planes[3][2], planes[3][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[0][0]);
13178 numpoints = PolygonF_Clip(numpoints, points[0][0], planes[4][0], planes[4][1], planes[4][2], planes[4][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), points[1][0]);
13181 numpoints = PolygonF_Clip(numpoints, points[1][0], planes[5][0], planes[5][1], planes[5][2], planes[5][3], 1.0f/64.0f, sizeof(points[0])/sizeof(points[0][0]), v[0]);
13184 // some part of the triangle survived, so we have to accept it...
13187 // dynamic always uses the original triangle
13189 for (cornerindex = 0;cornerindex < 3;cornerindex++)
13191 index = 3*e[cornerindex];
13192 VectorCopy(vertex3f + index, v[cornerindex]);
13195 for (cornerindex = 0;cornerindex < numpoints;cornerindex++)
13197 // convert vertex positions to texcoords
13198 Matrix4x4_Transform(projection, v[cornerindex], temp);
13199 tc[cornerindex][0] = (temp[1]+1.0f)*0.5f * (s2-s1) + s1;
13200 tc[cornerindex][1] = (temp[2]+1.0f)*0.5f * (t2-t1) + t1;
13201 // calculate distance fade from the projection origin
13202 f = a * (1.0f-fabs(temp[0])) * cl_decals_newsystem_intensitymultiplier.value;
13203 f = bound(0.0f, f, 1.0f);
13204 c[cornerindex][0] = r * f;
13205 c[cornerindex][1] = g * f;
13206 c[cornerindex][2] = b * f;
13207 c[cornerindex][3] = 1.0f;
13208 //VectorMA(v[cornerindex], cl_decals_bias.value, localnormal, v[cornerindex]);
13211 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[1], v[2], tc[0], tc[1], tc[2], c[0], c[1], c[2], triangleindex, surfaceindex, decalsequence);
13213 for (cornerindex = 0;cornerindex < numpoints-2;cornerindex++)
13214 R_DecalSystem_SpawnTriangle(decalsystem, v[0], v[cornerindex+1], v[cornerindex+2], tc[0], tc[cornerindex+1], tc[cornerindex+2], c[0], c[cornerindex+1], c[cornerindex+2], -1, surfaceindex, decalsequence);
13216 static void R_DecalSystem_SplatEntity(entity_render_t *ent, const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
13218 matrix4x4_t projection;
13219 decalsystem_t *decalsystem;
13222 const msurface_t *surface;
13223 const msurface_t *surfaces;
13224 const int *surfacelist;
13225 const texture_t *texture;
13227 int numsurfacelist;
13228 int surfacelistindex;
13231 float localorigin[3];
13232 float localnormal[3];
13233 float localmins[3];
13234 float localmaxs[3];
13237 float planes[6][4];
13240 int bih_triangles_count;
13241 int bih_triangles[256];
13242 int bih_surfaces[256];
13244 decalsystem = &ent->decalsystem;
13245 model = ent->model;
13246 if (!model || !ent->allowdecals || ent->alpha < 1 || (ent->flags & (RENDER_ADDITIVE | RENDER_NODEPTHTEST)))
13248 R_DecalSystem_Reset(&ent->decalsystem);
13252 if (!model->brush.data_leafs && !cl_decals_models.integer)
13254 if (decalsystem->model)
13255 R_DecalSystem_Reset(decalsystem);
13259 if (decalsystem->model != model)
13260 R_DecalSystem_Reset(decalsystem);
13261 decalsystem->model = model;
13263 RSurf_ActiveModelEntity(ent, false, false, false);
13265 Matrix4x4_Transform(&rsurface.inversematrix, worldorigin, localorigin);
13266 Matrix4x4_Transform3x3(&rsurface.inversematrix, worldnormal, localnormal);
13267 VectorNormalize(localnormal);
13268 localsize = worldsize*rsurface.inversematrixscale;
13269 localmins[0] = localorigin[0] - localsize;
13270 localmins[1] = localorigin[1] - localsize;
13271 localmins[2] = localorigin[2] - localsize;
13272 localmaxs[0] = localorigin[0] + localsize;
13273 localmaxs[1] = localorigin[1] + localsize;
13274 localmaxs[2] = localorigin[2] + localsize;
13276 //VectorCopy(localnormal, planes[4]);
13277 //VectorVectors(planes[4], planes[2], planes[0]);
13278 AnglesFromVectors(angles, localnormal, NULL, false);
13279 AngleVectors(angles, planes[0], planes[2], planes[4]);
13280 VectorNegate(planes[0], planes[1]);
13281 VectorNegate(planes[2], planes[3]);
13282 VectorNegate(planes[4], planes[5]);
13283 planes[0][3] = DotProduct(planes[0], localorigin) - localsize;
13284 planes[1][3] = DotProduct(planes[1], localorigin) - localsize;
13285 planes[2][3] = DotProduct(planes[2], localorigin) - localsize;
13286 planes[3][3] = DotProduct(planes[3], localorigin) - localsize;
13287 planes[4][3] = DotProduct(planes[4], localorigin) - localsize;
13288 planes[5][3] = DotProduct(planes[5], localorigin) - localsize;
13293 matrix4x4_t forwardprojection;
13294 Matrix4x4_CreateFromQuakeEntity(&forwardprojection, localorigin[0], localorigin[1], localorigin[2], angles[0], angles[1], angles[2], localsize);
13295 Matrix4x4_Invert_Simple(&projection, &forwardprojection);
13300 float projectionvector[4][3];
13301 VectorScale(planes[0], ilocalsize, projectionvector[0]);
13302 VectorScale(planes[2], ilocalsize, projectionvector[1]);
13303 VectorScale(planes[4], ilocalsize, projectionvector[2]);
13304 projectionvector[0][0] = planes[0][0] * ilocalsize;
13305 projectionvector[0][1] = planes[1][0] * ilocalsize;
13306 projectionvector[0][2] = planes[2][0] * ilocalsize;
13307 projectionvector[1][0] = planes[0][1] * ilocalsize;
13308 projectionvector[1][1] = planes[1][1] * ilocalsize;
13309 projectionvector[1][2] = planes[2][1] * ilocalsize;
13310 projectionvector[2][0] = planes[0][2] * ilocalsize;
13311 projectionvector[2][1] = planes[1][2] * ilocalsize;
13312 projectionvector[2][2] = planes[2][2] * ilocalsize;
13313 projectionvector[3][0] = -(localorigin[0]*projectionvector[0][0]+localorigin[1]*projectionvector[1][0]+localorigin[2]*projectionvector[2][0]);
13314 projectionvector[3][1] = -(localorigin[0]*projectionvector[0][1]+localorigin[1]*projectionvector[1][1]+localorigin[2]*projectionvector[2][1]);
13315 projectionvector[3][2] = -(localorigin[0]*projectionvector[0][2]+localorigin[1]*projectionvector[1][2]+localorigin[2]*projectionvector[2][2]);
13316 Matrix4x4_FromVectors(&projection, projectionvector[0], projectionvector[1], projectionvector[2], projectionvector[3]);
13320 dynamic = model->surfmesh.isanimated;
13321 numsurfacelist = model->nummodelsurfaces;
13322 surfacelist = model->sortedmodelsurfaces;
13323 surfaces = model->data_surfaces;
13326 bih_triangles_count = -1;
13329 if(model->render_bih.numleafs)
13330 bih = &model->render_bih;
13331 else if(model->collision_bih.numleafs)
13332 bih = &model->collision_bih;
13335 bih_triangles_count = BIH_GetTriangleListForBox(bih, sizeof(bih_triangles) / sizeof(*bih_triangles), bih_triangles, bih_surfaces, localmins, localmaxs);
13336 if(bih_triangles_count == 0)
13338 if(bih_triangles_count > (int) (sizeof(bih_triangles) / sizeof(*bih_triangles))) // hit too many, likely bad anyway
13340 if(bih_triangles_count > 0)
13342 for (triangleindex = 0; triangleindex < bih_triangles_count; ++triangleindex)
13344 surfaceindex = bih_surfaces[triangleindex];
13345 surface = surfaces + surfaceindex;
13346 texture = surface->texture;
13347 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13349 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13351 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, bih_triangles[triangleindex], surfaceindex);
13356 for (surfacelistindex = 0;surfacelistindex < numsurfacelist;surfacelistindex++)
13358 surfaceindex = surfacelist[surfacelistindex];
13359 surface = surfaces + surfaceindex;
13360 // check cull box first because it rejects more than any other check
13361 if (!dynamic && !BoxesOverlap(surface->mins, surface->maxs, localmins, localmaxs))
13363 // skip transparent surfaces
13364 texture = surface->texture;
13365 if (texture->currentmaterialflags & (MATERIALFLAG_BLENDED | MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_SKY | MATERIALFLAG_SHORTDEPTHRANGE | MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION))
13367 if (texture->surfaceflags & Q3SURFACEFLAG_NOMARKS)
13369 numtriangles = surface->num_triangles;
13370 for (triangleindex = 0; triangleindex < numtriangles; triangleindex++)
13371 R_DecalSystem_SplatTriangle(decalsystem, r, g, b, a, s1, t1, s2, t2, decalsequence, dynamic, planes, &projection, triangleindex + surface->num_firsttriangle, surfaceindex);
13376 // do not call this outside of rendering code - use R_DecalSystem_SplatEntities instead
13377 static void R_DecalSystem_ApplySplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize, int decalsequence)
13379 int renderentityindex;
13380 float worldmins[3];
13381 float worldmaxs[3];
13382 entity_render_t *ent;
13384 if (!cl_decals_newsystem.integer)
13387 worldmins[0] = worldorigin[0] - worldsize;
13388 worldmins[1] = worldorigin[1] - worldsize;
13389 worldmins[2] = worldorigin[2] - worldsize;
13390 worldmaxs[0] = worldorigin[0] + worldsize;
13391 worldmaxs[1] = worldorigin[1] + worldsize;
13392 worldmaxs[2] = worldorigin[2] + worldsize;
13394 R_DecalSystem_SplatEntity(r_refdef.scene.worldentity, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13396 for (renderentityindex = 0;renderentityindex < r_refdef.scene.numentities;renderentityindex++)
13398 ent = r_refdef.scene.entities[renderentityindex];
13399 if (!BoxesOverlap(ent->mins, ent->maxs, worldmins, worldmaxs))
13402 R_DecalSystem_SplatEntity(ent, worldorigin, worldnormal, r, g, b, a, s1, t1, s2, t2, worldsize, decalsequence);
13406 typedef struct r_decalsystem_splatqueue_s
13408 vec3_t worldorigin;
13409 vec3_t worldnormal;
13415 r_decalsystem_splatqueue_t;
13417 int r_decalsystem_numqueued = 0;
13418 r_decalsystem_splatqueue_t r_decalsystem_queue[MAX_DECALSYSTEM_QUEUE];
13420 void R_DecalSystem_SplatEntities(const vec3_t worldorigin, const vec3_t worldnormal, float r, float g, float b, float a, float s1, float t1, float s2, float t2, float worldsize)
13422 r_decalsystem_splatqueue_t *queue;
13424 if (!cl_decals_newsystem.integer || r_decalsystem_numqueued == MAX_DECALSYSTEM_QUEUE)
13427 queue = &r_decalsystem_queue[r_decalsystem_numqueued++];
13428 VectorCopy(worldorigin, queue->worldorigin);
13429 VectorCopy(worldnormal, queue->worldnormal);
13430 Vector4Set(queue->color, r, g, b, a);
13431 Vector4Set(queue->tcrange, s1, t1, s2, t2);
13432 queue->worldsize = worldsize;
13433 queue->decalsequence = cl.decalsequence++;
13436 static void R_DecalSystem_ApplySplatEntitiesQueue(void)
13439 r_decalsystem_splatqueue_t *queue;
13441 for (i = 0, queue = r_decalsystem_queue;i < r_decalsystem_numqueued;i++, queue++)
13442 R_DecalSystem_ApplySplatEntities(queue->worldorigin, queue->worldnormal, queue->color[0], queue->color[1], queue->color[2], queue->color[3], queue->tcrange[0], queue->tcrange[1], queue->tcrange[2], queue->tcrange[3], queue->worldsize, queue->decalsequence);
13443 r_decalsystem_numqueued = 0;
13446 extern cvar_t cl_decals_max;
13447 static void R_DrawModelDecals_FadeEntity(entity_render_t *ent)
13450 decalsystem_t *decalsystem = &ent->decalsystem;
13457 if (!decalsystem->numdecals)
13460 if (r_showsurfaces.integer)
13463 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13465 R_DecalSystem_Reset(decalsystem);
13469 killsequence = cl.decalsequence - max(1, cl_decals_max.integer);
13470 lifetime = cl_decals_time.value + cl_decals_fadetime.value;
13472 if (decalsystem->lastupdatetime)
13473 frametime = (cl.time - decalsystem->lastupdatetime);
13476 decalsystem->lastupdatetime = cl.time;
13477 decal = decalsystem->decals;
13478 numdecals = decalsystem->numdecals;
13480 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13482 if (decal->color4ub[0][3])
13484 decal->lived += frametime;
13485 if (killsequence - decal->decalsequence > 0 || decal->lived >= lifetime)
13487 memset(decal, 0, sizeof(*decal));
13488 if (decalsystem->freedecal > i)
13489 decalsystem->freedecal = i;
13493 decal = decalsystem->decals;
13494 while (numdecals > 0 && !decal[numdecals-1].color4ub[0][3])
13497 // collapse the array by shuffling the tail decals into the gaps
13500 while (decalsystem->freedecal < numdecals && decal[decalsystem->freedecal].color4ub[0][3])
13501 decalsystem->freedecal++;
13502 if (decalsystem->freedecal == numdecals)
13504 decal[decalsystem->freedecal] = decal[--numdecals];
13507 decalsystem->numdecals = numdecals;
13509 if (numdecals <= 0)
13511 // if there are no decals left, reset decalsystem
13512 R_DecalSystem_Reset(decalsystem);
13516 extern skinframe_t *decalskinframe;
13517 static void R_DrawModelDecals_Entity(entity_render_t *ent)
13520 decalsystem_t *decalsystem = &ent->decalsystem;
13529 const unsigned char *surfacevisible = ent == r_refdef.scene.worldentity ? r_refdef.viewcache.world_surfacevisible : NULL;
13532 numdecals = decalsystem->numdecals;
13536 if (r_showsurfaces.integer)
13539 if (ent->model != decalsystem->model || ent->alpha < 1 || (ent->flags & RENDER_ADDITIVE))
13541 R_DecalSystem_Reset(decalsystem);
13545 // if the model is static it doesn't matter what value we give for
13546 // wantnormals and wanttangents, so this logic uses only rules applicable
13547 // to a model, knowing that they are meaningless otherwise
13548 if (ent == r_refdef.scene.worldentity)
13549 RSurf_ActiveWorldEntity();
13551 RSurf_ActiveModelEntity(ent, false, false, false);
13553 decalsystem->lastupdatetime = cl.time;
13554 decal = decalsystem->decals;
13556 faderate = 1.0f / max(0.001f, cl_decals_fadetime.value);
13558 // update vertex positions for animated models
13559 v3f = decalsystem->vertex3f;
13560 c4f = decalsystem->color4f;
13561 t2f = decalsystem->texcoord2f;
13562 for (i = 0, decal = decalsystem->decals;i < numdecals;i++, decal++)
13564 if (!decal->color4ub[0][3])
13567 if (surfacevisible && !surfacevisible[decal->surfaceindex])
13570 // update color values for fading decals
13571 if (decal->lived >= cl_decals_time.value)
13573 alpha = 1 - faderate * (decal->lived - cl_decals_time.value);
13574 alpha *= (1.0f/255.0f);
13577 alpha = 1.0f/255.0f;
13579 c4f[ 0] = decal->color4ub[0][0] * alpha;
13580 c4f[ 1] = decal->color4ub[0][1] * alpha;
13581 c4f[ 2] = decal->color4ub[0][2] * alpha;
13583 c4f[ 4] = decal->color4ub[1][0] * alpha;
13584 c4f[ 5] = decal->color4ub[1][1] * alpha;
13585 c4f[ 6] = decal->color4ub[1][2] * alpha;
13587 c4f[ 8] = decal->color4ub[2][0] * alpha;
13588 c4f[ 9] = decal->color4ub[2][1] * alpha;
13589 c4f[10] = decal->color4ub[2][2] * alpha;
13592 t2f[0] = decal->texcoord2f[0][0];
13593 t2f[1] = decal->texcoord2f[0][1];
13594 t2f[2] = decal->texcoord2f[1][0];
13595 t2f[3] = decal->texcoord2f[1][1];
13596 t2f[4] = decal->texcoord2f[2][0];
13597 t2f[5] = decal->texcoord2f[2][1];
13599 // update vertex positions for animated models
13600 if (decal->triangleindex >= 0 && decal->triangleindex < rsurface.modelnumtriangles)
13602 e = rsurface.modelelement3i + 3*decal->triangleindex;
13603 VectorCopy(rsurface.modelvertex3f + 3*e[0], v3f);
13604 VectorCopy(rsurface.modelvertex3f + 3*e[1], v3f + 3);
13605 VectorCopy(rsurface.modelvertex3f + 3*e[2], v3f + 6);
13609 VectorCopy(decal->vertex3f[0], v3f);
13610 VectorCopy(decal->vertex3f[1], v3f + 3);
13611 VectorCopy(decal->vertex3f[2], v3f + 6);
13614 if (r_refdef.fogenabled)
13616 alpha = RSurf_FogVertex(v3f);
13617 VectorScale(c4f, alpha, c4f);
13618 alpha = RSurf_FogVertex(v3f + 3);
13619 VectorScale(c4f + 4, alpha, c4f + 4);
13620 alpha = RSurf_FogVertex(v3f + 6);
13621 VectorScale(c4f + 8, alpha, c4f + 8);
13632 r_refdef.stats.drawndecals += numtris;
13634 // now render the decals all at once
13635 // (this assumes they all use one particle font texture!)
13636 RSurf_ActiveCustomEntity(&rsurface.matrix, &rsurface.inversematrix, rsurface.ent_flags, rsurface.ent_shadertime, 1, 1, 1, 1, numdecals*3, decalsystem->vertex3f, decalsystem->texcoord2f, NULL, NULL, NULL, decalsystem->color4f, numtris, decalsystem->element3i, decalsystem->element3s, false, false);
13637 // R_Mesh_ResetTextureState();
13638 R_Mesh_PrepareVertices_Generic_Arrays(numtris * 3, decalsystem->vertex3f, decalsystem->color4f, decalsystem->texcoord2f);
13639 GL_DepthMask(false);
13640 GL_DepthRange(0, 1);
13641 GL_PolygonOffset(rsurface.basepolygonfactor + r_polygonoffset_decals_factor.value, rsurface.basepolygonoffset + r_polygonoffset_decals_offset.value);
13642 GL_DepthTest(true);
13643 GL_CullFace(GL_NONE);
13644 GL_BlendFunc(GL_ZERO, GL_ONE_MINUS_SRC_COLOR);
13645 R_SetupShader_Generic(decalskinframe->base, NULL, GL_MODULATE, 1);
13646 R_Mesh_Draw(0, numtris * 3, 0, numtris, decalsystem->element3i, NULL, 0, decalsystem->element3s, NULL, 0);
13650 static void R_DrawModelDecals(void)
13654 // fade faster when there are too many decals
13655 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13656 for (i = 0;i < r_refdef.scene.numentities;i++)
13657 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13659 R_DrawModelDecals_FadeEntity(r_refdef.scene.worldentity);
13660 for (i = 0;i < r_refdef.scene.numentities;i++)
13661 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13662 R_DrawModelDecals_FadeEntity(r_refdef.scene.entities[i]);
13664 R_DecalSystem_ApplySplatEntitiesQueue();
13666 numdecals = r_refdef.scene.worldentity->decalsystem.numdecals;
13667 for (i = 0;i < r_refdef.scene.numentities;i++)
13668 numdecals += r_refdef.scene.entities[i]->decalsystem.numdecals;
13670 r_refdef.stats.totaldecals += numdecals;
13672 if (r_showsurfaces.integer)
13675 R_DrawModelDecals_Entity(r_refdef.scene.worldentity);
13677 for (i = 0;i < r_refdef.scene.numentities;i++)
13679 if (!r_refdef.viewcache.entityvisible[i])
13681 if (r_refdef.scene.entities[i]->decalsystem.numdecals)
13682 R_DrawModelDecals_Entity(r_refdef.scene.entities[i]);
13686 extern cvar_t mod_collision_bih;
13687 void R_DrawDebugModel(void)
13689 entity_render_t *ent = rsurface.entity;
13690 int i, j, k, l, flagsmask;
13691 const msurface_t *surface;
13692 dp_model_t *model = ent->model;
13695 switch(vid.renderpath)
13697 case RENDERPATH_GL11:
13698 case RENDERPATH_GL13:
13699 case RENDERPATH_GL20:
13701 case RENDERPATH_D3D9:
13702 //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13704 case RENDERPATH_D3D10:
13705 Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13707 case RENDERPATH_D3D11:
13708 Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13710 case RENDERPATH_SOFT:
13711 //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13713 case RENDERPATH_GLES2:
13714 //Con_DPrintf("FIXME GLES2 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__);
13718 flagsmask = MATERIALFLAG_SKY | MATERIALFLAG_WALL;
13720 // R_Mesh_ResetTextureState();
13721 R_SetupShader_Generic(NULL, NULL, GL_MODULATE, 1);
13722 GL_DepthRange(0, 1);
13723 GL_DepthTest(!r_showdisabledepthtest.integer);
13724 GL_DepthMask(false);
13725 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13727 if (r_showcollisionbrushes.value > 0 && model->collision_bih.numleafs)
13731 qboolean cullbox = ent == r_refdef.scene.worldentity;
13732 const q3mbrush_t *brush;
13733 const bih_t *bih = &model->collision_bih;
13734 const bih_leaf_t *bihleaf;
13735 float vertex3f[3][3];
13736 GL_PolygonOffset(r_refdef.polygonfactor + r_showcollisionbrushes_polygonfactor.value, r_refdef.polygonoffset + r_showcollisionbrushes_polygonoffset.value);
13738 for (bihleafindex = 0, bihleaf = bih->leafs;bihleafindex < bih->numleafs;bihleafindex++, bihleaf++)
13740 if (cullbox && R_CullBox(bihleaf->mins, bihleaf->maxs))
13742 switch (bihleaf->type)
13745 brush = model->brush.data_brushes + bihleaf->itemindex;
13746 if (brush->colbrushf && brush->colbrushf->numtriangles)
13748 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
13749 R_Mesh_PrepareVertices_Generic_Arrays(brush->colbrushf->numpoints, brush->colbrushf->points->v, NULL, NULL);
13750 R_Mesh_Draw(0, brush->colbrushf->numpoints, 0, brush->colbrushf->numtriangles, brush->colbrushf->elements, NULL, 0, NULL, NULL, 0);
13753 case BIH_COLLISIONTRIANGLE:
13754 triangleindex = bihleaf->itemindex;
13755 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+0], vertex3f[0]);
13756 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+1], vertex3f[1]);
13757 VectorCopy(model->brush.data_collisionvertex3f + 3*model->brush.data_collisionelement3i[triangleindex*3+2], vertex3f[2]);
13758 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
13759 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13760 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13762 case BIH_RENDERTRIANGLE:
13763 triangleindex = bihleaf->itemindex;
13764 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+0], vertex3f[0]);
13765 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+1], vertex3f[1]);
13766 VectorCopy(model->surfmesh.data_vertex3f + 3*model->surfmesh.data_element3i[triangleindex*3+2], vertex3f[2]);
13767 GL_Color((bihleafindex & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 5) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, ((bihleafindex >> 10) & 31) * (1.0f / 32.0f) * r_refdef.view.colorscale, r_showcollisionbrushes.value);
13768 R_Mesh_PrepareVertices_Generic_Arrays(3, vertex3f[0], NULL, NULL);
13769 R_Mesh_Draw(0, 3, 0, 1, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
13775 GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
13777 if (r_showtris.integer || (r_shownormals.value != 0))
13779 if (r_showdisabledepthtest.integer)
13781 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
13782 GL_DepthMask(false);
13786 GL_BlendFunc(GL_ONE, GL_ZERO);
13787 GL_DepthMask(true);
13789 for (i = 0, j = model->firstmodelsurface, surface = model->data_surfaces + j;i < model->nummodelsurfaces;i++, j++, surface++)
13791 if (ent == r_refdef.scene.worldentity && !r_refdef.viewcache.world_surfacevisible[j])
13793 rsurface.texture = R_GetCurrentTexture(surface->texture);
13794 if ((rsurface.texture->currentmaterialflags & flagsmask) && surface->num_triangles)
13796 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ARRAY_NORMAL | BATCHNEED_ARRAY_VECTOR | BATCHNEED_NOGAPS, 1, &surface);
13797 if (r_showtris.value > 0)
13799 if (!rsurface.texture->currentlayers->depthmask)
13800 GL_Color(r_refdef.view.colorscale, 0, 0, r_showtris.value);
13801 else if (ent == r_refdef.scene.worldentity)
13802 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, r_showtris.value);
13804 GL_Color(0, r_refdef.view.colorscale, 0, r_showtris.value);
13805 R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL);
13806 qglPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
13808 qglPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
13811 if (r_shownormals.value < 0)
13813 qglBegin(GL_LINES);
13814 for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13816 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13817 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13818 qglVertex3f(v[0], v[1], v[2]);
13819 VectorMA(v, -r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13820 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13821 qglVertex3f(v[0], v[1], v[2]);
13826 if (r_shownormals.value > 0 && rsurface.batchsvector3f)
13828 qglBegin(GL_LINES);
13829 for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13831 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13832 GL_Color(r_refdef.view.colorscale, 0, 0, 1);
13833 qglVertex3f(v[0], v[1], v[2]);
13834 VectorMA(v, r_shownormals.value, rsurface.batchsvector3f + l * 3, v);
13835 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13836 qglVertex3f(v[0], v[1], v[2]);
13840 qglBegin(GL_LINES);
13841 for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13843 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13844 GL_Color(0, r_refdef.view.colorscale, 0, 1);
13845 qglVertex3f(v[0], v[1], v[2]);
13846 VectorMA(v, r_shownormals.value, rsurface.batchtvector3f + l * 3, v);
13847 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13848 qglVertex3f(v[0], v[1], v[2]);
13852 qglBegin(GL_LINES);
13853 for (k = 0, l = rsurface.batchfirstvertex;k < rsurface.batchnumvertices;k++, l++)
13855 VectorCopy(rsurface.batchvertex3f + l * 3, v);
13856 GL_Color(0, 0, r_refdef.view.colorscale, 1);
13857 qglVertex3f(v[0], v[1], v[2]);
13858 VectorMA(v, r_shownormals.value, rsurface.batchnormal3f + l * 3, v);
13859 GL_Color(r_refdef.view.colorscale, r_refdef.view.colorscale, r_refdef.view.colorscale, 1);
13860 qglVertex3f(v[0], v[1], v[2]);
13867 rsurface.texture = NULL;
13871 extern void R_BuildLightMap(const entity_render_t *ent, msurface_t *surface);
13872 int r_maxsurfacelist = 0;
13873 const msurface_t **r_surfacelist = NULL;
13874 void R_DrawWorldSurfaces(qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13876 int i, j, endj, flagsmask;
13877 dp_model_t *model = r_refdef.scene.worldmodel;
13878 msurface_t *surfaces;
13879 unsigned char *update;
13880 int numsurfacelist = 0;
13884 if (r_maxsurfacelist < model->num_surfaces)
13886 r_maxsurfacelist = model->num_surfaces;
13888 Mem_Free((msurface_t**)r_surfacelist);
13889 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13892 RSurf_ActiveWorldEntity();
13894 surfaces = model->data_surfaces;
13895 update = model->brushq1.lightmapupdateflags;
13897 // update light styles on this submodel
13898 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
13900 model_brush_lightstyleinfo_t *style;
13901 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
13903 if (style->value != r_refdef.scene.lightstylevalue[style->style])
13905 int *list = style->surfacelist;
13906 style->value = r_refdef.scene.lightstylevalue[style->style];
13907 for (j = 0;j < style->numsurfaces;j++)
13908 update[list[j]] = true;
13913 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
13917 R_DrawDebugModel();
13918 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13922 rsurface.lightmaptexture = NULL;
13923 rsurface.deluxemaptexture = NULL;
13924 rsurface.uselightmaptexture = false;
13925 rsurface.texture = NULL;
13926 rsurface.rtlight = NULL;
13927 numsurfacelist = 0;
13928 // add visible surfaces to draw list
13929 for (i = 0;i < model->nummodelsurfaces;i++)
13931 j = model->sortedmodelsurfaces[i];
13932 if (r_refdef.viewcache.world_surfacevisible[j])
13933 r_surfacelist[numsurfacelist++] = surfaces + j;
13935 // update lightmaps if needed
13936 if (model->brushq1.firstrender)
13938 model->brushq1.firstrender = false;
13939 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13941 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13945 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
13946 if (r_refdef.viewcache.world_surfacevisible[j])
13948 R_BuildLightMap(r_refdef.scene.worldentity, surfaces + j);
13950 // don't do anything if there were no surfaces
13951 if (!numsurfacelist)
13953 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13956 R_QueueWorldSurfaceList(numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
13958 // add to stats if desired
13959 if (r_speeds.integer && !skysurfaces && !depthonly)
13961 r_refdef.stats.world_surfaces += numsurfacelist;
13962 for (j = 0;j < numsurfacelist;j++)
13963 r_refdef.stats.world_triangles += r_surfacelist[j]->num_triangles;
13966 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
13969 void R_DrawModelSurfaces(entity_render_t *ent, qboolean skysurfaces, qboolean writedepth, qboolean depthonly, qboolean debug, qboolean prepass)
13971 int i, j, endj, flagsmask;
13972 dp_model_t *model = ent->model;
13973 msurface_t *surfaces;
13974 unsigned char *update;
13975 int numsurfacelist = 0;
13979 if (r_maxsurfacelist < model->num_surfaces)
13981 r_maxsurfacelist = model->num_surfaces;
13983 Mem_Free((msurface_t **)r_surfacelist);
13984 r_surfacelist = (const msurface_t **) Mem_Alloc(r_main_mempool, r_maxsurfacelist * sizeof(*r_surfacelist));
13987 // if the model is static it doesn't matter what value we give for
13988 // wantnormals and wanttangents, so this logic uses only rules applicable
13989 // to a model, knowing that they are meaningless otherwise
13990 if (ent == r_refdef.scene.worldentity)
13991 RSurf_ActiveWorldEntity();
13992 else if (r_showsurfaces.integer && r_showsurfaces.integer != 3)
13993 RSurf_ActiveModelEntity(ent, false, false, false);
13995 RSurf_ActiveModelEntity(ent, true, true, true);
13996 else if (depthonly)
13998 switch (vid.renderpath)
14000 case RENDERPATH_GL20:
14001 case RENDERPATH_D3D9:
14002 case RENDERPATH_D3D10:
14003 case RENDERPATH_D3D11:
14004 case RENDERPATH_SOFT:
14005 case RENDERPATH_GLES2:
14006 RSurf_ActiveModelEntity(ent, model->wantnormals, model->wanttangents, false);
14008 case RENDERPATH_GL13:
14009 case RENDERPATH_GL11:
14010 RSurf_ActiveModelEntity(ent, model->wantnormals, false, false);
14016 switch (vid.renderpath)
14018 case RENDERPATH_GL20:
14019 case RENDERPATH_D3D9:
14020 case RENDERPATH_D3D10:
14021 case RENDERPATH_D3D11:
14022 case RENDERPATH_SOFT:
14023 case RENDERPATH_GLES2:
14024 RSurf_ActiveModelEntity(ent, true, true, false);
14026 case RENDERPATH_GL13:
14027 case RENDERPATH_GL11:
14028 RSurf_ActiveModelEntity(ent, true, false, false);
14033 surfaces = model->data_surfaces;
14034 update = model->brushq1.lightmapupdateflags;
14036 // update light styles
14037 if (!skysurfaces && !depthonly && !prepass && model->brushq1.num_lightstyles && r_refdef.lightmapintensity > 0)
14039 model_brush_lightstyleinfo_t *style;
14040 for (i = 0, style = model->brushq1.data_lightstyleinfo;i < model->brushq1.num_lightstyles;i++, style++)
14042 if (style->value != r_refdef.scene.lightstylevalue[style->style])
14044 int *list = style->surfacelist;
14045 style->value = r_refdef.scene.lightstylevalue[style->style];
14046 for (j = 0;j < style->numsurfaces;j++)
14047 update[list[j]] = true;
14052 flagsmask = skysurfaces ? MATERIALFLAG_SKY : MATERIALFLAG_WALL;
14056 R_DrawDebugModel();
14057 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14061 rsurface.lightmaptexture = NULL;
14062 rsurface.deluxemaptexture = NULL;
14063 rsurface.uselightmaptexture = false;
14064 rsurface.texture = NULL;
14065 rsurface.rtlight = NULL;
14066 numsurfacelist = 0;
14067 // add visible surfaces to draw list
14068 for (i = 0;i < model->nummodelsurfaces;i++)
14069 r_surfacelist[numsurfacelist++] = surfaces + model->sortedmodelsurfaces[i];
14070 // don't do anything if there were no surfaces
14071 if (!numsurfacelist)
14073 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14076 // update lightmaps if needed
14080 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14085 R_BuildLightMap(ent, surfaces + j);
14090 for (j = model->firstmodelsurface, endj = model->firstmodelsurface + model->nummodelsurfaces;j < endj;j++)
14092 R_BuildLightMap(ent, surfaces + j);
14093 R_QueueModelSurfaceList(ent, numsurfacelist, r_surfacelist, flagsmask, writedepth, depthonly, prepass);
14095 // add to stats if desired
14096 if (r_speeds.integer && !skysurfaces && !depthonly)
14098 r_refdef.stats.entities_surfaces += numsurfacelist;
14099 for (j = 0;j < numsurfacelist;j++)
14100 r_refdef.stats.entities_triangles += r_surfacelist[j]->num_triangles;
14103 rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
14106 void R_DrawCustomSurface(skinframe_t *skinframe, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14108 static texture_t texture;
14109 static msurface_t surface;
14110 const msurface_t *surfacelist = &surface;
14112 // fake enough texture and surface state to render this geometry
14114 texture.update_lastrenderframe = -1; // regenerate this texture
14115 texture.basematerialflags = materialflags | MATERIALFLAG_CUSTOMSURFACE | MATERIALFLAG_WALL;
14116 texture.currentskinframe = skinframe;
14117 texture.currenttexmatrix = *texmatrix; // requires MATERIALFLAG_CUSTOMSURFACE
14118 texture.offsetmapping = OFFSETMAPPING_OFF;
14119 texture.offsetscale = 1;
14120 texture.specularscalemod = 1;
14121 texture.specularpowermod = 1;
14123 surface.texture = &texture;
14124 surface.num_triangles = numtriangles;
14125 surface.num_firsttriangle = firsttriangle;
14126 surface.num_vertices = numvertices;
14127 surface.num_firstvertex = firstvertex;
14130 rsurface.texture = R_GetCurrentTexture(surface.texture);
14131 rsurface.lightmaptexture = NULL;
14132 rsurface.deluxemaptexture = NULL;
14133 rsurface.uselightmaptexture = false;
14134 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);
14137 void R_DrawCustomSurface_Texture(texture_t *texture, const matrix4x4_t *texmatrix, int materialflags, int firstvertex, int numvertices, int firsttriangle, int numtriangles, qboolean writedepth, qboolean prepass)
14139 static msurface_t surface;
14140 const msurface_t *surfacelist = &surface;
14142 // fake enough texture and surface state to render this geometry
14143 surface.texture = texture;
14144 surface.num_triangles = numtriangles;
14145 surface.num_firsttriangle = firsttriangle;
14146 surface.num_vertices = numvertices;
14147 surface.num_firstvertex = firstvertex;
14150 rsurface.texture = R_GetCurrentTexture(surface.texture);
14151 rsurface.lightmaptexture = NULL;
14152 rsurface.deluxemaptexture = NULL;
14153 rsurface.uselightmaptexture = false;
14154 R_DrawModelTextureSurfaceList(1, &surfacelist, writedepth, prepass);