X-Git-Url: https://git.xonotic.org/?a=blobdiff_plain;f=r_shadow.c;h=c183be35e4de69a5f5229a6c440add86008aaf80;hb=75d7c43117740688f30a9ea432ea2638458457b0;hp=4413c062fef52ed3ac04e2f7907143dbd2686886;hpb=fae52291efa344ad98f83a13308ffa5dd583a11e;p=xonotic%2Fdarkplaces.git diff --git a/r_shadow.c b/r_shadow.c index 4413c062..c183be35 100644 --- a/r_shadow.c +++ b/r_shadow.c @@ -139,10 +139,14 @@ demonstrated by the game Doom3. #include "cl_collision.h" #include "portals.h" #include "image.h" +#include "dpsoftrast.h" -#define R_SHADOW_SHADOWMAP_NUMCUBEMAPS 8 +#ifdef SUPPORTD3D +#include +extern LPDIRECT3DDEVICE9 vid_d3d9dev; +#endif -extern void R_Shadow_EditLights_Init(void); +static void R_Shadow_EditLights_Init(void); typedef enum r_shadow_rendermode_e { @@ -154,22 +158,20 @@ typedef enum r_shadow_rendermode_e R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL, R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE, R_SHADOW_RENDERMODE_LIGHT_VERTEX, - R_SHADOW_RENDERMODE_LIGHT_DOT3, + R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN, + R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN, + R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN, R_SHADOW_RENDERMODE_LIGHT_GLSL, R_SHADOW_RENDERMODE_VISIBLEVOLUMES, R_SHADOW_RENDERMODE_VISIBLELIGHTING, - R_SHADOW_RENDERMODE_SHADOWMAP2D, - R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE, - R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE, + R_SHADOW_RENDERMODE_SHADOWMAP2D } r_shadow_rendermode_t; typedef enum r_shadow_shadowmode_e { - R_SHADOW_SHADOWMODE_STENCIL, - R_SHADOW_SHADOWMODE_SHADOWMAP2D, - R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE, - R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE + R_SHADOW_SHADOWMODE_STENCIL, + R_SHADOW_SHADOWMODE_SHADOWMAP2D } r_shadow_shadowmode_t; @@ -177,9 +179,8 @@ r_shadow_rendermode_t r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE; r_shadow_rendermode_t r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_NONE; r_shadow_rendermode_t r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_NONE; r_shadow_rendermode_t r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_NONE; -qboolean r_shadow_usingshadowmaprect; qboolean r_shadow_usingshadowmap2d; -qboolean r_shadow_usingshadowmapcube; +qboolean r_shadow_usingshadowmaportho; int r_shadow_shadowmapside; float r_shadow_shadowmap_texturescale[2]; float r_shadow_shadowmap_parameters[4]; @@ -188,20 +189,20 @@ int r_shadow_drawbuffer; int r_shadow_readbuffer; #endif int r_shadow_cullface_front, r_shadow_cullface_back; -GLuint r_shadow_fborectangle; -GLuint r_shadow_fbocubeside[R_SHADOW_SHADOWMAP_NUMCUBEMAPS]; GLuint r_shadow_fbo2d; r_shadow_shadowmode_t r_shadow_shadowmode; int r_shadow_shadowmapfilterquality; -int r_shadow_shadowmaptexturetype; int r_shadow_shadowmapdepthbits; int r_shadow_shadowmapmaxsize; qboolean r_shadow_shadowmapvsdct; qboolean r_shadow_shadowmapsampler; +qboolean r_shadow_shadowmapshadowsampler; int r_shadow_shadowmappcf; int r_shadow_shadowmapborder; +matrix4x4_t r_shadow_shadowmapmatrix; int r_shadow_lightscissor[4]; - +qboolean r_shadow_usingdeferredprepass; +qboolean r_shadow_shadowmapdepthtexture; int maxshadowtriangles; int *shadowelements; @@ -244,13 +245,27 @@ rtexture_t *r_shadow_attenuationgradienttexture; rtexture_t *r_shadow_attenuation2dtexture; rtexture_t *r_shadow_attenuation3dtexture; skinframe_t *r_shadow_lightcorona; -rtexture_t *r_shadow_shadowmaprectangletexture; -rtexture_t *r_shadow_shadowmap2dtexture; -rtexture_t *r_shadow_shadowmapcubetexture[R_SHADOW_SHADOWMAP_NUMCUBEMAPS]; +rtexture_t *r_shadow_shadowmap2ddepthbuffer; +rtexture_t *r_shadow_shadowmap2ddepthtexture; rtexture_t *r_shadow_shadowmapvsdcttexture; int r_shadow_shadowmapsize; // changes for each light based on distance int r_shadow_shadowmaplod; // changes for each light based on distance +GLuint r_shadow_prepassgeometryfbo; +GLuint r_shadow_prepasslightingdiffusespecularfbo; +GLuint r_shadow_prepasslightingdiffusefbo; +int r_shadow_prepass_width; +int r_shadow_prepass_height; +rtexture_t *r_shadow_prepassgeometrydepthbuffer; +rtexture_t *r_shadow_prepassgeometrynormalmaptexture; +rtexture_t *r_shadow_prepasslightingdiffusetexture; +rtexture_t *r_shadow_prepasslightingspeculartexture; + +// keep track of the provided framebuffer info +static int r_shadow_fb_fbo; +static rtexture_t *r_shadow_fb_depthtexture; +static rtexture_t *r_shadow_fb_colortexture; + // lights are reloaded when this changes char r_shadow_mapname[MAX_QPATH]; @@ -260,7 +275,8 @@ rtexturepool_t *r_shadow_filters_texturepool; cvar_t r_shadow_bumpscale_basetexture = {0, "r_shadow_bumpscale_basetexture", "0", "generate fake bumpmaps from diffuse textures at this bumpyness, try 4 to match tenebrae, higher values increase depth, requires r_restart to take effect"}; cvar_t r_shadow_bumpscale_bumpmap = {0, "r_shadow_bumpscale_bumpmap", "4", "what magnitude to interpret _bump.tga textures as, higher values increase depth, requires r_restart to take effect"}; cvar_t r_shadow_debuglight = {0, "r_shadow_debuglight", "-1", "renders only one light, for level design purposes or debugging"}; -cvar_t r_shadow_dot3 = {CVAR_SAVE, "r_shadow_dot3", "0", "enables use of (slow) per pixel lighting on GL1.3 hardware"}; +cvar_t r_shadow_deferred = {CVAR_SAVE, "r_shadow_deferred", "0", "uses image-based lighting instead of geometry-based lighting, the method used renders a depth image and a normalmap image, renders lights into separate diffuse and specular images, and then combines this into the normal rendering, requires r_shadow_shadowmapping"}; +cvar_t r_shadow_usebihculling = {0, "r_shadow_usebihculling", "1", "use BIH (Bounding Interval Hierarchy) for culling lit surfaces instead of BSP (Binary Space Partitioning)"}; cvar_t r_shadow_usenormalmap = {CVAR_SAVE, "r_shadow_usenormalmap", "1", "enables use of directional shading on lights"}; cvar_t r_shadow_gloss = {CVAR_SAVE, "r_shadow_gloss", "1", "0 disables gloss (specularity) rendering, 1 uses gloss if textures are found, 2 forces a flat metallic specular effect on everything without textures (similar to tenebrae)"}; cvar_t r_shadow_gloss2intensity = {0, "r_shadow_gloss2intensity", "0.125", "how bright the forced flat gloss should look if r_shadow_gloss is 2"}; @@ -272,8 +288,7 @@ cvar_t r_shadow_lightattenuationdividebias = {0, "r_shadow_lightattenuationdivid cvar_t r_shadow_lightattenuationlinearscale = {0, "r_shadow_lightattenuationlinearscale", "2", "changes attenuation texture generation"}; cvar_t r_shadow_lightintensityscale = {0, "r_shadow_lightintensityscale", "1", "renders all world lights brighter or darker"}; cvar_t r_shadow_lightradiusscale = {0, "r_shadow_lightradiusscale", "1", "renders all world lights larger or smaller"}; -cvar_t r_shadow_portallight = {0, "r_shadow_portallight", "1", "use portal culling to exactly determine lit triangles when compiling world lights"}; -cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "1000000", "how far to cast shadows"}; +cvar_t r_shadow_projectdistance = {0, "r_shadow_projectdistance", "0", "how far to cast shadows"}; cvar_t r_shadow_frontsidecasting = {0, "r_shadow_frontsidecasting", "1", "whether to cast shadows from illuminated triangles (front side of model) or unlit triangles (back side of model)"}; cvar_t r_shadow_realtime_dlight = {CVAR_SAVE, "r_shadow_realtime_dlight", "1", "enables rendering of dynamic lights such as explosions and rocket light"}; cvar_t r_shadow_realtime_dlight_shadows = {CVAR_SAVE, "r_shadow_realtime_dlight_shadows", "1", "enables rendering of shadows from dynamic lights"}; @@ -284,12 +299,12 @@ cvar_t r_shadow_realtime_world_lightmaps = {CVAR_SAVE, "r_shadow_realtime_world_ cvar_t r_shadow_realtime_world_shadows = {CVAR_SAVE, "r_shadow_realtime_world_shadows", "1", "enables rendering of shadows from world lights"}; cvar_t r_shadow_realtime_world_compile = {0, "r_shadow_realtime_world_compile", "1", "enables compilation of world lights for higher performance rendering"}; cvar_t r_shadow_realtime_world_compileshadow = {0, "r_shadow_realtime_world_compileshadow", "1", "enables compilation of shadows from world lights for higher performance rendering"}; -cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation"}; -cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation"}; +cvar_t r_shadow_realtime_world_compilesvbsp = {0, "r_shadow_realtime_world_compilesvbsp", "1", "enables svbsp optimization during compilation (slower than compileportalculling but more exact)"}; +cvar_t r_shadow_realtime_world_compileportalculling = {0, "r_shadow_realtime_world_compileportalculling", "1", "enables portal-based culling optimization during compilation (overrides compilesvbsp)"}; cvar_t r_shadow_scissor = {0, "r_shadow_scissor", "1", "use scissor optimization of light rendering (restricts rendering to the portion of the screen affected by the light)"}; -cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "0", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"}; -cvar_t r_shadow_shadowmapping_texturetype = {CVAR_SAVE, "r_shadow_shadowmapping_texturetype", "-1", "shadowmap texture types: -1 = auto-select, 0 = 2D, 1 = rectangle, 2 = cubemap"}; +cvar_t r_shadow_shadowmapping = {CVAR_SAVE, "r_shadow_shadowmapping", "1", "enables use of shadowmapping (depth texture sampling) instead of stencil shadow volumes, requires gl_fbo 1"}; cvar_t r_shadow_shadowmapping_filterquality = {CVAR_SAVE, "r_shadow_shadowmapping_filterquality", "-1", "shadowmap filter modes: -1 = auto-select, 0 = no filtering, 1 = bilinear, 2 = bilinear 2x2 blur (fast), 3 = 3x3 blur (moderate), 4 = 4x4 blur (slow)"}; +cvar_t r_shadow_shadowmapping_useshadowsampler = {CVAR_SAVE, "r_shadow_shadowmapping_useshadowsampler", "1", "whether to use sampler2DShadow if available"}; cvar_t r_shadow_shadowmapping_depthbits = {CVAR_SAVE, "r_shadow_shadowmapping_depthbits", "24", "requested minimum shadowmap texture depth bits"}; cvar_t r_shadow_shadowmapping_vsdct = {CVAR_SAVE, "r_shadow_shadowmapping_vsdct", "1", "enables use of virtual shadow depth cube texture"}; cvar_t r_shadow_shadowmapping_minsize = {CVAR_SAVE, "r_shadow_shadowmapping_minsize", "32", "shadowmap size limit"}; @@ -302,13 +317,36 @@ cvar_t r_shadow_shadowmapping_nearclip = {CVAR_SAVE, "r_shadow_shadowmapping_nea cvar_t r_shadow_shadowmapping_bias = {CVAR_SAVE, "r_shadow_shadowmapping_bias", "0.03", "shadowmap bias parameter (this is multiplied by nearclip * 1024 / lodsize)"}; cvar_t r_shadow_shadowmapping_polygonfactor = {CVAR_SAVE, "r_shadow_shadowmapping_polygonfactor", "2", "slope-dependent shadowmapping bias"}; cvar_t r_shadow_shadowmapping_polygonoffset = {CVAR_SAVE, "r_shadow_shadowmapping_polygonoffset", "0", "constant shadowmapping bias"}; -cvar_t r_shadow_culltriangles = {0, "r_shadow_culltriangles", "1", "performs more expensive tests to remove unnecessary triangles of lit surfaces"}; +cvar_t r_shadow_sortsurfaces = {0, "r_shadow_sortsurfaces", "1", "improve performance by sorting illuminated surfaces by texture"}; cvar_t r_shadow_polygonfactor = {0, "r_shadow_polygonfactor", "0", "how much to enlarge shadow volume polygons when rendering (should be 0!)"}; cvar_t r_shadow_polygonoffset = {0, "r_shadow_polygonoffset", "1", "how much to push shadow volumes into the distance when rendering, to reduce chances of zfighting artifacts (should not be less than 0)"}; -cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect r_glsl lighting)"}; -cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "1", "brightness of corona flare effects around certain lights, 0 disables corona effects"}; -cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksm the proportion of hidden pixels controls corona intensity"}; -cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "1", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility)"}; +cvar_t r_shadow_texture3d = {0, "r_shadow_texture3d", "1", "use 3D voxel textures for spherical attenuation rather than cylindrical (does not affect OpenGL 2.0 render path)"}; +cvar_t r_shadow_bouncegrid = {CVAR_SAVE, "r_shadow_bouncegrid", "0", "perform particle tracing for indirect lighting (Global Illumination / radiosity) using a 3D texture covering the scene, only active on levels with realtime lights active (r_shadow_realtime_world is usually required for these)"}; +cvar_t r_shadow_bouncegrid_bounceanglediffuse = {CVAR_SAVE, "r_shadow_bouncegrid_bounceanglediffuse", "0", "use random bounce direction rather than true reflection, makes some corner areas dark"}; +cvar_t r_shadow_bouncegrid_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_directionalshading", "0", "use diffuse shading rather than ambient, 3D texture becomes 8x as many pixels to hold the additional data"}; +cvar_t r_shadow_bouncegrid_dlightparticlemultiplier = {CVAR_SAVE, "r_shadow_bouncegrid_dlightparticlemultiplier", "0", "if set to a high value like 16 this can make dlights look great, but 0 is recommended for performance reasons"}; +cvar_t r_shadow_bouncegrid_hitmodels = {CVAR_SAVE, "r_shadow_bouncegrid_hitmodels", "0", "enables hitting character model geometry (SLOW)"}; +cvar_t r_shadow_bouncegrid_includedirectlighting = {CVAR_SAVE, "r_shadow_bouncegrid_includedirectlighting", "0", "allows direct lighting to be recorded, not just indirect (gives an effect somewhat like r_shadow_realtime_world_lightmaps)"}; +cvar_t r_shadow_bouncegrid_intensity = {CVAR_SAVE, "r_shadow_bouncegrid_intensity", "4", "overall brightness of bouncegrid texture"}; +cvar_t r_shadow_bouncegrid_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_lightradiusscale", "4", "particles stop at this fraction of light radius (can be more than 1)"}; +cvar_t r_shadow_bouncegrid_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_maxbounce", "2", "maximum number of bounces for a particle (minimum is 0)"}; +cvar_t r_shadow_bouncegrid_particlebounceintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particlebounceintensity", "1", "amount of energy carried over after each bounce, this is a multiplier of texture color and the result is clamped to 1 or less, to prevent adding energy on each bounce"}; +cvar_t r_shadow_bouncegrid_particleintensity = {CVAR_SAVE, "r_shadow_bouncegrid_particleintensity", "1", "brightness of particles contributing to bouncegrid texture"}; +cvar_t r_shadow_bouncegrid_photons = {CVAR_SAVE, "r_shadow_bouncegrid_photons", "2000", "total photons to shoot per update, divided proportionately between lights"}; +cvar_t r_shadow_bouncegrid_spacing = {CVAR_SAVE, "r_shadow_bouncegrid_spacing", "64", "unit size of bouncegrid pixel"}; +cvar_t r_shadow_bouncegrid_stablerandom = {CVAR_SAVE, "r_shadow_bouncegrid_stablerandom", "1", "make particle distribution consistent from frame to frame"}; +cvar_t r_shadow_bouncegrid_static = {CVAR_SAVE, "r_shadow_bouncegrid_static", "1", "use static radiosity solution (high quality) rather than dynamic (splotchy)"}; +cvar_t r_shadow_bouncegrid_static_directionalshading = {CVAR_SAVE, "r_shadow_bouncegrid_static_directionalshading", "1", "whether to use directionalshading when in static mode"}; +cvar_t r_shadow_bouncegrid_static_lightradiusscale = {CVAR_SAVE, "r_shadow_bouncegrid_static_lightradiusscale", "10", "particles stop at this fraction of light radius (can be more than 1) when in static mode"}; +cvar_t r_shadow_bouncegrid_static_maxbounce = {CVAR_SAVE, "r_shadow_bouncegrid_static_maxbounce", "5", "maximum number of bounces for a particle (minimum is 0) in static mode"}; +cvar_t r_shadow_bouncegrid_static_photons = {CVAR_SAVE, "r_shadow_bouncegrid_static_photons", "25000", "photons value to use when in static mode"}; +cvar_t r_shadow_bouncegrid_updateinterval = {CVAR_SAVE, "r_shadow_bouncegrid_updateinterval", "0", "update bouncegrid texture once per this many seconds, useful values are 0, 0.05, or 1000000"}; +cvar_t r_shadow_bouncegrid_x = {CVAR_SAVE, "r_shadow_bouncegrid_x", "64", "maximum texture size of bouncegrid on X axis"}; +cvar_t r_shadow_bouncegrid_y = {CVAR_SAVE, "r_shadow_bouncegrid_y", "64", "maximum texture size of bouncegrid on Y axis"}; +cvar_t r_shadow_bouncegrid_z = {CVAR_SAVE, "r_shadow_bouncegrid_z", "32", "maximum texture size of bouncegrid on Z axis"}; +cvar_t r_coronas = {CVAR_SAVE, "r_coronas", "0", "brightness of corona flare effects around certain lights, 0 disables corona effects"}; +cvar_t r_coronas_occlusionsizescale = {CVAR_SAVE, "r_coronas_occlusionsizescale", "0.1", "size of light source for corona occlusion checksum the proportion of hidden pixels controls corona intensity"}; +cvar_t r_coronas_occlusionquery = {CVAR_SAVE, "r_coronas_occlusionquery", "0", "use GL_ARB_occlusion_query extension if supported (fades coronas according to visibility) - bad performance (synchronous rendering) - worse on multi-gpu!"}; cvar_t gl_flashblend = {CVAR_SAVE, "gl_flashblend", "0", "render bright coronas for dynamic lights instead of actual lighting, fast but ugly"}; cvar_t gl_ext_separatestencil = {0, "gl_ext_separatestencil", "1", "make use of OpenGL 2.0 glStencilOpSeparate or GL_ATI_separate_stencil extension"}; cvar_t gl_ext_stenciltwoside = {0, "gl_ext_stenciltwoside", "1", "make use of GL_EXT_stenciltwoside extension (NVIDIA only)"}; @@ -318,6 +356,51 @@ cvar_t r_editlights_cursorpushback = {0, "r_editlights_cursorpushback", "0", "ho cvar_t r_editlights_cursorpushoff = {0, "r_editlights_cursorpushoff", "4", "how far to push the cursor off the impacted surface"}; cvar_t r_editlights_cursorgrid = {0, "r_editlights_cursorgrid", "4", "snaps cursor to this grid size"}; cvar_t r_editlights_quakelightsizescale = {CVAR_SAVE, "r_editlights_quakelightsizescale", "1", "changes size of light entities loaded from a map"}; +cvar_t r_editlights_drawproperties = {0, "r_editlights_drawproperties", "1", "draw properties of currently selected light"}; +cvar_t r_editlights_current_origin = {0, "r_editlights_current_origin", "0 0 0", "origin of selected light"}; +cvar_t r_editlights_current_angles = {0, "r_editlights_current_angles", "0 0 0", "angles of selected light"}; +cvar_t r_editlights_current_color = {0, "r_editlights_current_color", "1 1 1", "color of selected light"}; +cvar_t r_editlights_current_radius = {0, "r_editlights_current_radius", "0", "radius of selected light"}; +cvar_t r_editlights_current_corona = {0, "r_editlights_current_corona", "0", "corona intensity of selected light"}; +cvar_t r_editlights_current_coronasize = {0, "r_editlights_current_coronasize", "0", "corona size of selected light"}; +cvar_t r_editlights_current_style = {0, "r_editlights_current_style", "0", "style of selected light"}; +cvar_t r_editlights_current_shadows = {0, "r_editlights_current_shadows", "0", "shadows flag of selected light"}; +cvar_t r_editlights_current_cubemap = {0, "r_editlights_current_cubemap", "0", "cubemap of selected light"}; +cvar_t r_editlights_current_ambient = {0, "r_editlights_current_ambient", "0", "ambient intensity of selected light"}; +cvar_t r_editlights_current_diffuse = {0, "r_editlights_current_diffuse", "1", "diffuse intensity of selected light"}; +cvar_t r_editlights_current_specular = {0, "r_editlights_current_specular", "1", "specular intensity of selected light"}; +cvar_t r_editlights_current_normalmode = {0, "r_editlights_current_normalmode", "0", "normalmode flag of selected light"}; +cvar_t r_editlights_current_realtimemode = {0, "r_editlights_current_realtimemode", "0", "realtimemode flag of selected light"}; + + +typedef struct r_shadow_bouncegrid_settings_s +{ + qboolean staticmode; + qboolean bounceanglediffuse; + qboolean directionalshading; + qboolean includedirectlighting; + float dlightparticlemultiplier; + qboolean hitmodels; + float lightradiusscale; + int maxbounce; + float particlebounceintensity; + float particleintensity; + int photons; + float spacing[3]; + int stablerandom; +} +r_shadow_bouncegrid_settings_t; + +r_shadow_bouncegrid_settings_t r_shadow_bouncegridsettings; +rtexture_t *r_shadow_bouncegridtexture; +matrix4x4_t r_shadow_bouncegridmatrix; +vec_t r_shadow_bouncegridintensity; +qboolean r_shadow_bouncegriddirectional; +static double r_shadow_bouncegridtime; +static int r_shadow_bouncegridresolution[3]; +static int r_shadow_bouncegridnumpixels; +static unsigned char *r_shadow_bouncegridpixels; +static float *r_shadow_bouncegridhighpixels; // note the table actually includes one more value, just to avoid the need to clamp the distance index due to minor math error #define ATTENTABLESIZE 256 @@ -335,19 +418,10 @@ static memexpandablearray_t r_shadow_worldlightsarray; dlight_t *r_shadow_selectedlight; dlight_t r_shadow_bufferlight; vec3_t r_editlights_cursorlocation; +qboolean r_editlights_lockcursor; extern int con_vislines; -typedef struct cubemapinfo_s -{ - char basename[64]; - rtexture_t *texture; -} -cubemapinfo_t; - -static int numcubemaps; -static cubemapinfo_t cubemaps[MAX_CUBEMAPS]; - void R_Shadow_UncompileWorldLights(void); void R_Shadow_ClearWorldLights(void); void R_Shadow_SaveWorldLights(void); @@ -365,144 +439,140 @@ skinframe_t *r_editlights_sprnoshadowlight; skinframe_t *r_editlights_sprcubemaplight; skinframe_t *r_editlights_sprcubemapnoshadowlight; skinframe_t *r_editlights_sprselection; -extern cvar_t gl_max_size; -void R_Shadow_SetShadowMode(void) +static void R_Shadow_SetShadowMode(void) { - r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, gl_max_size.integer / 4); - r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0; + r_shadow_shadowmapmaxsize = bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4); + r_shadow_shadowmapvsdct = r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20; r_shadow_shadowmapfilterquality = r_shadow_shadowmapping_filterquality.integer; - r_shadow_shadowmaptexturetype = r_shadow_shadowmapping_texturetype.integer; + r_shadow_shadowmapshadowsampler = r_shadow_shadowmapping_useshadowsampler.integer != 0; r_shadow_shadowmapdepthbits = r_shadow_shadowmapping_depthbits.integer; r_shadow_shadowmapborder = bound(0, r_shadow_shadowmapping_bordersize.integer, 16); r_shadow_shadowmaplod = -1; r_shadow_shadowmapsize = 0; r_shadow_shadowmapsampler = false; r_shadow_shadowmappcf = 0; + r_shadow_shadowmapdepthtexture = r_fb.usedepthtextures; r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL; - if(r_shadow_shadowmapping.integer && r_glsl.integer && gl_support_fragment_shader && gl_support_ext_framebuffer_object) + if ((r_shadow_shadowmapping.integer || r_shadow_deferred.integer) && vid.support.ext_framebuffer_object) { - if(r_shadow_shadowmapfilterquality < 0) + switch(vid.renderpath) { - if(strstr(gl_vendor, "NVIDIA")) + case RENDERPATH_GL20: + if(r_shadow_shadowmapfilterquality < 0) { - r_shadow_shadowmapsampler = gl_support_arb_shadow; - r_shadow_shadowmappcf = 1; + if (!r_fb.usedepthtextures) + r_shadow_shadowmappcf = 1; + else if((strstr(gl_vendor, "NVIDIA") || strstr(gl_renderer, "Radeon HD")) && vid.support.arb_shadow && r_shadow_shadowmapshadowsampler) + { + r_shadow_shadowmapsampler = true; + r_shadow_shadowmappcf = 1; + } + else if(vid.support.amd_texture_texture4 || vid.support.arb_texture_gather) + r_shadow_shadowmappcf = 1; + else if((strstr(gl_vendor, "ATI") || strstr(gl_vendor, "Advanced Micro Devices")) && !strstr(gl_renderer, "Mesa") && !strstr(gl_version, "Mesa")) + r_shadow_shadowmappcf = 1; + else + r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler; } - else if(gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) - r_shadow_shadowmappcf = 1; - else if(strstr(gl_vendor, "ATI")) - r_shadow_shadowmappcf = 1; else - r_shadow_shadowmapsampler = gl_support_arb_shadow; - } - else - { - switch (r_shadow_shadowmapfilterquality) { - case 1: - r_shadow_shadowmapsampler = gl_support_arb_shadow; - break; - case 2: - r_shadow_shadowmapsampler = gl_support_arb_shadow; - r_shadow_shadowmappcf = 1; - break; - case 3: - r_shadow_shadowmappcf = 1; - break; - case 4: - r_shadow_shadowmappcf = 2; - break; + r_shadow_shadowmapsampler = vid.support.arb_shadow && r_shadow_shadowmapshadowsampler; + switch (r_shadow_shadowmapfilterquality) + { + case 1: + break; + case 2: + r_shadow_shadowmappcf = 1; + break; + case 3: + r_shadow_shadowmappcf = 1; + break; + case 4: + r_shadow_shadowmappcf = 2; + break; + } } - } - switch (r_shadow_shadowmaptexturetype) - { - case 0: - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D; - break; - case 1: - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE; - break; - case 2: - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE; - break; - default: - if((gl_support_amd_texture_texture4 || gl_support_arb_texture_gather) && r_shadow_shadowmappcf && !r_shadow_shadowmapsampler) - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D; - else if(gl_texturerectangle) - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE; - else - r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D; - break; + if (!r_fb.usedepthtextures) + r_shadow_shadowmapsampler = false; + r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D; + break; + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: + case RENDERPATH_SOFT: + r_shadow_shadowmapsampler = false; + r_shadow_shadowmappcf = 1; + r_shadow_shadowmode = R_SHADOW_SHADOWMODE_SHADOWMAP2D; + break; + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: + break; } } + + if(R_CompileShader_CheckStaticParms()) + R_GLSL_Restart_f(); } -void R_Shadow_FreeShadowMaps(void) +qboolean R_Shadow_ShadowMappingEnabled(void) { - int i; + switch (r_shadow_shadowmode) + { + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + return true; + default: + return false; + } +} +static void R_Shadow_FreeShadowMaps(void) +{ R_Shadow_SetShadowMode(); - if (r_shadow_fborectangle) - qglDeleteFramebuffersEXT(1, &r_shadow_fborectangle); - r_shadow_fborectangle = 0; - CHECKGLERROR + R_Mesh_DestroyFramebufferObject(r_shadow_fbo2d); - if (r_shadow_fbo2d) - qglDeleteFramebuffersEXT(1, &r_shadow_fbo2d); r_shadow_fbo2d = 0; - CHECKGLERROR - for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++) - if (r_shadow_fbocubeside[i]) - qglDeleteFramebuffersEXT(1, &r_shadow_fbocubeside[i]); - memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside)); - CHECKGLERROR - if (r_shadow_shadowmaprectangletexture) - R_FreeTexture(r_shadow_shadowmaprectangletexture); - r_shadow_shadowmaprectangletexture = NULL; + if (r_shadow_shadowmap2ddepthtexture) + R_FreeTexture(r_shadow_shadowmap2ddepthtexture); + r_shadow_shadowmap2ddepthtexture = NULL; - if (r_shadow_shadowmap2dtexture) - R_FreeTexture(r_shadow_shadowmap2dtexture); - r_shadow_shadowmap2dtexture = NULL; - - for (i = 0;i < R_SHADOW_SHADOWMAP_NUMCUBEMAPS;i++) - if (r_shadow_shadowmapcubetexture[i]) - R_FreeTexture(r_shadow_shadowmapcubetexture[i]); - memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture)); + if (r_shadow_shadowmap2ddepthbuffer) + R_FreeTexture(r_shadow_shadowmap2ddepthbuffer); + r_shadow_shadowmap2ddepthbuffer = NULL; if (r_shadow_shadowmapvsdcttexture) R_FreeTexture(r_shadow_shadowmapvsdcttexture); r_shadow_shadowmapvsdcttexture = NULL; - - CHECKGLERROR } -void r_shadow_start(void) +static void r_shadow_start(void) { // allocate vertex processing arrays - numcubemaps = 0; + r_shadow_bouncegridpixels = NULL; + r_shadow_bouncegridhighpixels = NULL; + r_shadow_bouncegridnumpixels = 0; + r_shadow_bouncegridtexture = NULL; + r_shadow_bouncegriddirectional = false; r_shadow_attenuationgradienttexture = NULL; r_shadow_attenuation2dtexture = NULL; r_shadow_attenuation3dtexture = NULL; r_shadow_shadowmode = R_SHADOW_SHADOWMODE_STENCIL; - r_shadow_shadowmaprectangletexture = NULL; - r_shadow_shadowmap2dtexture = NULL; - memset(r_shadow_shadowmapcubetexture, 0, sizeof(r_shadow_shadowmapcubetexture)); + r_shadow_shadowmap2ddepthtexture = NULL; + r_shadow_shadowmap2ddepthbuffer = NULL; r_shadow_shadowmapvsdcttexture = NULL; r_shadow_shadowmapmaxsize = 0; r_shadow_shadowmapsize = 0; r_shadow_shadowmaplod = 0; r_shadow_shadowmapfilterquality = -1; - r_shadow_shadowmaptexturetype = -1; r_shadow_shadowmapdepthbits = 0; r_shadow_shadowmapvsdct = false; r_shadow_shadowmapsampler = false; r_shadow_shadowmappcf = 0; - r_shadow_fborectangle = 0; r_shadow_fbo2d = 0; - memset(r_shadow_fbocubeside, 0, sizeof(r_shadow_fbocubeside)); R_Shadow_FreeShadowMaps(); @@ -539,17 +609,30 @@ void r_shadow_start(void) r_shadow_buffer_shadowtrispvs = NULL; r_shadow_buffer_numlighttrispvsbytes = 0; r_shadow_buffer_lighttrispvs = NULL; + + r_shadow_usingdeferredprepass = false; + r_shadow_prepass_width = r_shadow_prepass_height = 0; } -void r_shadow_shutdown(void) +static void R_Shadow_FreeDeferred(void); +static void r_shadow_shutdown(void) { CHECKGLERROR R_Shadow_UncompileWorldLights(); R_Shadow_FreeShadowMaps(); + r_shadow_usingdeferredprepass = false; + if (r_shadow_prepass_width) + R_Shadow_FreeDeferred(); + r_shadow_prepass_width = r_shadow_prepass_height = 0; + CHECKGLERROR - numcubemaps = 0; + r_shadow_bouncegridtexture = NULL; + r_shadow_bouncegridpixels = NULL; + r_shadow_bouncegridhighpixels = NULL; + r_shadow_bouncegridnumpixels = 0; + r_shadow_bouncegriddirectional = false; r_shadow_attenuationgradienttexture = NULL; r_shadow_attenuation2dtexture = NULL; r_shadow_attenuation3dtexture = NULL; @@ -615,8 +698,9 @@ void r_shadow_shutdown(void) Mem_Free(r_shadow_buffer_lighttrispvs); } -void r_shadow_newmap(void) +static void r_shadow_newmap(void) { + if (r_shadow_bouncegridtexture) R_FreeTexture(r_shadow_bouncegridtexture);r_shadow_bouncegridtexture = NULL; if (r_shadow_lightcorona) R_SkinFrame_MarkUsed(r_shadow_lightcorona); if (r_editlights_sprcursor) R_SkinFrame_MarkUsed(r_editlights_sprcursor); if (r_editlights_sprlight) R_SkinFrame_MarkUsed(r_editlights_sprlight); @@ -624,52 +708,18 @@ void r_shadow_newmap(void) if (r_editlights_sprcubemaplight) R_SkinFrame_MarkUsed(r_editlights_sprcubemaplight); if (r_editlights_sprcubemapnoshadowlight) R_SkinFrame_MarkUsed(r_editlights_sprcubemapnoshadowlight); if (r_editlights_sprselection) R_SkinFrame_MarkUsed(r_editlights_sprselection); - if (cl.worldmodel && strncmp(cl.worldmodel->name, r_shadow_mapname, sizeof(r_shadow_mapname))) + if (strncmp(cl.worldname, r_shadow_mapname, sizeof(r_shadow_mapname))) R_Shadow_EditLights_Reload_f(); } -void R_Shadow_Help_f(void) -{ - Con_Printf( -"Documentation on r_shadow system:\n" -"Settings:\n" -"r_shadow_bumpscale_basetexture : base texture as bumpmap with this scale\n" -"r_shadow_bumpscale_bumpmap : depth scale for bumpmap conversion\n" -"r_shadow_debuglight : render only this light number (-1 = all)\n" -"r_shadow_gloss 0/1/2 : no gloss, gloss textures only, force gloss\n" -"r_shadow_gloss2intensity : brightness of forced gloss\n" -"r_shadow_glossintensity : brightness of textured gloss\n" -"r_shadow_lightattenuationlinearscale : used to generate attenuation texture\n" -"r_shadow_lightattenuationdividebias : used to generate attenuation texture\n" -"r_shadow_lightintensityscale : scale rendering brightness of all lights\n" -"r_shadow_lightradiusscale : scale rendering radius of all lights\n" -"r_shadow_portallight : use portal visibility for static light precomputation\n" -"r_shadow_projectdistance : shadow volume projection distance\n" -"r_shadow_realtime_dlight : use high quality dynamic lights in normal mode\n" -"r_shadow_realtime_dlight_shadows : cast shadows from dlights\n" -"r_shadow_realtime_world : use high quality world lighting mode\n" -"r_shadow_realtime_world_lightmaps : use lightmaps in addition to lights\n" -"r_shadow_realtime_world_shadows : cast shadows from world lights\n" -"r_shadow_realtime_world_compile : compile surface/visibility information\n" -"r_shadow_realtime_world_compileshadow : compile shadow geometry\n" -"r_shadow_scissor : use scissor optimization\n" -"r_shadow_polygonfactor : nudge shadow volumes closer/further\n" -"r_shadow_polygonoffset : nudge shadow volumes closer/further\n" -"r_shadow_texture3d : use 3d attenuation texture (if hardware supports)\n" -"r_showlighting : useful for performance testing; bright = slow!\n" -"r_showshadowvolumes : useful for performance testing; bright = slow!\n" -"Commands:\n" -"r_shadow_help : this help\n" - ); -} - void R_Shadow_Init(void) { Cvar_RegisterVariable(&r_shadow_bumpscale_basetexture); Cvar_RegisterVariable(&r_shadow_bumpscale_bumpmap); - Cvar_RegisterVariable(&r_shadow_dot3); + Cvar_RegisterVariable(&r_shadow_usebihculling); Cvar_RegisterVariable(&r_shadow_usenormalmap); Cvar_RegisterVariable(&r_shadow_debuglight); + Cvar_RegisterVariable(&r_shadow_deferred); Cvar_RegisterVariable(&r_shadow_gloss); Cvar_RegisterVariable(&r_shadow_gloss2intensity); Cvar_RegisterVariable(&r_shadow_glossintensity); @@ -680,7 +730,6 @@ void R_Shadow_Init(void) Cvar_RegisterVariable(&r_shadow_lightattenuationlinearscale); Cvar_RegisterVariable(&r_shadow_lightintensityscale); Cvar_RegisterVariable(&r_shadow_lightradiusscale); - Cvar_RegisterVariable(&r_shadow_portallight); Cvar_RegisterVariable(&r_shadow_projectdistance); Cvar_RegisterVariable(&r_shadow_frontsidecasting); Cvar_RegisterVariable(&r_shadow_realtime_dlight); @@ -697,8 +746,8 @@ void R_Shadow_Init(void) Cvar_RegisterVariable(&r_shadow_scissor); Cvar_RegisterVariable(&r_shadow_shadowmapping); Cvar_RegisterVariable(&r_shadow_shadowmapping_vsdct); - Cvar_RegisterVariable(&r_shadow_shadowmapping_texturetype); Cvar_RegisterVariable(&r_shadow_shadowmapping_filterquality); + Cvar_RegisterVariable(&r_shadow_shadowmapping_useshadowsampler); Cvar_RegisterVariable(&r_shadow_shadowmapping_depthbits); Cvar_RegisterVariable(&r_shadow_shadowmapping_precision); Cvar_RegisterVariable(&r_shadow_shadowmapping_maxsize); @@ -710,22 +759,39 @@ void R_Shadow_Init(void) Cvar_RegisterVariable(&r_shadow_shadowmapping_bias); Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonfactor); Cvar_RegisterVariable(&r_shadow_shadowmapping_polygonoffset); - Cvar_RegisterVariable(&r_shadow_culltriangles); + Cvar_RegisterVariable(&r_shadow_sortsurfaces); Cvar_RegisterVariable(&r_shadow_polygonfactor); Cvar_RegisterVariable(&r_shadow_polygonoffset); Cvar_RegisterVariable(&r_shadow_texture3d); + Cvar_RegisterVariable(&r_shadow_bouncegrid); + Cvar_RegisterVariable(&r_shadow_bouncegrid_bounceanglediffuse); + Cvar_RegisterVariable(&r_shadow_bouncegrid_directionalshading); + Cvar_RegisterVariable(&r_shadow_bouncegrid_dlightparticlemultiplier); + Cvar_RegisterVariable(&r_shadow_bouncegrid_hitmodels); + Cvar_RegisterVariable(&r_shadow_bouncegrid_includedirectlighting); + Cvar_RegisterVariable(&r_shadow_bouncegrid_intensity); + Cvar_RegisterVariable(&r_shadow_bouncegrid_lightradiusscale); + Cvar_RegisterVariable(&r_shadow_bouncegrid_maxbounce); + Cvar_RegisterVariable(&r_shadow_bouncegrid_particlebounceintensity); + Cvar_RegisterVariable(&r_shadow_bouncegrid_particleintensity); + Cvar_RegisterVariable(&r_shadow_bouncegrid_photons); + Cvar_RegisterVariable(&r_shadow_bouncegrid_spacing); + Cvar_RegisterVariable(&r_shadow_bouncegrid_stablerandom); + Cvar_RegisterVariable(&r_shadow_bouncegrid_static); + Cvar_RegisterVariable(&r_shadow_bouncegrid_static_directionalshading); + Cvar_RegisterVariable(&r_shadow_bouncegrid_static_lightradiusscale); + Cvar_RegisterVariable(&r_shadow_bouncegrid_static_maxbounce); + Cvar_RegisterVariable(&r_shadow_bouncegrid_static_photons); + Cvar_RegisterVariable(&r_shadow_bouncegrid_updateinterval); + Cvar_RegisterVariable(&r_shadow_bouncegrid_x); + Cvar_RegisterVariable(&r_shadow_bouncegrid_y); + Cvar_RegisterVariable(&r_shadow_bouncegrid_z); Cvar_RegisterVariable(&r_coronas); Cvar_RegisterVariable(&r_coronas_occlusionsizescale); Cvar_RegisterVariable(&r_coronas_occlusionquery); Cvar_RegisterVariable(&gl_flashblend); Cvar_RegisterVariable(&gl_ext_separatestencil); Cvar_RegisterVariable(&gl_ext_stenciltwoside); - if (gamemode == GAME_TENEBRAE) - { - Cvar_SetValue("r_shadow_gloss", 2); - Cvar_SetValue("r_shadow_bumpscale_basetexture", 4); - } - Cmd_AddCommand("r_shadow_help", R_Shadow_Help_f, "prints documentation on console commands and variables used by realtime lighting and shadowing system"); R_Shadow_EditLights_Init(); Mem_ExpandableArray_NewArray(&r_shadow_worldlightsarray, r_main_mempool, sizeof(dlight_t), 128); maxshadowtriangles = 0; @@ -755,7 +821,7 @@ void R_Shadow_Init(void) r_shadow_buffer_surfacesides = NULL; r_shadow_buffer_shadowtrispvs = NULL; r_shadow_buffer_lighttrispvs = NULL; - R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap); + R_RegisterModule("R_Shadow", r_shadow_start, r_shadow_shutdown, r_shadow_newmap, NULL, NULL); } matrix4x4_t matrix_attenuationxyz = @@ -778,7 +844,7 @@ matrix4x4_t matrix_attenuationz = } }; -void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale) +static void R_Shadow_ResizeShadowArrays(int numvertices, int numtriangles, int vertscale, int triscale) { numvertices = ((numvertices + 255) & ~255) * vertscale; numtriangles = ((numtriangles + 255) & ~255) * triscale; @@ -874,10 +940,10 @@ void R_Shadow_PrepareShadowMark(int numtris) void R_Shadow_PrepareShadowSides(int numtris) { - if (maxshadowsides < numtris) - { - maxshadowsides = numtris; - if (shadowsides) + if (maxshadowsides < numtris) + { + maxshadowsides = numtris; + if (shadowsides) Mem_Free(shadowsides); if (shadowsideslist) Mem_Free(shadowsideslist); @@ -1234,7 +1300,7 @@ void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *inv v[2] = invertex3f + e[2] * 3; TriangleNormal(v[0], v[1], v[2], normal); if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0) - && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) + && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) shadowmarklist[numshadowmark++] = t; } } @@ -1246,14 +1312,14 @@ void R_Shadow_MarkVolumeFromBox(int firsttriangle, int numtris, const float *inv v[1] = invertex3f + e[1] * 3; v[2] = invertex3f + e[2] * 3; if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]) - && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) + && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) shadowmarklist[numshadowmark++] = t; } } } } -qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs) +static qboolean R_Shadow_UseZPass(vec3_t mins, vec3_t maxs) { #if 1 return false; @@ -1315,6 +1381,12 @@ void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris); Mod_ShadowMesh_AddMesh(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, NULL, NULL, NULL, shadowvertex3f, NULL, NULL, NULL, NULL, tris, shadowelements); } + else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_VISIBLEVOLUMES) + { + tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris); + R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL, 0); + R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0); + } else { // decide which type of shadow to generate and set stencil mode @@ -1324,169 +1396,166 @@ void R_Shadow_VolumeFromList(int numverts, int numtris, const float *invertex3f, tris = R_Shadow_ConstructShadowVolume_ZPass(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris); else tris = R_Shadow_ConstructShadowVolume_ZFail(numverts, numtris, elements, neighbors, invertex3f, &outverts, shadowelements, shadowvertex3f, projectorigin, projectdirection, projectdistance, nummarktris, marktris); - r_refdef.stats.lights_dynamicshadowtriangles += tris; - r_refdef.stats.lights_shadowtriangles += tris; - CHECKGLERROR - R_Mesh_VertexPointer(shadowvertex3f, 0, 0); - GL_LockArrays(0, outverts); + r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += tris; + r_refdef.stats[r_stat_lights_shadowtriangles] += tris; if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL) { // increment stencil if frontface is infront of depthbuffer GL_CullFace(r_refdef.view.cullface_front); - qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR - R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0); + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255); + R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0); // decrement stencil if backface is infront of depthbuffer GL_CullFace(r_refdef.view.cullface_back); - qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255); } else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL) { // decrement stencil if backface is behind depthbuffer GL_CullFace(r_refdef.view.cullface_front); - qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR - R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0); + R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255); + R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0); // increment stencil if frontface is behind depthbuffer GL_CullFace(r_refdef.view.cullface_back); - qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR + R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255); } - R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, 0); - GL_LockArrays(0, 0); - CHECKGLERROR + R_Mesh_PrepareVertices_Vertex3f(outverts, shadowvertex3f, NULL, 0); + R_Mesh_Draw(0, outverts, 0, tris, shadowelements, NULL, 0, NULL, NULL, 0); } } int R_Shadow_CalcTriangleSideMask(const vec3_t p1, const vec3_t p2, const vec3_t p3, float bias) { - // p1, p2, p3 are in the cubemap's local coordinate system - // bias = border/(size - border) + // p1, p2, p3 are in the cubemap's local coordinate system + // bias = border/(size - border) int mask = 0x3F; - float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2), - dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3); + float dp1 = p1[0] + p1[1], dn1 = p1[0] - p1[1], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = p2[0] + p2[1], dn2 = p2[0] - p2[1], ap2 = fabs(dp2), an2 = fabs(dn2), + dp3 = p3[0] + p3[1], dn3 = p3[0] - p3[1], ap3 = fabs(dp3), an3 = fabs(dn3); if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3) - mask &= (3<<4) + mask &= (3<<4) | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)) | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)) | (dp3 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)); - if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) - mask &= (3<<4) - | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) - | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) - | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); - - dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2), - dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3); - if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3) - mask &= (3<<0) - | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) - | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) - | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); - if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) - mask &= (3<<0) - | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) - | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) - | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); - - dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2), - dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3); - if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3) - mask &= (3<<2) - | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) - | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) - | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); - if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) - mask &= (3<<2) - | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) - | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) - | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); + if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) + mask &= (3<<4) + | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) + | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) + | (dn3 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); + + dp1 = p1[1] + p1[2], dn1 = p1[1] - p1[2], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = p2[1] + p2[2], dn2 = p2[1] - p2[2], ap2 = fabs(dp2), an2 = fabs(dn2), + dp3 = p3[1] + p3[2], dn3 = p3[1] - p3[2], ap3 = fabs(dp3), an3 = fabs(dn3); + if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3) + mask &= (3<<0) + | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) + | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) + | (dp3 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); + if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) + mask &= (3<<0) + | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) + | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) + | (dn3 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); + + dp1 = p1[2] + p1[0], dn1 = p1[2] - p1[0], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = p2[2] + p2[0], dn2 = p2[2] - p2[0], ap2 = fabs(dp2), an2 = fabs(dn2), + dp3 = p3[2] + p3[0], dn3 = p3[2] - p3[0], ap3 = fabs(dp3), an3 = fabs(dn3); + if(ap1 > bias*an1 && ap2 > bias*an2 && ap3 > bias*an3) + mask &= (3<<2) + | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) + | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) + | (dp3 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); + if(an1 > bias*ap1 && an2 > bias*ap2 && an3 > bias*ap3) + mask &= (3<<2) + | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) + | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) + | (dn3 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); return mask; } -int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias) +static int R_Shadow_CalcBBoxSideMask(const vec3_t mins, const vec3_t maxs, const matrix4x4_t *worldtolight, const matrix4x4_t *radiustolight, float bias) { vec3_t center, radius, lightcenter, lightradius, pmin, pmax; float dp1, dn1, ap1, an1, dp2, dn2, ap2, an2; int mask = 0x3F; VectorSubtract(maxs, mins, radius); - VectorScale(radius, 0.5f, radius); - VectorAdd(mins, radius, center); - Matrix4x4_Transform(worldtolight, center, lightcenter); + VectorScale(radius, 0.5f, radius); + VectorAdd(mins, radius, center); + Matrix4x4_Transform(worldtolight, center, lightcenter); Matrix4x4_Transform3x3(radiustolight, radius, lightradius); VectorSubtract(lightcenter, lightradius, pmin); VectorAdd(lightcenter, lightradius, pmax); - dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2); - if(ap1 > bias*an1 && ap2 > bias*an2) - mask &= (3<<4) - | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)) - | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)); - if(an1 > bias*ap1 && an2 > bias*ap2) - mask &= (3<<4) - | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) - | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); - - dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2); - if(ap1 > bias*an1 && ap2 > bias*an2) - mask &= (3<<0) - | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) - | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); - if(an1 > bias*ap1 && an2 > bias*ap2) - mask &= (3<<0) - | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) - | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); - - dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1), - dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2); - if(ap1 > bias*an1 && ap2 > bias*an2) - mask &= (3<<2) - | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) - | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); - if(an1 > bias*ap1 && an2 > bias*ap2) - mask &= (3<<2) - | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) - | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); - - return mask; + dp1 = pmax[0] + pmax[1], dn1 = pmax[0] - pmin[1], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = pmin[0] + pmin[1], dn2 = pmin[0] - pmax[1], ap2 = fabs(dp2), an2 = fabs(dn2); + if(ap1 > bias*an1 && ap2 > bias*an2) + mask &= (3<<4) + | (dp1 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)) + | (dp2 >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)); + if(an1 > bias*ap1 && an2 > bias*ap2) + mask &= (3<<4) + | (dn1 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)) + | (dn2 >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); + + dp1 = pmax[1] + pmax[2], dn1 = pmax[1] - pmin[2], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = pmin[1] + pmin[2], dn2 = pmin[1] - pmax[2], ap2 = fabs(dp2), an2 = fabs(dn2); + if(ap1 > bias*an1 && ap2 > bias*an2) + mask &= (3<<0) + | (dp1 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)) + | (dp2 >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); + if(an1 > bias*ap1 && an2 > bias*ap2) + mask &= (3<<0) + | (dn1 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)) + | (dn2 >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); + + dp1 = pmax[2] + pmax[0], dn1 = pmax[2] - pmin[0], ap1 = fabs(dp1), an1 = fabs(dn1), + dp2 = pmin[2] + pmin[0], dn2 = pmin[2] - pmax[0], ap2 = fabs(dp2), an2 = fabs(dn2); + if(ap1 > bias*an1 && ap2 > bias*an2) + mask &= (3<<2) + | (dp1 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)) + | (dp2 >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); + if(an1 > bias*ap1 && an2 > bias*ap2) + mask &= (3<<2) + | (dn1 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)) + | (dn2 >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); + + return mask; } #define R_Shadow_CalcEntitySideMask(ent, worldtolight, radiustolight, bias) R_Shadow_CalcBBoxSideMask((ent)->mins, (ent)->maxs, worldtolight, radiustolight, bias) int R_Shadow_CalcSphereSideMask(const vec3_t p, float radius, float bias) { - // p is in the cubemap's local coordinate system - // bias = border/(size - border) - float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn); - float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn); - float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn); - int mask = 0x3F; - if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2)); - if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2)); - if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4)); - if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4)); - if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0)); - if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0)); - return mask; + // p is in the cubemap's local coordinate system + // bias = border/(size - border) + float dxyp = p[0] + p[1], dxyn = p[0] - p[1], axyp = fabs(dxyp), axyn = fabs(dxyn); + float dyzp = p[1] + p[2], dyzn = p[1] - p[2], ayzp = fabs(dyzp), ayzn = fabs(dyzn); + float dzxp = p[2] + p[0], dzxn = p[2] - p[0], azxp = fabs(dzxp), azxn = fabs(dzxn); + int mask = 0x3F; + if(axyp > bias*axyn + radius) mask &= dxyp < 0 ? ~((1<<0)|(1<<2)) : ~((2<<0)|(2<<2)); + if(axyn > bias*axyp + radius) mask &= dxyn < 0 ? ~((1<<0)|(2<<2)) : ~((2<<0)|(1<<2)); + if(ayzp > bias*ayzn + radius) mask &= dyzp < 0 ? ~((1<<2)|(1<<4)) : ~((2<<2)|(2<<4)); + if(ayzn > bias*ayzp + radius) mask &= dyzn < 0 ? ~((1<<2)|(2<<4)) : ~((2<<2)|(1<<4)); + if(azxp > bias*azxn + radius) mask &= dzxp < 0 ? ~((1<<4)|(1<<0)) : ~((2<<4)|(2<<0)); + if(azxn > bias*azxp + radius) mask &= dzxn < 0 ? ~((1<<4)|(2<<0)) : ~((2<<4)|(1<<0)); + return mask; } -int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border) +static int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border) { int i; - vec3_t p, n; + vec3_t o, p, n; int sides = 0x3F, masks[6] = { 3<<4, 3<<4, 3<<0, 3<<0, 3<<2, 3<<2 }; float scale = (size - 2*border)/size, len; float bias = border / (float)(size - border), dp, dn, ap, an; // check if cone enclosing side would cross frustum plane scale = 2 / (scale*scale + 2); + Matrix4x4_OriginFromMatrix(&rtlight->matrix_lighttoworld, o); for (i = 0;i < 5;i++) { - if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) > -0.03125) + if (PlaneDiff(o, &r_refdef.view.frustum[i]) > -0.03125) continue; Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[i].normal, n); len = scale*VectorLength2(n); @@ -1494,29 +1563,58 @@ int R_Shadow_CullFrustumSides(rtlight_t *rtlight, float size, float border) if(n[1]*n[1] > len) sides &= n[1] < 0 ? ~(1<<2) : ~(2 << 2); if(n[2]*n[2] > len) sides &= n[2] < 0 ? ~(1<<4) : ~(2 << 4); } - if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125) + if (PlaneDiff(o, &r_refdef.view.frustum[4]) >= r_refdef.farclip - r_refdef.nearclip + 0.03125) { - Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n); - len = scale*VectorLength(n); + Matrix4x4_Transform3x3(&rtlight->matrix_worldtolight, r_refdef.view.frustum[4].normal, n); + len = scale*VectorLength2(n); if(n[0]*n[0] > len) sides &= n[0] >= 0 ? ~(1<<0) : ~(2 << 0); if(n[1]*n[1] > len) sides &= n[1] >= 0 ? ~(1<<2) : ~(2 << 2); if(n[2]*n[2] > len) sides &= n[2] >= 0 ? ~(1<<4) : ~(2 << 4); } // this next test usually clips off more sides than the former, but occasionally clips fewer/different ones, so do both and combine results // check if frustum corners/origin cross plane sides +#if 1 + // infinite version, assumes frustum corners merely give direction and extend to infinite distance + Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.origin, p); + dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn); + masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)); + masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); + dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn); + masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); + masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); + dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn); + masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); + masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); + for (i = 0;i < 4;i++) + { + Matrix4x4_Transform(&rtlight->matrix_worldtolight, r_refdef.view.frustumcorner[i], n); + VectorSubtract(n, p, n); + dp = n[0] + n[1], dn = n[0] - n[1], ap = fabs(dp), an = fabs(dn); + if(ap > 0) masks[0] |= dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2); + if(an > 0) masks[1] |= dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2); + dp = n[1] + n[2], dn = n[1] - n[2], ap = fabs(dp), an = fabs(dn); + if(ap > 0) masks[2] |= dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4); + if(an > 0) masks[3] |= dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4); + dp = n[2] + n[0], dn = n[2] - n[0], ap = fabs(dp), an = fabs(dn); + if(ap > 0) masks[4] |= dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0); + if(an > 0) masks[5] |= dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0); + } +#else + // finite version, assumes corners are a finite distance from origin dependent on far plane for (i = 0;i < 5;i++) { Matrix4x4_Transform(&rtlight->matrix_worldtolight, !i ? r_refdef.view.origin : r_refdef.view.frustumcorner[i-1], p); - dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn), + dp = p[0] + p[1], dn = p[0] - p[1], ap = fabs(dp), an = fabs(dn); masks[0] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<0)|(1<<2) : (2<<0)|(2<<2)); masks[1] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<0)|(2<<2) : (2<<0)|(1<<2)); - dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn), + dp = p[1] + p[2], dn = p[1] - p[2], ap = fabs(dp), an = fabs(dn); masks[2] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<2)|(1<<4) : (2<<2)|(2<<4)); masks[3] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<2)|(2<<4) : (2<<2)|(1<<4)); - dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn), + dp = p[2] + p[0], dn = p[2] - p[0], ap = fabs(dp), an = fabs(dn); masks[4] |= ap <= bias*an ? 0x3F : (dp >= 0 ? (1<<4)|(1<<0) : (2<<4)|(2<<0)); masks[5] |= an <= bias*ap ? 0x3F : (dn >= 0 ? (1<<4)|(2<<0) : (2<<4)|(1<<0)); } +#endif return sides & masks[0] & masks[1] & masks[2] & masks[3] & masks[4] & masks[5]; } @@ -1586,7 +1684,7 @@ int R_Shadow_ChooseSidesFromBox(int firsttriangle, int numtris, const float *inv v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3; TriangleNormal(v[0], v[1], v[2], normal); if (r_shadow_frontsidecasting.integer == (DotProduct(normal, projectdirection) < 0) - && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) + && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) { Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]); mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias); @@ -1606,7 +1704,7 @@ int R_Shadow_ChooseSidesFromBox(int firsttriangle, int numtris, const float *inv { v[0] = invertex3f + e[0] * 3, v[1] = invertex3f + e[1] * 3, v[2] = invertex3f + e[2] * 3; if (r_shadow_frontsidecasting.integer == PointInfrontOfTriangle(projectorigin, v[0], v[1], v[2]) - && TriangleOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) + && TriangleBBoxOverlapsBox(v[0], v[1], v[2], lightmins, lightmaxs)) { Matrix4x4_Transform(worldtolight, v[0], p[0]), Matrix4x4_Transform(worldtolight, v[1], p[1]), Matrix4x4_Transform(worldtolight, v[2], p[2]); mask = R_Shadow_CalcTriangleSideMask(p[0], p[1], p[2], bias); @@ -1683,7 +1781,7 @@ static void R_Shadow_MakeTextures_MakeCorona(void) pixels[y][x][3] = 255; } } - r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_PRECACHE | TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32); + r_shadow_lightcorona = R_SkinFrame_LoadInternalBGRA("lightcorona", TEXF_FORCELINEAR, &pixels[0][0][0], 32, 32, false); } static unsigned int R_Shadow_MakeTextures_SamplePoint(float x, float y, float z) @@ -1715,20 +1813,20 @@ static void R_Shadow_MakeTextures(void) // 1D gradient texture for (x = 0;x < ATTEN1DSIZE;x++) data[x] = R_Shadow_MakeTextures_SamplePoint((x + 0.5f) * (1.0f / ATTEN1DSIZE) * (1.0f / 0.9375), 0, 0); - r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL); + r_shadow_attenuationgradienttexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation1d", ATTEN1DSIZE, 1, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL); // 2D circle texture for (y = 0;y < ATTEN2DSIZE;y++) for (x = 0;x < ATTEN2DSIZE;x++) data[y*ATTEN2DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN2DSIZE) - 1.0f) * (1.0f / 0.9375), 0); - r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL); + r_shadow_attenuation2dtexture = R_LoadTexture2D(r_shadow_texturepool, "attenuation2d", ATTEN2DSIZE, ATTEN2DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL); // 3D sphere texture - if (r_shadow_texture3d.integer && gl_texture3d) + if (r_shadow_texture3d.integer && vid.support.ext_texture_3d) { for (z = 0;z < ATTEN3DSIZE;z++) for (y = 0;y < ATTEN3DSIZE;y++) for (x = 0;x < ATTEN3DSIZE;x++) data[(z*ATTEN3DSIZE+y)*ATTEN3DSIZE+x] = R_Shadow_MakeTextures_SamplePoint(((x + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((y + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375), ((z + 0.5f) * (2.0f / ATTEN3DSIZE) - 1.0f) * (1.0f / 0.9375)); - r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_PRECACHE | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, NULL); + r_shadow_attenuation3dtexture = R_LoadTexture3D(r_shadow_texturepool, "attenuation3d", ATTEN3DSIZE, ATTEN3DSIZE, ATTEN3DSIZE, (unsigned char *)data, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, -1, NULL); } else r_shadow_attenuation3dtexture = NULL; @@ -1737,7 +1835,7 @@ static void R_Shadow_MakeTextures(void) R_Shadow_MakeTextures_MakeCorona(); // Editor light sprites - r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) + r_editlights_sprcursor = R_SkinFrame_LoadInternal8bit("gfx/editlights/cursor", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) "................" ".3............3." "..5...2332...5.." @@ -1755,7 +1853,7 @@ static void R_Shadow_MakeTextures(void) ".3............3." "................" , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic); - r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) + r_editlights_sprlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/light", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) "................" "................" "......1111......" @@ -1773,7 +1871,7 @@ static void R_Shadow_MakeTextures(void) "................" "................" , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic); - r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) + r_editlights_sprnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/noshadow", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) "................" "................" "......1111......" @@ -1791,7 +1889,7 @@ static void R_Shadow_MakeTextures(void) "................" "................" , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic); - r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) + r_editlights_sprcubemaplight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemaplight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) "................" "................" "......2772......" @@ -1809,7 +1907,7 @@ static void R_Shadow_MakeTextures(void) "................" "................" , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic); - r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) + r_editlights_sprcubemapnoshadowlight = R_SkinFrame_LoadInternal8bit("gfx/editlights/cubemapnoshadowlight", TEXF_ALPHA | TEXF_CLAMP, (const unsigned char *) "................" "................" "......2772......" @@ -1827,7 +1925,7 @@ static void R_Shadow_MakeTextures(void) "................" "................" , 16, 16, palette_bgra_embeddedpic, palette_bgra_embeddedpic); - r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_PRECACHE | TEXF_ALPHA | TEXF_CLAMP, (unsigned char *) + r_editlights_sprselection = R_SkinFrame_LoadInternal8bit("gfx/editlights/selection", TEXF_ALPHA | TEXF_CLAMP, (unsigned char *) "................" ".777752..257777." ".742........247." @@ -1849,11 +1947,11 @@ static void R_Shadow_MakeTextures(void) void R_Shadow_ValidateCvars(void) { - if (r_shadow_texture3d.integer && !gl_texture3d) + if (r_shadow_texture3d.integer && !vid.support.ext_texture_3d) Cvar_SetValueQuick(&r_shadow_texture3d, 0); - if (gl_ext_separatestencil.integer && !gl_support_separatestencil) + if (gl_ext_separatestencil.integer && !vid.support.ati_separate_stencil) Cvar_SetValueQuick(&gl_ext_separatestencil, 0); - if (gl_ext_stenciltwoside.integer && !gl_support_stenciltwoside) + if (gl_ext_stenciltwoside.integer && !vid.support.ext_stencil_two_side) Cvar_SetValueQuick(&gl_ext_stenciltwoside, 0); } @@ -1872,7 +1970,6 @@ void R_Shadow_RenderMode_Begin(void) R_Shadow_MakeTextures(); CHECKGLERROR - R_Mesh_ColorPointer(NULL, 0, 0); R_Mesh_ResetTextureState(); GL_BlendFunc(GL_ONE, GL_ZERO); GL_DepthRange(0, 1); @@ -1881,15 +1978,15 @@ void R_Shadow_RenderMode_Begin(void) GL_DepthMask(false); GL_Color(0, 0, 0, 1); GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height); - + r_shadow_rendermode = R_SHADOW_RENDERMODE_NONE; - if (gl_ext_separatestencil.integer) + if (gl_ext_separatestencil.integer && vid.support.ati_separate_stencil) { r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL; r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL; } - else if (gl_ext_stenciltwoside.integer) + else if (gl_ext_stenciltwoside.integer && vid.support.ext_stencil_two_side) { r_shadow_shadowingrendermode_zpass = R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE; r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE; @@ -1900,12 +1997,29 @@ void R_Shadow_RenderMode_Begin(void) r_shadow_shadowingrendermode_zfail = R_SHADOW_RENDERMODE_ZFAIL_STENCIL; } - if (r_glsl.integer && gl_support_fragment_shader) + switch(vid.renderpath) + { + case RENDERPATH_GL20: + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: + case RENDERPATH_SOFT: + case RENDERPATH_GLES2: r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_GLSL; - else if (gl_dot3arb && gl_texturecubemap && r_shadow_dot3.integer && gl_stencil) - r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_DOT3; - else - r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX; + break; + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GLES1: + if (r_textureunits.integer >= 2 && vid.texunits >= 2 && r_shadow_texture3d.integer && r_shadow_attenuation3dtexture) + r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN; + else if (r_textureunits.integer >= 3 && vid.texunits >= 3) + r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN; + else if (r_textureunits.integer >= 2 && vid.texunits >= 2) + r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN; + else + r_shadow_lightingrendermode = R_SHADOW_RENDERMODE_LIGHT_VERTEX; + break; + } CHECKGLERROR #if 0 @@ -1925,50 +2039,31 @@ void R_Shadow_RenderMode_ActiveLight(const rtlight_t *rtlight) void R_Shadow_RenderMode_Reset(void) { - CHECKGLERROR - if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE) - { - qglDisable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR - } - if (gl_support_ext_framebuffer_object) - { - qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);CHECKGLERROR - } -#if 0 - qglDrawBuffer(r_shadow_drawbuffer);CHECKGLERROR - qglReadBuffer(r_shadow_readbuffer);CHECKGLERROR -#endif + R_Mesh_ResetTextureState(); + R_Mesh_SetRenderTargets(r_shadow_fb_fbo, r_shadow_fb_depthtexture, r_shadow_fb_colortexture, NULL, NULL, NULL); R_SetViewport(&r_refdef.view.viewport); GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]); - R_Mesh_ColorPointer(NULL, 0, 0); - R_Mesh_ResetTextureState(); GL_DepthRange(0, 1); GL_DepthTest(true); GL_DepthMask(false); - qglDepthFunc(GL_LEQUAL);CHECKGLERROR + GL_DepthFunc(GL_LEQUAL); GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);CHECKGLERROR - qglDisable(GL_STENCIL_TEST);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR - qglStencilFunc(GL_ALWAYS, 128, ~0);CHECKGLERROR r_refdef.view.cullface_front = r_shadow_cullface_front; r_refdef.view.cullface_back = r_shadow_cullface_back; GL_CullFace(r_refdef.view.cullface_back); GL_Color(1, 1, 1, 1); GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1); GL_BlendFunc(GL_ONE, GL_ZERO); - R_SetupGenericShader(false); - r_shadow_usingshadowmaprect = false; - r_shadow_usingshadowmapcube = false; + R_SetupShader_Generic_NoTexture(false, false); r_shadow_usingshadowmap2d = false; - CHECKGLERROR + r_shadow_usingshadowmaportho = false; + R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255); } void R_Shadow_ClearStencil(void) { - CHECKGLERROR - GL_Clear(GL_STENCIL_BUFFER_BIT); - r_refdef.stats.lights_clears++; + GL_Clear(GL_STENCIL_BUFFER_BIT, NULL, 1.0f, 128); + r_refdef.stats[r_stat_lights_clears]++; } void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass) @@ -1976,47 +2071,24 @@ void R_Shadow_RenderMode_StencilShadowVolumes(qboolean zpass) r_shadow_rendermode_t mode = zpass ? r_shadow_shadowingrendermode_zpass : r_shadow_shadowingrendermode_zfail; if (r_shadow_rendermode == mode) return; - CHECKGLERROR R_Shadow_RenderMode_Reset(); + GL_DepthFunc(GL_LESS); GL_ColorMask(0, 0, 0, 0); GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR - R_SetupDepthOrShadowShader(); - qglDepthFunc(GL_LESS);CHECKGLERROR - qglEnable(GL_STENCIL_TEST);CHECKGLERROR + GL_CullFace(GL_NONE); + R_SetupShader_DepthOrShadow(false, false, false); // FIXME test if we have a skeletal model? r_shadow_rendermode = mode; switch(mode) { default: break; - case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL: - GL_CullFace(GL_NONE); - qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR - qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR - break; - case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL: - GL_CullFace(GL_NONE); - qglStencilOpSeparate(r_refdef.view.cullface_front, GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR - qglStencilOpSeparate(r_refdef.view.cullface_back, GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR - break; case R_SHADOW_RENDERMODE_ZPASS_STENCILTWOSIDE: - GL_CullFace(GL_NONE); - qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR - qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR - qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR + case R_SHADOW_RENDERMODE_ZPASS_SEPARATESTENCIL: + R_SetStencilSeparate(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, GL_ALWAYS, 128, 255); break; case R_SHADOW_RENDERMODE_ZFAIL_STENCILTWOSIDE: - GL_CullFace(GL_NONE); - qglEnable(GL_STENCIL_TEST_TWO_SIDE_EXT);CHECKGLERROR - qglActiveStencilFaceEXT(r_refdef.view.cullface_front);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR - qglActiveStencilFaceEXT(r_refdef.view.cullface_back);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR + case R_SHADOW_RENDERMODE_ZFAIL_SEPARATESTENCIL: + R_SetStencilSeparate(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, GL_ALWAYS, 128, 255); break; } } @@ -2038,166 +2110,140 @@ static void R_Shadow_MakeVSDCT(void) 0, 0, 0x33, 0xFF, // +Z: <0, 0>, <0.5, 2.5> 0, 0, 0x99, 0xFF, // -Z: <0, 0>, <1.5, 2.5> }; - r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_ALWAYSPRECACHE | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, NULL); + r_shadow_shadowmapvsdcttexture = R_LoadTextureCubeMap(r_shadow_texturepool, "shadowmapvsdct", 1, data, TEXTYPE_RGBA, TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL); +} + +static void R_Shadow_MakeShadowMap(int side, int size) +{ + switch (r_shadow_shadowmode) + { + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + if (r_shadow_shadowmap2ddepthtexture) return; + if (r_fb.usedepthtextures) + { + r_shadow_shadowmap2ddepthtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits >= 24 ? (r_shadow_shadowmapsampler ? TEXTYPE_SHADOWMAP24_COMP : TEXTYPE_SHADOWMAP24_RAW) : (r_shadow_shadowmapsampler ? TEXTYPE_SHADOWMAP16_COMP : TEXTYPE_SHADOWMAP16_RAW), r_shadow_shadowmapsampler); + r_shadow_shadowmap2ddepthbuffer = NULL; + r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL); + } + else + { + r_shadow_shadowmap2ddepthtexture = R_LoadTexture2D(r_shadow_texturepool, "shadowmaprendertarget", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), NULL, TEXTYPE_COLORBUFFER, TEXF_RENDERTARGET | TEXF_FORCENEAREST | TEXF_CLAMP | TEXF_ALPHA, -1, NULL); + r_shadow_shadowmap2ddepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "shadowmap", size*2, size*(vid.support.arb_texture_non_power_of_two ? 3 : 4), r_shadow_shadowmapdepthbits >= 24 ? TEXTYPE_DEPTHBUFFER24 : TEXTYPE_DEPTHBUFFER16); + r_shadow_fbo2d = R_Mesh_CreateFramebufferObject(r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL); + } + break; + default: + return; + } } -void R_Shadow_RenderMode_ShadowMap(int side, qboolean clear, int size) +static void R_Shadow_RenderMode_ShadowMap(int side, int clear, int size) { - int status; - int maxsize; float nearclip, farclip, bias; r_viewport_t viewport; - GLuint fbo = 0; - CHECKGLERROR - maxsize = r_shadow_shadowmapmaxsize; + int flipped; + GLuint fbo2d = 0; + float clearcolor[4]; nearclip = r_shadow_shadowmapping_nearclip.value / rsurface.rtlight->radius; farclip = 1.0f; bias = r_shadow_shadowmapping_bias.value * nearclip * (1024.0f / size);// * rsurface.rtlight->radius; - r_shadow_shadowmap_parameters[2] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip); - r_shadow_shadowmap_parameters[3] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias; + r_shadow_shadowmap_parameters[1] = -nearclip * farclip / (farclip - nearclip) - 0.5f * bias; + r_shadow_shadowmap_parameters[3] = 0.5f + 0.5f * (farclip + nearclip) / (farclip - nearclip); r_shadow_shadowmapside = side; r_shadow_shadowmapsize = size; - if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D) - { - r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder); - r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size; - R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL); - if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done; - - // complex unrolled cube approach (more flexible) - if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture) - R_Shadow_MakeVSDCT(); - if (!r_shadow_shadowmap2dtexture) - { -#if 1 - int w = maxsize*2, h = gl_support_arb_texture_non_power_of_two ? maxsize*3 : maxsize*4; - r_shadow_shadowmap2dtexture = R_LoadTextureShadowMap2D(r_shadow_texturepool, "shadowmap", w, h, r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler); - qglGenFramebuffersEXT(1, &r_shadow_fbo2d);CHECKGLERROR - qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbo2d);CHECKGLERROR - qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, R_GetTexture(r_shadow_shadowmap2dtexture), 0);CHECKGLERROR - // render depth into the fbo, do not render color at all - qglDrawBuffer(GL_NONE);CHECKGLERROR - qglReadBuffer(GL_NONE);CHECKGLERROR - status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR - if (status != GL_FRAMEBUFFER_COMPLETE_EXT && r_shadow_shadowmapping.integer) - { - Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status); - Cvar_SetValueQuick(&r_shadow_shadowmapping, 0); - } -#endif - } - CHECKGLERROR - if (r_shadow_shadowmap2dtexture) fbo = r_shadow_fbo2d; - r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2dtexture); - r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2dtexture); - r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D; - } - else if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE) - { - r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder); - r_shadow_shadowmap_parameters[1] = r_shadow_shadowmapvsdct ? 2.5f*size : size; - R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL); - if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE) goto init_done; - - // complex unrolled cube approach (more flexible) - if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture) - R_Shadow_MakeVSDCT(); - if (!r_shadow_shadowmaprectangletexture) - { -#if 1 - r_shadow_shadowmaprectangletexture = R_LoadTextureShadowMapRectangle(r_shadow_texturepool, "shadowmap", maxsize*2, maxsize*3, r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler); - qglGenFramebuffersEXT(1, &r_shadow_fborectangle);CHECKGLERROR - qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fborectangle);CHECKGLERROR - qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_RECTANGLE_ARB, R_GetTexture(r_shadow_shadowmaprectangletexture), 0);CHECKGLERROR - // render depth into the fbo, do not render color at all - qglDrawBuffer(GL_NONE);CHECKGLERROR - qglReadBuffer(GL_NONE);CHECKGLERROR - status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR - if (status != GL_FRAMEBUFFER_COMPLETE_EXT && r_shadow_shadowmapping.integer) - { - Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status); - Cvar_SetValueQuick(&r_shadow_shadowmapping, 0); - } -#endif - } - CHECKGLERROR - if(r_shadow_shadowmaprectangletexture) fbo = r_shadow_fborectangle; - r_shadow_shadowmap_texturescale[0] = 1.0f; - r_shadow_shadowmap_texturescale[1] = 1.0f; - r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE; - } - else if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE) - { - r_shadow_shadowmap_parameters[0] = 1.0f; - r_shadow_shadowmap_parameters[1] = 1.0f; - R_Viewport_InitCubeSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, nearclip, farclip, NULL); - if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE) goto init_done; - // simple cube approach - if (!r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]) - { - #if 1 - r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod] = R_LoadTextureShadowMapCube(r_shadow_texturepool, "shadowmapcube", size, r_shadow_shadowmapdepthbits, r_shadow_shadowmapsampler); - qglGenFramebuffersEXT(1, &r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR - qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, r_shadow_fbocubeside[r_shadow_shadowmaplod]);CHECKGLERROR - qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR - // render depth into the fbo, do not render color at all - qglDrawBuffer(GL_NONE);CHECKGLERROR - qglReadBuffer(GL_NONE);CHECKGLERROR - status = qglCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);CHECKGLERROR - if (status != GL_FRAMEBUFFER_COMPLETE_EXT && r_shadow_shadowmapping.integer) - { - Con_Printf("R_Shadow_RenderMode_ShadowMap: glCheckFramebufferStatusEXT returned %i\n", status); - Cvar_SetValueQuick(&r_shadow_shadowmapping, 0); - } - #endif - } - CHECKGLERROR - if (r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]) fbo = r_shadow_fbocubeside[r_shadow_shadowmaplod]; - r_shadow_shadowmap_texturescale[0] = 0.0f; - r_shadow_shadowmap_texturescale[1] = 0.0f; - r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE; - } + r_shadow_shadowmap_parameters[0] = 0.5f * (size - r_shadow_shadowmapborder); + r_shadow_shadowmap_parameters[2] = r_shadow_shadowmapvsdct ? 2.5f*size : size; + R_Viewport_InitRectSideView(&viewport, &rsurface.rtlight->matrix_lighttoworld, side, size, r_shadow_shadowmapborder, nearclip, farclip, NULL); + if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) goto init_done; + + // complex unrolled cube approach (more flexible) + if (r_shadow_shadowmapvsdct && !r_shadow_shadowmapvsdcttexture) + R_Shadow_MakeVSDCT(); + if (!r_shadow_shadowmap2ddepthtexture) + R_Shadow_MakeShadowMap(side, r_shadow_shadowmapmaxsize); + fbo2d = r_shadow_fbo2d; + r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture); + r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture); + r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D; + R_Mesh_ResetTextureState(); R_Shadow_RenderMode_Reset(); - if (fbo) - { - qglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);CHECKGLERROR - R_SetupDepthOrShadowShader(); - } + if (r_shadow_shadowmap2ddepthbuffer) + R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL); else - { - R_SetupShowDepthShader(); - qglClearColor(1,1,1,1);CHECKGLERROR - } - CHECKGLERROR + R_Mesh_SetRenderTargets(fbo2d, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL); + R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL, false); // FIXME test if we have a skeletal model? GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value); GL_DepthMask(true); GL_DepthTest(true); - qglClearDepth(1); - CHECKGLERROR init_done: R_SetViewport(&viewport); - GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height); - if(r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE) - { - int flipped = (side&1)^(side>>2); - r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front; - r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back; + flipped = (side & 1) ^ (side >> 2); + r_refdef.view.cullface_front = flipped ? r_shadow_cullface_back : r_shadow_cullface_front; + r_refdef.view.cullface_back = flipped ? r_shadow_cullface_front : r_shadow_cullface_back; + if (r_shadow_shadowmap2ddepthbuffer) + { + // completely different meaning than in depthtexture approach + r_shadow_shadowmap_parameters[1] = 0; + r_shadow_shadowmap_parameters[3] = -bias; + } + Vector4Set(clearcolor, 1,1,1,1); + if (r_shadow_shadowmap2ddepthbuffer) + GL_ColorMask(1,1,1,1); + else + GL_ColorMask(0,0,0,0); + switch(vid.renderpath) + { + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GL20: + case RENDERPATH_SOFT: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: GL_CullFace(r_refdef.view.cullface_back); + // OpenGL lets us scissor larger than the viewport, so go ahead and clear all views at once + if ((clear & ((2 << side) - 1)) == (1 << side)) // only clear if the side is the first in the mask + { + // get tightest scissor rectangle that encloses all viewports in the clear mask + int x1 = clear & 0x15 ? 0 : size; + int x2 = clear & 0x2A ? 2 * size : size; + int y1 = clear & 0x03 ? 0 : (clear & 0xC ? size : 2 * size); + int y2 = clear & 0x30 ? 3 * size : (clear & 0xC ? 2 * size : size); + GL_Scissor(x1, y1, x2 - x1, y2 - y1); + if (clear) + { + if (r_shadow_shadowmap2ddepthbuffer) + GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0); + else + GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0); + } + } + GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height); + break; + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: + // we invert the cull mode because we flip the projection matrix + // NOTE: this actually does nothing because the DrawShadowMap code sets it to doublesided... + GL_CullFace(r_refdef.view.cullface_front); + // D3D considers it an error to use a scissor larger than the viewport... clear just this view + GL_Scissor(viewport.x, viewport.y, viewport.width, viewport.height); + if (clear) + { + if (r_shadow_shadowmap2ddepthbuffer) + GL_Clear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0); + else + GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0); + } + break; } - else if(r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE) - { - qglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB + side, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod]), 0);CHECKGLERROR - } - if (clear) - qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); - CHECKGLERROR } void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qboolean shadowmapping) { + R_Mesh_ResetTextureState(); if (transparent) { r_shadow_lightscissor[0] = r_refdef.view.viewport.x; @@ -2205,97 +2251,704 @@ void R_Shadow_RenderMode_Lighting(qboolean stenciltest, qboolean transparent, qb r_shadow_lightscissor[2] = r_refdef.view.viewport.width; r_shadow_lightscissor[3] = r_refdef.view.viewport.height; } - CHECKGLERROR R_Shadow_RenderMode_Reset(); GL_BlendFunc(GL_SRC_ALPHA, GL_ONE); if (!transparent) - { - qglDepthFunc(GL_EQUAL);CHECKGLERROR - } - if (stenciltest) - { - qglEnable(GL_STENCIL_TEST);CHECKGLERROR - // only draw light where this geometry was already rendered AND the - // stencil is 128 (values other than this mean shadow) - qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR - } - r_shadow_rendermode = r_shadow_lightingrendermode; + GL_DepthFunc(GL_EQUAL); // do global setup needed for the chosen lighting mode if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL) - { - R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); // light filter GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0); - CHECKGLERROR - if (shadowmapping) - { - if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D) - { - r_shadow_usingshadowmap2d = true; - R_Mesh_TexBind(GL20TU_SHADOWMAP2D, R_GetTexture(r_shadow_shadowmap2dtexture)); - CHECKGLERROR - } - else if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE) - { - r_shadow_usingshadowmaprect = true; - R_Mesh_TexBindRectangle(GL20TU_SHADOWMAPRECT, R_GetTexture(r_shadow_shadowmaprectangletexture)); - CHECKGLERROR - } - else if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE) - { - r_shadow_usingshadowmapcube = true; - R_Mesh_TexBindCubeMap(GL20TU_SHADOWMAPCUBE, R_GetTexture(r_shadow_shadowmapcubetexture[r_shadow_shadowmaplod])); - CHECKGLERROR - } - - if (r_shadow_shadowmapvsdct && (r_shadow_usingshadowmap2d || r_shadow_usingshadowmaprect)) - { - R_Mesh_TexBindCubeMap(GL20TU_CUBEPROJECTION, R_GetTexture(r_shadow_shadowmapvsdcttexture)); - CHECKGLERROR - } - } - } - else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_LIGHT_VERTEX) - R_Mesh_ColorPointer(rsurface.array_color4f, 0, 0); - //GL_BlendFunc(GL_SRC_ALPHA, GL_ONE); - CHECKGLERROR + r_shadow_usingshadowmap2d = shadowmapping; + r_shadow_rendermode = r_shadow_lightingrendermode; + // only draw light where this geometry was already rendered AND the + // stencil is 128 (values other than this mean shadow) + if (stenciltest) + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255); + else + R_SetStencil(false, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_ALWAYS, 128, 255); } -void R_Shadow_RenderMode_VisibleShadowVolumes(void) +static const unsigned short bboxelements[36] = { - CHECKGLERROR + 5, 1, 3, 5, 3, 7, + 6, 2, 0, 6, 0, 4, + 7, 3, 2, 7, 2, 6, + 4, 0, 1, 4, 1, 5, + 4, 5, 7, 4, 7, 6, + 1, 0, 2, 1, 2, 3, +}; + +static const float bboxpoints[8][3] = +{ + {-1,-1,-1}, + { 1,-1,-1}, + {-1, 1,-1}, + { 1, 1,-1}, + {-1,-1, 1}, + { 1,-1, 1}, + {-1, 1, 1}, + { 1, 1, 1}, +}; + +void R_Shadow_RenderMode_DrawDeferredLight(qboolean stenciltest, qboolean shadowmapping) +{ + int i; + float vertex3f[8*3]; + const matrix4x4_t *matrix = &rsurface.rtlight->matrix_lighttoworld; +// do global setup needed for the chosen lighting mode R_Shadow_RenderMode_Reset(); - GL_BlendFunc(GL_ONE, GL_ONE); + r_shadow_rendermode = r_shadow_lightingrendermode; + R_EntityMatrix(&identitymatrix); + GL_BlendFunc(GL_SRC_ALPHA, GL_ONE); + // only draw light where this geometry was already rendered AND the + // stencil is 128 (values other than this mean shadow) + R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255); + if (rsurface.rtlight->specularscale > 0 && r_shadow_gloss.integer > 0) + R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL); + else + R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL); + + r_shadow_usingshadowmap2d = shadowmapping; + + // render the lighting + R_SetupShader_DeferredLight(rsurface.rtlight); + for (i = 0;i < 8;i++) + Matrix4x4_Transform(matrix, bboxpoints[i], vertex3f + i*3); + GL_ColorMask(1,1,1,1); + GL_DepthMask(false); GL_DepthRange(0, 1); - GL_DepthTest(r_showshadowvolumes.integer < 2); - GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1); - GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR - GL_CullFace(GL_NONE); - r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES; + GL_PolygonOffset(0, 0); + GL_DepthTest(true); + GL_DepthFunc(GL_GREATER); + GL_CullFace(r_refdef.view.cullface_back); + R_Mesh_PrepareVertices_Vertex3f(8, vertex3f, NULL, 0); + R_Mesh_Draw(0, 8, 0, 12, NULL, NULL, 0, bboxelements, NULL, 0); } -void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent) +void R_Shadow_UpdateBounceGridTexture(void) { - CHECKGLERROR - R_Shadow_RenderMode_Reset(); - GL_BlendFunc(GL_ONE, GL_ONE); - GL_DepthRange(0, 1); - GL_DepthTest(r_showlighting.integer < 2); - GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1); - if (!transparent) - { - qglDepthFunc(GL_EQUAL);CHECKGLERROR +#define MAXBOUNCEGRIDPARTICLESPERLIGHT 1048576 + dlight_t *light; + int flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + int bouncecount; + int hitsupercontentsmask; + int maxbounce; + int numpixels; + int resolution[3]; + int shootparticles; + int shotparticles; + int photoncount; + int tex[3]; + trace_t cliptrace; + //trace_t cliptrace2; + //trace_t cliptrace3; + unsigned char *pixel; + unsigned char *pixels; + float *highpixel; + float *highpixels; + unsigned int lightindex; + unsigned int range; + unsigned int range1; + unsigned int range2; + unsigned int seed = (unsigned int)(realtime * 1000.0f); + vec3_t shotcolor; + vec3_t baseshotcolor; + vec3_t surfcolor; + vec3_t clipend; + vec3_t clipstart; + vec3_t clipdiff; + vec3_t ispacing; + vec3_t maxs; + vec3_t mins; + vec3_t size; + vec3_t spacing; + vec3_t lightcolor; + vec3_t steppos; + vec3_t stepdelta; + vec3_t cullmins, cullmaxs; + vec_t radius; + vec_t s; + vec_t lightintensity; + vec_t photonscaling; + vec_t photonresidual; + float m[16]; + float texlerp[2][3]; + float splatcolor[32]; + float pixelweight[8]; + float w; + int c[4]; + int pixelindex[8]; + int corner; + int pixelsperband; + int pixelband; + int pixelbands; + int numsteps; + int step; + int x, y, z; + rtlight_t *rtlight; + r_shadow_bouncegrid_settings_t settings; + qboolean enable = r_shadow_bouncegrid.integer != 0 && r_refdef.scene.worldmodel; + qboolean allowdirectionalshading = false; + switch(vid.renderpath) + { + case RENDERPATH_GL20: + allowdirectionalshading = true; + if (!vid.support.ext_texture_3d) + return; + break; + case RENDERPATH_GLES2: + // for performance reasons, do not use directional shading on GLES devices + if (!vid.support.ext_texture_3d) + return; + break; + // these renderpaths do not currently have the code to display the bouncegrid, so disable it on them... + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GLES1: + case RENDERPATH_SOFT: + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: + return; } - if (stenciltest) + + r_shadow_bouncegridintensity = r_shadow_bouncegrid_intensity.value; + + // see if there are really any lights to render... + if (enable && r_shadow_bouncegrid_static.integer) { - qglEnable(GL_STENCIL_TEST);CHECKGLERROR - qglStencilFunc(GL_EQUAL, 128, ~0);CHECKGLERROR + enable = false; + range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked + for (lightindex = 0;lightindex < range;lightindex++) + { + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (!light || !(light->flags & flag)) + continue; + rtlight = &light->rtlight; + // when static, we skip styled lights because they tend to change... + if (rtlight->style > 0) + continue; + VectorScale(rtlight->color, (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale), lightcolor); + if (!VectorLength2(lightcolor)) + continue; + enable = true; + break; + } } - r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING; -} -void R_Shadow_RenderMode_End(void) -{ - CHECKGLERROR + if (!enable) + { + if (r_shadow_bouncegridtexture) + { + R_FreeTexture(r_shadow_bouncegridtexture); + r_shadow_bouncegridtexture = NULL; + } + if (r_shadow_bouncegridpixels) + Mem_Free(r_shadow_bouncegridpixels); + r_shadow_bouncegridpixels = NULL; + if (r_shadow_bouncegridhighpixels) + Mem_Free(r_shadow_bouncegridhighpixels); + r_shadow_bouncegridhighpixels = NULL; + r_shadow_bouncegridnumpixels = 0; + r_shadow_bouncegriddirectional = false; + return; + } + + // build up a complete collection of the desired settings, so that memcmp can be used to compare parameters + memset(&settings, 0, sizeof(settings)); + settings.staticmode = r_shadow_bouncegrid_static.integer != 0; + settings.bounceanglediffuse = r_shadow_bouncegrid_bounceanglediffuse.integer != 0; + settings.directionalshading = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_directionalshading.integer != 0 : r_shadow_bouncegrid_directionalshading.integer != 0) && allowdirectionalshading; + settings.dlightparticlemultiplier = r_shadow_bouncegrid_dlightparticlemultiplier.value; + settings.hitmodels = r_shadow_bouncegrid_hitmodels.integer != 0; + settings.includedirectlighting = r_shadow_bouncegrid_includedirectlighting.integer != 0 || r_shadow_bouncegrid.integer == 2; + settings.lightradiusscale = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_lightradiusscale.value : r_shadow_bouncegrid_lightradiusscale.value); + settings.maxbounce = (r_shadow_bouncegrid_static.integer != 0 ? r_shadow_bouncegrid_static_maxbounce.integer : r_shadow_bouncegrid_maxbounce.integer); + settings.particlebounceintensity = r_shadow_bouncegrid_particlebounceintensity.value; + settings.particleintensity = r_shadow_bouncegrid_particleintensity.value * 16384.0f * (settings.directionalshading ? 4.0f : 1.0f) / (r_shadow_bouncegrid_spacing.value * r_shadow_bouncegrid_spacing.value); + settings.photons = r_shadow_bouncegrid_static.integer ? r_shadow_bouncegrid_static_photons.integer : r_shadow_bouncegrid_photons.integer; + settings.spacing[0] = r_shadow_bouncegrid_spacing.value; + settings.spacing[1] = r_shadow_bouncegrid_spacing.value; + settings.spacing[2] = r_shadow_bouncegrid_spacing.value; + settings.stablerandom = r_shadow_bouncegrid_stablerandom.integer; + + // bound the values for sanity + settings.photons = bound(1, settings.photons, 1048576); + settings.lightradiusscale = bound(0.0001f, settings.lightradiusscale, 1024.0f); + settings.maxbounce = bound(0, settings.maxbounce, 16); + settings.spacing[0] = bound(1, settings.spacing[0], 512); + settings.spacing[1] = bound(1, settings.spacing[1], 512); + settings.spacing[2] = bound(1, settings.spacing[2], 512); + + // get the spacing values + spacing[0] = settings.spacing[0]; + spacing[1] = settings.spacing[1]; + spacing[2] = settings.spacing[2]; + ispacing[0] = 1.0f / spacing[0]; + ispacing[1] = 1.0f / spacing[1]; + ispacing[2] = 1.0f / spacing[2]; + + // calculate texture size enclosing entire world bounds at the spacing + VectorMA(r_refdef.scene.worldmodel->normalmins, -2.0f, spacing, mins); + VectorMA(r_refdef.scene.worldmodel->normalmaxs, 2.0f, spacing, maxs); + VectorSubtract(maxs, mins, size); + // now we can calculate the resolution we want + c[0] = (int)floor(size[0] / spacing[0] + 0.5f); + c[1] = (int)floor(size[1] / spacing[1] + 0.5f); + c[2] = (int)floor(size[2] / spacing[2] + 0.5f); + // figure out the exact texture size (honoring power of 2 if required) + c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d); + c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d); + c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d); + if (vid.support.arb_texture_non_power_of_two) + { + resolution[0] = c[0]; + resolution[1] = c[1]; + resolution[2] = c[2]; + } + else + { + for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ; + for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ; + for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ; + } + size[0] = spacing[0] * resolution[0]; + size[1] = spacing[1] * resolution[1]; + size[2] = spacing[2] * resolution[2]; + + // if dynamic we may or may not want to use the world bounds + // if the dynamic size is smaller than the world bounds, use it instead + if (!settings.staticmode && (r_shadow_bouncegrid_x.integer * r_shadow_bouncegrid_y.integer * r_shadow_bouncegrid_z.integer < resolution[0] * resolution[1] * resolution[2])) + { + // we know the resolution we want + c[0] = r_shadow_bouncegrid_x.integer; + c[1] = r_shadow_bouncegrid_y.integer; + c[2] = r_shadow_bouncegrid_z.integer; + // now we can calculate the texture size (power of 2 if required) + c[0] = bound(4, c[0], (int)vid.maxtexturesize_3d); + c[1] = bound(4, c[1], (int)vid.maxtexturesize_3d); + c[2] = bound(4, c[2], (int)vid.maxtexturesize_3d); + if (vid.support.arb_texture_non_power_of_two) + { + resolution[0] = c[0]; + resolution[1] = c[1]; + resolution[2] = c[2]; + } + else + { + for (resolution[0] = 4;resolution[0] < c[0];resolution[0]*=2) ; + for (resolution[1] = 4;resolution[1] < c[1];resolution[1]*=2) ; + for (resolution[2] = 4;resolution[2] < c[2];resolution[2]*=2) ; + } + size[0] = spacing[0] * resolution[0]; + size[1] = spacing[1] * resolution[1]; + size[2] = spacing[2] * resolution[2]; + // center the rendering on the view + mins[0] = floor(r_refdef.view.origin[0] * ispacing[0] + 0.5f) * spacing[0] - 0.5f * size[0]; + mins[1] = floor(r_refdef.view.origin[1] * ispacing[1] + 0.5f) * spacing[1] - 0.5f * size[1]; + mins[2] = floor(r_refdef.view.origin[2] * ispacing[2] + 0.5f) * spacing[2] - 0.5f * size[2]; + } + + // recalculate the maxs in case the resolution was not satisfactory + VectorAdd(mins, size, maxs); + + // if all the settings seem identical to the previous update, return + if (r_shadow_bouncegridtexture && (settings.staticmode || realtime < r_shadow_bouncegridtime + r_shadow_bouncegrid_updateinterval.value) && !memcmp(&r_shadow_bouncegridsettings, &settings, sizeof(settings))) + return; + + // store the new settings + r_shadow_bouncegridsettings = settings; + + pixelbands = settings.directionalshading ? 8 : 1; + pixelsperband = resolution[0]*resolution[1]*resolution[2]; + numpixels = pixelsperband*pixelbands; + + // we're going to update the bouncegrid, update the matrix... + memset(m, 0, sizeof(m)); + m[0] = 1.0f / size[0]; + m[3] = -mins[0] * m[0]; + m[5] = 1.0f / size[1]; + m[7] = -mins[1] * m[5]; + m[10] = 1.0f / size[2]; + m[11] = -mins[2] * m[10]; + m[15] = 1.0f; + Matrix4x4_FromArrayFloatD3D(&r_shadow_bouncegridmatrix, m); + // reallocate pixels for this update if needed... + if (r_shadow_bouncegridnumpixels != numpixels || !r_shadow_bouncegridpixels || !r_shadow_bouncegridhighpixels) + { + if (r_shadow_bouncegridtexture) + { + R_FreeTexture(r_shadow_bouncegridtexture); + r_shadow_bouncegridtexture = NULL; + } + r_shadow_bouncegridpixels = (unsigned char *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridpixels, numpixels * sizeof(unsigned char[4])); + r_shadow_bouncegridhighpixels = (float *)Mem_Realloc(r_main_mempool, r_shadow_bouncegridhighpixels, numpixels * sizeof(float[4])); + } + r_shadow_bouncegridnumpixels = numpixels; + pixels = r_shadow_bouncegridpixels; + highpixels = r_shadow_bouncegridhighpixels; + x = pixelsperband*4; + for (pixelband = 0;pixelband < pixelbands;pixelband++) + { + if (pixelband == 1) + memset(pixels + pixelband * x, 128, x); + else + memset(pixels + pixelband * x, 0, x); + } + memset(highpixels, 0, numpixels * sizeof(float[4])); + // figure out what we want to interact with + if (settings.hitmodels) + hitsupercontentsmask = SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY;// | SUPERCONTENTS_LIQUIDSMASK; + else + hitsupercontentsmask = SUPERCONTENTS_SOLID;// | SUPERCONTENTS_LIQUIDSMASK; + maxbounce = settings.maxbounce; + // clear variables that produce warnings otherwise + memset(splatcolor, 0, sizeof(splatcolor)); + // iterate world rtlights + range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked + range1 = settings.staticmode ? 0 : r_refdef.scene.numlights; + range2 = range + range1; + photoncount = 0; + for (lightindex = 0;lightindex < range2;lightindex++) + { + if (lightindex < range) + { + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (!light) + continue; + rtlight = &light->rtlight; + VectorClear(rtlight->photoncolor); + rtlight->photons = 0; + if (!(light->flags & flag)) + continue; + if (settings.staticmode) + { + // when static, we skip styled lights because they tend to change... + if (rtlight->style > 0 && r_shadow_bouncegrid.integer != 2) + continue; + } + } + else + { + rtlight = r_refdef.scene.lights[lightindex - range]; + VectorClear(rtlight->photoncolor); + rtlight->photons = 0; + } + // draw only visible lights (major speedup) + radius = rtlight->radius * settings.lightradiusscale; + cullmins[0] = rtlight->shadoworigin[0] - radius; + cullmins[1] = rtlight->shadoworigin[1] - radius; + cullmins[2] = rtlight->shadoworigin[2] - radius; + cullmaxs[0] = rtlight->shadoworigin[0] + radius; + cullmaxs[1] = rtlight->shadoworigin[1] + radius; + cullmaxs[2] = rtlight->shadoworigin[2] + radius; + if (R_CullBox(cullmins, cullmaxs)) + continue; + if (r_refdef.scene.worldmodel + && r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs + && !r_refdef.scene.worldmodel->brush.BoxTouchingVisibleLeafs(r_refdef.scene.worldmodel, r_refdef.viewcache.world_leafvisible, cullmins, cullmaxs)) + continue; + w = r_shadow_lightintensityscale.value * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale); + if (w * VectorLength2(rtlight->color) == 0.0f) + continue; + w *= (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1); + VectorScale(rtlight->color, w, rtlight->photoncolor); + //if (!VectorLength2(rtlight->photoncolor)) + // continue; + // shoot particles from this light + // use a calculation for the number of particles that will not + // vary with lightstyle, otherwise we get randomized particle + // distribution, the seeded random is only consistent for a + // consistent number of particles on this light... + s = rtlight->radius; + lightintensity = VectorLength(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale); + if (lightindex >= range) + lightintensity *= settings.dlightparticlemultiplier; + rtlight->photons = max(0.0f, lightintensity * s * s); + photoncount += rtlight->photons; + } + photonscaling = (float)settings.photons / max(1, photoncount); + photonresidual = 0.0f; + for (lightindex = 0;lightindex < range2;lightindex++) + { + if (lightindex < range) + { + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (!light) + continue; + rtlight = &light->rtlight; + } + else + rtlight = r_refdef.scene.lights[lightindex - range]; + // skip a light with no photons + if (rtlight->photons == 0.0f) + continue; + // skip a light with no photon color) + if (VectorLength2(rtlight->photoncolor) == 0.0f) + continue; + photonresidual += rtlight->photons * photonscaling; + shootparticles = (int)bound(0, photonresidual, MAXBOUNCEGRIDPARTICLESPERLIGHT); + if (!shootparticles) + continue; + photonresidual -= shootparticles; + radius = rtlight->radius * settings.lightradiusscale; + s = settings.particleintensity / shootparticles; + VectorScale(rtlight->photoncolor, s, baseshotcolor); + r_refdef.stats[r_stat_bouncegrid_lights]++; + r_refdef.stats[r_stat_bouncegrid_particles] += shootparticles; + for (shotparticles = 0;shotparticles < shootparticles;shotparticles++) + { + if (settings.stablerandom > 0) + seed = lightindex * 11937 + shotparticles; + VectorCopy(baseshotcolor, shotcolor); + VectorCopy(rtlight->shadoworigin, clipstart); + if (settings.stablerandom < 0) + VectorRandom(clipend); + else + VectorCheeseRandom(clipend); + VectorMA(clipstart, radius, clipend, clipend); + for (bouncecount = 0;;bouncecount++) + { + r_refdef.stats[r_stat_bouncegrid_traces]++; + //r_refdef.scene.worldmodel->TraceLineAgainstSurfaces(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace, clipstart, clipend, hitsupercontentsmask); + //r_refdef.scene.worldmodel->TraceLine(r_refdef.scene.worldmodel, NULL, NULL, &cliptrace2, clipstart, clipend, hitsupercontentsmask); + if (settings.staticmode) + { + // static mode fires a LOT of rays but none of them are identical, so they are not cached + cliptrace = CL_TraceLine(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), NULL, hitsupercontentsmask, true, false, NULL, true, true); + } + else + { + // dynamic mode fires many rays and most will match the cache from the previous frame + cliptrace = CL_Cache_TraceLineSurfaces(clipstart, clipend, settings.staticmode ? MOVE_WORLDONLY : (settings.hitmodels ? MOVE_HITMODEL : MOVE_NOMONSTERS), hitsupercontentsmask); + } + if (bouncecount > 0 || settings.includedirectlighting) + { + // calculate second order spherical harmonics values (average, slopeX, slopeY, slopeZ) + // accumulate average shotcolor + w = VectorLength(shotcolor); + splatcolor[ 0] = shotcolor[0]; + splatcolor[ 1] = shotcolor[1]; + splatcolor[ 2] = shotcolor[2]; + splatcolor[ 3] = 0.0f; + if (pixelbands > 1) + { + VectorSubtract(clipstart, cliptrace.endpos, clipdiff); + VectorNormalize(clipdiff); + // store bentnormal in case the shader has a use for it + splatcolor[ 4] = clipdiff[0] * w; + splatcolor[ 5] = clipdiff[1] * w; + splatcolor[ 6] = clipdiff[2] * w; + splatcolor[ 7] = w; + // accumulate directional contributions (+X, +Y, +Z, -X, -Y, -Z) + splatcolor[ 8] = shotcolor[0] * max(0.0f, clipdiff[0]); + splatcolor[ 9] = shotcolor[0] * max(0.0f, clipdiff[1]); + splatcolor[10] = shotcolor[0] * max(0.0f, clipdiff[2]); + splatcolor[11] = 0.0f; + splatcolor[12] = shotcolor[1] * max(0.0f, clipdiff[0]); + splatcolor[13] = shotcolor[1] * max(0.0f, clipdiff[1]); + splatcolor[14] = shotcolor[1] * max(0.0f, clipdiff[2]); + splatcolor[15] = 0.0f; + splatcolor[16] = shotcolor[2] * max(0.0f, clipdiff[0]); + splatcolor[17] = shotcolor[2] * max(0.0f, clipdiff[1]); + splatcolor[18] = shotcolor[2] * max(0.0f, clipdiff[2]); + splatcolor[19] = 0.0f; + splatcolor[20] = shotcolor[0] * max(0.0f, -clipdiff[0]); + splatcolor[21] = shotcolor[0] * max(0.0f, -clipdiff[1]); + splatcolor[22] = shotcolor[0] * max(0.0f, -clipdiff[2]); + splatcolor[23] = 0.0f; + splatcolor[24] = shotcolor[1] * max(0.0f, -clipdiff[0]); + splatcolor[25] = shotcolor[1] * max(0.0f, -clipdiff[1]); + splatcolor[26] = shotcolor[1] * max(0.0f, -clipdiff[2]); + splatcolor[27] = 0.0f; + splatcolor[28] = shotcolor[2] * max(0.0f, -clipdiff[0]); + splatcolor[29] = shotcolor[2] * max(0.0f, -clipdiff[1]); + splatcolor[30] = shotcolor[2] * max(0.0f, -clipdiff[2]); + splatcolor[31] = 0.0f; + } + // calculate the number of steps we need to traverse this distance + VectorSubtract(cliptrace.endpos, clipstart, stepdelta); + numsteps = (int)(VectorLength(stepdelta) * ispacing[0]); + numsteps = bound(1, numsteps, 1024); + w = 1.0f / numsteps; + VectorScale(stepdelta, w, stepdelta); + VectorMA(clipstart, 0.5f, stepdelta, steppos); + for (step = 0;step < numsteps;step++) + { + r_refdef.stats[r_stat_bouncegrid_splats]++; + // figure out which texture pixel this is in + texlerp[1][0] = ((steppos[0] - mins[0]) * ispacing[0]) - 0.5f; + texlerp[1][1] = ((steppos[1] - mins[1]) * ispacing[1]) - 0.5f; + texlerp[1][2] = ((steppos[2] - mins[2]) * ispacing[2]) - 0.5f; + tex[0] = (int)floor(texlerp[1][0]); + tex[1] = (int)floor(texlerp[1][1]); + tex[2] = (int)floor(texlerp[1][2]); + if (tex[0] >= 1 && tex[1] >= 1 && tex[2] >= 1 && tex[0] < resolution[0] - 2 && tex[1] < resolution[1] - 2 && tex[2] < resolution[2] - 2) + { + // it is within bounds... do the real work now + // calculate the lerp factors + texlerp[1][0] -= tex[0]; + texlerp[1][1] -= tex[1]; + texlerp[1][2] -= tex[2]; + texlerp[0][0] = 1.0f - texlerp[1][0]; + texlerp[0][1] = 1.0f - texlerp[1][1]; + texlerp[0][2] = 1.0f - texlerp[1][2]; + // calculate individual pixel indexes and weights + pixelindex[0] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[0] = (texlerp[0][0]*texlerp[0][1]*texlerp[0][2]); + pixelindex[1] = (((tex[2] )*resolution[1]+tex[1] )*resolution[0]+tex[0]+1);pixelweight[1] = (texlerp[1][0]*texlerp[0][1]*texlerp[0][2]); + pixelindex[2] = (((tex[2] )*resolution[1]+tex[1]+1)*resolution[0]+tex[0] );pixelweight[2] = (texlerp[0][0]*texlerp[1][1]*texlerp[0][2]); + pixelindex[3] = (((tex[2] )*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[3] = (texlerp[1][0]*texlerp[1][1]*texlerp[0][2]); + pixelindex[4] = (((tex[2]+1)*resolution[1]+tex[1] )*resolution[0]+tex[0] );pixelweight[4] = (texlerp[0][0]*texlerp[0][1]*texlerp[1][2]); + pixelindex[5] = (((tex[2]+1)*resolution[1]+tex[1] )*resolution[0]+tex[0]+1);pixelweight[5] = (texlerp[1][0]*texlerp[0][1]*texlerp[1][2]); + pixelindex[6] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0] );pixelweight[6] = (texlerp[0][0]*texlerp[1][1]*texlerp[1][2]); + pixelindex[7] = (((tex[2]+1)*resolution[1]+tex[1]+1)*resolution[0]+tex[0]+1);pixelweight[7] = (texlerp[1][0]*texlerp[1][1]*texlerp[1][2]); + // update the 8 pixels... + for (pixelband = 0;pixelband < pixelbands;pixelband++) + { + for (corner = 0;corner < 8;corner++) + { + // calculate address for pixel + w = pixelweight[corner]; + pixel = pixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4; + highpixel = highpixels + 4 * pixelindex[corner] + pixelband * pixelsperband * 4; + // add to the high precision pixel color + highpixel[0] += (splatcolor[pixelband*4+0]*w); + highpixel[1] += (splatcolor[pixelband*4+1]*w); + highpixel[2] += (splatcolor[pixelband*4+2]*w); + highpixel[3] += (splatcolor[pixelband*4+3]*w); + // flag the low precision pixel as needing to be updated + pixel[3] = 255; + // advance to next band of coefficients + //pixel += pixelsperband*4; + //highpixel += pixelsperband*4; + } + } + } + VectorAdd(steppos, stepdelta, steppos); + } + } + if (cliptrace.fraction >= 1.0f) + break; + r_refdef.stats[r_stat_bouncegrid_hits]++; + if (bouncecount >= maxbounce) + break; + // scale down shot color by bounce intensity and texture color (or 50% if no texture reported) + // also clamp the resulting color to never add energy, even if the user requests extreme values + if (cliptrace.hittexture && cliptrace.hittexture->currentskinframe) + VectorCopy(cliptrace.hittexture->currentskinframe->avgcolor, surfcolor); + else + VectorSet(surfcolor, 0.5f, 0.5f, 0.5f); + VectorScale(surfcolor, settings.particlebounceintensity, surfcolor); + surfcolor[0] = min(surfcolor[0], 1.0f); + surfcolor[1] = min(surfcolor[1], 1.0f); + surfcolor[2] = min(surfcolor[2], 1.0f); + VectorMultiply(shotcolor, surfcolor, shotcolor); + if (VectorLength2(baseshotcolor) == 0.0f) + break; + r_refdef.stats[r_stat_bouncegrid_bounces]++; + if (settings.bounceanglediffuse) + { + // random direction, primarily along plane normal + s = VectorDistance(cliptrace.endpos, clipend); + if (settings.stablerandom < 0) + VectorRandom(clipend); + else + VectorCheeseRandom(clipend); + VectorMA(cliptrace.plane.normal, 0.95f, clipend, clipend); + VectorNormalize(clipend); + VectorScale(clipend, s, clipend); + } + else + { + // reflect the remaining portion of the line across plane normal + VectorSubtract(clipend, cliptrace.endpos, clipdiff); + VectorReflect(clipdiff, 1.0, cliptrace.plane.normal, clipend); + } + // calculate the new line start and end + VectorCopy(cliptrace.endpos, clipstart); + VectorAdd(clipstart, clipend, clipend); + } + } + } + // generate pixels array from highpixels array + // skip first and last columns, rows, and layers as these are blank + // the pixel[3] value was written above, so we can use it to detect only pixels that need to be calculated + for (pixelband = 0;pixelband < pixelbands;pixelband++) + { + for (z = 1;z < resolution[2]-1;z++) + { + for (y = 1;y < resolution[1]-1;y++) + { + for (x = 1, pixelindex[0] = ((pixelband*resolution[2]+z)*resolution[1]+y)*resolution[0]+x, pixel = pixels + 4*pixelindex[0], highpixel = highpixels + 4*pixelindex[0];x < resolution[0]-1;x++, pixel += 4, highpixel += 4) + { + // only convert pixels that were hit by photons + if (pixel[3] == 255) + { + // normalize the bentnormal... + if (pixelband == 1) + { + VectorNormalize(highpixel); + c[0] = (int)(highpixel[0]*128.0f+128.0f); + c[1] = (int)(highpixel[1]*128.0f+128.0f); + c[2] = (int)(highpixel[2]*128.0f+128.0f); + c[3] = (int)(highpixel[3]*128.0f+128.0f); + } + else + { + c[0] = (int)(highpixel[0]*256.0f); + c[1] = (int)(highpixel[1]*256.0f); + c[2] = (int)(highpixel[2]*256.0f); + c[3] = (int)(highpixel[3]*256.0f); + } + pixel[2] = (unsigned char)bound(0, c[0], 255); + pixel[1] = (unsigned char)bound(0, c[1], 255); + pixel[0] = (unsigned char)bound(0, c[2], 255); + pixel[3] = (unsigned char)bound(0, c[3], 255); + } + } + } + } + } + if (r_shadow_bouncegridtexture && r_shadow_bouncegridresolution[0] == resolution[0] && r_shadow_bouncegridresolution[1] == resolution[1] && r_shadow_bouncegridresolution[2] == resolution[2] && r_shadow_bouncegriddirectional == settings.directionalshading) + R_UpdateTexture(r_shadow_bouncegridtexture, pixels, 0, 0, 0, resolution[0], resolution[1], resolution[2]*pixelbands); + else + { + VectorCopy(resolution, r_shadow_bouncegridresolution); + r_shadow_bouncegriddirectional = settings.directionalshading; + if (r_shadow_bouncegridtexture) + R_FreeTexture(r_shadow_bouncegridtexture); + r_shadow_bouncegridtexture = R_LoadTexture3D(r_shadow_texturepool, "bouncegrid", resolution[0], resolution[1], resolution[2]*pixelbands, pixels, TEXTYPE_BGRA, TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCELINEAR, 0, NULL); + } + r_shadow_bouncegridtime = realtime; +} + +void R_Shadow_RenderMode_VisibleShadowVolumes(void) +{ + R_Shadow_RenderMode_Reset(); + GL_BlendFunc(GL_ONE, GL_ONE); + GL_DepthRange(0, 1); + GL_DepthTest(r_showshadowvolumes.integer < 2); + GL_Color(0.0, 0.0125 * r_refdef.view.colorscale, 0.1 * r_refdef.view.colorscale, 1); + GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);CHECKGLERROR + GL_CullFace(GL_NONE); + r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLEVOLUMES; +} + +void R_Shadow_RenderMode_VisibleLighting(qboolean stenciltest, qboolean transparent) +{ + R_Shadow_RenderMode_Reset(); + GL_BlendFunc(GL_ONE, GL_ONE); + GL_DepthRange(0, 1); + GL_DepthTest(r_showlighting.integer < 2); + GL_Color(0.1 * r_refdef.view.colorscale, 0.0125 * r_refdef.view.colorscale, 0, 1); + if (!transparent) + GL_DepthFunc(GL_EQUAL); + R_SetStencil(stenciltest, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_EQUAL, 128, 255); + r_shadow_rendermode = R_SHADOW_RENDERMODE_VISIBLELIGHTING; +} + +void R_Shadow_RenderMode_End(void) +{ R_Shadow_RenderMode_Reset(); R_Shadow_RenderMode_ActiveLight(NULL); GL_DepthMask(true); @@ -2324,130 +2977,38 @@ int bboxedges[12][2] = qboolean R_Shadow_ScissorForBBox(const float *mins, const float *maxs) { - int i, ix1, iy1, ix2, iy2; - float x1, y1, x2, y2; - vec4_t v, v2; - float vertex[20][3]; - int j, k; - vec4_t plane4f; - int numvertices; - float corner[8][4]; - float dist[8]; - int sign[8]; - float f; - - r_shadow_lightscissor[0] = r_refdef.view.viewport.x; - r_shadow_lightscissor[1] = r_refdef.view.viewport.y; - r_shadow_lightscissor[2] = r_refdef.view.viewport.width; - r_shadow_lightscissor[3] = r_refdef.view.viewport.height; - - if (!r_shadow_scissor.integer) - return false; - - // if view is inside the light box, just say yes it's visible - if (BoxesOverlap(r_refdef.view.origin, r_refdef.view.origin, mins, maxs)) - return false; - - x1 = y1 = x2 = y2 = 0; - - // transform all corners that are infront of the nearclip plane - VectorNegate(r_refdef.view.frustum[4].normal, plane4f); - plane4f[3] = r_refdef.view.frustum[4].dist; - numvertices = 0; - for (i = 0;i < 8;i++) + if (!r_shadow_scissor.integer || r_shadow_usingdeferredprepass || r_trippy.integer) { - Vector4Set(corner[i], (i & 1) ? maxs[0] : mins[0], (i & 2) ? maxs[1] : mins[1], (i & 4) ? maxs[2] : mins[2], 1); - dist[i] = DotProduct4(corner[i], plane4f); - sign[i] = dist[i] > 0; - if (!sign[i]) - { - VectorCopy(corner[i], vertex[numvertices]); - numvertices++; - } - } - // if some points are behind the nearclip, add clipped edge points to make - // sure that the scissor boundary is complete - if (numvertices > 0 && numvertices < 8) - { - // add clipped edge points - for (i = 0;i < 12;i++) - { - j = bboxedges[i][0]; - k = bboxedges[i][1]; - if (sign[j] != sign[k]) - { - f = dist[j] / (dist[j] - dist[k]); - VectorLerp(corner[j], f, corner[k], vertex[numvertices]); - numvertices++; - } - } - } - - // if we have no points to check, the light is behind the view plane - if (!numvertices) - return true; - - // if we have some points to transform, check what screen area is covered - x1 = y1 = x2 = y2 = 0; - v[3] = 1.0f; - //Con_Printf("%i vertices to transform...\n", numvertices); - for (i = 0;i < numvertices;i++) - { - VectorCopy(vertex[i], v); - R_Viewport_TransformToScreen(&r_refdef.view.viewport, v, v2); - //Con_Printf("%.3f %.3f %.3f %.3f transformed to %.3f %.3f %.3f %.3f\n", v[0], v[1], v[2], v[3], v2[0], v2[1], v2[2], v2[3]); - if (i) - { - if (x1 > v2[0]) x1 = v2[0]; - if (x2 < v2[0]) x2 = v2[0]; - if (y1 > v2[1]) y1 = v2[1]; - if (y2 < v2[1]) y2 = v2[1]; - } - else - { - x1 = x2 = v2[0]; - y1 = y2 = v2[1]; - } + r_shadow_lightscissor[0] = r_refdef.view.viewport.x; + r_shadow_lightscissor[1] = r_refdef.view.viewport.y; + r_shadow_lightscissor[2] = r_refdef.view.viewport.width; + r_shadow_lightscissor[3] = r_refdef.view.viewport.height; + return false; } - - // now convert the scissor rectangle to integer screen coordinates - ix1 = (int)(x1 - 1.0f); - iy1 = vid.height - (int)(y2 - 1.0f); - ix2 = (int)(x2 + 1.0f); - iy2 = vid.height - (int)(y1 + 1.0f); - //Con_Printf("%f %f %f %f\n", x1, y1, x2, y2); - - // clamp it to the screen - if (ix1 < r_refdef.view.viewport.x) ix1 = r_refdef.view.viewport.x; - if (iy1 < r_refdef.view.viewport.y) iy1 = r_refdef.view.viewport.y; - if (ix2 > r_refdef.view.viewport.x + r_refdef.view.viewport.width) ix2 = r_refdef.view.viewport.x + r_refdef.view.viewport.width; - if (iy2 > r_refdef.view.viewport.y + r_refdef.view.viewport.height) iy2 = r_refdef.view.viewport.y + r_refdef.view.viewport.height; - - // if it is inside out, it's not visible - if (ix2 <= ix1 || iy2 <= iy1) - return true; - - // the light area is visible, set up the scissor rectangle - r_shadow_lightscissor[0] = ix1; - r_shadow_lightscissor[1] = iy1; - r_shadow_lightscissor[2] = ix2 - ix1; - r_shadow_lightscissor[3] = iy2 - iy1; - - r_refdef.stats.lights_scissored++; + if(R_ScissorForBBox(mins, maxs, r_shadow_lightscissor)) + return true; // invisible + if(r_shadow_lightscissor[0] != r_refdef.view.viewport.x + || r_shadow_lightscissor[1] != r_refdef.view.viewport.y + || r_shadow_lightscissor[2] != r_refdef.view.viewport.width + || r_shadow_lightscissor[3] != r_refdef.view.viewport.height) + r_refdef.stats[r_stat_lights_scissored]++; return false; } -static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, int numtriangles, const int *element3i, const float *diffusecolor, const float *ambientcolor) +static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int numverts, const float *diffusecolor, const float *ambientcolor) { - const float *vertex3f = rsurface.vertex3f + 3 * firstvertex; - const float *normal3f = rsurface.normal3f + 3 * firstvertex; - float *color4f = rsurface.array_color4f + 4 * firstvertex; + int i; + const float *vertex3f; + const float *normal3f; + float *color4f; float dist, dot, distintensity, shadeintensity, v[3], n[3]; - if (r_textureunits.integer >= 3) + switch (r_shadow_rendermode) { + case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN: + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN: if (VectorLength2(diffusecolor) > 0) { - for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4) { Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); Matrix4x4_Transform3x3(&rsurface.entitytolight, normal3f, n); @@ -2469,7 +3030,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu } else { - for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4) { VectorCopy(ambientcolor, color4f); if (r_refdef.fogenabled) @@ -2477,17 +3038,16 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu float f; Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); f = RSurf_FogVertex(vertex3f); - VectorScale(color4f, f, color4f); + VectorScale(color4f + 4*i, f, color4f); } color4f[3] = 1; } } - } - else if (r_textureunits.integer >= 2) - { + break; + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN: if (VectorLength2(diffusecolor) > 0) { - for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4) { Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)])) @@ -2520,7 +3080,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu } else { - for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4) { Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); if ((dist = fabs(v[2])) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)])) @@ -2540,12 +3100,11 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu color4f[3] = 1; } } - } - else - { + break; + case R_SHADOW_RENDERMODE_LIGHT_VERTEX: if (VectorLength2(diffusecolor) > 0) { - for (;numverts > 0;numverts--, vertex3f += 3, normal3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, normal3f = rsurface.batchnormal3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, normal3f += 3, color4f += 4) { Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)])) @@ -2579,7 +3138,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu } else { - for (;numverts > 0;numverts--, vertex3f += 3, color4f += 4) + for (i = 0, vertex3f = rsurface.batchvertex3f + 3*firstvertex, color4f = rsurface.passcolor4f + 4 * firstvertex;i < numverts;i++, vertex3f += 3, color4f += 4) { Matrix4x4_Transform(&rsurface.entitytolight, vertex3f, v); if ((dist = VectorLength(v)) < 1 && (distintensity = r_shadow_attentable[(int)(dist * ATTENTABLESIZE)])) @@ -2600,695 +3159,25 @@ static void R_Shadow_RenderLighting_Light_Vertex_Shading(int firstvertex, int nu color4f[3] = 1; } } + break; + default: + break; } } -// TODO: use glTexGen instead of feeding vertices to texcoordpointer? - -static void R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i) -{ - int i; - float *out3f = rsurface.array_texcoord3f + 3 * firstvertex; - const float *vertex3f = rsurface.vertex3f + 3 * firstvertex; - const float *svector3f = rsurface.svector3f + 3 * firstvertex; - const float *tvector3f = rsurface.tvector3f + 3 * firstvertex; - const float *normal3f = rsurface.normal3f + 3 * firstvertex; - float lightdir[3]; - for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3) - { - VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir); - // the cubemap normalizes this for us - out3f[0] = DotProduct(svector3f, lightdir); - out3f[1] = DotProduct(tvector3f, lightdir); - out3f[2] = DotProduct(normal3f, lightdir); - } -} - -static void R_Shadow_GenTexCoords_Specular_NormalCubeMap(int firstvertex, int numvertices, int numtriangles, const int *element3i) -{ - int i; - float *out3f = rsurface.array_texcoord3f + 3 * firstvertex; - const float *vertex3f = rsurface.vertex3f + 3 * firstvertex; - const float *svector3f = rsurface.svector3f + 3 * firstvertex; - const float *tvector3f = rsurface.tvector3f + 3 * firstvertex; - const float *normal3f = rsurface.normal3f + 3 * firstvertex; - float lightdir[3], eyedir[3], halfdir[3]; - for (i = 0;i < numvertices;i++, vertex3f += 3, svector3f += 3, tvector3f += 3, normal3f += 3, out3f += 3) - { - VectorSubtract(rsurface.entitylightorigin, vertex3f, lightdir); - VectorNormalize(lightdir); - VectorSubtract(rsurface.localvieworigin, vertex3f, eyedir); - VectorNormalize(eyedir); - VectorAdd(lightdir, eyedir, halfdir); - // the cubemap normalizes this for us - out3f[0] = DotProduct(svector3f, halfdir); - out3f[1] = DotProduct(tvector3f, halfdir); - out3f[2] = DotProduct(normal3f, halfdir); - } -} - -static void R_Shadow_RenderLighting_VisibleLighting(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt) +static void R_Shadow_RenderLighting_VisibleLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist) { // used to display how many times a surface is lit for level design purposes - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); + RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist); + R_Mesh_PrepareVertices_Generic_Arrays(rsurface.batchnumvertices, rsurface.batchvertex3f, NULL, NULL); + RSurf_DrawBatch(); } -static void R_Shadow_RenderLighting_Light_GLSL(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt) +static void R_Shadow_RenderLighting_Light_GLSL(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale, float specularscale) { // ARB2 GLSL shader path (GFFX5200, Radeon 9500) - R_SetupSurfaceShader(lightcolorbase, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT); - if ((rsurface.texture->currentmaterialflags & MATERIALFLAG_VERTEXTEXTUREBLEND)) - R_Mesh_ColorPointer(rsurface.modellightmapcolor4f, rsurface.modellightmapcolor4f_bufferobject, rsurface.modellightmapcolor4f_bufferoffset); - else - R_Mesh_ColorPointer(NULL, 0, 0); - R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix); - R_Mesh_TexMatrix(1, &rsurface.texture->currentbackgroundtexmatrix); - R_Mesh_TexBind(GL20TU_NORMAL, R_GetTexture(rsurface.texture->currentskinframe->nmap)); - R_Mesh_TexBind(GL20TU_COLOR, R_GetTexture(rsurface.texture->basetexture)); - R_Mesh_TexBind(GL20TU_GLOSS, R_GetTexture(rsurface.texture->glosstexture)); - if (rsurface.texture->backgroundcurrentskinframe) - { - R_Mesh_TexBind(GL20TU_SECONDARY_NORMAL, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->nmap)); - R_Mesh_TexBind(GL20TU_SECONDARY_COLOR, R_GetTexture(rsurface.texture->backgroundbasetexture)); - R_Mesh_TexBind(GL20TU_SECONDARY_GLOSS, R_GetTexture(rsurface.texture->backgroundglosstexture)); - R_Mesh_TexBind(GL20TU_SECONDARY_GLOW, R_GetTexture(rsurface.texture->backgroundcurrentskinframe->glow)); - } - //R_Mesh_TexBindCubeMap(GL20TU_CUBE, R_GetTexture(rsurface.rtlight->currentcubemap)); - R_Mesh_TexBind(GL20TU_FOGMASK, R_GetTexture(r_texture_fogattenuation)); - if(rsurface.texture->colormapping) - { - R_Mesh_TexBind(GL20TU_PANTS, R_GetTexture(rsurface.texture->currentskinframe->pants)); - R_Mesh_TexBind(GL20TU_SHIRT, R_GetTexture(rsurface.texture->currentskinframe->shirt)); - } - R_Mesh_TexBind(GL20TU_ATTENUATION, R_GetTexture(r_shadow_attenuationgradienttexture)); - R_Mesh_TexCoordPointer(0, 2, rsurface.texcoordtexture2f, rsurface.texcoordtexture2f_bufferobject, rsurface.texcoordtexture2f_bufferoffset); - R_Mesh_TexCoordPointer(1, 3, rsurface.svector3f, rsurface.svector3f_bufferobject, rsurface.svector3f_bufferoffset); - R_Mesh_TexCoordPointer(2, 3, rsurface.tvector3f, rsurface.tvector3f_bufferobject, rsurface.tvector3f_bufferoffset); - R_Mesh_TexCoordPointer(3, 3, rsurface.normal3f, rsurface.normal3f_bufferobject, rsurface.normal3f_bufferoffset); - if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) - { - qglDepthFunc(GL_EQUAL);CHECKGLERROR - } - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - if (rsurface.texture->currentmaterialflags & MATERIALFLAG_ALPHATEST) - { - qglDepthFunc(GL_LEQUAL);CHECKGLERROR - } -} - -static void R_Shadow_RenderLighting_Light_Dot3_Finalize(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, float r, float g, float b) -{ - // shared final code for all the dot3 layers - int renders; - GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 0); - for (renders = 0;renders < 64 && (r > 0 || g > 0 || b > 0);renders++, r--, g--, b--) - { - GL_Color(bound(0, r, 1), bound(0, g, 1), bound(0, b, 1), 1); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - } -} - -static void R_Shadow_RenderLighting_Light_Dot3_AmbientPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, float colorscale) -{ - rmeshstate_t m; - // colorscale accounts for how much we multiply the brightness - // during combine. - // - // mult is how many times the final pass of the lighting will be - // performed to get more brightness than otherwise possible. - // - // Limit mult to 64 for sanity sake. - GL_Color(1,1,1,1); - if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap != r_texture_whitecube && r_textureunits.integer >= 4) - { - // 3 3D combine path (Geforce3, Radeon 8500) - memset(&m, 0, sizeof(m)); - m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(basetexture); - m.pointer_texcoord[1] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[1] = rsurface.texture->currenttexmatrix; - m.texcubemap[2] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[2] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset; - m.texmatrix[2] = rsurface.entitytolight; - GL_BlendFunc(GL_ONE, GL_ONE); - } - else if (r_shadow_texture3d.integer && rsurface.rtlight->currentcubemap == r_texture_whitecube && r_textureunits.integer >= 2) - { - // 2 3D combine path (Geforce3, original Radeon) - memset(&m, 0, sizeof(m)); - m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(basetexture); - m.pointer_texcoord[1] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[1] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[1] = rsurface.texture->currenttexmatrix; - GL_BlendFunc(GL_ONE, GL_ONE); - } - else if (r_textureunits.integer >= 4 && rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - // 4 2D combine path (Geforce3, Radeon 8500) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationz; - m.tex[2] = R_GetTexture(basetexture); - m.pointer_texcoord[2] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[2] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[3] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[3] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset; - m.texmatrix[3] = rsurface.entitytolight; - } - GL_BlendFunc(GL_ONE, GL_ONE); - } - else if (r_textureunits.integer >= 3 && rsurface.rtlight->currentcubemap == r_texture_whitecube) - { - // 3 2D combine path (Geforce3, original Radeon) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationz; - m.tex[2] = R_GetTexture(basetexture); - m.pointer_texcoord[2] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[2] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[2] = rsurface.texture->currenttexmatrix; - GL_BlendFunc(GL_ONE, GL_ONE); - } - else - { - // 2/2/2 2D combine path (any dot3 card) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationz; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - // this final code is shared - R_Mesh_TextureState(&m); - R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale); -} - -static void R_Shadow_RenderLighting_Light_Dot3_DiffusePass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *basetexture, rtexture_t *normalmaptexture, float colorscale) -{ - rmeshstate_t m; - // colorscale accounts for how much we multiply the brightness - // during combine. - // - // mult is how many times the final pass of the lighting will be - // performed to get more brightness than otherwise possible. - // - // Limit mult to 64 for sanity sake. - GL_Color(1,1,1,1); - // generate normalization cubemap texcoords - R_Shadow_GenTexCoords_Diffuse_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i); - if (r_shadow_texture3d.integer && r_textureunits.integer >= 4) - { - // 3/2 3D combine path (Geforce3, Radeon 8500) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.texcombinergb[0] = GL_REPLACE; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - m.tex3d[2] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[2] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset; - m.texmatrix[2] = rsurface.entitytoattenuationxyz; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - // 1/2/2 3D combine path (original Radeon) - memset(&m, 0, sizeof(m)); - m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.texcombinergb[0] = GL_REPLACE; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_BlendFunc(GL_DST_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube) - { - // 2/2 3D combine path (original Radeon) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.texcombinergb[0] = GL_REPLACE; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationxyz; - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else if (r_textureunits.integer >= 4) - { - // 4/2 2D combine path (Geforce3, Radeon 8500) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.texcombinergb[0] = GL_REPLACE; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[2] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset; - m.texmatrix[2] = rsurface.entitytoattenuationxyz; - m.tex[3] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[3] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[3] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[3] = rsurface.vertex3f_bufferoffset; - m.texmatrix[3] = rsurface.entitytoattenuationz; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else - { - // 2/2/2 2D combine path (any dot3 card) - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationz; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - GL_BlendFunc(GL_ONE, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.texcombinergb[0] = GL_REPLACE; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_BlendFunc(GL_DST_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - // this final code is shared - R_Mesh_TextureState(&m); - R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale); -} - -static void R_Shadow_RenderLighting_Light_Dot3_SpecularPass(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, rtexture_t *glosstexture, rtexture_t *normalmaptexture, float colorscale) -{ - float glossexponent; - rmeshstate_t m; - // FIXME: detect blendsquare! - //if (!gl_support_blendsquare) - // return; - GL_Color(1,1,1,1); - // generate normalization cubemap texcoords - R_Shadow_GenTexCoords_Specular_NormalCubeMap(firstvertex, numvertices, numtriangles, element3i); - if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - // 2/0/0/1/2 3D combine blendsquare path - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - // this squares the result - GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second and third pass - R_Mesh_ResetTextureState(); - // square alpha in framebuffer a few times to make it shiny - GL_BlendFunc(GL_ZERO, GL_DST_ALPHA); - for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2) - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // fourth pass - memset(&m, 0, sizeof(m)); - m.tex3d[0] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - R_Mesh_TextureState(&m); - GL_BlendFunc(GL_DST_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // fifth pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(glosstexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else if (r_shadow_texture3d.integer && r_textureunits.integer >= 2 && rsurface.rtlight->currentcubemap == r_texture_whitecube /* && gl_support_blendsquare*/) // FIXME: detect blendsquare! - { - // 2/0/0/2 3D combine blendsquare path - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - // this squares the result - GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second and third pass - R_Mesh_ResetTextureState(); - // square alpha in framebuffer a few times to make it shiny - GL_BlendFunc(GL_ZERO, GL_DST_ALPHA); - for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2) - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // fourth pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(glosstexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.tex3d[1] = R_GetTexture(r_shadow_attenuation3dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationxyz; - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - else - { - // 2/0/0/2/2 2D combine blendsquare path - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(normalmaptexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.texcubemap[1] = R_GetTexture(r_texture_normalizationcube); - m.texcombinergb[1] = GL_DOT3_RGBA_ARB; - m.pointer_texcoord3f[1] = rsurface.array_texcoord3f; - m.pointer_texcoord_bufferobject[1] = 0; - m.pointer_texcoord_bufferoffset[1] = 0; - R_Mesh_TextureState(&m); - GL_ColorMask(0,0,0,1); - // this squares the result - GL_BlendFunc(GL_SRC_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // second and third pass - R_Mesh_ResetTextureState(); - // square alpha in framebuffer a few times to make it shiny - GL_BlendFunc(GL_ZERO, GL_DST_ALPHA); - for (glossexponent = 2;glossexponent * 2 <= r_shadow_glossexponent.value;glossexponent *= 2) - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // fourth pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[0] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[0] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.vertex3f_bufferoffset; - m.texmatrix[0] = rsurface.entitytoattenuationxyz; - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytoattenuationz; - R_Mesh_TextureState(&m); - GL_BlendFunc(GL_DST_ALPHA, GL_ZERO); - R_Mesh_Draw(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject); - - // fifth pass - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(glosstexture); - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - if (rsurface.rtlight->currentcubemap != r_texture_whitecube) - { - m.texcubemap[1] = R_GetTexture(rsurface.rtlight->currentcubemap); - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - m.texmatrix[1] = rsurface.entitytolight; - } - GL_BlendFunc(GL_DST_ALPHA, GL_ONE); - } - // this final code is shared - R_Mesh_TextureState(&m); - R_Shadow_RenderLighting_Light_Dot3_Finalize(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase[0] * colorscale, lightcolorbase[1] * colorscale, lightcolorbase[2] * colorscale); -} - -static void R_Shadow_RenderLighting_Light_Dot3(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt) -{ - // ARB path (any Geforce, any Radeon) - qboolean doambient = ambientscale > 0; - qboolean dodiffuse = diffusescale > 0; - qboolean dospecular = specularscale > 0; - if (!doambient && !dodiffuse && !dospecular) - return; - R_Mesh_ColorPointer(NULL, 0, 0); - if (doambient) - R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, ambientscale * r_refdef.view.colorscale); - if (dodiffuse) - R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, basetexture, normalmaptexture, diffusescale * r_refdef.view.colorscale); - if (dopants) - { - if (doambient) - R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, ambientscale * r_refdef.view.colorscale); - if (dodiffuse) - R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorpants, pantstexture, normalmaptexture, diffusescale * r_refdef.view.colorscale); - } - if (doshirt) - { - if (doambient) - R_Shadow_RenderLighting_Light_Dot3_AmbientPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, ambientscale * r_refdef.view.colorscale); - if (dodiffuse) - R_Shadow_RenderLighting_Light_Dot3_DiffusePass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorshirt, shirttexture, normalmaptexture, diffusescale * r_refdef.view.colorscale); - } - if (dospecular) - R_Shadow_RenderLighting_Light_Dot3_SpecularPass(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, glosstexture, normalmaptexture, specularscale * r_refdef.view.colorscale); + R_SetupShader_Surface(lightcolor, false, ambientscale, diffusescale, specularscale, RSURFPASS_RTLIGHT, texturenumsurfaces, texturesurfacelist, NULL, false); + RSurf_DrawBatch(); } static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numvertices, int numtriangles, const int *element3i, vec3_t diffusecolor2, vec3_t ambientcolor2) @@ -3302,10 +3191,10 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve int *newe; const int *e; float *c; - int maxtriangles = 4096; - int newelements[4096*3]; - R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, numtriangles, element3i, diffusecolor2, ambientcolor2); - for (renders = 0;renders < 64;renders++) + int maxtriangles = 1024; + int newelements[1024*3]; + R_Shadow_RenderLighting_Light_Vertex_Shading(firstvertex, numvertices, diffusecolor2, ambientcolor2); + for (renders = 0;renders < 4;renders++) { stop = true; newfirstvertex = 0; @@ -3319,7 +3208,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve // renders them at once for (i = 0, e = element3i;i < numtriangles;i++, e += 3) { - if (VectorLength2(rsurface.array_color4f + e[0] * 4) + VectorLength2(rsurface.array_color4f + e[1] * 4) + VectorLength2(rsurface.array_color4f + e[2] * 4) >= 0.01) + if (VectorLength2(rsurface.passcolor4f + e[0] * 4) + VectorLength2(rsurface.passcolor4f + e[1] * 4) + VectorLength2(rsurface.passcolor4f + e[2] * 4) >= 0.01) { if (newnumtriangles) { @@ -3342,7 +3231,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve newe += 3; if (newnumtriangles >= maxtriangles) { - R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0); + R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0); newnumtriangles = 0; newe = newelements; stop = false; @@ -3351,7 +3240,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve } if (newnumtriangles >= 1) { - R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, 0); + R_Mesh_Draw(newfirstvertex, newlastvertex - newfirstvertex + 1, 0, newnumtriangles, newelements, NULL, 0, NULL, NULL, 0); stop = false; } // if we couldn't find any lit triangles, exit early @@ -3362,7 +3251,7 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve // handling of negative colors // (some old drivers even have improper handling of >1 color) stop = true; - for (i = 0, c = rsurface.array_color4f + 4 * firstvertex;i < numvertices;i++, c += 4) + for (i = 0, c = rsurface.passcolor4f + 4 * firstvertex;i < numvertices;i++, c += 4) { if (c[0] > 1 || c[1] > 1 || c[2] > 1) { @@ -3380,71 +3269,84 @@ static void R_Shadow_RenderLighting_Light_Vertex_Pass(int firstvertex, int numve } } -static void R_Shadow_RenderLighting_Light_Vertex(int firstvertex, int numvertices, int numtriangles, const int *element3i, const vec3_t lightcolorbase, const vec3_t lightcolorpants, const vec3_t lightcolorshirt, rtexture_t *basetexture, rtexture_t *pantstexture, rtexture_t *shirttexture, rtexture_t *normalmaptexture, rtexture_t *glosstexture, float ambientscale, float diffusescale, float specularscale, qboolean dopants, qboolean doshirt) +static void R_Shadow_RenderLighting_Light_Vertex(int texturenumsurfaces, const msurface_t **texturesurfacelist, const vec3_t lightcolor, float ambientscale, float diffusescale) { // OpenGL 1.1 path (anything) float ambientcolorbase[3], diffusecolorbase[3]; float ambientcolorpants[3], diffusecolorpants[3]; float ambientcolorshirt[3], diffusecolorshirt[3]; - rmeshstate_t m; - VectorScale(lightcolorbase, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorbase); - VectorScale(lightcolorbase, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorbase); - VectorScale(lightcolorpants, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorpants); - VectorScale(lightcolorpants, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorpants); - VectorScale(lightcolorshirt, ambientscale * 2 * r_refdef.view.colorscale, ambientcolorshirt); - VectorScale(lightcolorshirt, diffusescale * 2 * r_refdef.view.colorscale, diffusecolorshirt); - memset(&m, 0, sizeof(m)); - m.tex[0] = R_GetTexture(basetexture); - m.texmatrix[0] = rsurface.texture->currenttexmatrix; - m.pointer_texcoord[0] = rsurface.texcoordtexture2f; - m.pointer_texcoord_bufferobject[0] = rsurface.texcoordtexture2f_bufferobject; - m.pointer_texcoord_bufferoffset[0] = rsurface.texcoordtexture2f_bufferoffset; - if (r_textureunits.integer >= 2) - { - // voodoo2 or TNT - m.tex[1] = R_GetTexture(r_shadow_attenuation2dtexture); - m.texmatrix[1] = rsurface.entitytoattenuationxyz; - m.pointer_texcoord3f[1] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[1] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[1] = rsurface.vertex3f_bufferoffset; - if (r_textureunits.integer >= 3) - { - // Voodoo4 or Kyro (or Geforce3/Radeon with r_shadow_dot3 off) - m.tex[2] = R_GetTexture(r_shadow_attenuation2dtexture); - m.texmatrix[2] = rsurface.entitytoattenuationz; - m.pointer_texcoord3f[2] = rsurface.vertex3f; - m.pointer_texcoord_bufferobject[2] = rsurface.vertex3f_bufferobject; - m.pointer_texcoord_bufferoffset[2] = rsurface.vertex3f_bufferoffset; - } - } - R_Mesh_TextureState(&m); - //R_Mesh_TexBind(0, R_GetTexture(basetexture)); - R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorbase, ambientcolorbase); - if (dopants) - { - R_Mesh_TexBind(0, R_GetTexture(pantstexture)); - R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorpants, ambientcolorpants); - } + const float *surfacecolor = rsurface.texture->dlightcolor; + const float *surfacepants = rsurface.colormap_pantscolor; + const float *surfaceshirt = rsurface.colormap_shirtcolor; + rtexture_t *basetexture = rsurface.texture->basetexture; + rtexture_t *pantstexture = rsurface.texture->pantstexture; + rtexture_t *shirttexture = rsurface.texture->shirttexture; + qboolean dopants = pantstexture && VectorLength2(surfacepants) >= (1.0f / 1048576.0f); + qboolean doshirt = shirttexture && VectorLength2(surfaceshirt) >= (1.0f / 1048576.0f); + ambientscale *= 2 * r_refdef.view.colorscale; + diffusescale *= 2 * r_refdef.view.colorscale; + ambientcolorbase[0] = lightcolor[0] * ambientscale * surfacecolor[0];ambientcolorbase[1] = lightcolor[1] * ambientscale * surfacecolor[1];ambientcolorbase[2] = lightcolor[2] * ambientscale * surfacecolor[2]; + diffusecolorbase[0] = lightcolor[0] * diffusescale * surfacecolor[0];diffusecolorbase[1] = lightcolor[1] * diffusescale * surfacecolor[1];diffusecolorbase[2] = lightcolor[2] * diffusescale * surfacecolor[2]; + ambientcolorpants[0] = ambientcolorbase[0] * surfacepants[0];ambientcolorpants[1] = ambientcolorbase[1] * surfacepants[1];ambientcolorpants[2] = ambientcolorbase[2] * surfacepants[2]; + diffusecolorpants[0] = diffusecolorbase[0] * surfacepants[0];diffusecolorpants[1] = diffusecolorbase[1] * surfacepants[1];diffusecolorpants[2] = diffusecolorbase[2] * surfacepants[2]; + ambientcolorshirt[0] = ambientcolorbase[0] * surfaceshirt[0];ambientcolorshirt[1] = ambientcolorbase[1] * surfaceshirt[1];ambientcolorshirt[2] = ambientcolorbase[2] * surfaceshirt[2]; + diffusecolorshirt[0] = diffusecolorbase[0] * surfaceshirt[0];diffusecolorshirt[1] = diffusecolorbase[1] * surfaceshirt[1];diffusecolorshirt[2] = diffusecolorbase[2] * surfaceshirt[2]; + RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | (diffusescale > 0 ? BATCHNEED_ARRAY_NORMAL : 0) | BATCHNEED_ARRAY_TEXCOORD | BATCHNEED_NOGAPS, texturenumsurfaces, texturesurfacelist); + rsurface.passcolor4f = (float *)R_FrameData_Alloc((rsurface.batchfirstvertex + rsurface.batchnumvertices) * sizeof(float[4])); + R_Mesh_VertexPointer(3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset); + R_Mesh_ColorPointer(4, GL_FLOAT, sizeof(float[4]), rsurface.passcolor4f, 0, 0); + R_Mesh_TexCoordPointer(0, 2, GL_FLOAT, sizeof(float[2]), rsurface.batchtexcoordtexture2f, rsurface.batchtexcoordtexture2f_vertexbuffer, rsurface.batchtexcoordtexture2f_bufferoffset); + R_Mesh_TexBind(0, basetexture); + R_Mesh_TexMatrix(0, &rsurface.texture->currenttexmatrix); + R_Mesh_TexCombine(0, GL_MODULATE, GL_MODULATE, 1, 1); + switch(r_shadow_rendermode) + { + case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN: + R_Mesh_TexBind(1, r_shadow_attenuation3dtexture); + R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz); + R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1); + R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset); + break; + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN: + R_Mesh_TexBind(2, r_shadow_attenuation2dtexture); + R_Mesh_TexMatrix(2, &rsurface.entitytoattenuationz); + R_Mesh_TexCombine(2, GL_MODULATE, GL_MODULATE, 1, 1); + R_Mesh_TexCoordPointer(2, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset); + // fall through + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN: + R_Mesh_TexBind(1, r_shadow_attenuation2dtexture); + R_Mesh_TexMatrix(1, &rsurface.entitytoattenuationxyz); + R_Mesh_TexCombine(1, GL_MODULATE, GL_MODULATE, 1, 1); + R_Mesh_TexCoordPointer(1, 3, GL_FLOAT, sizeof(float[3]), rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset); + break; + case R_SHADOW_RENDERMODE_LIGHT_VERTEX: + break; + default: + break; + } + //R_Mesh_TexBind(0, basetexture); + R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorbase, ambientcolorbase); + if (dopants) + { + R_Mesh_TexBind(0, pantstexture); + R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorpants, ambientcolorpants); + } if (doshirt) { - R_Mesh_TexBind(0, R_GetTexture(shirttexture)); - R_Shadow_RenderLighting_Light_Vertex_Pass(firstvertex, numvertices, numtriangles, element3i, diffusecolorshirt, ambientcolorshirt); + R_Mesh_TexBind(0, shirttexture); + R_Shadow_RenderLighting_Light_Vertex_Pass(rsurface.batchfirstvertex, rsurface.batchnumvertices, rsurface.batchnumtriangles, rsurface.batchelement3i + 3*rsurface.batchfirsttriangle, diffusecolorshirt, ambientcolorshirt); } } extern cvar_t gl_lightmaps; -void R_Shadow_RenderLighting(int firstvertex, int numvertices, int firsttriangle, int numtriangles, const int *element3i, const unsigned short *element3s, int element3i_bufferobject, int element3s_bufferobject) +void R_Shadow_RenderLighting(int texturenumsurfaces, const msurface_t **texturesurfacelist) { float ambientscale, diffusescale, specularscale; qboolean negated; - vec3_t lightcolorbase, lightcolorpants, lightcolorshirt; - rtexture_t *nmap; - // calculate colors to render this texture with - lightcolorbase[0] = rsurface.rtlight->currentcolor[0] * rsurface.texture->dlightcolor[0]; - lightcolorbase[1] = rsurface.rtlight->currentcolor[1] * rsurface.texture->dlightcolor[1]; - lightcolorbase[2] = rsurface.rtlight->currentcolor[2] * rsurface.texture->dlightcolor[2]; - ambientscale = rsurface.rtlight->ambientscale; - diffusescale = rsurface.rtlight->diffusescale; + float lightcolor[3]; + VectorCopy(rsurface.rtlight->currentcolor, lightcolor); + ambientscale = rsurface.rtlight->ambientscale + rsurface.texture->rtlightambient; + diffusescale = rsurface.rtlight->diffusescale * max(0, 1.0 - rsurface.texture->rtlightambient); specularscale = rsurface.rtlight->specularscale * rsurface.texture->specularscale; if (!r_shadow_usenormalmap.integer) { @@ -3452,82 +3354,36 @@ void R_Shadow_RenderLighting(int firstvertex, int numvertices, int firsttriangle diffusescale = 0; specularscale = 0; } - if ((ambientscale + diffusescale) * VectorLength2(lightcolorbase) + specularscale * VectorLength2(lightcolorbase) < (1.0f / 1048576.0f)) + if ((ambientscale + diffusescale) * VectorLength2(lightcolor) + specularscale * VectorLength2(lightcolor) < (1.0f / 1048576.0f)) return; - negated = (lightcolorbase[0] + lightcolorbase[1] + lightcolorbase[2] < 0) && gl_support_ext_blend_subtract; + negated = (lightcolor[0] + lightcolor[1] + lightcolor[2] < 0) && vid.support.ext_blend_subtract; if(negated) { - VectorNegate(lightcolorbase, lightcolorbase); - qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); + VectorNegate(lightcolor, lightcolor); + GL_BlendEquationSubtract(true); } RSurf_SetupDepthAndCulling(); - nmap = rsurface.texture->currentskinframe->nmap; - if (gl_lightmaps.integer) - nmap = r_texture_blanknormalmap; - if (rsurface.texture->colormapping && !gl_lightmaps.integer) - { - qboolean dopants = rsurface.texture->currentskinframe->pants != NULL && VectorLength2(rsurface.colormap_pantscolor) >= (1.0f / 1048576.0f); - qboolean doshirt = rsurface.texture->currentskinframe->shirt != NULL && VectorLength2(rsurface.colormap_shirtcolor) >= (1.0f / 1048576.0f); - if (dopants) - { - lightcolorpants[0] = lightcolorbase[0] * rsurface.colormap_pantscolor[0]; - lightcolorpants[1] = lightcolorbase[1] * rsurface.colormap_pantscolor[1]; - lightcolorpants[2] = lightcolorbase[2] * rsurface.colormap_pantscolor[2]; - } - else - VectorClear(lightcolorpants); - if (doshirt) - { - lightcolorshirt[0] = lightcolorbase[0] * rsurface.colormap_shirtcolor[0]; - lightcolorshirt[1] = lightcolorbase[1] * rsurface.colormap_shirtcolor[1]; - lightcolorshirt[2] = lightcolorbase[2] * rsurface.colormap_shirtcolor[2]; - } - else - VectorClear(lightcolorshirt); - switch (r_shadow_rendermode) - { - case R_SHADOW_RENDERMODE_VISIBLELIGHTING: - GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer); - R_Shadow_RenderLighting_VisibleLighting(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt); - break; - case R_SHADOW_RENDERMODE_LIGHT_GLSL: - R_Shadow_RenderLighting_Light_GLSL(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt); - break; - case R_SHADOW_RENDERMODE_LIGHT_DOT3: - R_Shadow_RenderLighting_Light_Dot3(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt); - break; - case R_SHADOW_RENDERMODE_LIGHT_VERTEX: - R_Shadow_RenderLighting_Light_Vertex(firstvertex, numvertices, numtriangles, element3i + firsttriangle * 3, lightcolorbase, lightcolorpants, lightcolorshirt, rsurface.texture->basetexture, rsurface.texture->currentskinframe->pants, rsurface.texture->currentskinframe->shirt, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, dopants, doshirt); - break; - default: - Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode); - break; - } - } - else + switch (r_shadow_rendermode) { - switch (r_shadow_rendermode) - { - case R_SHADOW_RENDERMODE_VISIBLELIGHTING: - GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer); - R_Shadow_RenderLighting_VisibleLighting(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false); - break; - case R_SHADOW_RENDERMODE_LIGHT_GLSL: - R_Shadow_RenderLighting_Light_GLSL(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false); - break; - case R_SHADOW_RENDERMODE_LIGHT_DOT3: - R_Shadow_RenderLighting_Light_Dot3(firstvertex, numvertices, firsttriangle, numtriangles, element3i, element3s, element3i_bufferobject, element3s_bufferobject, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false); - break; - case R_SHADOW_RENDERMODE_LIGHT_VERTEX: - R_Shadow_RenderLighting_Light_Vertex(firstvertex, numvertices, numtriangles, element3i + firsttriangle * 3, lightcolorbase, vec3_origin, vec3_origin, rsurface.texture->basetexture, r_texture_black, r_texture_black, nmap, rsurface.texture->glosstexture, ambientscale, diffusescale, specularscale, false, false); - break; - default: - Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode); - break; - } + case R_SHADOW_RENDERMODE_VISIBLELIGHTING: + GL_DepthTest(!(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) && !r_showdisabledepthtest.integer); + R_Shadow_RenderLighting_VisibleLighting(texturenumsurfaces, texturesurfacelist); + break; + case R_SHADOW_RENDERMODE_LIGHT_GLSL: + R_Shadow_RenderLighting_Light_GLSL(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale, specularscale); + break; + case R_SHADOW_RENDERMODE_LIGHT_VERTEX3DATTEN: + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2D1DATTEN: + case R_SHADOW_RENDERMODE_LIGHT_VERTEX2DATTEN: + case R_SHADOW_RENDERMODE_LIGHT_VERTEX: + R_Shadow_RenderLighting_Light_Vertex(texturenumsurfaces, texturesurfacelist, lightcolor, ambientscale, diffusescale); + break; + default: + Con_Printf("R_Shadow_RenderLighting: unknown r_shadow_rendermode %i\n", r_shadow_rendermode); + break; } if(negated) - qglBlendEquationEXT(GL_FUNC_ADD_EXT); + GL_BlendEquationSubtract(false); } void R_RTLight_Update(rtlight_t *rtlight, int isstatic, matrix4x4_t *matrix, vec3_t color, int style, const char *cubemapname, int shadow, vec_t corona, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags) @@ -3605,8 +3461,9 @@ void R_RTLight_Compile(rtlight_t *rtlight) { // this variable must be set for the CompileShadowVolume/CompileShadowMap code r_shadow_compilingrtlight = rtlight; - R_Shadow_EnlargeLeafSurfaceTrisBuffer(model->brush.num_leafs, model->num_surfaces, model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles, model->surfmesh.num_triangles); - model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs); + R_FrameData_SetMark(); + model->GetLightInfo(ent, rtlight->shadoworigin, rtlight->radius, rtlight->cullmins, rtlight->cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, 0, NULL); + R_FrameData_ReturnToMark(); numleafpvsbytes = (model->brush.num_leafs + 7) >> 3; numshadowtrispvsbytes = ((model->brush.shadowmesh ? model->brush.shadowmesh->numtriangles : model->surfmesh.num_triangles) + 7) >> 3; numlighttrispvsbytes = (model->surfmesh.num_triangles + 7) >> 3; @@ -3631,11 +3488,10 @@ void R_RTLight_Compile(rtlight_t *rtlight) memcpy(rtlight->static_shadowtrispvs, r_shadow_buffer_shadowtrispvs, rtlight->static_numshadowtrispvsbytes); if (rtlight->static_numlighttrispvsbytes) memcpy(rtlight->static_lighttrispvs, r_shadow_buffer_lighttrispvs, rtlight->static_numlighttrispvsbytes); + R_FrameData_SetMark(); switch (rtlight->shadowmode) { case R_SHADOW_SHADOWMODE_SHADOWMAP2D: - case R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE: - case R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE: if (model->CompileShadowMap && rtlight->shadow) model->CompileShadowMap(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist); break; @@ -3644,6 +3500,7 @@ void R_RTLight_Compile(rtlight_t *rtlight) model->CompileShadowVolume(ent, rtlight->shadoworigin, NULL, rtlight->radius, numsurfaces, r_shadow_buffer_surfacelist); break; } + R_FrameData_ReturnToMark(); // now we're done compiling the rtlight r_shadow_compilingrtlight = NULL; } @@ -3675,8 +3532,8 @@ void R_RTLight_Compile(rtlight_t *rtlight) if (CHECKPVSBIT(rtlight->static_shadowtrispvs, i)) shadowtris++; - if (developer.integer >= 10) - Con_Printf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris); + if (developer_extra.integer) + Con_DPrintf("static light built: %f %f %f : %f %f %f box, %i light triangles, %i shadow triangles, %i zpass/%i zfail compiled shadow volume triangles\n", rtlight->cullmins[0], rtlight->cullmins[1], rtlight->cullmins[2], rtlight->cullmaxs[0], rtlight->cullmaxs[1], rtlight->cullmaxs[2], lighttris, shadowtris, shadowzpasstris, shadowzfailtris); } void R_RTLight_Uncompile(rtlight_t *rtlight) @@ -3723,14 +3580,17 @@ void R_Shadow_UncompileWorldLights(void) } } -void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) +static void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) { int i, j; mplane_t plane; // reset the count of frustum planes - // see rsurface.rtlight_frustumplanes definition for how much this array + // see rtlight->cached_frustumplanes definition for how much this array // can hold - rsurface.rtlight_numfrustumplanes = 0; + rtlight->cached_numfrustumplanes = 0; + + if (r_trippy.integer) + return; // haven't implemented a culling path for ortho rendering if (!r_refdef.view.useperspective) @@ -3741,7 +3601,7 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) break; if (i == 4) for (i = 0;i < 4;i++) - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = r_refdef.view.frustum[i]; + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i]; return; } @@ -3763,11 +3623,11 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) if (PlaneDiff(rtlight->shadoworigin, &r_refdef.view.frustum[i]) < -0.03125) continue; // copy the plane - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = r_refdef.view.frustum[i]; + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = r_refdef.view.frustum[i]; } // if all the standard frustum planes were accepted, the light is onscreen // otherwise we need to generate some more planes below... - if (rsurface.rtlight_numfrustumplanes < 4) + if (rtlight->cached_numfrustumplanes < 4) { // at least one of the stock frustum planes failed, so we need to // create one or two custom planes to enclose the light origin @@ -3798,12 +3658,12 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) // we have created a valid plane, compute extra info PlaneClassify(&plane); // copy the plane - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane; + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane; #if 1 // if we've found 5 frustum planes then we have constructed a // proper split-side case and do not need to keep searching for // planes to enclose the light origin - if (rsurface.rtlight_numfrustumplanes == 5) + if (rtlight->cached_numfrustumplanes == 5) break; #endif } @@ -3811,9 +3671,9 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) #endif #if 0 - for (i = 0;i < rsurface.rtlight_numfrustumplanes;i++) + for (i = 0;i < rtlight->cached_numfrustumplanes;i++) { - plane = rsurface.rtlight_frustumplanes[i]; + plane = rtlight->cached_frustumplanes[i]; Con_Printf("light %p plane #%i %f %f %f : %f (%f %f %f %f %f)\n", rtlight, i, plane.normal[0], plane.normal[1], plane.normal[2], plane.dist, PlaneDiff(r_refdef.view.frustumcorner[0], &plane), PlaneDiff(r_refdef.view.frustumcorner[1], &plane), PlaneDiff(r_refdef.view.frustumcorner[2], &plane), PlaneDiff(r_refdef.view.frustumcorner[3], &plane), PlaneDiff(rtlight->shadoworigin, &plane)); } #endif @@ -3833,7 +3693,7 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) VectorSubtract(plane.normal, rtlight->shadoworigin, plane.normal); plane.dist = VectorNormalizeLength(plane.normal); plane.dist += DotProduct(plane.normal, rtlight->shadoworigin); - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane; + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane; } } #endif @@ -3844,8 +3704,8 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) { VectorClear(plane.normal); plane.normal[i >> 1] = (i & 1) ? -1 : 1; - plane.dist = (i & 1) ? -rsurface.rtlight_cullmaxs[i >> 1] : rsurface.rtlight_cullmins[i >> 1]; - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = plane; + plane.dist = (i & 1) ? -rtlight->cached_cullmaxs[i >> 1] : rtlight->cached_cullmins[i >> 1]; + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = plane; } #endif @@ -3856,40 +3716,40 @@ void R_Shadow_ComputeShadowCasterCullingPlanes(rtlight_t *rtlight) vec_t bestdist; // reduce all plane distances to tightly fit the rtlight cull box, which // is in worldspace - VectorSet(points[0], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmins[2]); - VectorSet(points[1], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmins[2]); - VectorSet(points[2], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmins[2]); - VectorSet(points[3], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmins[2]); - VectorSet(points[4], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmaxs[2]); - VectorSet(points[5], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmins[1], rsurface.rtlight_cullmaxs[2]); - VectorSet(points[6], rsurface.rtlight_cullmins[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmaxs[2]); - VectorSet(points[7], rsurface.rtlight_cullmaxs[0], rsurface.rtlight_cullmaxs[1], rsurface.rtlight_cullmaxs[2]); - oldnum = rsurface.rtlight_numfrustumplanes; - rsurface.rtlight_numfrustumplanes = 0; + VectorSet(points[0], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]); + VectorSet(points[1], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmins[2]); + VectorSet(points[2], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]); + VectorSet(points[3], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmins[2]); + VectorSet(points[4], rtlight->cached_cullmins[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]); + VectorSet(points[5], rtlight->cached_cullmaxs[0], rtlight->cached_cullmins[1], rtlight->cached_cullmaxs[2]); + VectorSet(points[6], rtlight->cached_cullmins[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]); + VectorSet(points[7], rtlight->cached_cullmaxs[0], rtlight->cached_cullmaxs[1], rtlight->cached_cullmaxs[2]); + oldnum = rtlight->cached_numfrustumplanes; + rtlight->cached_numfrustumplanes = 0; for (j = 0;j < oldnum;j++) { // find the nearest point on the box to this plane - bestdist = DotProduct(rsurface.rtlight_frustumplanes[j].normal, points[0]); + bestdist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[0]); for (i = 1;i < 8;i++) { - dist = DotProduct(rsurface.rtlight_frustumplanes[j].normal, points[i]); + dist = DotProduct(rtlight->cached_frustumplanes[j].normal, points[i]); if (bestdist > dist) bestdist = dist; } - Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rsurface.rtlight_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rsurface.rtlight_frustumplanes[j].normal[0], rsurface.rtlight_frustumplanes[j].normal[1], rsurface.rtlight_frustumplanes[j].normal[2], rsurface.rtlight_frustumplanes[j].dist, bestdist); + Con_Printf("light %p %splane #%i %f %f %f : %f < %f\n", rtlight, rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125 ? "^2" : "^1", j, rtlight->cached_frustumplanes[j].normal[0], rtlight->cached_frustumplanes[j].normal[1], rtlight->cached_frustumplanes[j].normal[2], rtlight->cached_frustumplanes[j].dist, bestdist); // if the nearest point is near or behind the plane, we want this // plane, otherwise the plane is useless as it won't cull anything - if (rsurface.rtlight_frustumplanes[j].dist < bestdist + 0.03125) + if (rtlight->cached_frustumplanes[j].dist < bestdist + 0.03125) { - PlaneClassify(&rsurface.rtlight_frustumplanes[j]); - rsurface.rtlight_frustumplanes[rsurface.rtlight_numfrustumplanes++] = rsurface.rtlight_frustumplanes[j]; + PlaneClassify(&rtlight->cached_frustumplanes[j]); + rtlight->cached_frustumplanes[rtlight->cached_numfrustumplanes++] = rtlight->cached_frustumplanes[j]; } } } #endif } -void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides) +static void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const unsigned char *trispvs, const unsigned char *surfacesides) { shadowmesh_t *mesh; @@ -3899,71 +3759,77 @@ void R_Shadow_DrawWorldShadow_ShadowMap(int numsurfaces, int *surfacelist, const { CHECKGLERROR GL_CullFace(GL_NONE); - mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap; - for (;mesh;mesh = mesh->next) - { + mesh = rsurface.rtlight->static_meshchain_shadow_shadowmap; + for (;mesh;mesh = mesh->next) + { if (!mesh->sidetotals[r_shadow_shadowmapside]) continue; - r_refdef.stats.lights_shadowtriangles += mesh->sidetotals[r_shadow_shadowmapside]; - R_Mesh_VertexPointer(mesh->vertex3f, mesh->vbo, mesh->vbooffset_vertex3f); - R_Mesh_Draw(0, mesh->numverts, mesh->sideoffsets[r_shadow_shadowmapside], mesh->sidetotals[r_shadow_shadowmapside], mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s); - } - CHECKGLERROR - } + r_refdef.stats[r_stat_lights_shadowtriangles] += mesh->sidetotals[r_shadow_shadowmapside]; + R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer, mesh->vbooffset_vertex3f); + R_Mesh_Draw(0, mesh->numverts, mesh->sideoffsets[r_shadow_shadowmapside], mesh->sidetotals[r_shadow_shadowmapside], mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset); + } + CHECKGLERROR + } else if (r_refdef.scene.worldentity->model) - r_refdef.scene.worldmodel->DrawShadowMap(r_shadow_shadowmapside, r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, surfacesides, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs); + r_refdef.scene.worldmodel->DrawShadowMap(r_shadow_shadowmapside, r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, surfacesides, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs); rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } -void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs) +static void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, const unsigned char *trispvs) { - qboolean zpass; + qboolean zpass = false; shadowmesh_t *mesh; int t, tend; int surfacelistindex; msurface_t *surface; + // if triangle neighbors are disabled, shadowvolumes are disabled + if (r_refdef.scene.worldmodel->brush.shadowmesh ? !r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i : !r_refdef.scene.worldmodel->surfmesh.data_neighbor3i) + return; + RSurf_ActiveWorldEntity(); if (rsurface.rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer) { CHECKGLERROR - zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs); - R_Shadow_RenderMode_StencilShadowVolumes(zpass); + if (r_shadow_rendermode != R_SHADOW_RENDERMODE_VISIBLEVOLUMES) + { + zpass = R_Shadow_UseZPass(r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs); + R_Shadow_RenderMode_StencilShadowVolumes(zpass); + } mesh = zpass ? rsurface.rtlight->static_meshchain_shadow_zpass : rsurface.rtlight->static_meshchain_shadow_zfail; for (;mesh;mesh = mesh->next) { - r_refdef.stats.lights_shadowtriangles += mesh->numtriangles; - R_Mesh_VertexPointer(mesh->vertex3f, mesh->vbo, mesh->vbooffset_vertex3f); - GL_LockArrays(0, mesh->numverts); + r_refdef.stats[r_stat_lights_shadowtriangles] += mesh->numtriangles; + R_Mesh_PrepareVertices_Vertex3f(mesh->numverts, mesh->vertex3f, mesh->vbo_vertexbuffer, mesh->vbooffset_vertex3f); if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZPASS_STENCIL) { // increment stencil if frontface is infront of depthbuffer GL_CullFace(r_refdef.view.cullface_back); - qglStencilOp(GL_KEEP, GL_KEEP, GL_INCR);CHECKGLERROR - R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s); + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_INCR, GL_ALWAYS, 128, 255); + R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset); // decrement stencil if backface is infront of depthbuffer GL_CullFace(r_refdef.view.cullface_front); - qglStencilOp(GL_KEEP, GL_KEEP, GL_DECR);CHECKGLERROR + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_DECR, GL_ALWAYS, 128, 255); } else if (r_shadow_rendermode == R_SHADOW_RENDERMODE_ZFAIL_STENCIL) { // decrement stencil if backface is behind depthbuffer GL_CullFace(r_refdef.view.cullface_front); - qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);CHECKGLERROR - R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s); + R_SetStencil(true, 255, GL_KEEP, GL_DECR, GL_KEEP, GL_ALWAYS, 128, 255); + R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset); // increment stencil if frontface is behind depthbuffer GL_CullFace(r_refdef.view.cullface_back); - qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);CHECKGLERROR + R_SetStencil(true, 255, GL_KEEP, GL_INCR, GL_KEEP, GL_ALWAYS, 128, 255); } - R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3s, mesh->ebo3i, mesh->ebo3s); - GL_LockArrays(0, 0); + R_Mesh_Draw(0, mesh->numverts, 0, mesh->numtriangles, mesh->element3i, mesh->element3i_indexbuffer, mesh->element3i_bufferoffset, mesh->element3s, mesh->element3s_indexbuffer, mesh->element3s_bufferoffset); } CHECKGLERROR } - else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh && r_shadow_culltriangles.integer) + else if (numsurfaces && r_refdef.scene.worldmodel->brush.shadowmesh) { + // use the shadow trispvs calculated earlier by GetLightInfo to cull world triangles on this dynamic light R_Shadow_PrepareShadowMark(r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles); for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++) { @@ -3975,17 +3841,20 @@ void R_Shadow_DrawWorldShadow_ShadowVolume(int numsurfaces, int *surfacelist, co R_Shadow_VolumeFromList(r_refdef.scene.worldmodel->brush.shadowmesh->numverts, r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles, r_refdef.scene.worldmodel->brush.shadowmesh->vertex3f, r_refdef.scene.worldmodel->brush.shadowmesh->element3i, r_refdef.scene.worldmodel->brush.shadowmesh->neighbor3i, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius + r_refdef.scene.worldmodel->radius*2 + r_shadow_projectdistance.value, numshadowmark, shadowmarklist, r_refdef.scene.worldmodel->normalmins, r_refdef.scene.worldmodel->normalmaxs); } else if (numsurfaces) - r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs); + { + r_refdef.scene.worldmodel->DrawShadowVolume(r_refdef.scene.worldentity, rsurface.rtlight->shadoworigin, NULL, rsurface.rtlight->radius, numsurfaces, surfacelist, rsurface.rtlight->cached_cullmins, rsurface.rtlight->cached_cullmaxs); + } rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } -void R_Shadow_DrawEntityShadow(entity_render_t *ent) +static void R_Shadow_DrawEntityShadow(entity_render_t *ent) { vec3_t relativeshadoworigin, relativeshadowmins, relativeshadowmaxs; vec_t relativeshadowradius; - RSurf_ActiveModelEntity(ent, false, false); + RSurf_ActiveModelEntity(ent, false, false, false); Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, relativeshadoworigin); + // we need to re-init the shader for each entity because the matrix changed relativeshadowradius = rsurface.rtlight->radius / ent->scale; relativeshadowmins[0] = relativeshadoworigin[0] - relativeshadowradius; relativeshadowmins[1] = relativeshadoworigin[1] - relativeshadowradius; @@ -3993,49 +3862,46 @@ void R_Shadow_DrawEntityShadow(entity_render_t *ent) relativeshadowmaxs[0] = relativeshadoworigin[0] + relativeshadowradius; relativeshadowmaxs[1] = relativeshadoworigin[1] + relativeshadowradius; relativeshadowmaxs[2] = relativeshadoworigin[2] + relativeshadowradius; - if (r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPRECTANGLE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAPCUBESIDE || r_shadow_rendermode == R_SHADOW_RENDERMODE_SHADOWMAP2D) + switch (r_shadow_rendermode) { + case R_SHADOW_RENDERMODE_SHADOWMAP2D: ent->model->DrawShadowMap(r_shadow_shadowmapside, ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs); - } - else + break; + default: ent->model->DrawShadowVolume(ent, relativeshadoworigin, NULL, relativeshadowradius, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs); + break; + } rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } void R_Shadow_SetupEntityLight(const entity_render_t *ent) { // set up properties for rendering light onto this entity - RSurf_ActiveModelEntity(ent, true, true); - GL_AlphaTest(false); + RSurf_ActiveModelEntity(ent, true, true, false); Matrix4x4_Concat(&rsurface.entitytolight, &rsurface.rtlight->matrix_worldtolight, &ent->matrix); Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight); Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight); Matrix4x4_Transform(&ent->inversematrix, rsurface.rtlight->shadoworigin, rsurface.entitylightorigin); - if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL) - R_Mesh_TexMatrix(3, &rsurface.entitytolight); } -void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *trispvs) +static void R_Shadow_DrawWorldLight(int numsurfaces, int *surfacelist, const unsigned char *lighttrispvs) { if (!r_refdef.scene.worldmodel->DrawLight) return; // set up properties for rendering light onto this entity RSurf_ActiveWorldEntity(); - GL_AlphaTest(false); rsurface.entitytolight = rsurface.rtlight->matrix_worldtolight; Matrix4x4_Concat(&rsurface.entitytoattenuationxyz, &matrix_attenuationxyz, &rsurface.entitytolight); Matrix4x4_Concat(&rsurface.entitytoattenuationz, &matrix_attenuationz, &rsurface.entitytolight); VectorCopy(rsurface.rtlight->shadoworigin, rsurface.entitylightorigin); - if (r_shadow_lightingrendermode == R_SHADOW_RENDERMODE_LIGHT_GLSL) - R_Mesh_TexMatrix(3, &rsurface.entitytolight); - r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, trispvs); + r_refdef.scene.worldmodel->DrawLight(r_refdef.scene.worldentity, numsurfaces, surfacelist, lighttrispvs); rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } -void R_Shadow_DrawEntityLight(entity_render_t *ent) +static void R_Shadow_DrawEntityLight(entity_render_t *ent) { dp_model_t *model = ent->model; if (!model->DrawLight) @@ -4048,37 +3914,49 @@ void R_Shadow_DrawEntityLight(entity_render_t *ent) rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } -void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) +static void R_Shadow_PrepareLight(rtlight_t *rtlight) { int i; float f; int numleafs, numsurfaces; int *leaflist, *surfacelist; - unsigned char *leafpvs, *shadowtrispvs, *lighttrispvs, *surfacesides; + unsigned char *leafpvs; + unsigned char *shadowtrispvs; + unsigned char *lighttrispvs; + //unsigned char *surfacesides; int numlightentities; int numlightentities_noselfshadow; int numshadowentities; int numshadowentities_noselfshadow; static entity_render_t *lightentities[MAX_EDICTS]; + static entity_render_t *lightentities_noselfshadow[MAX_EDICTS]; static entity_render_t *shadowentities[MAX_EDICTS]; - static unsigned char entitysides[MAX_EDICTS]; - int lightentities_noselfshadow; - int shadowentities_noselfshadow; - vec3_t nearestpoint; - vec_t distance; - qboolean castshadows; - int lodlinear; + static entity_render_t *shadowentities_noselfshadow[MAX_EDICTS]; + qboolean nolight; + + rtlight->draw = false; + rtlight->cached_numlightentities = 0; + rtlight->cached_numlightentities_noselfshadow = 0; + rtlight->cached_numshadowentities = 0; + rtlight->cached_numshadowentities_noselfshadow = 0; + rtlight->cached_numsurfaces = 0; + rtlight->cached_lightentities = NULL; + rtlight->cached_lightentities_noselfshadow = NULL; + rtlight->cached_shadowentities = NULL; + rtlight->cached_shadowentities_noselfshadow = NULL; + rtlight->cached_shadowtrispvs = NULL; + rtlight->cached_lighttrispvs = NULL; + rtlight->cached_surfacelist = NULL; // skip lights that don't light because of ambientscale+diffusescale+specularscale being 0 (corona only lights) // skip lights that are basically invisible (color 0 0 0) - if (VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f)) - return; + nolight = VectorLength2(rtlight->color) * (rtlight->ambientscale + rtlight->diffusescale + rtlight->specularscale) < (1.0f / 1048576.0f); // loading is done before visibility checks because loading should happen // all at once at the start of a level, not when it stalls gameplay. // (especially important to benchmarks) // compile light - if (rtlight->isstatic && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer) + if (rtlight->isstatic && !nolight && (!rtlight->compiled || (rtlight->shadow && rtlight->shadowmode != (int)r_shadow_shadowmode)) && r_shadow_realtime_world_compile.integer) { if (rtlight->compiled) R_RTLight_Uncompile(rtlight); @@ -4086,7 +3964,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) } // load cubemap - rtlight->currentcubemap = rtlight->cubemapname[0] ? R_Shadow_Cubemap(rtlight->cubemapname) : r_texture_whitecube; + rtlight->currentcubemap = rtlight->cubemapname[0] ? R_GetCubemap(rtlight->cubemapname) : r_texture_whitecube; // look up the light style value at this time f = (rtlight->style >= 0 ? r_refdef.scene.rtlightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value; @@ -4103,12 +3981,22 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) if (VectorLength2(rtlight->currentcolor) < (1.0f / 1048576.0f)) return; + // skip processing on corona-only lights + if (nolight) + return; + // if the light box is offscreen, skip it if (R_CullBox(rtlight->cullmins, rtlight->cullmaxs)) return; - VectorCopy(rtlight->cullmins, rsurface.rtlight_cullmins); - VectorCopy(rtlight->cullmaxs, rsurface.rtlight_cullmaxs); + VectorCopy(rtlight->cullmins, rtlight->cached_cullmins); + VectorCopy(rtlight->cullmaxs, rtlight->cached_cullmaxs); + + R_Shadow_ComputeShadowCasterCullingPlanes(rtlight); + + // don't allow lights to be drawn if using r_shadow_bouncegrid 2, except if we're using static bouncegrid where dynamic lights still need to draw + if (r_shadow_bouncegrid.integer == 2 && (rtlight->isstatic || !r_shadow_bouncegrid_static.integer)) + return; if (rtlight->compiled && r_shadow_realtime_world_compile.integer) { @@ -4119,7 +4007,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) leafpvs = rtlight->static_leafpvs; numsurfaces = rtlight->static_numsurfaces; surfacelist = rtlight->static_surfacelist; - surfacesides = NULL; + //surfacesides = NULL; shadowtrispvs = rtlight->static_shadowtrispvs; lighttrispvs = rtlight->static_lighttrispvs; } @@ -4127,16 +4015,16 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) { // dynamic light, world available and can receive realtime lighting // calculate lit surfaces and leafs - R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles); - r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs); + r_refdef.scene.worldmodel->GetLightInfo(r_refdef.scene.worldentity, rtlight->shadoworigin, rtlight->radius, rtlight->cached_cullmins, rtlight->cached_cullmaxs, r_shadow_buffer_leaflist, r_shadow_buffer_leafpvs, &numleafs, r_shadow_buffer_surfacelist, r_shadow_buffer_surfacepvs, &numsurfaces, r_shadow_buffer_shadowtrispvs, r_shadow_buffer_lighttrispvs, r_shadow_buffer_visitingleafpvs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes); + R_Shadow_ComputeShadowCasterCullingPlanes(rtlight); leaflist = r_shadow_buffer_leaflist; leafpvs = r_shadow_buffer_leafpvs; surfacelist = r_shadow_buffer_surfacelist; - surfacesides = r_shadow_buffer_surfacesides; + //surfacesides = r_shadow_buffer_surfacesides; shadowtrispvs = r_shadow_buffer_shadowtrispvs; lighttrispvs = r_shadow_buffer_lighttrispvs; // if the reduced leaf bounds are offscreen, skip it - if (R_CullBox(rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs)) + if (R_CullBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs)) return; } else @@ -4147,7 +4035,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) leafpvs = NULL; numsurfaces = 0; surfacelist = NULL; - surfacesides = NULL; + //surfacesides = NULL; shadowtrispvs = NULL; lighttrispvs = NULL; } @@ -4160,88 +4048,160 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) if (i == numleafs) return; } - // set up a scissor rectangle for this light - if (R_Shadow_ScissorForBBox(rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs)) - return; - - R_Shadow_ComputeShadowCasterCullingPlanes(rtlight); // make a list of lit entities and shadow casting entities numlightentities = 0; numlightentities_noselfshadow = 0; - lightentities_noselfshadow = sizeof(lightentities)/sizeof(lightentities[0]) - 1; numshadowentities = 0; numshadowentities_noselfshadow = 0; - shadowentities_noselfshadow = sizeof(shadowentities)/sizeof(shadowentities[0]) - 1; // add dynamic entities that are lit by the light - if (r_drawentities.integer) + for (i = 0;i < r_refdef.scene.numentities;i++) { - for (i = 0;i < r_refdef.scene.numentities;i++) + dp_model_t *model; + entity_render_t *ent = r_refdef.scene.entities[i]; + vec3_t org; + if (!BoxesOverlap(ent->mins, ent->maxs, rtlight->cached_cullmins, rtlight->cached_cullmaxs)) + continue; + // skip the object entirely if it is not within the valid + // shadow-casting region (which includes the lit region) + if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes)) + continue; + if (!(model = ent->model)) + continue; + if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT)) { - dp_model_t *model; - entity_render_t *ent = r_refdef.scene.entities[i]; - vec3_t org; - if (!BoxesOverlap(ent->mins, ent->maxs, rsurface.rtlight_cullmins, rsurface.rtlight_cullmaxs)) - continue; - // skip the object entirely if it is not within the valid - // shadow-casting region (which includes the lit region) - if (R_CullBoxCustomPlanes(ent->mins, ent->maxs, rsurface.rtlight_numfrustumplanes, rsurface.rtlight_frustumplanes)) - continue; - if (!(model = ent->model)) + // this entity wants to receive light, is visible, and is + // inside the light box + // TODO: check if the surfaces in the model can receive light + // so now check if it's in a leaf seen by the light + if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs)) continue; - if (r_refdef.viewcache.entityvisible[i] && model->DrawLight && (ent->flags & RENDER_LIGHT)) + if (ent->flags & RENDER_NOSELFSHADOW) + lightentities_noselfshadow[numlightentities_noselfshadow++] = ent; + else + lightentities[numlightentities++] = ent; + // since it is lit, it probably also casts a shadow... + // about the VectorDistance2 - light emitting entities should not cast their own shadow + Matrix4x4_OriginFromMatrix(&ent->matrix, org); + if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1) { - // this entity wants to receive light, is visible, and is - // inside the light box - // TODO: check if the surfaces in the model can receive light - // so now check if it's in a leaf seen by the light - if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs)) - continue; - if (ent->flags & RENDER_NOSELFSHADOW) - lightentities[lightentities_noselfshadow - numlightentities_noselfshadow++] = ent; + // note: exterior models without the RENDER_NOSELFSHADOW + // flag still create a RENDER_NOSELFSHADOW shadow but + // are lit normally, this means that they are + // self-shadowing but do not shadow other + // RENDER_NOSELFSHADOW entities such as the gun + // (very weird, but keeps the player shadow off the gun) + if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL)) + shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent; else - lightentities[numlightentities++] = ent; - // since it is lit, it probably also casts a shadow... - // about the VectorDistance2 - light emitting entities should not cast their own shadow - Matrix4x4_OriginFromMatrix(&ent->matrix, org); - if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1) - { - // note: exterior models without the RENDER_NOSELFSHADOW - // flag still create a RENDER_NOSELFSHADOW shadow but - // are lit normally, this means that they are - // self-shadowing but do not shadow other - // RENDER_NOSELFSHADOW entities such as the gun - // (very weird, but keeps the player shadow off the gun) - if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL)) - shadowentities[shadowentities_noselfshadow - numshadowentities_noselfshadow++] = ent; - else - shadowentities[numshadowentities++] = ent; - } + shadowentities[numshadowentities++] = ent; } - else if (ent->flags & RENDER_SHADOW) + } + else if (ent->flags & RENDER_SHADOW) + { + // this entity is not receiving light, but may still need to + // cast a shadow... + // TODO: check if the surfaces in the model can cast shadow + // now check if it is in a leaf seen by the light + if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs)) + continue; + // about the VectorDistance2 - light emitting entities should not cast their own shadow + Matrix4x4_OriginFromMatrix(&ent->matrix, org); + if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1) { - // this entity is not receiving light, but may still need to - // cast a shadow... - // TODO: check if the surfaces in the model can cast shadow - // now check if it is in a leaf seen by the light - if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS && !r_refdef.scene.worldmodel->brush.BoxTouchingLeafPVS(r_refdef.scene.worldmodel, leafpvs, ent->mins, ent->maxs)) - continue; - // about the VectorDistance2 - light emitting entities should not cast their own shadow - Matrix4x4_OriginFromMatrix(&ent->matrix, org); - if ((ent->flags & RENDER_SHADOW) && model->DrawShadowVolume && VectorDistance2(org, rtlight->shadoworigin) > 0.1) - { - if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL)) - shadowentities[shadowentities_noselfshadow - numshadowentities_noselfshadow++] = ent; - else - shadowentities[numshadowentities++] = ent; - } + if (ent->flags & (RENDER_NOSELFSHADOW | RENDER_EXTERIORMODEL)) + shadowentities_noselfshadow[numshadowentities_noselfshadow++] = ent; + else + shadowentities[numshadowentities++] = ent; } } } // return if there's nothing at all to light - if (!numlightentities && !numsurfaces) + if (numsurfaces + numlightentities + numlightentities_noselfshadow == 0) + return; + + // count this light in the r_speeds + r_refdef.stats[r_stat_lights]++; + + // flag it as worth drawing later + rtlight->draw = true; + + // cache all the animated entities that cast a shadow but are not visible + for (i = 0;i < numshadowentities;i++) + R_AnimCache_GetEntity(shadowentities[i], false, false); + for (i = 0;i < numshadowentities_noselfshadow;i++) + R_AnimCache_GetEntity(shadowentities_noselfshadow[i], false, false); + + // allocate some temporary memory for rendering this light later in the frame + // reusable buffers need to be copied, static data can be used as-is + rtlight->cached_numlightentities = numlightentities; + rtlight->cached_numlightentities_noselfshadow = numlightentities_noselfshadow; + rtlight->cached_numshadowentities = numshadowentities; + rtlight->cached_numshadowentities_noselfshadow = numshadowentities_noselfshadow; + rtlight->cached_numsurfaces = numsurfaces; + rtlight->cached_lightentities = (entity_render_t**)R_FrameData_Store(numlightentities*sizeof(entity_render_t*), (void*)lightentities); + rtlight->cached_lightentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numlightentities_noselfshadow*sizeof(entity_render_t*), (void*)lightentities_noselfshadow); + rtlight->cached_shadowentities = (entity_render_t**)R_FrameData_Store(numshadowentities*sizeof(entity_render_t*), (void*)shadowentities); + rtlight->cached_shadowentities_noselfshadow = (entity_render_t**)R_FrameData_Store(numshadowentities_noselfshadow*sizeof(entity_render_t *), (void*)shadowentities_noselfshadow); + if (shadowtrispvs == r_shadow_buffer_shadowtrispvs) + { + int numshadowtrispvsbytes = (((r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles) + 7) >> 3); + int numlighttrispvsbytes = ((r_refdef.scene.worldmodel->surfmesh.num_triangles + 7) >> 3); + rtlight->cached_shadowtrispvs = (unsigned char *)R_FrameData_Store(numshadowtrispvsbytes, shadowtrispvs); + rtlight->cached_lighttrispvs = (unsigned char *)R_FrameData_Store(numlighttrispvsbytes, lighttrispvs); + rtlight->cached_surfacelist = (int*)R_FrameData_Store(numsurfaces*sizeof(int), (void*)surfacelist); + } + else + { + // compiled light data + rtlight->cached_shadowtrispvs = shadowtrispvs; + rtlight->cached_lighttrispvs = lighttrispvs; + rtlight->cached_surfacelist = surfacelist; + } +} + +static void R_Shadow_DrawLight(rtlight_t *rtlight) +{ + int i; + int numsurfaces; + unsigned char *shadowtrispvs, *lighttrispvs, *surfacesides; + int numlightentities; + int numlightentities_noselfshadow; + int numshadowentities; + int numshadowentities_noselfshadow; + entity_render_t **lightentities; + entity_render_t **lightentities_noselfshadow; + entity_render_t **shadowentities; + entity_render_t **shadowentities_noselfshadow; + int *surfacelist; + static unsigned char entitysides[MAX_EDICTS]; + static unsigned char entitysides_noselfshadow[MAX_EDICTS]; + vec3_t nearestpoint; + vec_t distance; + qboolean castshadows; + int lodlinear; + + // check if we cached this light this frame (meaning it is worth drawing) + if (!rtlight->draw) + return; + + numlightentities = rtlight->cached_numlightentities; + numlightentities_noselfshadow = rtlight->cached_numlightentities_noselfshadow; + numshadowentities = rtlight->cached_numshadowentities; + numshadowentities_noselfshadow = rtlight->cached_numshadowentities_noselfshadow; + numsurfaces = rtlight->cached_numsurfaces; + lightentities = rtlight->cached_lightentities; + lightentities_noselfshadow = rtlight->cached_lightentities_noselfshadow; + shadowentities = rtlight->cached_shadowentities; + shadowentities_noselfshadow = rtlight->cached_shadowentities_noselfshadow; + shadowtrispvs = rtlight->cached_shadowtrispvs; + lighttrispvs = rtlight->cached_lighttrispvs; + surfacelist = rtlight->cached_surfacelist; + + // set up a scissor rectangle for this light + if (R_Shadow_ScissorForBBox(rtlight->cached_cullmins, rtlight->cached_cullmaxs)) return; // don't let sound skip if going slow @@ -4250,8 +4210,6 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) // make this the active rtlight for rendering purposes R_Shadow_RenderMode_ActiveLight(rtlight); - // count this light in the r_speeds - r_refdef.stats.lights++; if (r_showshadowvolumes.integer && r_refdef.view.showdebug && numsurfaces + numshadowentities + numshadowentities_noselfshadow && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows)) { @@ -4263,7 +4221,8 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) for (i = 0;i < numshadowentities;i++) R_Shadow_DrawEntityShadow(shadowentities[i]); for (i = 0;i < numshadowentities_noselfshadow;i++) - R_Shadow_DrawEntityShadow(shadowentities[shadowentities_noselfshadow - i]); + R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]); + R_Shadow_RenderMode_VisibleLighting(false, false); } if (r_showlighting.integer && r_refdef.view.showdebug && numsurfaces + numlightentities + numlightentities_noselfshadow) @@ -4276,7 +4235,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) for (i = 0;i < numlightentities;i++) R_Shadow_DrawEntityLight(lightentities[i]); for (i = 0;i < numlightentities_noselfshadow;i++) - R_Shadow_DrawEntityLight(lightentities[lightentities_noselfshadow - i]); + R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]); } castshadows = numsurfaces + numshadowentities + numshadowentities_noselfshadow > 0 && rtlight->shadow && (rtlight->isstatic ? r_refdef.scene.rtworldshadows : r_refdef.scene.rtdlightshadows); @@ -4290,7 +4249,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) //lodlinear = (int)(r_shadow_shadowmapping_lod_bias.value + r_shadow_shadowmapping_lod_scale.value * rtlight->radius / max(1.0f, distance)); lodlinear = bound(r_shadow_shadowmapping_minsize.integer, lodlinear, r_shadow_shadowmapmaxsize); - if (castshadows && (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPRECTANGLE || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE)) + if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D) { float borderbias; int side; @@ -4305,13 +4264,11 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) if ((r_shadow_shadowmapmaxsize >> i) > lodlinear) r_shadow_shadowmaplod = i; - if (r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAPCUBESIDE) - size = max(1, r_shadow_shadowmapmaxsize >> r_shadow_shadowmaplod); - else - size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize); + size = bound(r_shadow_shadowmapborder, lodlinear, r_shadow_shadowmapmaxsize); borderbias = r_shadow_shadowmapborder / (float)(size - r_shadow_shadowmapborder); + surfacesides = NULL; if (numsurfaces) { if (rtlight->compiled && r_shadow_realtime_world_compile.integer && r_shadow_realtime_world_compileshadow.integer) @@ -4321,6 +4278,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) } else { + surfacesides = r_shadow_buffer_surfacesides; for(i = 0;i < numsurfaces;i++) { msurface_t *surface = r_refdef.scene.worldmodel->data_surfaces + surfacelist[i]; @@ -4336,7 +4294,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) receivermask |= R_Shadow_CalcEntitySideMask(lightentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias); if (receivermask < 0x3F) for(i = 0; i < numlightentities_noselfshadow;i++) - receivermask |= R_Shadow_CalcEntitySideMask(lightentities[lightentities_noselfshadow - i], &rtlight->matrix_worldtolight, &radiustolight, borderbias); + receivermask |= R_Shadow_CalcEntitySideMask(lightentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias); } receivermask &= R_Shadow_CullFrustumSides(rtlight, size, r_shadow_shadowmapborder); @@ -4346,7 +4304,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) for (i = 0;i < numshadowentities;i++) castermask |= (entitysides[i] = R_Shadow_CalcEntitySideMask(shadowentities[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); for (i = 0;i < numshadowentities_noselfshadow;i++) - castermask |= (entitysides[shadowentities_noselfshadow - i] = R_Shadow_CalcEntitySideMask(shadowentities[shadowentities_noselfshadow - i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); + castermask |= (entitysides_noselfshadow[i] = R_Shadow_CalcEntitySideMask(shadowentities_noselfshadow[i], &rtlight->matrix_worldtolight, &radiustolight, borderbias)); } //Con_Printf("distance %f lodlinear %i (lod %i) size %i\n", distance, lodlinear, r_shadow_shadowmaplod, size); @@ -4354,7 +4312,7 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) // render shadow casters into 6 sided depth texture for (side = 0;side < 6;side++) if (receivermask & (1 << side)) { - R_Shadow_RenderMode_ShadowMap(side, true, size); + R_Shadow_RenderMode_ShadowMap(side, receivermask, size); if (! (castermask & (1 << side))) continue; if (numsurfaces) R_Shadow_DrawWorldShadow_ShadowMap(numsurfaces, surfacelist, shadowtrispvs, surfacesides); @@ -4368,17 +4326,17 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) // draw lighting in the unmasked areas R_Shadow_RenderMode_Lighting(false, false, true); for (i = 0;i < numlightentities_noselfshadow;i++) - R_Shadow_DrawEntityLight(lightentities[lightentities_noselfshadow - i]); + R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]); } // render shadow casters into 6 sided depth texture - if (numshadowentities_noselfshadow) + if (numshadowentities_noselfshadow) { for (side = 0;side < 6;side++) if ((receivermask & castermask) & (1 << side)) { - R_Shadow_RenderMode_ShadowMap(side, false, size); - for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides[shadowentities_noselfshadow - i] & (1 << side)) - R_Shadow_DrawEntityShadow(shadowentities[shadowentities_noselfshadow - i]); + R_Shadow_RenderMode_ShadowMap(side, 0, size); + for (i = 0;i < numshadowentities_noselfshadow;i++) if (entitysides_noselfshadow[i] & (1 << side)) + R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]); } } @@ -4391,132 +4349,606 @@ void R_DrawRTLight(rtlight_t *rtlight, qboolean visible) for (i = 0;i < numlightentities;i++) R_Shadow_DrawEntityLight(lightentities[i]); } - else if (castshadows && gl_stencil) + else if (castshadows && vid.stencil) { // draw stencil shadow volumes to mask off pixels that are in shadow // so that they won't receive lighting GL_Scissor(r_shadow_lightscissor[0], r_shadow_lightscissor[1], r_shadow_lightscissor[2], r_shadow_lightscissor[3]); R_Shadow_ClearStencil(); + if (numsurfaces) R_Shadow_DrawWorldShadow_ShadowVolume(numsurfaces, surfacelist, shadowtrispvs); for (i = 0;i < numshadowentities;i++) R_Shadow_DrawEntityShadow(shadowentities[i]); - if (numlightentities_noselfshadow) + + // draw lighting in the unmasked areas + R_Shadow_RenderMode_Lighting(true, false, false); + for (i = 0;i < numlightentities_noselfshadow;i++) + R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]); + + for (i = 0;i < numshadowentities_noselfshadow;i++) + R_Shadow_DrawEntityShadow(shadowentities_noselfshadow[i]); + + // draw lighting in the unmasked areas + R_Shadow_RenderMode_Lighting(true, false, false); + if (numsurfaces) + R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs); + for (i = 0;i < numlightentities;i++) + R_Shadow_DrawEntityLight(lightentities[i]); + } + else + { + // draw lighting in the unmasked areas + R_Shadow_RenderMode_Lighting(false, false, false); + if (numsurfaces) + R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs); + for (i = 0;i < numlightentities;i++) + R_Shadow_DrawEntityLight(lightentities[i]); + for (i = 0;i < numlightentities_noselfshadow;i++) + R_Shadow_DrawEntityLight(lightentities_noselfshadow[i]); + } + + if (r_shadow_usingdeferredprepass) + { + // when rendering deferred lighting, we simply rasterize the box + if (castshadows && r_shadow_shadowmode == R_SHADOW_SHADOWMODE_SHADOWMAP2D) + R_Shadow_RenderMode_DrawDeferredLight(false, true); + else if (castshadows && vid.stencil) + R_Shadow_RenderMode_DrawDeferredLight(true, false); + else + R_Shadow_RenderMode_DrawDeferredLight(false, false); + } +} + +static void R_Shadow_FreeDeferred(void) +{ + R_Mesh_DestroyFramebufferObject(r_shadow_prepassgeometryfbo); + r_shadow_prepassgeometryfbo = 0; + + R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusespecularfbo); + r_shadow_prepasslightingdiffusespecularfbo = 0; + + R_Mesh_DestroyFramebufferObject(r_shadow_prepasslightingdiffusefbo); + r_shadow_prepasslightingdiffusefbo = 0; + + if (r_shadow_prepassgeometrydepthbuffer) + R_FreeTexture(r_shadow_prepassgeometrydepthbuffer); + r_shadow_prepassgeometrydepthbuffer = NULL; + + if (r_shadow_prepassgeometrynormalmaptexture) + R_FreeTexture(r_shadow_prepassgeometrynormalmaptexture); + r_shadow_prepassgeometrynormalmaptexture = NULL; + + if (r_shadow_prepasslightingdiffusetexture) + R_FreeTexture(r_shadow_prepasslightingdiffusetexture); + r_shadow_prepasslightingdiffusetexture = NULL; + + if (r_shadow_prepasslightingspeculartexture) + R_FreeTexture(r_shadow_prepasslightingspeculartexture); + r_shadow_prepasslightingspeculartexture = NULL; +} + +void R_Shadow_DrawPrepass(void) +{ + int i; + int flag; + int lnum; + size_t lightindex; + dlight_t *light; + size_t range; + entity_render_t *ent; + float clearcolor[4]; + + R_Mesh_ResetTextureState(); + GL_DepthMask(true); + GL_ColorMask(1,1,1,1); + GL_BlendFunc(GL_ONE, GL_ZERO); + GL_Color(1,1,1,1); + GL_DepthTest(true); + R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL); + Vector4Set(clearcolor, 0.5f,0.5f,0.5f,1.0f); + GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0); + if (r_timereport_active) + R_TimeReport("prepasscleargeom"); + + if (cl.csqc_vidvars.drawworld && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->DrawPrepass) + r_refdef.scene.worldmodel->DrawPrepass(r_refdef.scene.worldentity); + if (r_timereport_active) + R_TimeReport("prepassworld"); + + for (i = 0;i < r_refdef.scene.numentities;i++) + { + if (!r_refdef.viewcache.entityvisible[i]) + continue; + ent = r_refdef.scene.entities[i]; + if (ent->model && ent->model->DrawPrepass != NULL) + ent->model->DrawPrepass(ent); + } + + if (r_timereport_active) + R_TimeReport("prepassmodels"); + + GL_DepthMask(false); + GL_ColorMask(1,1,1,1); + GL_Color(1,1,1,1); + GL_DepthTest(true); + R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL); + Vector4Set(clearcolor, 0, 0, 0, 0); + GL_Clear(GL_COLOR_BUFFER_BIT, clearcolor, 1.0f, 0); + if (r_timereport_active) + R_TimeReport("prepassclearlit"); + + R_Shadow_RenderMode_Begin(); + + flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + if (r_shadow_debuglight.integer >= 0) + { + lightindex = r_shadow_debuglight.integer; + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light && (light->flags & flag) && light->rtlight.draw) + R_Shadow_DrawLight(&light->rtlight); + } + else + { + range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked + for (lightindex = 0;lightindex < range;lightindex++) { - // draw lighting in the unmasked areas - R_Shadow_RenderMode_Lighting(true, false, false); - for (i = 0;i < numlightentities_noselfshadow;i++) - R_Shadow_DrawEntityLight(lightentities[lightentities_noselfshadow - i]); + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light && (light->flags & flag) && light->rtlight.draw) + R_Shadow_DrawLight(&light->rtlight); + } + } + if (r_refdef.scene.rtdlight) + for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) + if (r_refdef.scene.lights[lnum]->draw) + R_Shadow_DrawLight(r_refdef.scene.lights[lnum]); - // optionally draw the illuminated areas - // for performance analysis by level designers - if (r_showlighting.integer && r_refdef.view.showdebug) - { - R_Shadow_RenderMode_VisibleLighting(!r_showdisabledepthtest.integer, false); - for (i = 0;i < numlightentities_noselfshadow;i++) - R_Shadow_DrawEntityLight(lightentities[lightentities_noselfshadow - i]); - } + R_Shadow_RenderMode_End(); + + if (r_timereport_active) + R_TimeReport("prepasslights"); +} + +void R_Shadow_DrawLightSprites(void); +void R_Shadow_PrepareLights(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture) +{ + int flag; + int lnum; + size_t lightindex; + dlight_t *light; + size_t range; + float f; + + if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, (int)vid.maxtexturesize_2d / 4) || + (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer || r_shadow_deferred.integer) || + r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0 && vid.renderpath == RENDERPATH_GL20) || + r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || + r_shadow_shadowmapshadowsampler != (vid.support.arb_shadow && r_shadow_shadowmapping_useshadowsampler.integer) || + r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer || + r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16) || + r_shadow_shadowmapdepthtexture != r_fb.usedepthtextures) + R_Shadow_FreeShadowMaps(); + + r_shadow_fb_fbo = fbo; + r_shadow_fb_depthtexture = depthtexture; + r_shadow_fb_colortexture = colortexture; + + r_shadow_usingshadowmaportho = false; + + switch (vid.renderpath) + { + case RENDERPATH_GL20: + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: + case RENDERPATH_SOFT: +#ifndef USE_GLES2 + if (!r_shadow_deferred.integer || r_shadow_shadowmode == R_SHADOW_SHADOWMODE_STENCIL || !vid.support.ext_framebuffer_object || vid.maxdrawbuffers < 2) + { + r_shadow_usingdeferredprepass = false; + if (r_shadow_prepass_width) + R_Shadow_FreeDeferred(); + r_shadow_prepass_width = r_shadow_prepass_height = 0; + break; } - for (i = 0;i < numshadowentities_noselfshadow;i++) - R_Shadow_DrawEntityShadow(shadowentities[shadowentities_noselfshadow - i]); - if (numsurfaces + numlightentities) + if (r_shadow_prepass_width != vid.width || r_shadow_prepass_height != vid.height) { - // draw lighting in the unmasked areas - R_Shadow_RenderMode_Lighting(true, false, false); - if (numsurfaces) - R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs); - for (i = 0;i < numlightentities;i++) - R_Shadow_DrawEntityLight(lightentities[i]); + R_Shadow_FreeDeferred(); + + r_shadow_usingdeferredprepass = true; + r_shadow_prepass_width = vid.width; + r_shadow_prepass_height = vid.height; + r_shadow_prepassgeometrydepthbuffer = R_LoadTextureRenderBuffer(r_shadow_texturepool, "prepassgeometrydepthbuffer", vid.width, vid.height, TEXTYPE_DEPTHBUFFER24); + r_shadow_prepassgeometrynormalmaptexture = R_LoadTexture2D(r_shadow_texturepool, "prepassgeometrynormalmap", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER32F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL); + r_shadow_prepasslightingdiffusetexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingdiffuse", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL); + r_shadow_prepasslightingspeculartexture = R_LoadTexture2D(r_shadow_texturepool, "prepasslightingspecular", vid.width, vid.height, NULL, TEXTYPE_COLORBUFFER16F, TEXF_RENDERTARGET | TEXF_CLAMP | TEXF_ALPHA | TEXF_FORCENEAREST, -1, NULL); + + // set up the geometry pass fbo (depth + normalmap) + r_shadow_prepassgeometryfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL); + R_Mesh_SetRenderTargets(r_shadow_prepassgeometryfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepassgeometrynormalmaptexture, NULL, NULL, NULL); + // render depth into a renderbuffer and other important properties into the normalmap texture + + // set up the lighting pass fbo (diffuse + specular) + r_shadow_prepasslightingdiffusespecularfbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL); + R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusespecularfbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, r_shadow_prepasslightingspeculartexture, NULL, NULL); + // render diffuse into one texture and specular into another, + // with depth and normalmap bound as textures, + // with depth bound as attachment as well + + // set up the lighting pass fbo (diffuse) + r_shadow_prepasslightingdiffusefbo = R_Mesh_CreateFramebufferObject(r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL); + R_Mesh_SetRenderTargets(r_shadow_prepasslightingdiffusefbo, r_shadow_prepassgeometrydepthbuffer, r_shadow_prepasslightingdiffusetexture, NULL, NULL, NULL); + // render diffuse into one texture, + // with depth and normalmap bound as textures, + // with depth bound as attachment as well } +#endif + break; + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: + r_shadow_usingdeferredprepass = false; + break; + } + + R_Shadow_EnlargeLeafSurfaceTrisBuffer(r_refdef.scene.worldmodel->brush.num_leafs, r_refdef.scene.worldmodel->num_surfaces, r_refdef.scene.worldmodel->brush.shadowmesh ? r_refdef.scene.worldmodel->brush.shadowmesh->numtriangles : r_refdef.scene.worldmodel->surfmesh.num_triangles, r_refdef.scene.worldmodel->surfmesh.num_triangles); + + flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + if (r_shadow_debuglight.integer >= 0) + { + lightindex = r_shadow_debuglight.integer; + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light) + R_Shadow_PrepareLight(&light->rtlight); } else { - if (numsurfaces + numlightentities) + range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked + for (lightindex = 0;lightindex < range;lightindex++) { - // draw lighting in the unmasked areas - R_Shadow_RenderMode_Lighting(false, false, false); - if (numsurfaces) - R_Shadow_DrawWorldLight(numsurfaces, surfacelist, lighttrispvs); - for (i = 0;i < numlightentities;i++) - R_Shadow_DrawEntityLight(lightentities[i]); - for (i = 0;i < numlightentities_noselfshadow;i++) - R_Shadow_DrawEntityLight(lightentities[lightentities_noselfshadow - i]); + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light && (light->flags & flag)) + R_Shadow_PrepareLight(&light->rtlight); } } + if (r_refdef.scene.rtdlight) + { + for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) + R_Shadow_PrepareLight(r_refdef.scene.lights[lnum]); + } + else if(gl_flashblend.integer) + { + for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) + { + rtlight_t *rtlight = r_refdef.scene.lights[lnum]; + f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value; + VectorScale(rtlight->color, f, rtlight->currentcolor); + } + } + + if (r_editlights.integer) + R_Shadow_DrawLightSprites(); } -void R_Shadow_DrawLightSprites(void); -void R_ShadowVolumeLighting(qboolean visible) +void R_Shadow_DrawLights(void) { int flag; int lnum; size_t lightindex; dlight_t *light; size_t range; - float f; - if (r_shadow_shadowmapmaxsize != bound(1, r_shadow_shadowmapping_maxsize.integer, gl_max_size.integer / 4) || - (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL) != (r_shadow_shadowmapping.integer && r_glsl.integer && gl_support_fragment_shader && gl_support_ext_framebuffer_object) || - r_shadow_shadowmapvsdct != (r_shadow_shadowmapping_vsdct.integer != 0) || - r_shadow_shadowmaptexturetype != r_shadow_shadowmapping_texturetype.integer || - r_shadow_shadowmapfilterquality != r_shadow_shadowmapping_filterquality.integer || - r_shadow_shadowmapdepthbits != r_shadow_shadowmapping_depthbits.integer || - r_shadow_shadowmapborder != bound(0, r_shadow_shadowmapping_bordersize.integer, 16)) - R_Shadow_FreeShadowMaps(); + R_Shadow_RenderMode_Begin(); + + flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + if (r_shadow_debuglight.integer >= 0) + { + lightindex = r_shadow_debuglight.integer; + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light) + R_Shadow_DrawLight(&light->rtlight); + } + else + { + range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked + for (lightindex = 0;lightindex < range;lightindex++) + { + light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); + if (light && (light->flags & flag)) + R_Shadow_DrawLight(&light->rtlight); + } + } + if (r_refdef.scene.rtdlight) + for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) + R_Shadow_DrawLight(r_refdef.scene.lights[lnum]); + + R_Shadow_RenderMode_End(); +} + +#define MAX_MODELSHADOWS 1024 +static int r_shadow_nummodelshadows; +static entity_render_t *r_shadow_modelshadows[MAX_MODELSHADOWS]; + +void R_Shadow_PrepareModelShadows(void) +{ + int i; + float scale, size, radius, dot1, dot2; + prvm_vec3_t prvmshadowdir, prvmshadowfocus; + vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus, shadowmins, shadowmaxs; + entity_render_t *ent; + + r_shadow_nummodelshadows = 0; + if (!r_refdef.scene.numentities) + return; + + switch (r_shadow_shadowmode) + { + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + if (r_shadows.integer >= 2) + break; + // fall through + case R_SHADOW_SHADOWMODE_STENCIL: + if (!vid.stencil) + return; + for (i = 0;i < r_refdef.scene.numentities;i++) + { + ent = r_refdef.scene.entities[i]; + if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW)) + { + if (r_shadow_nummodelshadows >= MAX_MODELSHADOWS) + break; + r_shadow_modelshadows[r_shadow_nummodelshadows++] = ent; + R_AnimCache_GetEntity(ent, false, false); + } + } + return; + default: + return; + } + + size = 2*r_shadow_shadowmapmaxsize; + scale = r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value; + radius = 0.5f * size / scale; + + Math_atov(r_shadows_throwdirection.string, prvmshadowdir); + VectorCopy(prvmshadowdir, shadowdir); + VectorNormalize(shadowdir); + dot1 = DotProduct(r_refdef.view.forward, shadowdir); + dot2 = DotProduct(r_refdef.view.up, shadowdir); + if (fabs(dot1) <= fabs(dot2)) + VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward); + else + VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward); + VectorNormalize(shadowforward); + CrossProduct(shadowdir, shadowforward, shadowright); + Math_atov(r_shadows_focus.string, prvmshadowfocus); + VectorCopy(prvmshadowfocus, shadowfocus); + VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin); + VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin); + VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin); + VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin); + if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2]) + dot1 = 1; + VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin); + + shadowmins[0] = shadoworigin[0] - r_shadows_throwdistance.value * fabs(shadowdir[0]) - radius * (fabs(shadowforward[0]) + fabs(shadowright[0])); + shadowmins[1] = shadoworigin[1] - r_shadows_throwdistance.value * fabs(shadowdir[1]) - radius * (fabs(shadowforward[1]) + fabs(shadowright[1])); + shadowmins[2] = shadoworigin[2] - r_shadows_throwdistance.value * fabs(shadowdir[2]) - radius * (fabs(shadowforward[2]) + fabs(shadowright[2])); + shadowmaxs[0] = shadoworigin[0] + r_shadows_throwdistance.value * fabs(shadowdir[0]) + radius * (fabs(shadowforward[0]) + fabs(shadowright[0])); + shadowmaxs[1] = shadoworigin[1] + r_shadows_throwdistance.value * fabs(shadowdir[1]) + radius * (fabs(shadowforward[1]) + fabs(shadowright[1])); + shadowmaxs[2] = shadoworigin[2] + r_shadows_throwdistance.value * fabs(shadowdir[2]) + radius * (fabs(shadowforward[2]) + fabs(shadowright[2])); + + for (i = 0;i < r_refdef.scene.numentities;i++) + { + ent = r_refdef.scene.entities[i]; + if (!BoxesOverlap(ent->mins, ent->maxs, shadowmins, shadowmaxs)) + continue; + // cast shadows from anything of the map (submodels are optional) + if (ent->model && ent->model->DrawShadowMap != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW)) + { + if (r_shadow_nummodelshadows >= MAX_MODELSHADOWS) + break; + r_shadow_modelshadows[r_shadow_nummodelshadows++] = ent; + R_AnimCache_GetEntity(ent, false, false); + } + } +} + +void R_DrawModelShadowMaps(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture) +{ + int i; + float relativethrowdistance, scale, size, radius, nearclip, farclip, bias, dot1, dot2; + entity_render_t *ent; + vec3_t relativelightorigin; + vec3_t relativelightdirection, relativeforward, relativeright; + vec3_t relativeshadowmins, relativeshadowmaxs; + vec3_t shadowdir, shadowforward, shadowright, shadoworigin, shadowfocus; + prvm_vec3_t prvmshadowdir, prvmshadowfocus; + float m[12]; + matrix4x4_t shadowmatrix, cameramatrix, mvpmatrix, invmvpmatrix, scalematrix, texmatrix; + r_viewport_t viewport; + GLuint shadowfbo = 0; + float clearcolor[4]; + + if (!r_shadow_nummodelshadows) + return; - if (r_editlights.integer) - R_Shadow_DrawLightSprites(); + switch (r_shadow_shadowmode) + { + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + break; + default: + return; + } + r_shadow_fb_fbo = fbo; + r_shadow_fb_depthtexture = depthtexture; + r_shadow_fb_colortexture = colortexture; + + R_ResetViewRendering3D(fbo, depthtexture, colortexture); R_Shadow_RenderMode_Begin(); + R_Shadow_RenderMode_ActiveLight(NULL); - flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; - if (r_shadow_debuglight.integer >= 0) + switch (r_shadow_shadowmode) { - lightindex = r_shadow_debuglight.integer; - light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); - if (light && (light->flags & flag)) - R_DrawRTLight(&light->rtlight, visible); + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + if (!r_shadow_shadowmap2ddepthtexture) + R_Shadow_MakeShadowMap(0, r_shadow_shadowmapmaxsize); + shadowfbo = r_shadow_fbo2d; + r_shadow_shadowmap_texturescale[0] = 1.0f / R_TextureWidth(r_shadow_shadowmap2ddepthtexture); + r_shadow_shadowmap_texturescale[1] = 1.0f / R_TextureHeight(r_shadow_shadowmap2ddepthtexture); + r_shadow_rendermode = R_SHADOW_RENDERMODE_SHADOWMAP2D; + break; + default: + break; } + + size = 2*r_shadow_shadowmapmaxsize; + scale = (r_shadow_shadowmapping_precision.value * r_shadows_shadowmapscale.value) / size; + radius = 0.5f / scale; + nearclip = -r_shadows_throwdistance.value; + farclip = r_shadows_throwdistance.value; + bias = (r_shadows_shadowmapbias.value < 0) ? r_shadow_shadowmapping_bias.value : r_shadows_shadowmapbias.value * r_shadow_shadowmapping_nearclip.value / (2 * r_shadows_throwdistance.value) * (1024.0f / size); + + r_shadow_shadowmap_parameters[0] = size; + r_shadow_shadowmap_parameters[1] = size; + r_shadow_shadowmap_parameters[2] = 1.0; + r_shadow_shadowmap_parameters[3] = bound(0.0f, 1.0f - r_shadows_darken.value, 1.0f); + + Math_atov(r_shadows_throwdirection.string, prvmshadowdir); + VectorCopy(prvmshadowdir, shadowdir); + VectorNormalize(shadowdir); + Math_atov(r_shadows_focus.string, prvmshadowfocus); + VectorCopy(prvmshadowfocus, shadowfocus); + VectorM(shadowfocus[0], r_refdef.view.right, shadoworigin); + VectorMA(shadoworigin, shadowfocus[1], r_refdef.view.up, shadoworigin); + VectorMA(shadoworigin, -shadowfocus[2], r_refdef.view.forward, shadoworigin); + VectorAdd(shadoworigin, r_refdef.view.origin, shadoworigin); + dot1 = DotProduct(r_refdef.view.forward, shadowdir); + dot2 = DotProduct(r_refdef.view.up, shadowdir); + if (fabs(dot1) <= fabs(dot2)) + VectorMA(r_refdef.view.forward, -dot1, shadowdir, shadowforward); else - { - range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked - for (lightindex = 0;lightindex < range;lightindex++) - { - light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); - if (light && (light->flags & flag)) - R_DrawRTLight(&light->rtlight, visible); - } - } - if (r_refdef.scene.rtdlight) - { - for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) - R_DrawRTLight(r_refdef.scene.lights[lnum], visible); + VectorMA(r_refdef.view.up, -dot2, shadowdir, shadowforward); + VectorNormalize(shadowforward); + VectorM(scale, shadowforward, &m[0]); + if (shadowfocus[0] || shadowfocus[1] || shadowfocus[2]) + dot1 = 1; + m[3] = fabs(dot1) * 0.5f - DotProduct(shadoworigin, &m[0]); + CrossProduct(shadowdir, shadowforward, shadowright); + VectorM(scale, shadowright, &m[4]); + m[7] = 0.5f - DotProduct(shadoworigin, &m[4]); + VectorM(1.0f / (farclip - nearclip), shadowdir, &m[8]); + m[11] = 0.5f - DotProduct(shadoworigin, &m[8]); + Matrix4x4_FromArray12FloatD3D(&shadowmatrix, m); + Matrix4x4_Invert_Full(&cameramatrix, &shadowmatrix); + R_Viewport_InitOrtho(&viewport, &cameramatrix, 0, 0, size, size, 0, 0, 1, 1, 0, -1, NULL); + + VectorMA(shadoworigin, (1.0f - fabs(dot1)) * radius, shadowforward, shadoworigin); + + if (r_shadow_shadowmap2ddepthbuffer) + R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthbuffer, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL); + else + R_Mesh_SetRenderTargets(shadowfbo, r_shadow_shadowmap2ddepthtexture, NULL, NULL, NULL, NULL); + R_SetupShader_DepthOrShadow(true, r_shadow_shadowmap2ddepthbuffer != NULL, false); // FIXME test if we have a skeletal model? + GL_PolygonOffset(r_shadow_shadowmapping_polygonfactor.value, r_shadow_shadowmapping_polygonoffset.value); + GL_DepthMask(true); + GL_DepthTest(true); + R_SetViewport(&viewport); + GL_Scissor(viewport.x, viewport.y, min(viewport.width + r_shadow_shadowmapborder, 2*r_shadow_shadowmapmaxsize), viewport.height + r_shadow_shadowmapborder); + Vector4Set(clearcolor, 1,1,1,1); + // in D3D9 we have to render to a color texture shadowmap + // in GL we render directly to a depth texture only + if (r_shadow_shadowmap2ddepthbuffer) + GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0); + else + GL_Clear(GL_DEPTH_BUFFER_BIT, clearcolor, 1.0f, 0); + // render into a slightly restricted region so that the borders of the + // shadowmap area fade away, rather than streaking across everything + // outside the usable area + GL_Scissor(viewport.x + r_shadow_shadowmapborder, viewport.y + r_shadow_shadowmapborder, viewport.width - 2*r_shadow_shadowmapborder, viewport.height - 2*r_shadow_shadowmapborder); + + for (i = 0;i < r_shadow_nummodelshadows;i++) + { + ent = r_shadow_modelshadows[i]; + relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix); + Matrix4x4_Transform(&ent->inversematrix, shadoworigin, relativelightorigin); + Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection); + Matrix4x4_Transform3x3(&ent->inversematrix, shadowforward, relativeforward); + Matrix4x4_Transform3x3(&ent->inversematrix, shadowright, relativeright); + relativeshadowmins[0] = relativelightorigin[0] - r_shadows_throwdistance.value * fabs(relativelightdirection[0]) - radius * (fabs(relativeforward[0]) + fabs(relativeright[0])); + relativeshadowmins[1] = relativelightorigin[1] - r_shadows_throwdistance.value * fabs(relativelightdirection[1]) - radius * (fabs(relativeforward[1]) + fabs(relativeright[1])); + relativeshadowmins[2] = relativelightorigin[2] - r_shadows_throwdistance.value * fabs(relativelightdirection[2]) - radius * (fabs(relativeforward[2]) + fabs(relativeright[2])); + relativeshadowmaxs[0] = relativelightorigin[0] + r_shadows_throwdistance.value * fabs(relativelightdirection[0]) + radius * (fabs(relativeforward[0]) + fabs(relativeright[0])); + relativeshadowmaxs[1] = relativelightorigin[1] + r_shadows_throwdistance.value * fabs(relativelightdirection[1]) + radius * (fabs(relativeforward[1]) + fabs(relativeright[1])); + relativeshadowmaxs[2] = relativelightorigin[2] + r_shadows_throwdistance.value * fabs(relativelightdirection[2]) + radius * (fabs(relativeforward[2]) + fabs(relativeright[2])); + RSurf_ActiveModelEntity(ent, false, false, false); + ent->model->DrawShadowMap(0, ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, NULL, relativeshadowmins, relativeshadowmaxs); + rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } - else if(gl_flashblend.integer) + +#if 0 + if (r_test.integer) { - for (lnum = 0;lnum < r_refdef.scene.numlights;lnum++) - { - rtlight_t *rtlight = r_refdef.scene.lights[lnum]; - f = (rtlight->style >= 0 ? r_refdef.scene.lightstylevalue[rtlight->style] : 1) * r_shadow_lightintensityscale.value; - VectorScale(rtlight->color, f, rtlight->currentcolor); - } + unsigned char *rawpixels = Z_Malloc(viewport.width*viewport.height*4); + CHECKGLERROR + qglReadPixels(viewport.x, viewport.y, viewport.width, viewport.height, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, rawpixels); + CHECKGLERROR + Image_WriteTGABGRA("r_shadows_2.tga", viewport.width, viewport.height, rawpixels); + Cvar_SetValueQuick(&r_test, 0); + Z_Free(rawpixels); } +#endif R_Shadow_RenderMode_End(); + + Matrix4x4_Concat(&mvpmatrix, &r_refdef.view.viewport.projectmatrix, &r_refdef.view.viewport.viewmatrix); + Matrix4x4_Invert_Full(&invmvpmatrix, &mvpmatrix); + Matrix4x4_CreateScale3(&scalematrix, size, -size, 1); + Matrix4x4_AdjustOrigin(&scalematrix, 0, size, -0.5f * bias); + Matrix4x4_Concat(&texmatrix, &scalematrix, &shadowmatrix); + Matrix4x4_Concat(&r_shadow_shadowmapmatrix, &texmatrix, &invmvpmatrix); + + switch (vid.renderpath) + { + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GL20: + case RENDERPATH_SOFT: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: + break; + case RENDERPATH_D3D9: + case RENDERPATH_D3D10: + case RENDERPATH_D3D11: +#ifdef MATRIX4x4_OPENGLORIENTATION + r_shadow_shadowmapmatrix.m[0][0] *= -1.0f; + r_shadow_shadowmapmatrix.m[0][1] *= -1.0f; + r_shadow_shadowmapmatrix.m[0][2] *= -1.0f; + r_shadow_shadowmapmatrix.m[0][3] *= -1.0f; +#else + r_shadow_shadowmapmatrix.m[0][0] *= -1.0f; + r_shadow_shadowmapmatrix.m[1][0] *= -1.0f; + r_shadow_shadowmapmatrix.m[2][0] *= -1.0f; + r_shadow_shadowmapmatrix.m[3][0] *= -1.0f; +#endif + break; + } + + r_shadow_usingshadowmaportho = true; + switch (r_shadow_shadowmode) + { + case R_SHADOW_SHADOWMODE_SHADOWMAP2D: + r_shadow_usingshadowmap2d = true; + break; + default: + break; + } } -extern const float r_screenvertex3f[12]; -extern void R_SetupView(qboolean allowwaterclippingplane); -extern void R_ResetViewRendering3D(void); -extern void R_ResetViewRendering2D(void); -extern cvar_t r_shadows; -extern cvar_t r_shadows_darken; -extern cvar_t r_shadows_drawafterrtlighting; -extern cvar_t r_shadows_castfrombmodels; -extern cvar_t r_shadows_throwdistance; -extern cvar_t r_shadows_throwdirection; -void R_DrawModelShadows(void) +void R_DrawModelShadows(int fbo, rtexture_t *depthtexture, rtexture_t *colortexture) { int i; float relativethrowdistance; @@ -4525,12 +4957,16 @@ void R_DrawModelShadows(void) vec3_t relativelightdirection; vec3_t relativeshadowmins, relativeshadowmaxs; vec3_t tmp, shadowdir; + prvm_vec3_t prvmshadowdir; - if (!r_drawentities.integer || !gl_stencil) + if (!r_shadow_nummodelshadows || (r_shadow_shadowmode != R_SHADOW_SHADOWMODE_STENCIL && r_shadows.integer != 1)) return; - CHECKGLERROR - R_ResetViewRendering3D(); + r_shadow_fb_fbo = fbo; + r_shadow_fb_depthtexture = depthtexture; + r_shadow_fb_colortexture = colortexture; + + R_ResetViewRendering3D(fbo, depthtexture, colortexture); //GL_Scissor(r_refdef.view.viewport.x, r_refdef.view.viewport.y, r_refdef.view.viewport.width, r_refdef.view.viewport.height); //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height); R_Shadow_RenderMode_Begin(); @@ -4544,27 +4980,33 @@ void R_DrawModelShadows(void) // get shadow dir if (r_shadows.integer == 2) { - Math_atov(r_shadows_throwdirection.string, shadowdir); + Math_atov(r_shadows_throwdirection.string, prvmshadowdir); + VectorCopy(prvmshadowdir, shadowdir); VectorNormalize(shadowdir); } R_Shadow_ClearStencil(); - for (i = 0;i < r_refdef.scene.numentities;i++) + for (i = 0;i < r_shadow_nummodelshadows;i++) { - ent = r_refdef.scene.entities[i]; + ent = r_shadow_modelshadows[i]; // cast shadows from anything of the map (submodels are optional) - if (ent->model && ent->model->DrawShadowVolume != NULL && (!ent->model->brush.submodel || r_shadows_castfrombmodels.integer) && (ent->flags & RENDER_SHADOW)) + relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix); + VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance); + VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance); + if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction + Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection); + else { - relativethrowdistance = r_shadows_throwdistance.value * Matrix4x4_ScaleFromMatrix(&ent->inversematrix); - VectorSet(relativeshadowmins, -relativethrowdistance, -relativethrowdistance, -relativethrowdistance); - VectorSet(relativeshadowmaxs, relativethrowdistance, relativethrowdistance, relativethrowdistance); - if (r_shadows.integer == 2) // 2: simpler mode, throw shadows always in same direction - Matrix4x4_Transform3x3(&ent->inversematrix, shadowdir, relativelightdirection); - else + if(ent->entitynumber != 0) { - if(ent->entitynumber != 0) + if(ent->entitynumber >= MAX_EDICTS) // csqc entity + { + // FIXME handle this + VectorNegate(ent->modellight_lightdir, relativelightdirection); + } + else { // networked entity - might be attached in some way (then we should use the parent's light direction, to not tear apart attached entities) int entnum, entnum2, recursion; @@ -4587,15 +5029,15 @@ void R_DrawModelShadows(void) else VectorNegate(ent->modellight_lightdir, relativelightdirection); } - else - VectorNegate(ent->modellight_lightdir, relativelightdirection); } - - VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin); - RSurf_ActiveModelEntity(ent, false, false); - ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs); - rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity + else + VectorNegate(ent->modellight_lightdir, relativelightdirection); } + + VectorScale(relativelightdirection, -relativethrowdistance, relativelightorigin); + RSurf_ActiveModelEntity(ent, false, false, false); + ent->model->DrawShadowVolume(ent, relativelightorigin, relativelightdirection, relativethrowdistance, ent->model->nummodelsurfaces, ent->model->sortedmodelsurfaces, relativeshadowmins, relativeshadowmaxs); + rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity } // not really the right mode, but this will disable any silly stencil features @@ -4605,12 +5047,9 @@ void R_DrawModelShadows(void) //GL_Scissor(r_refdef.view.x, vid.height - r_refdef.view.height - r_refdef.view.y, r_refdef.view.width, r_refdef.view.height); //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1); //GL_ScissorTest(true); - //R_Mesh_Matrix(&identitymatrix); + //R_EntityMatrix(&identitymatrix); //R_Mesh_ResetTextureState(); - R_ResetViewRendering2D(); - R_Mesh_VertexPointer(r_screenvertex3f, 0, 0); - R_Mesh_ColorPointer(NULL, 0, 0); - R_SetupGenericShader(false); + R_ResetViewRendering2D(fbo, depthtexture, colortexture); // set up a darkening blend on shadowed areas GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -4620,14 +5059,13 @@ void R_DrawModelShadows(void) //GL_PolygonOffset(0, 0);CHECKGLERROR GL_Color(0, 0, 0, r_shadows_darken.value); //GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1); - //qglDepthFunc(GL_ALWAYS);CHECKGLERROR - qglEnable(GL_STENCIL_TEST);CHECKGLERROR - qglStencilMask(~0);CHECKGLERROR - qglStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);CHECKGLERROR - qglStencilFunc(GL_NOTEQUAL, 128, ~0);CHECKGLERROR + //GL_DepthFunc(GL_ALWAYS); + R_SetStencil(true, 255, GL_KEEP, GL_KEEP, GL_KEEP, GL_NOTEQUAL, 128, 255); // apply the blend to the shadowed areas - R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0); + R_Mesh_PrepareVertices_Generic_Arrays(4, r_screenvertex3f, NULL, NULL); + R_SetupShader_Generic_NoTexture(false, true); + R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0); // restore the viewport R_SetViewport(&r_refdef.view.viewport); @@ -4636,11 +5074,13 @@ void R_DrawModelShadows(void) //R_Shadow_RenderMode_End(); } -void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery) +static void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery) { float zdist; vec3_t centerorigin; +#if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2) float vertex3f[12]; +#endif // if it's too close, skip it if (VectorLength(rtlight->currentcolor) < (1.0f / 256.0f)) return; @@ -4654,38 +5094,84 @@ void R_BeginCoronaQuery(rtlight_t *rtlight, float scale, qboolean usequery) // we count potential samples in the middle of the screen, we count actual samples at the light location, this allows counting potential samples of off-screen lights VectorMA(r_refdef.view.origin, zdist, r_refdef.view.forward, centerorigin); - CHECKGLERROR - // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use qglDepthFunc instead - qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels); - qglDepthFunc(GL_ALWAYS); - R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale); - R_Mesh_VertexPointer(vertex3f, 0, 0); - R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0); - qglEndQueryARB(GL_SAMPLES_PASSED_ARB); - qglDepthFunc(GL_LEQUAL); - qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels); - R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale); - R_Mesh_VertexPointer(vertex3f, 0, 0); - R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, polygonelement3s, 0, 0); - qglEndQueryARB(GL_SAMPLES_PASSED_ARB); - CHECKGLERROR + switch(vid.renderpath) + { + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GL20: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: +#if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2) + CHECKGLERROR + // NOTE: GL_DEPTH_TEST must be enabled or ATI won't count samples, so use GL_DepthFunc instead + qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_allpixels); + GL_DepthFunc(GL_ALWAYS); + R_CalcSprite_Vertex3f(vertex3f, centerorigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale); + R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL, 0); + R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0); + qglEndQueryARB(GL_SAMPLES_PASSED_ARB); + GL_DepthFunc(GL_LEQUAL); + qglBeginQueryARB(GL_SAMPLES_PASSED_ARB, rtlight->corona_queryindex_visiblepixels); + R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale); + R_Mesh_PrepareVertices_Vertex3f(4, vertex3f, NULL, 0); + R_Mesh_Draw(0, 4, 0, 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0); + qglEndQueryARB(GL_SAMPLES_PASSED_ARB); + CHECKGLERROR +#endif + break; + case RENDERPATH_D3D9: + Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D10: + Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D11: + Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_SOFT: + //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + } } rtlight->corona_visibility = bound(0, (zdist - 32) / 32, 1); } static float spritetexcoord2f[4*2] = {0, 1, 0, 0, 1, 0, 1, 1}; -void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale) +static void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale) { vec3_t color; GLint allpixels = 0, visiblepixels = 0; // now we have to check the query result if (rtlight->corona_queryindex_visiblepixels) { - CHECKGLERROR - qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels); - qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels); - CHECKGLERROR + switch(vid.renderpath) + { + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GL20: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: +#if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2) + CHECKGLERROR + qglGetQueryObjectivARB(rtlight->corona_queryindex_visiblepixels, GL_QUERY_RESULT_ARB, &visiblepixels); + qglGetQueryObjectivARB(rtlight->corona_queryindex_allpixels, GL_QUERY_RESULT_ARB, &allpixels); + CHECKGLERROR +#endif + break; + case RENDERPATH_D3D9: + Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D10: + Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D11: + Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_SOFT: + //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + } //Con_Printf("%i of %i pixels\n", (int)visiblepixels, (int)allpixels); if (visiblepixels < 1 || allpixels < 1) return; @@ -4695,41 +5181,41 @@ void R_DrawCorona(rtlight_t *rtlight, float cscale, float scale) else { // FIXME: these traces should scan all render entities instead of cl.world - if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction < 1) + if (CL_TraceLine(r_refdef.view.origin, rtlight->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1) return; } VectorScale(rtlight->currentcolor, cscale, color); if (VectorLength(color) > (1.0f / 256.0f)) { float vertex3f[12]; - qboolean negated = (color[0] + color[1] + color[2] < 0) && gl_support_ext_blend_subtract; + qboolean negated = (color[0] + color[1] + color[2] < 0) && vid.support.ext_blend_subtract; if(negated) { VectorNegate(color, color); - qglBlendEquationEXT(GL_FUNC_REVERSE_SUBTRACT_EXT); + GL_BlendEquationSubtract(true); } R_CalcSprite_Vertex3f(vertex3f, rtlight->shadoworigin, r_refdef.view.right, r_refdef.view.up, scale, -scale, -scale, scale); RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, RENDER_NODEPTHTEST, 0, color[0], color[1], color[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false); - R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false); + R_DrawCustomSurface(r_shadow_lightcorona, &identitymatrix, MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE | MATERIALFLAG_NODEPTHTEST, 0, 4, 0, 2, false, false); if(negated) - qglBlendEquationEXT(GL_FUNC_ADD_EXT); + GL_BlendEquationSubtract(false); } } -void R_DrawCoronas(void) +void R_Shadow_DrawCoronas(void) { int i, flag; - qboolean usequery; + qboolean usequery = false; size_t lightindex; dlight_t *light; rtlight_t *rtlight; size_t range; if (r_coronas.value < (1.0f / 256.0f) && !gl_flashblend.integer) return; - if (r_waterstate.renderingscene) + if (r_fb.water.renderingscene) return; flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; - R_Mesh_Matrix(&identitymatrix); + R_EntityMatrix(&identitymatrix); range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked @@ -4737,30 +5223,54 @@ void R_DrawCoronas(void) // use GL_ARB_occlusion_query if available // otherwise use raytraces r_numqueries = 0; - usequery = gl_support_arb_occlusion_query && r_coronas_occlusionquery.integer; - if (usequery) - { - GL_ColorMask(0,0,0,0); - if (r_maxqueries < (range + r_refdef.scene.numlights) * 2) - if (r_maxqueries < MAX_OCCLUSION_QUERIES) + switch (vid.renderpath) + { + case RENDERPATH_GL11: + case RENDERPATH_GL13: + case RENDERPATH_GL20: + case RENDERPATH_GLES1: + case RENDERPATH_GLES2: + usequery = vid.support.arb_occlusion_query && r_coronas_occlusionquery.integer; +#if defined(GL_SAMPLES_PASSED_ARB) && !defined(USE_GLES2) + if (usequery) { - i = r_maxqueries; - r_maxqueries = (range + r_refdef.scene.numlights) * 4; - r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES); - CHECKGLERROR - qglGenQueriesARB(r_maxqueries - i, r_queries + i); - CHECKGLERROR + GL_ColorMask(0,0,0,0); + if (r_maxqueries < (range + r_refdef.scene.numlights) * 2) + if (r_maxqueries < MAX_OCCLUSION_QUERIES) + { + i = r_maxqueries; + r_maxqueries = (range + r_refdef.scene.numlights) * 4; + r_maxqueries = min(r_maxqueries, MAX_OCCLUSION_QUERIES); + CHECKGLERROR + qglGenQueriesARB(r_maxqueries - i, r_queries + i); + CHECKGLERROR + } + RSurf_ActiveWorldEntity(); + GL_BlendFunc(GL_ONE, GL_ZERO); + GL_CullFace(GL_NONE); + GL_DepthMask(false); + GL_DepthRange(0, 1); + GL_PolygonOffset(0, 0); + GL_DepthTest(true); + R_Mesh_ResetTextureState(); + R_SetupShader_Generic_NoTexture(false, false); } - RSurf_ActiveWorldEntity(); - GL_BlendFunc(GL_ONE, GL_ZERO); - GL_CullFace(GL_NONE); - GL_DepthMask(false); - GL_DepthRange(0, 1); - GL_PolygonOffset(0, 0); - GL_DepthTest(true); - R_Mesh_ColorPointer(NULL, 0, 0); - R_Mesh_ResetTextureState(); - R_SetupGenericShader(false); +#endif + break; + case RENDERPATH_D3D9: + usequery = false; + //Con_DPrintf("FIXME D3D9 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D10: + Con_DPrintf("FIXME D3D10 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_D3D11: + Con_DPrintf("FIXME D3D11 %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; + case RENDERPATH_SOFT: + usequery = false; + //Con_DPrintf("FIXME SOFT %s:%i %s\n", __FILE__, __LINE__, __FUNCTION__); + break; } for (lightindex = 0;lightindex < range;lightindex++) { @@ -4819,146 +5329,12 @@ void R_DrawCoronas(void) -//static char *suffix[6] = {"ft", "bk", "rt", "lf", "up", "dn"}; -typedef struct suffixinfo_s -{ - char *suffix; - qboolean flipx, flipy, flipdiagonal; -} -suffixinfo_t; -static suffixinfo_t suffix[3][6] = -{ - { - {"px", false, false, false}, - {"nx", false, false, false}, - {"py", false, false, false}, - {"ny", false, false, false}, - {"pz", false, false, false}, - {"nz", false, false, false} - }, - { - {"posx", false, false, false}, - {"negx", false, false, false}, - {"posy", false, false, false}, - {"negy", false, false, false}, - {"posz", false, false, false}, - {"negz", false, false, false} - }, - { - {"rt", true, false, true}, - {"lf", false, true, true}, - {"ft", true, true, false}, - {"bk", false, false, false}, - {"up", true, false, true}, - {"dn", true, false, true} - } -}; - -static int componentorder[4] = {0, 1, 2, 3}; - -rtexture_t *R_Shadow_LoadCubemap(const char *basename) -{ - int i, j, cubemapsize; - unsigned char *cubemappixels, *image_buffer; - rtexture_t *cubemaptexture; - char name[256]; - // must start 0 so the first loadimagepixels has no requested width/height - cubemapsize = 0; - cubemappixels = NULL; - cubemaptexture = NULL; - // keep trying different suffix groups (posx, px, rt) until one loads - for (j = 0;j < 3 && !cubemappixels;j++) - { - // load the 6 images in the suffix group - for (i = 0;i < 6;i++) - { - // generate an image name based on the base and and suffix - dpsnprintf(name, sizeof(name), "%s%s", basename, suffix[j][i].suffix); - // load it - if ((image_buffer = loadimagepixelsbgra(name, false, false))) - { - // an image loaded, make sure width and height are equal - if (image_width == image_height && (!cubemappixels || image_width == cubemapsize)) - { - // if this is the first image to load successfully, allocate the cubemap memory - if (!cubemappixels && image_width >= 1) - { - cubemapsize = image_width; - // note this clears to black, so unavailable sides are black - cubemappixels = (unsigned char *)Mem_Alloc(tempmempool, 6*cubemapsize*cubemapsize*4); - } - // copy the image with any flipping needed by the suffix (px and posx types don't need flipping) - if (cubemappixels) - 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); - } - else - Con_Printf("Cubemap image \"%s\" (%ix%i) is not square, OpenGL requires square cubemaps.\n", name, image_width, image_height); - // free the image - Mem_Free(image_buffer); - } - } - } - // if a cubemap loaded, upload it - if (cubemappixels) - { - if (developer_loading.integer) - Con_Printf("loading cubemap \"%s\"\n", basename); - - if (!r_shadow_filters_texturepool) - r_shadow_filters_texturepool = R_AllocTexturePool(); - cubemaptexture = R_LoadTextureCubeMap(r_shadow_filters_texturepool, basename, cubemapsize, cubemappixels, TEXTYPE_BGRA, TEXF_PRECACHE | (gl_texturecompression_lightcubemaps.integer ? TEXF_COMPRESS : 0) | TEXF_FORCELINEAR, NULL); - Mem_Free(cubemappixels); - } - else - { - Con_DPrintf("failed to load cubemap \"%s\"\n", basename); - if (developer_loading.integer) - { - Con_Printf("(tried tried images "); - for (j = 0;j < 3;j++) - for (i = 0;i < 6;i++) - Con_Printf("%s\"%s%s.tga\"", j + i > 0 ? ", " : "", basename, suffix[j][i].suffix); - Con_Print(" and was unable to find any of them).\n"); - } - } - return cubemaptexture; -} - -rtexture_t *R_Shadow_Cubemap(const char *basename) -{ - int i; - for (i = 0;i < numcubemaps;i++) - if (!strcasecmp(cubemaps[i].basename, basename)) - return cubemaps[i].texture ? cubemaps[i].texture : r_texture_whitecube; - if (i >= MAX_CUBEMAPS) - return r_texture_whitecube; - numcubemaps++; - strlcpy(cubemaps[i].basename, basename, sizeof(cubemaps[i].basename)); - cubemaps[i].texture = R_Shadow_LoadCubemap(cubemaps[i].basename); - return cubemaps[i].texture; -} - -void R_Shadow_FreeCubemaps(void) -{ - int i; - for (i = 0;i < numcubemaps;i++) - { - if (developer_loading.integer) - Con_Printf("unloading cubemap \"%s\"\n", cubemaps[i].basename); - if (cubemaps[i].texture) - R_FreeTexture(cubemaps[i].texture); - } - - numcubemaps = 0; - R_FreeTexturePool(&r_shadow_filters_texturepool); -} - -dlight_t *R_Shadow_NewWorldLight(void) +static dlight_t *R_Shadow_NewWorldLight(void) { return (dlight_t *)Mem_ExpandableArray_AllocRecord(&r_shadow_worldlightsarray); } -void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags) +static void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, vec3_t color, vec_t radius, vec_t corona, int style, int shadowenable, const char *cubemapname, vec_t coronasizescale, vec_t ambientscale, vec_t diffusescale, vec_t specularscale, int flags) { matrix4x4_t matrix; // validate parameters @@ -4999,7 +5375,7 @@ void R_Shadow_UpdateWorldLight(dlight_t *light, vec3_t origin, vec3_t angles, ve R_RTLight_Update(&light->rtlight, true, &matrix, light->color, light->style, light->cubemapname[0] ? light->cubemapname : NULL, light->shadow, light->corona, light->coronasizescale, light->ambientscale, light->diffusescale, light->specularscale, light->flags); } -void R_Shadow_FreeWorldLight(dlight_t *light) +static void R_Shadow_FreeWorldLight(dlight_t *light) { if (r_shadow_selectedlight == light) r_shadow_selectedlight = NULL; @@ -5019,10 +5395,9 @@ void R_Shadow_ClearWorldLights(void) R_Shadow_FreeWorldLight(light); } r_shadow_selectedlight = NULL; - R_Shadow_FreeCubemaps(); } -void R_Shadow_SelectLight(dlight_t *light) +static void R_Shadow_SelectLight(dlight_t *light) { if (r_shadow_selectedlight) r_shadow_selectedlight->selected = false; @@ -5031,16 +5406,16 @@ void R_Shadow_SelectLight(dlight_t *light) r_shadow_selectedlight->selected = true; } -void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist) +static void R_Shadow_DrawCursor_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist) { // this is never batched (there can be only one) float vertex3f[12]; R_CalcSprite_Vertex3f(vertex3f, r_editlights_cursorlocation, r_refdef.view.right, r_refdef.view.up, EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, -EDLIGHTSPRSIZE, EDLIGHTSPRSIZE); RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false); - R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false); + R_DrawCustomSurface(r_editlights_sprcursor, &identitymatrix, MATERIALFLAG_NODEPTHTEST | MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false); } -void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist) +static void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist) { float intensity; float s; @@ -5073,13 +5448,13 @@ void R_Shadow_DrawLightSprite_TransparentCallback(const entity_render_t *ent, co skinframe = r_editlights_sprlight; RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, spritecolor[0], spritecolor[1], spritecolor[2], 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false); - R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false); + R_DrawCustomSurface(skinframe, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false); // draw selection sprite if light is selected if (light->selected) { RSurf_ActiveCustomEntity(&identitymatrix, &identitymatrix, 0, 0, 1, 1, 1, 1, 4, vertex3f, spritetexcoord2f, NULL, NULL, NULL, NULL, 2, polygonelement3i, polygonelement3s, false, false); - R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false); + R_DrawCustomSurface(r_editlights_sprselection, &identitymatrix, MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOCULLFACE, 0, 4, 0, 2, false, false); // VorteX todo: add normalmode/realtime mode light overlay sprites? } } @@ -5093,9 +5468,10 @@ void R_Shadow_DrawLightSprites(void) { light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); if (light) - R_MeshQueue_AddTransparent(light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight); + R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, light->origin, R_Shadow_DrawLightSprite_TransparentCallback, (entity_render_t *)light, 5, &light->rtlight); } - R_MeshQueue_AddTransparent(r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL); + if (!r_editlights_lockcursor) + R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, r_editlights_cursorlocation, R_Shadow_DrawCursor_TransparentCallback, NULL, 0, NULL); } int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radius, float *color) @@ -5118,7 +5494,7 @@ int R_Shadow_GetRTLightInfo(unsigned int lightindex, float *origin, float *radiu return 1; } -void R_Shadow_SelectLightInView(void) +static void R_Shadow_SelectLightInView(void) { float bestrating, rating, temp[3]; dlight_t *best; @@ -5127,6 +5503,9 @@ void R_Shadow_SelectLightInView(void) size_t range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked best = NULL; bestrating = 0; + + if (r_editlights_lockcursor) + return; for (lightindex = 0;lightindex < range;lightindex++) { light = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, lightindex); @@ -5137,7 +5516,7 @@ void R_Shadow_SelectLightInView(void) if (rating >= 0.95) { rating /= (1 + 0.0625f * sqrt(DotProduct(temp, temp))); - if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction == 1.0f) + if (bestrating < rating && CL_TraceLine(light->origin, r_refdef.view.origin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1.0f) { bestrating = rating; best = light; @@ -5157,8 +5536,7 @@ void R_Shadow_LoadWorldLights(void) Con_Print("No map loaded.\n"); return; } - FS_StripExtension (cl.worldmodel->name, name, sizeof (name)); - strlcat (name, ".rtlights", sizeof (name)); + dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension); lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL); if (lightsstring) { @@ -5166,8 +5544,8 @@ void R_Shadow_LoadWorldLights(void) n = 0; while (*s) { - t = s; /* + t = s; shadow = true; for (;COM_Parse(t, true) && strcmp( if (COM_Parse(t, true)) @@ -5268,8 +5646,7 @@ void R_Shadow_SaveWorldLights(void) Con_Print("No map loaded.\n"); return; } - FS_StripExtension (cl.worldmodel->name, name, sizeof (name)); - strlcat (name, ".rtlights", sizeof (name)); + dpsnprintf(name, sizeof(name), "%s.rtlights", cl.worldnamenoextension); bufchars = bufmaxchars = 0; buf = NULL; for (lightindex = 0;lightindex < range;lightindex++) @@ -5317,8 +5694,7 @@ void R_Shadow_LoadLightsFile(void) Con_Print("No map loaded.\n"); return; } - FS_StripExtension (cl.worldmodel->name, name, sizeof (name)); - strlcat (name, ".lights", sizeof (name)); + dpsnprintf(name, sizeof(name), "%s.lights", cl.worldnamenoextension); lightsstring = (char *)FS_LoadFile(name, tempmempool, false, NULL); if (lightsstring) { @@ -5361,11 +5737,19 @@ typedef enum lighttype_e {LIGHTTYPE_MINUSX, LIGHTTYPE_RECIPX, LIGHTTYPE_RECIPXX, void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) { - int entnum, style, islight, skin, pflags, effects, type, n; + int entnum; + int style; + int islight; + int skin; + int pflags; + //int effects; + int type; + int n; char *entfiledata; const char *data; float origin[3], angles[3], radius, color[3], light[4], fadescale, lightscale, originhack[3], overridecolor[3], vec[4]; char key[256], value[MAX_INPUTLINE]; + char vabuf[1024]; if (cl.worldmodel == NULL) { @@ -5373,15 +5757,14 @@ void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) return; } // try to load a .ent file first - FS_StripExtension (cl.worldmodel->name, key, sizeof (key)); - strlcat (key, ".ent", sizeof (key)); + dpsnprintf(key, sizeof(key), "%s.ent", cl.worldnamenoextension); data = entfiledata = (char *)FS_LoadFile(key, tempmempool, true, NULL); // and if that is not found, fall back to the bsp file entity string if (!data) data = cl.worldmodel->brush.entities; if (!data) return; - for (entnum = 0;COM_ParseToken_Simple(&data, false, false) && com_token[0] == '{';entnum++) + for (entnum = 0;COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{';entnum++) { type = LIGHTTYPE_MINUSX; origin[0] = origin[1] = origin[2] = 0; @@ -5395,11 +5778,11 @@ void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) style = 0; skin = 0; pflags = 0; - effects = 0; + //effects = 0; islight = false; while (1) { - if (!COM_ParseToken_Simple(&data, false, false)) + if (!COM_ParseToken_Simple(&data, false, false, true)) break; // error if (com_token[0] == '}') break; // end of entity @@ -5409,7 +5792,7 @@ void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) strlcpy(key, com_token, sizeof(key)); while (key[strlen(key)-1] == ' ') // remove trailing spaces key[strlen(key)-1] = 0; - if (!COM_ParseToken_Simple(&data, false, false)) + if (!COM_ParseToken_Simple(&data, false, false, true)) break; // error strlcpy(value, com_token, sizeof(value)); @@ -5522,8 +5905,8 @@ void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) skin = (int)atof(value); else if (!strcmp("pflags", key)) pflags = (int)atof(value); - else if (!strcmp("effects", key)) - effects = (int)atof(value); + //else if (!strcmp("effects", key)) + // effects = (int)atof(value); else if (cl.worldmodel->type == mod_brushq3) { if (!strcmp("scale", key)) @@ -5570,20 +5953,20 @@ void R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(void) } VectorAdd(origin, originhack, origin); if (radius >= 1) - R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va("cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE); + R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), origin, angles, color, radius, (pflags & PFLAGS_CORONA) != 0, style, (pflags & PFLAGS_NOSHADOW) == 0, skin >= 16 ? va(vabuf, sizeof(vabuf), "cubemaps/%i", skin) : NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE); } if (entfiledata) Mem_Free(entfiledata); } -void R_Shadow_SetCursorLocationForView(void) +static void R_Shadow_SetCursorLocationForView(void) { vec_t dist, push; vec3_t dest, endpos; trace_t trace; VectorMA(r_refdef.view.origin, r_editlights_cursordistance.value, r_refdef.view.forward, dest); - trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false); + trace = CL_TraceLine(r_refdef.view.origin, dest, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true); if (trace.fraction < 1) { dist = trace.fraction * r_editlights_cursordistance.value; @@ -5614,7 +5997,7 @@ void R_Shadow_UpdateWorldLightSelection(void) R_Shadow_SelectLight(NULL); } -void R_Shadow_EditLights_Clear_f(void) +static void R_Shadow_EditLights_Clear_f(void) { R_Shadow_ClearWorldLights(); } @@ -5623,7 +6006,7 @@ void R_Shadow_EditLights_Reload_f(void) { if (!cl.worldmodel) return; - strlcpy(r_shadow_mapname, cl.worldmodel->name, sizeof(r_shadow_mapname)); + strlcpy(r_shadow_mapname, cl.worldname, sizeof(r_shadow_mapname)); R_Shadow_ClearWorldLights(); R_Shadow_LoadWorldLights(); if (!Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)) @@ -5634,26 +6017,26 @@ void R_Shadow_EditLights_Reload_f(void) } } -void R_Shadow_EditLights_Save_f(void) +static void R_Shadow_EditLights_Save_f(void) { if (!cl.worldmodel) return; R_Shadow_SaveWorldLights(); } -void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void) +static void R_Shadow_EditLights_ImportLightEntitiesFromMap_f(void) { R_Shadow_ClearWorldLights(); R_Shadow_LoadWorldLightsFromMap_LightArghliteTyrlite(); } -void R_Shadow_EditLights_ImportLightsFile_f(void) +static void R_Shadow_EditLights_ImportLightsFile_f(void) { R_Shadow_ClearWorldLights(); R_Shadow_LoadLightsFile(); } -void R_Shadow_EditLights_Spawn_f(void) +static void R_Shadow_EditLights_Spawn_f(void) { vec3_t color; if (!r_editlights.integer) @@ -5670,7 +6053,7 @@ void R_Shadow_EditLights_Spawn_f(void) R_Shadow_UpdateWorldLight(R_Shadow_NewWorldLight(), r_editlights_cursorlocation, vec3_origin, color, 200, 0, 0, true, NULL, 0.25, 0, 1, 1, LIGHTFLAG_REALTIMEMODE); } -void R_Shadow_EditLights_Edit_f(void) +static void R_Shadow_EditLights_Edit_f(void) { vec3_t origin, angles, color; vec_t radius, corona, coronasizescale, ambientscale, diffusescale, specularscale; @@ -5715,6 +6098,17 @@ void R_Shadow_EditLights_Edit_f(void) origin[1] = atof(Cmd_Argv(3)); origin[2] = atof(Cmd_Argv(4)); } + else if (!strcmp(Cmd_Argv(1), "originscale")) + { + if (Cmd_Argc() != 5) + { + Con_Printf("usage: r_editlights_edit %s x y z\n", Cmd_Argv(1)); + return; + } + origin[0] *= atof(Cmd_Argv(2)); + origin[1] *= atof(Cmd_Argv(3)); + origin[2] *= atof(Cmd_Argv(4)); + } else if (!strcmp(Cmd_Argv(1), "originx")) { if (Cmd_Argc() != 3) @@ -5985,10 +6379,10 @@ void R_Shadow_EditLights_Edit_f(void) R_Shadow_UpdateWorldLight(r_shadow_selectedlight, origin, angles, color, radius, corona, style, shadows, cubemapname, coronasizescale, ambientscale, diffusescale, specularscale, flags); } -void R_Shadow_EditLights_EditAll_f(void) +static void R_Shadow_EditLights_EditAll_f(void) { size_t lightindex; - dlight_t *light; + dlight_t *light, *oldselected; size_t range; if (!r_editlights.integer) @@ -5997,6 +6391,7 @@ void R_Shadow_EditLights_EditAll_f(void) return; } + oldselected = r_shadow_selectedlight; // EditLights doesn't seem to have a "remove" command or something so: range = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); // checked for (lightindex = 0;lightindex < range;lightindex++) @@ -6007,6 +6402,8 @@ void R_Shadow_EditLights_EditAll_f(void) R_Shadow_SelectLight(light); R_Shadow_EditLights_Edit_f(); } + // return to old selected (to not mess editing once selection is locked) + R_Shadow_SelectLight(oldselected); } void R_Shadow_EditLights_DrawSelectedLightProperties(void) @@ -6014,10 +6411,37 @@ void R_Shadow_EditLights_DrawSelectedLightProperties(void) int lightnumber, lightcount; size_t lightindex, range; dlight_t *light; - float x, y; char temp[256]; + float x, y; + if (!r_editlights.integer) return; + + // update cvars so QC can query them + if (r_shadow_selectedlight) + { + dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]); + Cvar_SetQuick(&r_editlights_current_origin, temp); + dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]); + Cvar_SetQuick(&r_editlights_current_angles, temp); + dpsnprintf(temp, sizeof(temp), "%f %f %f", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]); + Cvar_SetQuick(&r_editlights_current_color, temp); + Cvar_SetValueQuick(&r_editlights_current_radius, r_shadow_selectedlight->radius); + Cvar_SetValueQuick(&r_editlights_current_corona, r_shadow_selectedlight->corona); + Cvar_SetValueQuick(&r_editlights_current_coronasize, r_shadow_selectedlight->coronasizescale); + Cvar_SetValueQuick(&r_editlights_current_style, r_shadow_selectedlight->style); + Cvar_SetValueQuick(&r_editlights_current_shadows, r_shadow_selectedlight->shadow); + Cvar_SetQuick(&r_editlights_current_cubemap, r_shadow_selectedlight->cubemapname); + Cvar_SetValueQuick(&r_editlights_current_ambient, r_shadow_selectedlight->ambientscale); + Cvar_SetValueQuick(&r_editlights_current_diffuse, r_shadow_selectedlight->diffusescale); + Cvar_SetValueQuick(&r_editlights_current_specular, r_shadow_selectedlight->specularscale); + Cvar_SetValueQuick(&r_editlights_current_normalmode, (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? 1 : 0); + Cvar_SetValueQuick(&r_editlights_current_realtimemode, (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? 1 : 0); + } + + // draw properties on screen + if (!r_editlights_drawproperties.integer) + return; x = vid_conwidth.value - 240; y = 5; DrawQ_Pic(x-5, y-5, NULL, 250, 155, 0, 0, 0, 0.75, 0); @@ -6033,29 +6457,29 @@ void R_Shadow_EditLights_DrawSelectedLightProperties(void) lightnumber = lightindex; lightcount++; } - dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8; - dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false);y += 8; + dpsnprintf(temp, sizeof(temp), "Cursor origin: %.0f %.0f %.0f", r_editlights_cursorlocation[0], r_editlights_cursorlocation[1], r_editlights_cursorlocation[2]); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Total lights : %i active (%i total)", lightcount, (int)Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray)); DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, false, FONT_DEFAULT);y += 8; y += 8; if (r_shadow_selectedlight == NULL) return; - dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Origin : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Angles : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Color : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Radius : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Corona : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Style : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Cubemap : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "CoronaSize : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Ambient : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Diffuse : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "Specular : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; - dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true);y += 8; + dpsnprintf(temp, sizeof(temp), "Light #%i properties:", lightnumber);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Origin : %.0f %.0f %.0f\n", r_shadow_selectedlight->origin[0], r_shadow_selectedlight->origin[1], r_shadow_selectedlight->origin[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Angles : %.0f %.0f %.0f\n", r_shadow_selectedlight->angles[0], r_shadow_selectedlight->angles[1], r_shadow_selectedlight->angles[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Color : %.2f %.2f %.2f\n", r_shadow_selectedlight->color[0], r_shadow_selectedlight->color[1], r_shadow_selectedlight->color[2]);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Radius : %.0f\n", r_shadow_selectedlight->radius);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Corona : %.0f\n", r_shadow_selectedlight->corona);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Style : %i\n", r_shadow_selectedlight->style);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Shadows : %s\n", r_shadow_selectedlight->shadow ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Cubemap : %s\n", r_shadow_selectedlight->cubemapname);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "CoronaSize : %.2f\n", r_shadow_selectedlight->coronasizescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Ambient : %.2f\n", r_shadow_selectedlight->ambientscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Diffuse : %.2f\n", r_shadow_selectedlight->diffusescale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "Specular : %.2f\n", r_shadow_selectedlight->specularscale);DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "NormalMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_NORMALMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; + dpsnprintf(temp, sizeof(temp), "RealTimeMode : %s\n", (r_shadow_selectedlight->flags & LIGHTFLAG_REALTIMEMODE) ? "yes" : "no");DrawQ_String(x, y, temp, 0, 8, 8, 1, 1, 1, 1, 0, NULL, true, FONT_DEFAULT);y += 8; } -void R_Shadow_EditLights_ToggleShadow_f(void) +static void R_Shadow_EditLights_ToggleShadow_f(void) { if (!r_editlights.integer) { @@ -6070,7 +6494,7 @@ void R_Shadow_EditLights_ToggleShadow_f(void) R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, r_shadow_selectedlight->corona, r_shadow_selectedlight->style, !r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags); } -void R_Shadow_EditLights_ToggleCorona_f(void) +static void R_Shadow_EditLights_ToggleCorona_f(void) { if (!r_editlights.integer) { @@ -6085,7 +6509,7 @@ void R_Shadow_EditLights_ToggleCorona_f(void) R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_selectedlight->angles, r_shadow_selectedlight->color, r_shadow_selectedlight->radius, !r_shadow_selectedlight->corona, r_shadow_selectedlight->style, r_shadow_selectedlight->shadow, r_shadow_selectedlight->cubemapname, r_shadow_selectedlight->coronasizescale, r_shadow_selectedlight->ambientscale, r_shadow_selectedlight->diffusescale, r_shadow_selectedlight->specularscale, r_shadow_selectedlight->flags); } -void R_Shadow_EditLights_Remove_f(void) +static void R_Shadow_EditLights_Remove_f(void) { if (!r_editlights.integer) { @@ -6101,7 +6525,7 @@ void R_Shadow_EditLights_Remove_f(void) r_shadow_selectedlight = NULL; } -void R_Shadow_EditLights_Help_f(void) +static void R_Shadow_EditLights_Help_f(void) { Con_Print( "Documentation on r_editlights system:\n" @@ -6116,6 +6540,7 @@ void R_Shadow_EditLights_Help_f(void) "r_editlights_help : this help\n" "r_editlights_clear : remove all lights\n" "r_editlights_reload : reload .rtlights, .lights file, or entities\n" +"r_editlights_lock : lock selection to current light, if already locked - unlock\n" "r_editlights_save : save to .rtlights file\n" "r_editlights_spawn : create a light with default settings\n" "r_editlights_edit command : edit selected light - more documentation below\n" @@ -6142,8 +6567,9 @@ void R_Shadow_EditLights_Help_f(void) "colorscale r g b : multiply color of light (1 1 1 does nothing)\n" "radiusscale scale : multiply radius (size) of light (1 does nothing)\n" "sizescale scale : multiply radius (size) of light (1 does nothing)\n" +"originscale x y z : multiply origin of light (1 1 1 does nothing)\n" "style style : set lightstyle of light (flickering patterns, switches, etc)\n" -"cubemap basename : set filter cubemap of light (not yet supported)\n" +"cubemap basename : set filter cubemap of light\n" "shadows 1/0 : turn on/off shadows\n" "corona n : set corona intensity\n" "coronasize n : set corona size (0-1)\n" @@ -6156,7 +6582,7 @@ void R_Shadow_EditLights_Help_f(void) ); } -void R_Shadow_EditLights_CopyInfo_f(void) +static void R_Shadow_EditLights_CopyInfo_f(void) { if (!r_editlights.integer) { @@ -6185,7 +6611,7 @@ void R_Shadow_EditLights_CopyInfo_f(void) r_shadow_bufferlight.flags = r_shadow_selectedlight->flags; } -void R_Shadow_EditLights_PasteInfo_f(void) +static void R_Shadow_EditLights_PasteInfo_f(void) { if (!r_editlights.integer) { @@ -6200,7 +6626,27 @@ void R_Shadow_EditLights_PasteInfo_f(void) R_Shadow_UpdateWorldLight(r_shadow_selectedlight, r_shadow_selectedlight->origin, r_shadow_bufferlight.angles, r_shadow_bufferlight.color, r_shadow_bufferlight.radius, r_shadow_bufferlight.corona, r_shadow_bufferlight.style, r_shadow_bufferlight.shadow, r_shadow_bufferlight.cubemapname, r_shadow_bufferlight.coronasizescale, r_shadow_bufferlight.ambientscale, r_shadow_bufferlight.diffusescale, r_shadow_bufferlight.specularscale, r_shadow_bufferlight.flags); } -void R_Shadow_EditLights_Init(void) +static void R_Shadow_EditLights_Lock_f(void) +{ + if (!r_editlights.integer) + { + Con_Print("Cannot lock on light when not in editing mode. Set r_editlights to 1.\n"); + return; + } + if (r_editlights_lockcursor) + { + r_editlights_lockcursor = false; + return; + } + if (!r_shadow_selectedlight) + { + Con_Print("No selected light to lock on.\n"); + return; + } + r_editlights_lockcursor = true; +} + +static void R_Shadow_EditLights_Init(void) { Cvar_RegisterVariable(&r_editlights); Cvar_RegisterVariable(&r_editlights_cursordistance); @@ -6208,6 +6654,21 @@ void R_Shadow_EditLights_Init(void) Cvar_RegisterVariable(&r_editlights_cursorpushoff); Cvar_RegisterVariable(&r_editlights_cursorgrid); Cvar_RegisterVariable(&r_editlights_quakelightsizescale); + Cvar_RegisterVariable(&r_editlights_drawproperties); + Cvar_RegisterVariable(&r_editlights_current_origin); + Cvar_RegisterVariable(&r_editlights_current_angles); + Cvar_RegisterVariable(&r_editlights_current_color); + Cvar_RegisterVariable(&r_editlights_current_radius); + Cvar_RegisterVariable(&r_editlights_current_corona); + Cvar_RegisterVariable(&r_editlights_current_coronasize); + Cvar_RegisterVariable(&r_editlights_current_style); + Cvar_RegisterVariable(&r_editlights_current_shadows); + Cvar_RegisterVariable(&r_editlights_current_cubemap); + Cvar_RegisterVariable(&r_editlights_current_ambient); + Cvar_RegisterVariable(&r_editlights_current_diffuse); + Cvar_RegisterVariable(&r_editlights_current_specular); + Cvar_RegisterVariable(&r_editlights_current_normalmode); + Cvar_RegisterVariable(&r_editlights_current_realtimemode); Cmd_AddCommand("r_editlights_help", R_Shadow_EditLights_Help_f, "prints documentation on console commands and variables in rtlight editing system"); Cmd_AddCommand("r_editlights_clear", R_Shadow_EditLights_Clear_f, "removes all world lights (let there be darkness!)"); Cmd_AddCommand("r_editlights_reload", R_Shadow_EditLights_Reload_f, "reloads rtlights file (or imports from .lights file or .ent file or the map itself)"); @@ -6222,6 +6683,7 @@ void R_Shadow_EditLights_Init(void) Cmd_AddCommand("r_editlights_importlightsfile", R_Shadow_EditLights_ImportLightsFile_f, "load lights from .lights file (ignoring .rtlights or .ent files and map entities)"); Cmd_AddCommand("r_editlights_copyinfo", R_Shadow_EditLights_CopyInfo_f, "store a copy of all properties (except origin) of the selected light"); Cmd_AddCommand("r_editlights_pasteinfo", R_Shadow_EditLights_PasteInfo_f, "apply the stored properties onto the selected light (making it exactly identical except for origin)"); + Cmd_AddCommand("r_editlights_lock", R_Shadow_EditLights_Lock_f, "lock selection to current light, if already locked - unlock"); } @@ -6234,31 +6696,224 @@ LIGHT SAMPLING ============================================================================= */ -void R_CompleteLightPoint(vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const vec3_t p, int dynamic) +void R_LightPoint(float *color, const vec3_t p, const int flags) { - VectorClear(diffusecolor); - VectorClear(diffusenormal); + int i, numlights, flag; + float f, relativepoint[3], dist, dist2, lightradius2; + vec3_t diffuse, n; + rtlight_t *light; + dlight_t *dlight; + + if (r_fullbright.integer) + { + VectorSet(color, 1, 1, 1); + return; + } + + VectorClear(color); - if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->brush.LightPoint) + if (flags & LP_LIGHTMAP) { - ambientcolor[0] = ambientcolor[1] = ambientcolor[2] = r_refdef.scene.ambient * (2.0f / 128.0f); - r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambientcolor, diffusecolor, diffusenormal); + if (!r_fullbright.integer && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint) + { + VectorClear(diffuse); + r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, color, diffuse, n); + VectorAdd(color, diffuse, color); + } + else + VectorSet(color, 1, 1, 1); + color[0] += r_refdef.scene.ambient; + color[1] += r_refdef.scene.ambient; + color[2] += r_refdef.scene.ambient; + } + + if (flags & LP_RTWORLD) + { + flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); + for (i = 0; i < numlights; i++) + { + dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i); + if (!dlight) + continue; + light = &dlight->rtlight; + if (!(light->flags & flag)) + continue; + // sample + lightradius2 = light->radius * light->radius; + VectorSubtract(light->shadoworigin, p, relativepoint); + dist2 = VectorLength2(relativepoint); + if (dist2 >= lightradius2) + continue; + dist = sqrt(dist2) / light->radius; + f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0; + if (f <= 0) + continue; + // todo: add to both ambient and diffuse + if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1) + VectorMA(color, f, light->currentcolor, color); + } + } + if (flags & LP_DYNLIGHT) + { + // sample dlights + for (i = 0;i < r_refdef.scene.numlights;i++) + { + light = r_refdef.scene.lights[i]; + // sample + lightradius2 = light->radius * light->radius; + VectorSubtract(light->shadoworigin, p, relativepoint); + dist2 = VectorLength2(relativepoint); + if (dist2 >= lightradius2) + continue; + dist = sqrt(dist2) / light->radius; + f = dist < 1 ? (r_shadow_lightintensityscale.value * ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist))) : 0; + if (f <= 0) + continue; + // todo: add to both ambient and diffuse + if (!light->shadow || CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction == 1) + VectorMA(color, f, light->color, color); + } + } +} + +void R_CompleteLightPoint(vec3_t ambient, vec3_t diffuse, vec3_t lightdir, const vec3_t p, const int flags) +{ + int i, numlights, flag; + rtlight_t *light; + dlight_t *dlight; + float relativepoint[3]; + float color[3]; + float dir[3]; + float dist; + float dist2; + float intensity; + float sample[5*3]; + float lightradius2; + + if (r_fullbright.integer) + { + VectorSet(ambient, 1, 1, 1); + VectorClear(diffuse); + VectorClear(lightdir); + return; + } + + if (flags == LP_LIGHTMAP) + { + VectorSet(ambient, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient); + VectorClear(diffuse); + VectorClear(lightdir); + if (r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint) + r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, ambient, diffuse, lightdir); + else + VectorSet(ambient, 1, 1, 1); + return; + } + + memset(sample, 0, sizeof(sample)); + VectorSet(sample, r_refdef.scene.ambient, r_refdef.scene.ambient, r_refdef.scene.ambient); + + if ((flags & LP_LIGHTMAP) && r_refdef.scene.worldmodel && r_refdef.scene.worldmodel->lit && r_refdef.scene.worldmodel->brush.LightPoint) + { + vec3_t tempambient; + VectorClear(tempambient); + VectorClear(color); + VectorClear(relativepoint); + r_refdef.scene.worldmodel->brush.LightPoint(r_refdef.scene.worldmodel, p, tempambient, color, relativepoint); + VectorScale(tempambient, r_refdef.lightmapintensity, tempambient); + VectorScale(color, r_refdef.lightmapintensity, color); + VectorAdd(sample, tempambient, sample); + VectorMA(sample , 0.5f , color, sample ); + VectorMA(sample + 3, relativepoint[0], color, sample + 3); + VectorMA(sample + 6, relativepoint[1], color, sample + 6); + VectorMA(sample + 9, relativepoint[2], color, sample + 9); + // calculate a weighted average light direction as well + intensity = VectorLength(color); + VectorMA(sample + 12, intensity, relativepoint, sample + 12); + } + + if (flags & LP_RTWORLD) + { + flag = r_refdef.scene.rtworld ? LIGHTFLAG_REALTIMEMODE : LIGHTFLAG_NORMALMODE; + numlights = Mem_ExpandableArray_IndexRange(&r_shadow_worldlightsarray); + for (i = 0; i < numlights; i++) + { + dlight = (dlight_t *) Mem_ExpandableArray_RecordAtIndex(&r_shadow_worldlightsarray, i); + if (!dlight) + continue; + light = &dlight->rtlight; + if (!(light->flags & flag)) + continue; + // sample + lightradius2 = light->radius * light->radius; + VectorSubtract(light->shadoworigin, p, relativepoint); + dist2 = VectorLength2(relativepoint); + if (dist2 >= lightradius2) + continue; + dist = sqrt(dist2) / light->radius; + intensity = min(1.0f, (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) * r_shadow_lightintensityscale.value; + if (intensity <= 0.0f) + continue; + if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1) + continue; + // scale down intensity to add to both ambient and diffuse + //intensity *= 0.5f; + VectorNormalize(relativepoint); + VectorScale(light->currentcolor, intensity, color); + VectorMA(sample , 0.5f , color, sample ); + VectorMA(sample + 3, relativepoint[0], color, sample + 3); + VectorMA(sample + 6, relativepoint[1], color, sample + 6); + VectorMA(sample + 9, relativepoint[2], color, sample + 9); + // calculate a weighted average light direction as well + intensity *= VectorLength(color); + VectorMA(sample + 12, intensity, relativepoint, sample + 12); + } + // FIXME: sample bouncegrid too! } - else - VectorSet(ambientcolor, 1, 1, 1); - if (dynamic) + if (flags & LP_DYNLIGHT) { - int i; - float f, v[3]; - rtlight_t *light; + // sample dlights for (i = 0;i < r_refdef.scene.numlights;i++) { light = r_refdef.scene.lights[i]; - Matrix4x4_Transform(&light->matrix_worldtolight, p, v); - f = 1 - VectorLength2(v); - if (f > 0 && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false).fraction == 1) - VectorMA(ambientcolor, f, light->currentcolor, ambientcolor); + // sample + lightradius2 = light->radius * light->radius; + VectorSubtract(light->shadoworigin, p, relativepoint); + dist2 = VectorLength2(relativepoint); + if (dist2 >= lightradius2) + continue; + dist = sqrt(dist2) / light->radius; + intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist) * r_shadow_lightintensityscale.value; + if (intensity <= 0.0f) + continue; + if (light->shadow && CL_TraceLine(p, light->shadoworigin, MOVE_NOMONSTERS, NULL, SUPERCONTENTS_SOLID, true, false, NULL, false, true).fraction < 1) + continue; + // scale down intensity to add to both ambient and diffuse + //intensity *= 0.5f; + VectorNormalize(relativepoint); + VectorScale(light->currentcolor, intensity, color); + VectorMA(sample , 0.5f , color, sample ); + VectorMA(sample + 3, relativepoint[0], color, sample + 3); + VectorMA(sample + 6, relativepoint[1], color, sample + 6); + VectorMA(sample + 9, relativepoint[2], color, sample + 9); + // calculate a weighted average light direction as well + intensity *= VectorLength(color); + VectorMA(sample + 12, intensity, relativepoint, sample + 12); } } + + // calculate the direction we'll use to reduce the sample to a directional light source + VectorCopy(sample + 12, dir); + //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]); + VectorNormalize(dir); + // extract the diffuse color along the chosen direction and scale it + diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]); + diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]); + diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]); + // subtract some of diffuse from ambient + VectorMA(sample, -0.333f, diffuse, ambient); + // store the normalized lightdir + VectorCopy(dir, lightdir); }