/////////////////////////////////////////////////////////////////////// // Billboard Shaders // // *** INTERACTIVE DATA VISUALIZATION (IDV) PROPRIETARY INFORMATION *** // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Interactive Data Visualization and may // not be copied or disclosed except in accordance with the terms of // that agreement. // // Copyright (c) 2003-6 IDV, Inc. // All Rights Reserved. // // IDV, Inc. // Web: http://www.idvinc.com // // *** Release Version 4.0 *** /////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // stuff which should most certainly not be enabled in final build //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // visual aids are stuff like the thread profiler, light probe visualizer, ... // this should most certainly be disabled in final builds //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // standard defines //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define SCREEN_ROTATE_180 // rotates scene 180 degrees, this should theoretically give a slight gain; however, we don't see this. (speedtree?) //#define OCCLUSION_QUERIES_ENABLE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // radiosity+light probes are now integrated into the same gathering pass //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // defined by project settings //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // enable this to gather radiosity for the scene / enable the radiosity gathered //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // light probes integrate dynamic objects into the static world of indirect lighting //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define LIGHTPROBE_SAMPLES_DEBUG // shows where the probes will be, but does no actual sampling - this is for debugging //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // enable the vertex cube renderer if either radiosity or light probes are enabled //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // debug stuff //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // shadows - additional defines //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define SHADOWS_DEBUG_AID_ENABLE //#define SHADOWS_TRAPEZOIDAL_ZCORRECTED // really, really slow as sets the depth in the pixelshader //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // HDR range - rendering to 7e3 buffer //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // floating point rendertarget? // the 360 can't use a 10F_10F_10F as a texture, so we resolve as 10_10_10's, and convert to 10F's in the pixel shaders //#define USE_FP_RENDERTARGET_RUNTIME_CONVERSION //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // point light shadows on the PC are necessary for radiosity gathering, but too expensive otherwise //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // interpolator fixing - this is effectively hacking the VS->PS interpolators //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // this is starting to be a strain on the profiling.... //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define PIX_SET_MARKER_ENABLE //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // crash reporting? //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define USE_MORTENS_DODGY_MEMORY_TRACKER //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // if this is enabled, fog blending will use the color of the atmospheric scattering - if not, a static value is used //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // multithreaded FIND_ALL_DATA? //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //PS3 has been updated -- use this define in case it is ever required to revert to the old method -- contains multiple model bug //#define USE_OLD_SINGLE_PASS_FIND_FIRST_DATA //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // texture defines //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // THIS CAUSES AI CODE TO RUN IN A THREAD ALONGSIDE RENDERING // FRAMETIME SAVINGS ARE SIGNIFICANT /////////////////////////////////////////////////////////////////////// // Utility Effects // // *** INTERACTIVE DATA VISUALIZATION (IDV) PROPRIETARY INFORMATION *** // // This software is supplied under the terms of a license agreement or // nondisclosure agreement with Interactive Data Visualization and may // not be copied or disclosed except in accordance with the terms of // that agreement. // // Copyright (c) 2003-6 IDV, Inc. // All Rights Reserved. // // IDV, Inc. // Web: http://www.idvinc.com // // *** Release Version 4.0 *** // Some generic definitions to simplify shader code - Morv //!MP! I use this in shadows.h, so I can use the same header file for C code //MP! with hierarchical z-testing, this is no longer LE of all platforms // Some max-specific definitions //////////////////////////////////////////////////////////////////////////////////////////////////// // constants in HLSL //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // these are VERTEX SHADER constants //////////////////////////////////////////////////////////////////////////////////////////////////// // 15..26 used by generic constant table, and facial morphing weights float4 PA_StartColour : register(c9); float4 PA_EndColour : register(c10); float4 PA_StartMMEndMMSize : register(c11); float4 PA_Velocity_Alpha_Rotation_Min_AspectRatio : register(c14); float4 PA_Velocity_Alpha_Rotation_Max_Gravity : register(c15); float PA_DrawAsBillboard : register(c16); float4 SpreadNumParticlesAnimationCountLoopSystem : register(c18); float4 PA_MidMinMaxEndMinMaxVelocity : register(c19); float4 PA_EmissionArea : register(c21); float4 PA_ExpiryTime : register(c23); float4 PA_AnimationFrames : register(c24); float4 PA_Wind : register(c26); float4 ParticleFadeValue : register(c28); float4 Radiosity_YCbCr [3] : register(c36); float4 TrapezoidalShadowEpsilon : register(c39); float4 LightIndexScalar : register(c40); float4 LightIndexOffset : register(c41); float4 Foliage_Animation_Scalars : register(c42); float4 Foliage_Animation_Offsets : register(c43); float4 LeafUnitSquare [4] : register(c44); float4 FontXYScalarOffset : register(c48); float4 FontUVScalarOffset : register(c49); float4 VCMainLightDirection : register(c50); float4 CubeShadowMap_LightPosition : register(c51); float4 FarFogPlane : register(c52); float4 CharacterInertiaAndVertexScale : register(c53); float4 DualBumpLODBias : register(c54); float4 VertexBonePaletteTexture : register(c55); float4x4 ShadowMapMatrix : register(c56); float4x4 WorldViewProjection : register(c60); float4x4 WorldMatrix : register(c64); float4x4 ViewMatrix : register(c68); float4x4 ViewProj : register(c72); float4x4 TextureTransform : register(c76); float4 ScreenRes [2] : register(c80); float4 ParticleRoot : register(c88); float4 TimeIntoEffect : register(c89); float4 RadiosityInfluence : register(c90); float4 TexCoordScaleLODBlur : register(c91); // used by the cube variance shadow map blending float4x4 ProjMatrix : register(c92); float4 RicsFontShaderConstants : register(c100); float4 BillboardTextureCoords [60] : register(c100); float4 CameraRightAxis : register(c160); float4 CameraUpAxis : register(c161); float4 InstancingData : register(c162); float4 TreePos : register(c163); float4 TreeRot : register(c164); float4 TreeScale : register(c165); float4 WindSettings : register(c208); float4 SpeedTreeLightSettings : register(c209); float4 CameraAngles : register(c210); float4 SelfShadowMotion : register(c211); float4 LeafAngles [20] : register(c216); float4x4 BillboardNormals : register(c236); float4x4 BillboardBinormals : register(c240); float4x4 BillboardTangents : register(c244); float4 BillboardSpecialAzimuth : register(c248); float4 FoliageSettings : register(c249); float4 PS3StaticLightData [33 * 2] : register(c352); //////////////////////////////////////////////////////////////////////////////////////////////////// // these are PIXEL SHADER constants //////////////////////////////////////////////////////////////////////////////////////////////////// float4 FogColour : register(c0); float4 SpecularPower : register(c2); float4 MainLightInvColor : register(c7); // inverse direction light color - to show off bump maps float4 DualBumpNormalErrorThreshold : register(c8); float4 ShadowBias : register(c9); float4 MainLightDirection : register(c10); float4 MainLightColor : register(c11); float4 VarianceShadowMap_Setup : register(c12); float4 VarianceShadowMap_EdgeDelta : register(c13); float4 ShadowMapDimensions : register(c14); // 15..26 used by generic constant table float4 RadiosityCSC : register(c29); float4 RayleighMieConstants : register(c30); float BodySolidity : register(c31); float4 PostProcessing_BloomScalarOffset : register(c32); float4 PostProcessing_OverlaySettings : register(c33); float4 PostProcessing_Distortion : register(c34); // xy=distortion range, z=LOD range, w=luminance range float4 PostProcessing_TintScalar : register(c35); float4 PostProcessing_TintOffset : register(c36); float4 FilterOptions : register(c37); float4 DirectionalLightingIntensities : register(c38); float4 FogEquation [2] : register(c39); float4 HDR_Constants : register(c41); float4 AmbientDiffuse : register(c42); float4 DirectLightingInfluence : register(c43); float4 DynamicLightData [12] : register(c44); // 12 used (ie 4 lights, 1 extra just in case...), followed by static data float4 DynamicLight0_Data : register(c44); float4 DynamicLight1_Data : register(c47); float4 DynamicLight2_Data : register(c50); float4 DynamicLight3_Data : register(c53); float4 StaticLightData [96] : register(c56); float4 AmbientScalar : register(c142); // used by dynamic objects to offset the ambient values float4 AmbientOffset : register(c143); // ... float4 LightProbeColors [6] : register(c144); half4 PostProcessing_TintEq [4] : register(c150); float4 DOFFocalPointSpread : register(c154); float4 DOFReverseZPerspective : register(c155); float4 DOFKernelConstants : register(c156); float4 MotionBlurMovement : register(c157); float4 MotionBlurConstants : register(c158); float4x4 MotionBlurCurrInvViewProjection : register(c160); float4x4 MotionBlurPrevViewProjection : register(c164); float4 RayleighMieScatteringWavelengthsQuad : register(c168); // wavelengths used by rayleigh/mie to the 4th, ie "lambda^4" float4 CloudTextureDef0 : register(c169); // scrolling float4 CloudTextureDef1 : register(c170); // scrolling float4 CloudTextureDef2 : register(c171); // scrolling float4 CloudTextureDef3 : register(c172); // rotating float4 CloudBlendParams : register(c173); // blend params float4 RayleighMieSunPosition : register(c174); // blend params float4 RayleighMieRGBTranslation [3] : register(c175); // translates RGB -> whichever color float4 ShadowParameters : register(c179); // scalar, offset float4 ScreenResolution [4] : register(c180); // we only use 1, but we need 4 for tiled hack to work //////////////////////////////////////////////////////////////////////////////////////////////////// bool CubicShadowReceive : register(b0); bool RadiosityGatheringInProgress : register(b1); //////////////////////////////////////////////////////////////////////////////////////////////////// // these are VERTEX AND PIXEL SHADER constants //////////////////////////////////////////////////////////////////////////////////////////////////// float4 ConstantColour : register(c1); // !MP! do not rely on this; it's part of the old lighting system and will disappear after this milestone float4 TimeAndRainLevel : register(c3); // in .x float4 RainLevel : register(c3); // in .y float4 CameraPosition : register(c5); // 15..26 used by generic constant table //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // Generic constants (loaded into a table at c15, but the shaders that use them don't know that) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // radiosity backface hack //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float lfInputFaceDirection = 0.f; // less than ideal - this will internally be 'overwritten', if a variable of this name exists locally float4 BlankReverseSideDuringRadiosityGathering( float lfFaceDirection, float4 lOutputColor) { //not necessary any longer i think return lOutputColor; return lOutputColor; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // snow //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float3 SnowValue (float3 input_colour, float world_space_normal_y) { return lerp (input_colour, float3 (1, 1, 1), saturate (world_space_normal_y - 0.5f) * (TimeAndRainLevel.z)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // transformed vertex z position to pixel depth calculation : used for soft sprites //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float VertexToPixelDepth(float PositionZ) // PositionZ = mul(float4(world_pos, 1), ViewProj).z; { PositionZ = 1.f - PositionZ; // hierarchical z flips the range return DOFReverseZPerspective.x / (PositionZ * DOFReverseZPerspective.y - DOFReverseZPerspective.z); // m32/(o*m23-m22) } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // color range tweak //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static const float g_overbright = 32; // Ivan: experimentally shown that hdr range of 99% of the scene is 0..4 //static const float MAX_HDR_RANGE = 3.5f; // test stuff //half4 RGBHighlightRange( half4 c, float mv ) //{ // half scale = max( c.x, max( c.y, c.z ) ); // // if( scale > mv ) // { // c = half4( 1, 0, 0, 1 ); // } // // return c; //} // classic rgbs //half4 RGB_to_RGBS( half4 c ) //{ // half scale = max( c.x, max( c.y, c.z ) ); // // half3 rgb = c.xyz / scale; // half a = saturate( scale / MAX_HDR_RANGE ); // // return half4( rgb, a ); //} // classic rgbs //half4 RGBS_to_RGB( half4 c ) //{ // return half4( c.xyz * c.a * MAX_HDR_RANGE, c.a ); //} // classic exponential //half4 RGB_to_ScaledRGB( half4 c ) //{ // return half4( c.xyz / MAX_HDR_RANGE, c.a ); //} // classic exponential //half4 ScaledRGB_to_RGB( half4 c ) //{ // return half4( c.xyz * MAX_HDR_RANGE, c.a ); //} // classic exponential // TODO: use halfs throughout for better compilation //half4 RGB_to_PPP( half4 c ) //{ // return half4( sqrt( ( half3( c.xyz ) / half( MAX_HDR_RANGE ) ) ), c.a ); //} // classic exponential //half4 PPP_to_RGB( half4 c ) //{ // return half4( c.xyz * c.xyz * MAX_HDR_RANGE, c.a ); //} //float4 RGBA_to_SonyRGBS( float4 ) static const float fLinearRange = 2.f; // scales the output color float4 HDRColorCorrected(float4 lColor) { float3 corrected = lColor.xyz / fLinearRange; return float4( corrected, lColor.a ); } // scales the output color float4 HDRColorCorrected0(float4 lColor) { return float4( lColor.xyz / fLinearRange, lColor.a ); } // scales the output color half4 HDRColorCorrected(half4 lColor) { half3 corrected = lColor.xyz / (half)fLinearRange; return half4( corrected, lColor.a ); } float4 HDRColorReverted(float4 lColor) { float multiply = lColor.a == 0 ? g_overbright : 1; return float4( lColor.xyz * fLinearRange * multiply, 1.f ); } half4 HDRColorReverted(half4 lColor) { half multiply = lColor.a == 0 ? (half)g_overbright : 1; return half4( lColor.xyz * (half)fLinearRange * multiply, 1.f ); } float4 HDRForceReversion(float4 lColor) { return lColor; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // normal = tangent X normal //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float3 CreateBinormal( float3 lNormal, float3 lTangent) { //!MP! i actually thought it was the other way around, but this produces consistent results return cross(lTangent,lNormal); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // color space conversion //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // performs color space conversion float3 ConvertYCbCr2RGB( float3 lYCbCr) { float3x4 lNewMatrix; // Keef - Casting to float3x4 doesn't work with Cg for some reason lNewMatrix._m00_m01_m02_m03 = Radiosity_YCbCr[0]; lNewMatrix._m10_m11_m12_m13 = Radiosity_YCbCr[1]; lNewMatrix._m20_m21_m22_m23 = Radiosity_YCbCr[2]; //!MP! the PS3 should use this version as well return max(0,mul(lNewMatrix,float4(lYCbCr,1))); } // we use YCbCr rather than YUV due to YUV's limited range float3 DecompressYCbCr844( int2 lYCbCr) { // get Y:8,Cb:4,Cr:4 from the zw components (Cb,Cr are packed into the second byte) float lfY = lYCbCr.x; float lfCr = lYCbCr.y*0.0625f; //1/16 float lfCb = floor(lfCr); lfCr = lfCr-lfCb; float4 lfYCbCr1 = float4(lfY,lfCb,lfCr,1); // Keef - Casting to float3x4 doesn't work with Cg for some reason float3x4 lNewMatrix; lNewMatrix._m00_m01_m02_m03 = Radiosity_YCbCr[0]; lNewMatrix._m10_m11_m12_m13 = Radiosity_YCbCr[1]; lNewMatrix._m20_m21_m22_m23 = Radiosity_YCbCr[2]; float3 lRGB = saturate(mul(lNewMatrix,lfYCbCr1)); return lRGB; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // character UV scalar - centralized, as editing only the standard shaders mess up the shadows //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //The 360 FXLite differs from the PC FX interfaces in one important area. //The textures can only be shared on the PC and the 360 can only share and read samplers. //So when you need to define and use a texture and sampler use the macros below. // Max MapChannels make me cry // #define _USE_INSTANCING_ // #define BRANCH_DETAIL_LAYER float3 test_ambient = float3(0.8f, 0.8f, 0.8f); /////////////////////////////////////////////////////////////////////// // Modulate_Float float Modulate_Float(float x, float y) { return x - (int(x / y) * y); } /////////////////////////////////////////////////////////////////////// // LightDiffse // // Very simple lighting equation, used by the fronds and leaves (branches // are normal mapped). /* float3 LightDiffse(float3 vVertex, float3 vNormal, float3 vLightDir, float3 vLightColor, float3 vDiffuseMaterial) { // return vLightColor * max(dot(vNormal, vLightDir), 0.0f); return vLightColor * max(dot(vNormal, vLightDir), vDiffuseMaterial); } */ float3 LightDiffuse(float3 vVertex, float3 vNormal, float3 vLightDir, float3 vLightColor, float3 vDiffuseMaterial) { // return vDiffuseMaterial * vLightColor * max(dot(vNormal, vLightDir), 0); return vDiffuseMaterial * vLightColor * dot(vLightDir, vNormal); } /////////////////////////////////////////////////////////////////////// // LightDiffse_Capped // // Very simple lighting equation, used by the fronds and leaves (branches // are normal mapped). float3 LightDiffse_Capped(float3 vVertex, float3 vNormal, float3 vLightDir, float3 vLightColor, float3 vDiffuseMaterial) { float fDotProduct = max(dot(vNormal, vLightDir), 0.0f); fDotProduct = clamp(fDotProduct, 0, 1); fDotProduct = lerp(SpeedTreeLightSettings.y, 1.0f, fDotProduct); // return vDiffuseMaterial * vLightColor * fDotProduct; return vLightColor * fDotProduct; } /////////////////////////////////////////////////////////////////////// // RotationMatrix_zAxis // // Constructs a Z-axis rotation matrix float3x3 RotationMatrix_zAxis(float fAngle) { // compute sin/cos of fAngle float2 vSinCos; sincos(fAngle, vSinCos.x, vSinCos.y); return float3x3(vSinCos.y, -vSinCos.x, 0.0f, vSinCos.x, vSinCos.y, 0.0f, 0.0f, 0.0f, 1.0f); } /////////////////////////////////////////////////////////////////////// // RotationMatrix_yAxis // // Constructs a Y-axis rotation matrix float3x3 RotationMatrix_yAxis(float fAngle) { // compute sin/cos of fAngle float2 vSinCos; sincos(fAngle, vSinCos.x, vSinCos.y); return float3x3(vSinCos.y, 0.0f, vSinCos.x, 0.0f, 1.0f, 0.0f, -vSinCos.x, 0.0f, vSinCos.y); } /////////////////////////////////////////////////////////////////////// // RotationMatrix_xAxis // // Constructs a X-axis rotation matrix float3x3 RotationMatrix_xAxis(float fAngle) { // compute sin/cos of fAngle float2 vSinCos; sincos(fAngle, vSinCos.x, vSinCos.y); return float3x3(1.0f, 0.0f, 0.0f, 0.0f, vSinCos.y, -vSinCos.x, 0.0f, vSinCos.x, vSinCos.y); } /////////////////////////////////////////////////////////////////////// // // These are here for debug purposes and the fact that the // fx replacement stuff removes global variables from shaders. // /////////////////////////////////////////////////////////////////////// int get_billboard_index(int active_pass, float adjusted_azimuth, float slice_diameter, int num_images) { int index; if(!active_pass) { index = int(adjusted_azimuth / slice_diameter + 1); } else { index = int(adjusted_azimuth / slice_diameter); } if (index > num_images - 1) index = 0; return index; } float get_billboard_vertex_alpha(int active_pass, int index, float adjusted_azimuth, float slice_diameter) { // return 0; float alpha; if(!active_pass) { alpha = 1.0f - Modulate_Float(adjusted_azimuth, slice_diameter) / slice_diameter; } else { alpha = (adjusted_azimuth - (index * slice_diameter)) / slice_diameter; } return alpha; } float get_tree_light_scale() { return 1.0f; } float4 get_tree_ambient_light() { float4 col = float4(0.5, 0.45, 0.45, 1.0f); // float4 col = ConstantColour; // float4 col = PosLightCol; return saturate(col * get_tree_light_scale()); } float4 get_tree_diffuse_light() { float4 col = float4(0.6, 0.55, 0.55, 1.0f); // float4 col = PosLightCol2; return saturate(col * get_tree_light_scale()); } float3 get_light_dir(float3 vertex_world_pos) { // return float3(-1, 0, 0); // float3 light_dir = vertex_world_pos - PosLightPos; // light_dir = normalize(light_dir); // return light_dir; return float3(-0.707f, 0, 0.707f); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // instance data gather //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct sInstanceData3D { float4 data0; float4 data1; float4 data2; }; struct sInstanceData4D { float4 data0; float4 data1; float4 data2; float4 data3; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Fog - all fog calculations go in here //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LightStructures.hlsl - Structures and Macros used by the lighting code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // speedtree - decompress light indices //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 UnpackInstanceLightInfo( float lfIncomingLightData) { float lfIndex0 = lfIncomingLightData; float lfIndex1 = lfIncomingLightData+1; return float4( lfIndex0, lfIndex1, 0, 0 ); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // light input, and unpacking //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // temp bodge for PS3 to avoid shader input semantic collisions! struct sInputLightInfo { int4 LightIndices : COLOR1; }; // Remap COLOR2 back to what it is in generic.h void UnpackLightInfo( out float4 lLightIndices, out float4 lRadiosity, in sInputLightInfo lLightInfo) { // the 360 & PS3 pack additional info into the bottom 3 bits of the light index channels (3 bits * 2 channels = 6 bits) float4 lLightIdxData = lLightInfo.LightIndices * float4(1.f/8.f, 1.f/8.f, 1.f/255.f, 1.f/16384.f); float4 lLightDetail = floor(lLightIdxData); float4 lRemains = lLightIdxData - lLightDetail; float lMergedData = (lLightIdxData.w + lRemains.x + lRemains.y/8.f); float lChrominanceData = lMergedData * 128.f; float lCb = floor(lChrominanceData) / 127.f; float lCr = frac(lChrominanceData) * (128.f/127.f); float3 lYCbCr = float3(float3(lLightIdxData.z,lCb-0.5f,lCr-0.5f)); lLightIndices.xy = lLightDetail.xy; lRadiosity.xyz = ConvertYCbCr2RGB(lYCbCr); lRadiosity.w = 0.f; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // world space lighting //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct sLightDataXfer_LowDetail { float4 Normal : TEXCOORD4; // vertex normal (in world space) float4 DiffuseLightResult0 : COLOR0; float4 DiffuseLightResult1 : COLOR1; float4 WorldPos_Depth : TEXCOORD6; // world space position in xyz, depth of fragment float4 ShadowUV : TEXCOORD7; // shadow map texture coordinate (in xy/w, z=depth) }; struct sLightDataXfer { sLightDataXfer_LowDetail core; float4 Binormal : TEXCOORD2; // NBT float4 Tangent : TEXCOORD3; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // output from lighting calculations struct sLightResult { float4 diffuse; float4 specular; }; sLightResult ZeroLightResult() { sLightResult lReturn; lReturn.diffuse = float4(0,0,0,0); lReturn.specular = float4(0,0,0,0); return lReturn; } sLightResult AddLightResults(sLightResult lLight0,sLightResult lLight1) { sLightResult Out; Out.diffuse = lLight0.diffuse + lLight1.diffuse; Out.specular = lLight0.specular + lLight1.specular; return Out; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // width and height of incoming light definition texture //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define SHOW_POINT_LIGHT_SHADOW_AFFECTED_GEOM //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#define FOGGING_DISABLED //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // vertex shader function; calculates a value and passes it to the pixelshader float GenerateFogValue( float lfDepth) { return (1.f - lfDepth*FarFogPlane.y); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float CalculateFogIntensity_WorldPos( float3 lWorldPosition) { float3 lDir = lWorldPosition - CameraPosition.xyz; float lfDistance = length(lDir); float lfDistanceExp = FogEquation[0].x*lfDistance; float lfHeightExp = max(0,FogEquation[0].y*lWorldPosition.y); float lfLinearEq = FogEquation[0].z + lfDistance*FogEquation[1].y; float lfOut = saturate(exp((lfDistanceExp + lfHeightExp)*FogEquation[0].w) + lfLinearEq); return lfOut; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // pixel shader function - uses the light data structure in preparation for a more realistic fog intensity calculation float CalculateFogIntensity( sLightDataXfer_LowDetail lLightData) { return CalculateFogIntensity_WorldPos(lLightData.WorldPos_Depth.xyz); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#undef USE_SKYTEXTURE_FILTERING sampler SkyBackgroundTexture : register(s11) = sampler_state { MinFilter = Linear; MagFilter = Linear; MipFilter = None; ADDRESSU = Clamp; ADDRESSV = Clamp; }; float4 CalculateFogColor( float4 lInputColor, float lfFogIntensity, float2 lScreenPos) { float2 lTexUV = float2(lScreenPos.x,ScreenResolution[0].z - lScreenPos.y) * ScreenResolution[0].xy; float4 lFogColor = tex2D(SkyBackgroundTexture,lTexUV); return float4 (lerp (lFogColor.rgb, lInputColor.rgb, lfFogIntensity), lInputColor.a); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 ApplyFog( float3 lWorldPosition, float4 lInputColor, float2 lScreenPos) { float lfFogIntensity = CalculateFogIntensity_WorldPos(lWorldPosition); return CalculateFogColor(lInputColor,lfFogIntensity,lScreenPos); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 ApplyFog( sLightDataXfer_LowDetail lLightData, float4 lInputColor, float2 lScreenPos) { return ApplyFog( lLightData.WorldPos_Depth.xyz, lInputColor, lScreenPos); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Billboard-specific global variables // ps texture2D s0_Texture < int Texcoord = 0; int MapChannel = 1; string UIName = "Billboard diffuse map"; >; sampler s0_Sampler : register(s0) = sampler_state { Texture = (s0_Texture); MinFilter = Linear; MagFilter = Linear; MipFilter = Linear; AddressU = WRAP; AddressV = WRAP; }; // composite billboard diffuse map texture2D s1_Texture < int Texcoord = 0; int MapChannel = 1; string UIName = "Billboard normal map"; >; sampler s1_Sampler : register(s1) = sampler_state { Texture = (s1_Texture); MinFilter = Linear; MagFilter = Linear; MipFilter = Linear; AddressU = WRAP; AddressV = WRAP; }; // composite billboard normal map /////////////////////////////////////////////////////////////////////// // SBillboardOutput structure struct SBillboardOutput { float4 vPosition : POSITION; float2 vTexCoord0 : TEXCOORD0; float3 vLightAdjusts : TEXCOORD1; float4 vWorldPosition : TEXCOORD2; // using FOG here causes a ps_2_0 compilation failure float4 vNormal : TEXCOORD3; }; /////////////////////////////////////////////////////////////////////// // Billboard1VS // // In order to ensure smooth LOD transitions, two billboards are rendered // per tree instance. Each billboard represents a partially faded rendering // of the two closest billboard images for the current camera azimuth and // current tree instance rotation. // // Separate shaders are necessary because since different equations are used // to pick the billboard index and fade values for the two bb's. SBillboardOutput Billboard1VS(float4 vPosition : POSITION, // .w = corner index float4 vGeom : TEXCOORD0, // .x = width, .y = height, .z = tree azimuth, .w = lod fade float3 vMiscParams : TEXCOORD1, // .x = scale, .y = texcoord offset, .z = num images float3 vLightAdjusts : TEXCOORD2) // .x = bright side adjustment, .y = dark side adjustment, .z = ambient scale { //global float4 g_v360TexCoords[NUM_360_IMAGES]; // this will be fed to the frond pixel shader SBillboardOutput sOutput; // define attribute aliases for readability float fAzimuth = CameraAngles.x; // current camera azimuth float fPitch = CameraAngles.y; // current camera pitch int nCorner = vPosition.w; // which card corner this vertex represents [0,3] float c_fTwoPi = 6.28318530f; // 2 * pi int nNumImages = vMiscParams.z; // # of 360-degree images float c_fSliceDiameter = c_fTwoPi / float(nNumImages); // diameter = 360 / g_nNum360Images float c_fLodFade = vGeom.w; // computed on CPU - the amount the billboard as a whole is faded from 3D geometry float c_fClearAlpha = 255.0f; // alpha testing, 255 means not visible float c_fOpaqueAlpha = 84.0f; // alpha testing, 84 means fully visible float c_fAlphaSpread = 171.0f; // 171 = 255 - 84 float c_fTreeScale = vMiscParams.x; // uniform scale of tree instance int nTexCoordTableOffset = vMiscParams.y; // offset into BillboardTextureCoords where this instance's texcoords begin // there are two azimuth values to consider: // 1) fAzimuth: the azimuth of the camera position // 2) fAdjustedAzimuth: the azimuth of the camera plus the orientation of the tree the billboard // represents (used to determine which bb image to use and its alpha value) // modify the adjusted azimuth to appear in range [0,2*pi] float fAdjustedAzimuth = BillboardSpecialAzimuth + vGeom.z; if (fAdjustedAzimuth < 0.0f) fAdjustedAzimuth += c_fTwoPi; else if (fAdjustedAzimuth >= c_fTwoPi) fAdjustedAzimuth -= c_fTwoPi; fAdjustedAzimuth = c_fTwoPi-fAdjustedAzimuth; // pick the billboard image index and access the extract texcoords from the table int index = get_billboard_index(SpeedTreeLightSettings.z, fAdjustedAzimuth, c_fSliceDiameter, nNumImages); float4x4 g_afTexCoordScales = // used to compress & optimize the g_v360TexCoord lookups (x = s scale, y = t scale) { float4(0.0f, 0.0f, 0.0f, 0.0f), float4(1.0f, 0.0f, 0.0f, 0.0f), float4(1.0f, 1.0f, 0.0f, 0.0f), float4(0.0f, 1.0f, 0.0f, 0.0f) }; // determine texcoords based on corner position - while not a straighforward method for determining the texcoords // for a specific corner, this one provided a good compromise of speed and space float4 vTexCoords = BillboardTextureCoords[index + nTexCoordTableOffset]; // We can't index constant arrays by a variable on PS3 because constants are inlined in the microcode sOutput.vTexCoord0.x = vTexCoords.x - vTexCoords.z * g_afTexCoordScales[0].x; sOutput.vTexCoord0.y = vTexCoords.y - vTexCoords.w * g_afTexCoordScales[0].y; if((nCorner==0) || (nCorner==1)) { sOutput.vTexCoord0.y += 0.001f; } // compute the alpha fade value float fAlpha0 = get_billboard_vertex_alpha(SpeedTreeLightSettings.z, index, fAdjustedAzimuth, c_fSliceDiameter); float fFadePoint = lerp(c_fClearAlpha, c_fOpaqueAlpha, c_fLodFade); fAlpha0 = lerp(fFadePoint, c_fClearAlpha, pow(fAlpha0, 1.7)); // each billboard may be faded at a distinct value, but it isn't efficient to change // the alpha test value per billboard. instead we adjust the alpha value of the // billboards's outgoing color to achieve the same effect against a static alpha test // value (c_gOpaqueAlpha). fAlpha0 = 1.0f - (fAlpha0 - c_fOpaqueAlpha) / c_fAlphaSpread; float4x4 unit_square = // unit billboard card that's turned towards the camera. card is aligned on { // YZ plane and centered at (0.0f, 0.0f, 0.5f) float4(0.0f, 0.5f, 1.0f, 0.0f), float4(0.0f, -0.5f, 1.0f, 0.0f), float4(0.0f, -0.5f, 0.0f, 0.0f), float4(0.0f, 0.5f, 0.0f, 0.0f) }; // multiply by the correct corner // We can't index constant arrays by a variable on PS3 because constants are inlined in the microcode float3 vecCorner = unit_square[0].xzy * vGeom.xyx * c_fTreeScale; // apply rotation to scaled corner float3x3 matRotation = RotationMatrix_yAxis(fAzimuth); vPosition.xyz += mul(matRotation, vecCorner); vPosition.w = 1.0f; // setup per-pixel normal mapping (assumes normalized light direction) float3 light_dir = get_light_dir(vPosition.xyz); // float3 light_dir = float3(-1, 0, 0); // 0.5f + 0.5f * expr not used since texcoords aren't clamped to [0,1] range - this approach saves // several instructions sOutput.vNormal.x = dot(light_dir.xyz, BillboardTangents[nCorner].xyz); sOutput.vNormal.y = dot(light_dir.xyz, BillboardBinormals[nCorner].xyz); sOutput.vNormal.z = dot(light_dir.xyz, BillboardNormals[nCorner].xyz); sOutput.vNormal.w = fAlpha0; // project to the screen sOutput.vPosition = mul(vPosition,WorldViewProjection); // pass through light adjustments sOutput.vLightAdjusts = vLightAdjusts; sOutput.vLightAdjusts = SpeedTreeLightSettings.z; // calc fog (cheap in vertex shader, relatively expensive later in the pixel shader) sOutput.vWorldPosition = mul(float4(vPosition.xyz,1),WorldMatrix); return sOutput; } /////////////////////////////////////////////////////////////////////// // BillboardPS // // Billboard geometry pixel shader float4 BillboardPS( float2 lAbsoluteScreenPos : WPOS, SBillboardOutput In) : COLOR { float4 light_diffuse = float4(get_tree_diffuse_light().rgb, 1.0f), light_ambient = float4(get_tree_ambient_light().rgb, 1.0f); // look up the diffuse and normal-map layers float4 texDiffuse = tex2D(s0_Sampler, In.vTexCoord0.xy); float4 texNormal = tex2D(s1_Sampler, In.vTexCoord0); // compute the ambient value const float4 vecNoiseOffset = { -0.32f, -0.32f, -0.32f, 0.0f }; float4 vecAmbient = (texNormal.aaaa + vecNoiseOffset) * In.vLightAdjusts.z; vecAmbient = vecAmbient * texDiffuse; // since the normal map normal values (normally ranged [-1,1]) are store // as a color value (ranged [0,1]), they must be uncompressed. a dot product // is used to compute the diffuse lighting contribution. const float3 vecHalves = { 0.5f, 0.5f, 0.5f }; float fDot = saturate(dot(texNormal.rgb - vecHalves, In.vNormal.rgb)) * 2.0f; // lighting adjustment to use SpeedTreeCAD parameters to help make the bb // match the 3D geometry float fLightAdjust = lerp(In.vLightAdjusts.x, In.vLightAdjusts.y, SpeedTreeLightSettings.y); // float4 vColor = (fDot * texDiffuse * fLightAdjust) + vecAmbient; float4 vColor = (fDot * texDiffuse * light_diffuse) + (light_ambient * texDiffuse); // use an alpha value that is the diffuse map's noisy alpha channel multiplied // against the faded alpha color from the vertex shader vColor.a = texDiffuse.a * In.vNormal.w; // vColor.a = texDiffuse.a; // calc fog (cheap in vertex shader, relatively expensive later in the pixel shader) float4 lFogApplied = ApplyFog(In.vWorldPosition.xyz,vColor,lAbsoluteScreenPos); vColor.xyz = lFogApplied.xyz; return HDRColorCorrected(vColor); } /////////////////////////////////////////////////////////////////////// // Techniques technique Billboards { pass P0 { VertexShader = compile vs_3_0 Billboard1VS( ); PixelShader = compile ps_3_0 BillboardPS( ); } }