// // Particle Effect Additive Fast.fx // Author: Morvyn Myles // // // Generic Particle Effect Shader // Author: Morvyn Myles // //!MP! we've run out of constants //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 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 // 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 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 struct LIGHTING_RESULT { float diffuse; float specular; }; LIGHTING_RESULT calc_lighting ( float3 Normal, float3 DirectionalLight, uniform float SpecularPower, float Specularity, float3 EyeVector, float falloff_at) { // Get light direction, light distance and half vector float lightDist = length (DirectionalLight); float3 LightDir = DirectionalLight / lightDist; // Normalised float3 vHalf = normalize (-EyeVector + LightDir); float4 lighting_result = lit (dot (Normal, LightDir), dot (Normal, vHalf), SpecularPower); LIGHTING_RESULT result; result.diffuse = lighting_result.y /* * saturate (1 - lightDist / falloff_at)*/; result.specular = lighting_result.z * Specularity; return result; } LIGHTING_RESULT calc_lighting_skin ( float3 Normal, float3 DirectionalLight, uniform float SpecularPower, float Specularity, float3 EyeVector, float falloff_at) { // Get light direction, light distance and half vector float lightDist = length (DirectionalLight); float3 LightDir = DirectionalLight / lightDist; // Normalised float3 vHalf = normalize (-EyeVector + LightDir); float4 lighting_result = lit (dot (Normal, LightDir), dot (Normal, vHalf), SpecularPower); LIGHTING_RESULT result; result.diffuse = lighting_result.y /* * saturate (1 - lightDist / falloff_at)*/; result.specular = lighting_result.z * Specularity; float specular; if (dot (Normal, vHalf) < 0) specular = 0; else specular = pow (dot (vHalf , Normal), SpecularPower) * Specularity; result.specular = specular; return result; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LightEquation - main functions for lighting //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 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 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LightingDirectional.hlsl - Directional Lighting code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float CheapScatterFunction(float lIntensity) { return lIntensity*((1.0f-0.2f)/2.f)+(0.2f+((1.0f-0.2f)/2.f)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // all things shadow - this is the HLSL code used to receive the shadows (generation and blurring is in ShadowProcessing.fxg) // v1 - 03/11/2006 - Morten Pedersen - initial version //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// // shadow reception //////////////////////////////////////////////////////////////////////////////////////////////////// sampler shadowSamplerReg : register(s7) = sampler_state { MinFilter = Linear; MagFilter = Linear; MipFilter = Point; AddressU = CLAMP; AddressV = CLAMP; }; float get_shadow_influence( float4 lTextureCoord) { // read shadow float shadow_start_depth = tex2D(shadowSamplerReg,lTextureCoord.xy).r; float curr_depth = lTextureCoord.z; float shadow_intensity = 0.f; if(shadow_start_depth+-0.002f>curr_depth) { // fade it around the edges float2 post_scalars = min(1,max(0,((0.5 - abs((lTextureCoord.xy)-0.5)) * 4))); float post_scalar = min(post_scalars.x,post_scalars.y); shadow_intensity = post_scalar; } return shadow_intensity; } float ShadowSample_PCF( float2 lTextureCoord, float lShadowDepth) { float4 DepthSamples0123; // We have dedicated shadow testing hardware so this entire function is totally simplified // This does the depth compare for us (based on the comparison set in cellGcmSetTextureAddress // and also does PCF filtering. DepthSamples0123.x = tex2D( shadowSamplerReg, float3( lTextureCoord, lShadowDepth ) ); //!MP! DAVE, please test this code, and check it in, cheers return DepthSamples0123.x;// * (DirectionalLightingIntensities.x-DirectionalLightingIntensities.y) + DirectionalLightingIntensities.x; float2 lTextureStep = ShadowMapDimensions.zw*0.5; DepthSamples0123.x = tex2D(shadowSamplerReg,lTextureCoord+float2(-lTextureStep.x,-lTextureStep.y)); DepthSamples0123.y = tex2D(shadowSamplerReg,lTextureCoord+float2(+lTextureStep.x,-lTextureStep.y)); DepthSamples0123.z = tex2D(shadowSamplerReg,lTextureCoord+float2(-lTextureStep.x,+lTextureStep.y)); DepthSamples0123.w = tex2D(shadowSamplerReg,lTextureCoord+float2(+lTextureStep.x,+lTextureStep.y)); float2 lTextureCoordScaled = (lTextureCoord*ShadowMapDimensions.xy)+0.5; float2 lTextureCoordScaledFraction = frac(lTextureCoordScaled); float _yes_ = DirectionalLightingIntensities.x; float _no_ = DirectionalLightingIntensities.y; float lSample00 = ( DepthSamples0123.x > lShadowDepth ) ? _yes_ : _no_; float lSample01 = ( DepthSamples0123.y > lShadowDepth ) ? _yes_ : _no_; float lSample10 = ( DepthSamples0123.z > lShadowDepth ) ? _yes_ : _no_; float lSample11 = ( DepthSamples0123.w > lShadowDepth ) ? _yes_ : _no_; float lSamplesTop = lSample00 + (lSample01-lSample00)*lTextureCoordScaledFraction.x; float lSamplesBot = lSample10 + (lSample11-lSample10)*lTextureCoordScaledFraction.x; float lSampleFiltered = lSamplesTop + (lSamplesBot-lSamplesTop)*lTextureCoordScaledFraction.y; return lSampleFiltered; } float CalculateShadowVariance( float2 lSampledDepthValue, float lDistance) { float lfIntensity = 1.f; if( lDistance > lSampledDepthValue.x ) { float E_x2 = lSampledDepthValue.y; float Ex_2 = lSampledDepthValue.x * lSampledDepthValue.x; float lVarUnclamp = E_x2 - Ex_2; float lVariance = min(max(lVarUnclamp+VarianceShadowMap_Setup.x,0.0), 1.0); float lMue = lDistance - lSampledDepthValue.x; lfIntensity = lVariance / (lVariance + lMue * lMue); lfIntensity = pow(lfIntensity,4); } return lfIntensity; } float ShadowSample_Variance( float2 lTextureCoord, float lGeometricDepth, float lShadowPerspective, uniform bool lbTrapezoidal) { float4 lVarianceSample = tex2D( shadowSamplerReg, lTextureCoord ); float lAverageZ = lVarianceSample.r; // Filtered z float lAverageZ2 = lVarianceSample.g; // Filtered z-squared float lShadowAttn = 1.f; float lShadowDepth = lGeometricDepth + (ShadowBias.x/lGeometricDepth) + (ShadowBias.y/lShadowPerspective) + ShadowBias.z; // Standard shadow map comparison if( lShadowDepth > lAverageZ ) { // Use variance shadow mapping to compute the maximum probability that the pixel is in shadow float lVariance = (lAverageZ2)-(lAverageZ*lAverageZ); float lVarianceClamped = min( 1.0f, max( 0.0f, lVariance + VarianceShadowMap_Setup.x ) ); float lMean = lAverageZ; float lDifference = lShadowDepth - lMean; float lp_max = lVarianceClamped / ( lVarianceClamped + lDifference*lDifference ); // To combat light-bleeding, experiment with raising p_max to some power // (Try values from 0.1 to 100.0, if you like.) lShadowAttn = pow( lp_max, VarianceShadowMap_Setup.y /*4.0f*/ ); if(lbTrapezoidal) { lShadowAttn = VarianceShadowMap_Setup.w*VarianceShadowMap_Setup.z + (1-VarianceShadowMap_Setup.w)*lShadowAttn; } } return lShadowAttn; } float ComputeShadowAttenuation( float lFragmentDepth, float4 lShadowCoord, float lShadowBias) { float2 tc_d = lShadowCoord.xy/lShadowCoord.w; float2 tc = float2(tc_d.x,tc_d.y); lShadowCoord.z+=lShadowBias; float lfShadowSample = min( ShadowSample_PCF(tc,lShadowCoord.z), 0.9f ); // depending on z-distance, gradually fade out shadows float lfShadowFadeFactor = saturate(lFragmentDepth*ShadowParameters.x + ShadowParameters.y); // i assume PS3 is within range 0..1, so use 1 //!MP! DAVE, please remove this code, and check it in, cheers float lfNotInShadow = 1.f; return lfNotInShadow - (lfNotInShadow-lfShadowSample)*lfShadowFadeFactor; } float4 ShadowTransformPosition(float4 WorldPosition) { return mul(WorldPosition,(float4x4)ShadowMapMatrix); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // world space lighting //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 WorldSpace_CalculateDirectionalLight_NoSpecular( float lFragmentDepth, float4 lWorldSpaceNormal, float4 lShadowUV, uniform bool lbCheapScattering) { float lNormalDotLight = dot(MainLightDirection.xyz,lWorldSpaceNormal.xyz); if(lbCheapScattering) { lNormalDotLight = CheapScatterFunction(lNormalDotLight); } lNormalDotLight = saturate(lNormalDotLight); return MainLightColor * lNormalDotLight; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sLightResult WorldSpace_CalculateDirectionalLight_Specular( float lFragmentDepth, float4 lWorldSpaceNormal, float4 lShadowUV, float3 lEyeVector, float lSpecularPower, uniform bool lbCheapScattering) { float3 lHalfVector = normalize(MainLightDirection.xyz+lEyeVector.xyz); float lNormalDotLight = dot(lWorldSpaceNormal.xyz,MainLightDirection.xyz); if(lbCheapScattering) { lNormalDotLight = CheapScatterFunction(lNormalDotLight); } float lInvLighting = saturate(-lNormalDotLight); lNormalDotLight = saturate(lNormalDotLight); float4 lLightResult = lit(lNormalDotLight, dot(lWorldSpaceNormal.xyz,lHalfVector),lSpecularPower); sLightResult Out; Out.diffuse = MainLightColor * lLightResult.y + MainLightInvColor * lInvLighting; Out.specular = MainLightColor * lLightResult.z; return Out; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LightingPoint.hlsl - Point Lighting code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static const float2 lMidTextureOfs = float2(0.5f/4.f,0.5f/2048.f); static const float2 lTexColorOfs = float2(0.25f,0); samplerCUBE shadowCubeSampler : register(s8) = sampler_state { MinFilter = Point; MagFilter = Point; MipFilter = Linear; AddressU = CLAMP; AddressV = CLAMP; }; sampler lightData : register(s9) = sampler_state { MinFilter = Point; MagFilter = Point; MipFilter = None; AddressU = CLAMP; AddressV = CLAMP; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // shadow calculation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float GetShadowAttenuation( float4 lParameters, float3 lLightVector, float lDistanceToLight ) { float lfIntensity = 1.f; // Ignore point light shadows for now. return 0.f; // in shadow? // if(PSCb_EnableStaticCubicShadowReceiver) { float lShadowSlice = lParameters.x; // if(lShadowSlice<10) { float lShadow_ooDepth = lParameters.y; float4 lShadowTexCoord = float4(-lLightVector,lShadowSlice); float lDistanceFromLight = lDistanceToLight * lShadow_ooDepth; // if we're further away from the light than the depth in the buffer, we're in shadow float lShadowMapDepth = texCUBElod(shadowCubeSampler,lShadowTexCoord).r; if(lDistanceFromLight>lShadowMapDepth) { lfIntensity = 0.f; } } } return lfIntensity; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // core functionality //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sLightResult WorldSpace_CalculatePointLight_Specular( float4 lPosition_Scalar, float4 lColor_Offset, float4 lParameters, float3 lWorldPosition, float3 lEyeVector, float3 lWorldSpaceNormal, float lSpecularPower, uniform bool lbShadowsEnable) { float3 lLightPixelVector = lPosition_Scalar.xyz - lWorldPosition.xyz; float3 lLightPixelVectorLen = sqrt(dot(lLightPixelVector,lLightPixelVector)); float lAttenuation = saturate(lLightPixelVectorLen*lPosition_Scalar.w+lColor_Offset.w); float3 lLightPixelVectorNorm = lLightPixelVector/lLightPixelVectorLen; float3 lHalfVector = normalize(lLightPixelVectorNorm+lEyeVector); float diffuse_dot = dot(lWorldSpaceNormal,lLightPixelVectorNorm); float4 lLightCalc = lit(diffuse_dot, dot(lWorldSpaceNormal,lHalfVector),lSpecularPower); float4 lLightAttenuated = lLightCalc*lAttenuation; if(lbShadowsEnable) { lLightAttenuated *= GetShadowAttenuation(lParameters,lLightPixelVectorNorm,lLightPixelVectorLen); } sLightResult Out; Out.diffuse = lColor_Offset * lLightAttenuated.y; Out.specular = lColor_Offset * lLightAttenuated.z * lParameters.z; return Out; } float4 WorldSpace_CalculatePointLight_NoSpecular( float4 lPosition_Scalar, float4 lColor_Offset, float4 lParameters, float3 lWorldPosition, float3 lWorldSpaceNormal, uniform bool lbShadowsEnable) { float3 lLightPixelVector = lPosition_Scalar.xyz - lWorldPosition.xyz; float3 lLightPixelVectorLen = sqrt(dot(lLightPixelVector,lLightPixelVector)); float lAttenuation = saturate(lLightPixelVectorLen*lPosition_Scalar.w+lColor_Offset.w); float3 lLightPixelVectorNorm = lLightPixelVector/lLightPixelVectorLen; float lLightCalc = saturate(dot(lWorldSpaceNormal,lLightPixelVectorNorm)); float lLightAttenuated = lLightCalc*lAttenuation; if(lbShadowsEnable) { lLightAttenuated *= GetShadowAttenuation(lParameters,lLightPixelVector,lLightPixelVectorLen); } return lColor_Offset * lLightAttenuated; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // shader constant, with specular //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sLightResult WorldSpace_CalculatePointLight_Const_Specular( float3 lWorldPosition, float3 lEyeVector, float3 lWorldSpaceNormal, int lLightOffset, float lSpecularPower, uniform bool lbShadowsEnable) { float4 lPosition_Scalar = DynamicLightData[lLightOffset+0]; float4 lColor_Offset = DynamicLightData[lLightOffset+1]; float4 lParameters = DynamicLightData[lLightOffset+2]; return WorldSpace_CalculatePointLight_Specular( lPosition_Scalar, lColor_Offset, lParameters, lWorldPosition, lEyeVector, lWorldSpaceNormal, lSpecularPower, lbShadowsEnable); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // shader constant, without specular //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 WorldSpace_CalculatePointLight_Const_NoSpecular( float3 lWorldPosition, float3 lWorldSpaceNormal, int lLightOffset, uniform bool lbShadowsEnable) { float4 lPosition_Scalar = DynamicLightData[lLightOffset+0]; float4 lColor_Offset = DynamicLightData[lLightOffset+1]; return WorldSpace_CalculatePointLight_NoSpecular( lPosition_Scalar, lColor_Offset, float4(0,0,0,0), lWorldPosition, lWorldSpaceNormal, lbShadowsEnable); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // texture lookup, with specular //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sLightResult WorldSpace_CalculatePointLight_Texture_Specular( float3 lWorldPosition, float3 lEyeVector, float3 lWorldSpaceNormal, float lLightOffset, float lSpecularPower, uniform bool lbShadowsEnable) { float2 lLightTexCoord_Position = float2(0,(float)lLightOffset/2048.f)+lMidTextureOfs; float2 lLightTexCoord_Color = lLightTexCoord_Position+lTexColorOfs; float2 lLightTexCoord_Parameters = lLightTexCoord_Color+lTexColorOfs; float4 lPosition_Scalar = tex2D(lightData,lLightTexCoord_Position); float4 lColor_Offset = tex2D(lightData,lLightTexCoord_Color); float4 lParameters = tex2D(lightData,lLightTexCoord_Parameters); return WorldSpace_CalculatePointLight_Specular( lPosition_Scalar, lColor_Offset, lParameters, lWorldPosition, lEyeVector, lWorldSpaceNormal, lSpecularPower, lbShadowsEnable); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // texture lookup, with specular //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 WorldSpace_CalculatePointLight_Texture_NoSpecular( float3 lWorldPosition, float3 lWorldSpaceNormal, float lLightOffset, uniform bool lbShadowsEnable) { float2 lLightTexCoord_Position = float2(0,(float)lLightOffset/2048.f)+lMidTextureOfs; float2 lLightTexCoord_Color = lLightTexCoord_Position+lTexColorOfs; float4 lPosition_Scalar = tex2D(lightData,lLightTexCoord_Position); float4 lColor_Offset = tex2D(lightData,lLightTexCoord_Color); return WorldSpace_CalculatePointLight_NoSpecular( lPosition_Scalar, lColor_Offset, float4(0,0,0,0), lWorldPosition, lWorldSpaceNormal, lbShadowsEnable); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Fog - all fog calculations go in here //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // LightStructures.hlsl - Structures and Macros used by the lighting code //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //#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); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // core lighting equation - the one which does the inner work of the lighting equation //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 PS_CoreLightingEquation_NoSpecular( float4 lBaseTexture, float4 lDirectionalLight, float4 lPointLight, float3 lBaseTextureModulator, float3 lRadiosity) { float4 Color=lBaseTexture; Color.rgb *= lBaseTextureModulator.rgb * ( + lRadiosity.rgb + lDirectionalLight.rgb + lPointLight.rgb ); return Color; } float4 Ps3PackColor( float4 i ) { float4 o; // o.w = max( i.x, max( i.y, i.z ) ); // o.xyz = i.xyz / o.w; o.w = min( i.x, min( i.y, i.z ) ); o.xyz = (i.xyz - o.www) * 0.5f; o = i; return o; // automatic saturate and nan handling because goes out of color interpolator } float4 Ps3UnpackColor( float4 i ) { // return float4( i.xyz * i.a, 1 ); return float4( i.xyz * 2.f + i.www, 1 ); // return i; } float3 RGB2YUV(float3 lColor) { float R = lColor.r; float G = lColor.g; float B = lColor.b; float Y = + 0.299*R + 0.587*G + 0.114*B; float Cb = - 0.169*R - 0.331*G + 0.500*B; float Cr = + 0.500*R - 0.419*G - 0.081*B; return float3(Y,Cb,Cr); } float3 YUV2RGB(float3 lColor) { float Y = lColor.r; float Cb = lColor.g; float Cr = lColor.b; float R = Y + Cr*1.403f; float G = Y - Cb*0.344f - 0.714*Cr; float B = Y + Cb*1.770f; return float3(R,G,B); } float4 PS_CoreLightingEquation( float4 lBaseTexture, sLightResult lDirectionalLight, sLightResult lPointLight, float3 lBaseTextureModulator, float3 lRadiosity, float lSpecularity) { float4 Color=PS_CoreLightingEquation_NoSpecular( lBaseTexture, lDirectionalLight.diffuse, lPointLight.diffuse, lBaseTextureModulator, lRadiosity); Color.rgb += lSpecularity * SpecularPower.w * // acts as boost value ( + lDirectionalLight.specular.rgb + lPointLight.specular.rgb ); return Color; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // transformation of tangent space normal into world space, and renormalization //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 CalculateWorldSpaceNormal( sLightDataXfer lIn, float3 lNormalMapSample ) { // correct, but slightly slower lNormalMapSample.z = sqrt(1-lNormalMapSample.x*lNormalMapSample.x-lNormalMapSample.y*lNormalMapSample.y); // 3 float3x3 lTangentFrame = {lIn.Binormal.xyz,lIn.Tangent.xyz,lIn.core.Normal.xyz}; float3 lWorldSpaceNormal = mul(lNormalMapSample,lTangentFrame); // 6 float mylen = dot(lWorldSpaceNormal,lWorldSpaceNormal); // 7 float myrcplen = rsqrt(mylen); // 8 lWorldSpaceNormal *= myrcplen; // 9 return float4(lWorldSpaceNormal,lIn.core.Normal.w); } // // This is just like CalculateWorldSpaceNormal(), but assumes z is already in place, // and doesn't renormalise after multiplying by the tangent->world matrix. This // will mess up any specular calculations done with this normal, so use it for non- // specular items only. e.g. Normal mapped particles // float3 CalculateWorldSpaceNormalNoSpecular ( sLightDataXfer lIn, float3 lNormalMapSample ) { float3x3 lTangentFrame = {lIn.Binormal.xyz, lIn.Tangent.xyz, lIn.core.Normal.xyz}; return mul (lNormalMapSample,lTangentFrame); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // vertex shader structure setup //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// sLightDataXfer_LowDetail VS_SetupLighting_LowDetail( float3 lNormal, float4 lLightInfo, float4 lWorldPosition, float4 lClipSpacePosition, int numStaticLights = 2) { sLightDataXfer_LowDetail Out; float lfTemp = saturate(dot(VCMainLightDirection.xyz,lNormal)*VCMainLightDirection.w); float lfLightingDot = lClipSpacePosition.w; // get view-z for shadow distance fade (PS3 doesn't use TSM biasing) Out.Normal = float4(lNormal,lfLightingDot); Out.WorldPos_Depth.xyz = lWorldPosition.xyz; Out.WorldPos_Depth.w = lClipSpacePosition.w; Out.ShadowUV = ShadowTransformPosition(lWorldPosition); // do both lights right here in the vs per vertex like our grandfathers used to do Out.DiffuseLightResult0 = 0; Out.DiffuseLightResult1 = 0; if(numStaticLights>0) { float index = 2 * lLightInfo.x; float4 lPosition_Scalar = PS3StaticLightData[ index + 0 ]; float4 lColor_Offset = PS3StaticLightData[ index + 1 ]; Out.DiffuseLightResult0 = WorldSpace_CalculatePointLight_NoSpecular( lPosition_Scalar, lColor_Offset, float4(0,0,0,0), lWorldPosition, lNormal, false); if(numStaticLights>1) { float index = 2 * lLightInfo.y; float4 lPosition_Scalar = PS3StaticLightData[ index + 0 ]; float4 lColor_Offset = PS3StaticLightData[ index + 1 ]; Out.DiffuseLightResult1 = WorldSpace_CalculatePointLight_NoSpecular( lPosition_Scalar, lColor_Offset, float4(0,0,0,0), lWorldPosition, lNormal, false); } } float dimFactor = 0.65f; Out.DiffuseLightResult0 = Ps3PackColor( Out.DiffuseLightResult0 * dimFactor ); Out.DiffuseLightResult1 = Ps3PackColor( Out.DiffuseLightResult1 * dimFactor ); return Out; } sLightDataXfer VS_SetupLighting( float3 lBinormal, float3 lTangent, float3 lNormal, float4 lLightInfo, float4 lWorldPosition, float4 lClipSpacePosition, int numStaticLights=2) { sLightDataXfer Out; Out.core = VS_SetupLighting_LowDetail(lNormal,lLightInfo,lWorldPosition,lClipSpacePosition, numStaticLights); Out.Binormal = float4(lBinormal,0); Out.Tangent = float4(lTangent,0); return Out; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // world space lighting with bump mapping //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 PS_CalculateLighting( sLightDataXfer lIn, float4 lBaseTexture, float3 lWorldSpaceNormal, float3 lVertexDiffuse, float3 lVertexRadiosity, float lSpecularPower, float lSpecularity, uniform int lnStaticLightCount, uniform int lnDynamicLightCount, uniform bool lbPointShadowsEnable, uniform bool lbCheapScattering) { float3 lEyeVector = normalize(CameraPosition - lIn.core.WorldPos_Depth.xyz); sLightResult lPointLights = ZeroLightResult(); lPointLights.diffuse += Ps3UnpackColor( lIn.core.DiffuseLightResult0 ) + Ps3UnpackColor( lIn.core.DiffuseLightResult1 ); // add the dynamic lights if(lnDynamicLightCount>0) { sLightResult lPoint0 = WorldSpace_CalculatePointLight_Const_Specular( lIn.core.WorldPos_Depth.xyz, lEyeVector, lWorldSpaceNormal, 0*3, lSpecularPower, lbPointShadowsEnable); lPointLights = AddLightResults(lPointLights,lPoint0); if(lnDynamicLightCount>1) { sLightResult lPoint1 = WorldSpace_CalculatePointLight_Const_Specular( lIn.core.WorldPos_Depth.xyz, lEyeVector, lWorldSpaceNormal, 1*3, lSpecularPower, lbPointShadowsEnable); lPointLights = AddLightResults(lPointLights,lPoint1); if(lnDynamicLightCount>2) { sLightResult lPoint2 = WorldSpace_CalculatePointLight_Const_Specular( lIn.core.WorldPos_Depth.xyz, lEyeVector, lWorldSpaceNormal, 2*3, lSpecularPower, lbPointShadowsEnable); lPointLights = AddLightResults(lPointLights,lPoint2); } } } // directional light always enabled sLightResult lDirectionalLight = WorldSpace_CalculateDirectionalLight_Specular( lIn.core.WorldPos_Depth.w, float4(lWorldSpaceNormal,lIn.core.Normal.w), lIn.core.ShadowUV, lEyeVector, lSpecularPower, lbCheapScattering); // sum it all up in the core lighting equation float4 lOutputColor = PS_CoreLightingEquation( lBaseTexture, lDirectionalLight, lPointLights, lVertexDiffuse, lVertexRadiosity, lSpecularity); return lOutputColor; } float4 PS_CalculateLighting_Dynamic_NoSpecular ( sLightDataXfer lIn, float4 lBaseTexture, float3 lWorldSpaceNormal, // normalized, and in world space float3 lVertexDiffuse, float3 lVertexRadiosity, uniform int lnLightCount, uniform bool lbPointShadowsEnable, uniform bool lbCheapScattering) { float4 lPointLights = WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.core.WorldPos_Depth.xyz, lWorldSpaceNormal, 0*3, lbPointShadowsEnable); //return float4 (lPointLights.rgb, 1); if(lnLightCount>1) { float4 lPoint1 = WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.core.WorldPos_Depth.xyz, lWorldSpaceNormal, 1*3, lbPointShadowsEnable); lPointLights = lPointLights + lPoint1; if(lnLightCount>2) { float4 lPoint2 = WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.core.WorldPos_Depth.xyz, lWorldSpaceNormal, 2*3, lbPointShadowsEnable); lPointLights = lPointLights + lPoint2; } } float4 lDirectionalLight = WorldSpace_CalculateDirectionalLight_NoSpecular( lIn.core.WorldPos_Depth.w, float4(lWorldSpaceNormal,lIn.core.Normal.w), lIn.core.ShadowUV, lbCheapScattering); float4 lOutputColor = PS_CoreLightingEquation_NoSpecular ( lBaseTexture, lDirectionalLight, lPointLights, lVertexDiffuse, lVertexRadiosity); return lOutputColor; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // without bump mapping //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float4 PS_CalculateLighting_LowDetail( sLightDataXfer_LowDetail lIn, float4 lBaseTexture, float3 lVertexDiffuse, float3 lVertexRadiosity, uniform int lnStaticLightCount, uniform int lnDynamicLightCount, uniform bool lbPointShadowsEnable, uniform bool lbCheapScattering) { float4 lPointLights = float4(0,0,0,0); lPointLights += Ps3UnpackColor( lIn.DiffuseLightResult0 ) + Ps3UnpackColor( lIn.DiffuseLightResult1 ); if(lnDynamicLightCount>0) { float4 lPointLights = WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.WorldPos_Depth.xyz, lIn.Normal, 0*3, lbPointShadowsEnable); if(lnDynamicLightCount>1) { lPointLights += WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.WorldPos_Depth.xyz, lIn.Normal, 1*3, lbPointShadowsEnable); if(lnDynamicLightCount>2) { lPointLights += WorldSpace_CalculatePointLight_Const_NoSpecular( lIn.WorldPos_Depth.xyz, lIn.Normal, 2*3, lbPointShadowsEnable); } } } float4 lDirectionalLight = WorldSpace_CalculateDirectionalLight_NoSpecular( lIn.WorldPos_Depth.w, lIn.Normal, lIn.ShadowUV, lbCheapScattering); return PS_CoreLightingEquation_NoSpecular( lBaseTexture, lDirectionalLight, lPointLights, lVertexDiffuse, lVertexRadiosity); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // end of lighting.inc //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Fog - all fog calculations go in here //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Texture texture2D s0_Texture < int Texcoord = 0; int MapChannel = 1; string UIName = "Base"; >; sampler s0_Sampler : register(s0) = sampler_state { Texture = (s0_Texture); MinFilter = Linear; MagFilter = Linear; MipFilter = Linear; AddressU = WRAP; AddressV = WRAP; }; texture2D s1_Texture < int Texcoord = 1; int MapChannel = 2; string UIName = "Max FX is wank"; >; sampler s1_Sampler : register(s1) = sampler_state { Texture = (s1_Texture); MaxAnisotropy = 7; MinFilter = Anisotropic; MagFilter = Anisotropic; MipFilter = Linear; AddressU = WRAP; AddressV = WRAP; }; // Remap COLOR2 to avoid semantic collision struct VS_OUTPUT { float4 Position : POSITION; float4 colour : TEXCOORD5; float2 uv : TEXCOORD0; float3 WorldSpacePosition : TEXCOORD2; }; // ------------------ // Particle System VS // ------------------ VS_OUTPUT main_VS ( float3 GeomPosition : POSITION, float2 uv : TEXCOORD0, float2 GeomPosition2 : TEXCOORD1, float4 Diffuse : COLOR0) { VS_OUTPUT Out; // It's been through entity.exe - so the UVs and position are compressed uv *= 16; // Particle's (floating point) index, and random number float random = GeomPosition2.x; float liinear = GeomPosition2.y; // Particle's personal time, and effect start time float PTime; float ETime = (TimeAndRainLevel.x) - ConstantColour.w; // Form groups of random numbers using SIMD operation for performance float4 randomA = frac (random * float4 (2317, 1271, 7533, 9427) + ConstantColour.x /* To randomize each effect uniquely */); float4 randomB = frac (random * float4 (7817, 4157, 5137, 3217)); // SIMD lerping on various particle properties float ParticleExpiryTime = lerp ((PA_ExpiryTime.x), (PA_ExpiryTime.y), frac (random * 7194.0f)); float size_start = lerp ((PA_StartMMEndMMSize.x) , (PA_StartMMEndMMSize.y) , frac (random * 9385.0f)); float size_end = lerp ((PA_StartMMEndMMSize.z) , (PA_StartMMEndMMSize.w) , frac (random * 9385.0f)); if ((SpreadNumParticlesAnimationCountLoopSystem.w)) { PTime = fmod (ETime + ((randomA.w - 1) * ParticleExpiryTime), ParticleExpiryTime); // loop round after ParticleExpiryTime // Hide particles that haven't had their first launch yet, or // are dying out due to old age - prevent a particle from looping // around if the system will expire before this particle has a chance // to complete its next cycle if (ETime + ((randomA.w - 1) * ParticleExpiryTime) < 0 || ETime - PTime + ParticleExpiryTime > ConstantColour.y) { size_start = 0.0f; // [TODO] Optimise me size_end = 0.0f; } } else { PTime = ETime; // Simultaneous launch } float tFrac = saturate (PTime / ParticleExpiryTime); // Size float size = lerp (size_start, size_end, tFrac); // Emission position float4 ParticleRoot = float4 (WorldMatrix [3][0], WorldMatrix [3][1], WorldMatrix [3][2], 1); float3 random_offset = (randomA.xyz - float3 (0.5, 0.5, 0.5)) * PA_EmissionArea; // Initial velocity float3 initial_velocity; { // Pick a random direction initial_velocity = randomB.xyz; // Constrain Z by spread - an approximation initial_velocity.z = 1 - (initial_velocity.z * (SpreadNumParticlesAnimationCountLoopSystem.x)); initial_velocity -= float3 (0.5, 0.5, 0.5); if ((SpreadNumParticlesAnimationCountLoopSystem.x) < 0.2) { initial_velocity.xy *= (SpreadNumParticlesAnimationCountLoopSystem.x) / 0.2f; } // Normalize - 'corners' will be slightly more popular than axes // with this technique initial_velocity = normalize (initial_velocity); initial_velocity = (mul (float4 ((initial_velocity), 0), WorldMatrix)); // Pick a speed float start_speed = lerp (PA_Velocity_Alpha_Rotation_Min_AspectRatio.x , PA_Velocity_Alpha_Rotation_Max_Gravity.x , randomB.w); float mid_speed = lerp ((PA_MidMinMaxEndMinMaxVelocity.x), (PA_MidMinMaxEndMinMaxVelocity.y), randomB.w); float final_speed = lerp ((PA_MidMinMaxEndMinMaxVelocity.z), (PA_MidMinMaxEndMinMaxVelocity.w), randomB.w); // Moving from start to mid speed float average_speed; float curr_speed; curr_speed = lerp (start_speed, final_speed, tFrac); average_speed = (start_speed + curr_speed) / 2.0f; initial_velocity *= average_speed; } // Particle positional behaviour float3 total_velocity = initial_velocity + PA_Wind; float3 Position = (ParticleRoot) + random_offset; { // Velocity Position += total_velocity * PTime; // Graaaaaaaaaaavity... going down (u.t + half.a.t.t) Position.y -= PA_Velocity_Alpha_Rotation_Max_Gravity.w * PTime * PTime; } Position = (Position); // Back to Max co-ords // Particle colour behaviour { Out.colour = lerp (PA_StartColour, PA_EndColour, tFrac); if (tFrac < PA_Velocity_Alpha_Rotation_Min_AspectRatio.y) Out.colour.a = tFrac / PA_Velocity_Alpha_Rotation_Min_AspectRatio.y; // Fading in else if (tFrac >= PA_Velocity_Alpha_Rotation_Max_Gravity.y) Out.colour.a = 1 - (tFrac - PA_Velocity_Alpha_Rotation_Max_Gravity.y) / (1 - PA_Velocity_Alpha_Rotation_Max_Gravity.y); // Fading out } // Particle size / rotation float2 vert_delta = {(uv.x - 0.5) * PA_Velocity_Alpha_Rotation_Min_AspectRatio.w, uv.y - 0.5}; // Form a particle shape { if (PA_DrawAsBillboard.x) { // Calculate world-space movement required to face camera //#ifdef _MAX_ float3 right_unr = float3 (ViewMatrix [0][0], ViewMatrix [1][0], ViewMatrix [2][0]) * size; //#else // float3 right_unr = float3 (ViewMatrix [0][0], ViewMatrix [0][1], ViewMatrix [0][2]) * size; //#endif float3 up_unr = (float3 (0, 1, 0)) * size; float3 right = right_unr; float3 up = up_unr; Position += (vert_delta.x * right); Position += (vert_delta.y * up); } Out.Position = mul (float4 (Position, 1), ViewProj); // position (view space) // Some particle fading, with hard-coded constants float fade_at = (PA_ExpiryTime.w) * 1.25f; float fFadeValue = Out.Position.w / (size * size * PA_Velocity_Alpha_Rotation_Min_AspectRatio.w) - (PA_ExpiryTime.w); if (fFadeValue < 0) { size = 0; // Fade value nearer than PA_DisappearAt = don't render particle } if (fFadeValue < fade_at - (PA_ExpiryTime.w)) { Out.colour.a *= (fFadeValue / (fade_at - (PA_ExpiryTime.w))); } if (!PA_DrawAsBillboard.x) { Out.Position.x += (vert_delta.x) * size * ProjMatrix [0][0]; Out.Position.y -= (vert_delta.y) * size * ProjMatrix [1][1]; } } // Just show the texture { Out.uv = uv; } //Out.colour.a = PA_AlphaOut; Out.colour.a *= GenerateFogValue (Out.Position.w); // Fade particles near cull distance float curr_dist = ParticleFadeValue.x; float fade_end = ParticleFadeValue.y; float fade_start = fade_end * 0.9f; // Fade for the last 10% of depth float fade_range = fade_end * 0.1f; Out.colour.a *= 1.0f - saturate ((curr_dist - fade_start) / fade_range); Out.WorldSpacePosition = Position.xyz; return Out; } // pixel shader half4 main_PS( float2 lAbsoluteScreenPos : WPOS, VS_OUTPUT In ) : COLOR { float4 Color; //return float4 (frac (In.uv + float2 (10, 10)), 0, 1); //return float4 (1, 1, 0, 1); // No texture animation in fast 2D, or 3D particles Color = tex2D (s0_Sampler, In.uv); Color *= In.colour; //Color.rgb = In.colour.a; //Color.a = 1.0f; //return Color; Color.rgb *= Color.a * In.colour.a; // Blend alpha into colour as alpha is ignored return HDRColorCorrected ((half4)Color); } // technique technique TMain { pass P0 { VertexShader = compile vs_3_0 main_VS (); PixelShader = compile ps_3_0 main_PS (); // These are defaults - individual shaders can override these ZEnable = TRUE; ZFunc = LESSEQUAL; CullMode = ccw; ShadeMode = Gouraud; SrcBlend = SrcAlpha; DestBlend = InvSrcAlpha; // This is handled by game code, not by the shaders // Z writing is handled by game code, not by the shaders CullMode = NONE; SrcBlend = One /*RESTORE*/; DestBlend = One /*RESTORE */; HighPrecisionBlendEnable = false /*RESTORE*/; } }