diff --git a/Effects/DeferredPBREffect.cs b/Effects/DeferredPBREffect.cs index 83da9f7..e59a277 100644 --- a/Effects/DeferredPBREffect.cs +++ b/Effects/DeferredPBREffect.cs @@ -9,18 +9,25 @@ namespace Kav EffectParameter gAlbedoParam; EffectParameter gNormalParam; EffectParameter gMetallicRoughnessParam; - EffectParameter shadowMapParam; + + EffectParameter directionalShadowMapParam; + EffectParameter directionalLightDirectionParam; + EffectParameter directionalLightColorParam; + EffectParameter directionalLightMatrixParam; EffectParameter eyePositionParam; PointLightCollection pointLightCollection; - DirectionalLightCollection directionalLightCollection; public Texture2D GPosition { get; set; } public Texture2D GAlbedo { get; set; } public Texture2D GNormal { get; set; } public Texture2D GMetallicRoughness { get; set; } - public TextureCube DirectionalShadowMap { get; set; } + + public Texture2D DirectionalShadowMap { get; set; } + public Vector3 DirectionalLightDirection { get; set; } + public Vector3 DirectionalLightColor { get; set; } + public Matrix DirectionalLightMatrix { get; set; } public Vector3 EyePosition { get; set; } @@ -32,14 +39,6 @@ namespace Kav private set { pointLightCollection = value; } } - public int MaxDirectionalLights { get; } = 6; - - public DirectionalLightCollection DirectionalLights - { - get { return directionalLightCollection; } - private set { directionalLightCollection = value; } - } - public DeferredPBREffect(GraphicsDevice graphicsDevice) : base(graphicsDevice, Resources.DeferredPBREffect) { CacheEffectParameters(); @@ -49,12 +48,6 @@ namespace Kav Parameters["PointLightColors"], MaxPointLights ); - - DirectionalLights = new DirectionalLightCollection( - Parameters["DirectionalLightDirections"], - Parameters["DirectionalLightColors"], - Parameters["DirectionalLightMatrices"] - ); } protected DeferredPBREffect(DeferredPBREffect cloneSource) : base(cloneSource) @@ -76,17 +69,6 @@ namespace Kav { PointLights[i] = cloneSource.PointLights[i]; } - - DirectionalLights = new DirectionalLightCollection( - Parameters["DirectionalLightDirections"], - Parameters["DirectionalLightColors"], - Parameters["DirectionalLightMatrices"] - ); - - for (int i = 0; i < MaxDirectionalLights; i++) - { - DirectionalLights[i] = cloneSource.DirectionalLights[i]; - } } public override Effect Clone() @@ -100,7 +82,11 @@ namespace Kav gAlbedoParam.SetValue(GAlbedo); gNormalParam.SetValue(GNormal); gMetallicRoughnessParam.SetValue(GMetallicRoughness); - shadowMapParam.SetValue(DirectionalShadowMap); + + directionalShadowMapParam.SetValue(DirectionalShadowMap); + directionalLightDirectionParam.SetValue(DirectionalLightDirection); + directionalLightColorParam.SetValue(DirectionalLightColor); + directionalLightMatrixParam.SetValue(DirectionalLightMatrix); eyePositionParam.SetValue(EyePosition); } @@ -111,7 +97,11 @@ namespace Kav gAlbedoParam = Parameters["gAlbedo"]; gNormalParam = Parameters["gNormal"]; gMetallicRoughnessParam = Parameters["gMetallicRoughness"]; - shadowMapParam = Parameters["shadowMap"]; + directionalShadowMapParam = Parameters["directionalShadowMap"]; + + directionalLightDirectionParam = Parameters["DirectionalLightDirection"]; + directionalLightColorParam = Parameters["DirectionalLightColor"]; + directionalLightMatrixParam = Parameters["DirectionalLightMatrix"]; eyePositionParam = Parameters["EyePosition"]; } diff --git a/Effects/DirectionalLightCollection.cs b/Effects/DirectionalLightCollection.cs index 75047c3..7dc1d47 100644 --- a/Effects/DirectionalLightCollection.cs +++ b/Effects/DirectionalLightCollection.cs @@ -8,7 +8,9 @@ namespace Kav private readonly Vector3[] directions = new Vector3[6]; private readonly Vector3[] colors = new Vector3[6]; private readonly float[] intensities = new float[6]; - private readonly Matrix[] lightSpaceMatrices = new Matrix[6]; + private readonly Matrix[] viewMatrices = new Matrix[6]; + private readonly Matrix[] projectionMatrices = new Matrix[6]; + private readonly Matrix[] viewProjectionMatrices = new Matrix[6]; readonly EffectParameter lightDirectionsParam; readonly EffectParameter lightColorsParam; @@ -24,6 +26,22 @@ namespace Kav this.lightSpaceMatricesParam = lightSpaceMatricesParam; } + public void SetMatrices(int index, Matrix view, Matrix projection) + { + viewMatrices[index] = view; + projectionMatrices[index] = projection; + } + + public void Apply() + { + for (int i = 0; i < 6; i++) + { + viewProjectionMatrices[i] = viewMatrices[i] * projectionMatrices[i]; + } + + lightSpaceMatricesParam.SetValue(viewProjectionMatrices); + } + public DirectionalLight this[int i] { get @@ -45,10 +63,8 @@ namespace Kav directions[i] = value.Direction; colors[i] = value.Color.ToVector3() * value.Intensity; intensities[i] = value.Intensity; - lightSpaceMatrices[i] = value.View * value.Projection; lightDirectionsParam.SetValue(directions); lightColorsParam.SetValue(colors); - lightSpaceMatricesParam.SetValue(lightSpaceMatrices); } } } diff --git a/Effects/FXB/DeferredPBREffect.fxb b/Effects/FXB/DeferredPBREffect.fxb index 669ec7c..e30250b 100644 Binary files a/Effects/FXB/DeferredPBREffect.fxb and b/Effects/FXB/DeferredPBREffect.fxb differ diff --git a/Effects/FXB/SimpleDepthEffect.fxb b/Effects/FXB/SimpleDepthEffect.fxb index ab998b2..64ee5cd 100644 Binary files a/Effects/FXB/SimpleDepthEffect.fxb and b/Effects/FXB/SimpleDepthEffect.fxb differ diff --git a/Effects/HLSL/DeferredPBREffect.fx b/Effects/HLSL/DeferredPBREffect.fx index f685ffa..b9ae64a 100644 --- a/Effects/HLSL/DeferredPBREffect.fx +++ b/Effects/HLSL/DeferredPBREffect.fx @@ -2,13 +2,12 @@ static const float PI = 3.141592653589793; static const int MAX_POINT_LIGHTS = 64; -static const int MAX_DIRECTIONAL_LIGHTS = 6; DECLARE_TEXTURE(gPosition, 0); DECLARE_TEXTURE(gAlbedo, 1); DECLARE_TEXTURE(gNormal, 2); DECLARE_TEXTURE(gMetallicRoughness, 3); -DECLARE_CUBEMAP(shadowMap, 4); +DECLARE_TEXTURE(directionalShadowMap, 4); BEGIN_CONSTANTS @@ -17,21 +16,37 @@ BEGIN_CONSTANTS float3 PointLightPositions[MAX_POINT_LIGHTS] _ps(c1) _cb(c1); float3 PointLightColors[MAX_POINT_LIGHTS] _ps(c65) _cb(c65); - float3 DirectionalLightDirections[MAX_DIRECTIONAL_LIGHTS] _ps(c129) _cb(c129); - float3 DirectionalLightColors[MAX_DIRECTIONAL_LIGHTS] _ps(c135) _cb(c135); + float3 DirectionalLightDirection _ps(c129) _cb(c129); + float3 DirectionalLightColor _ps(c130) _cb(c130); MATRIX_CONSTANTS - float4x4 DirectionalLightMatrices[MAX_DIRECTIONAL_LIGHTS] _ps(c141) _cb(c141); + float4x4 DirectionalLightMatrix _ps(c131) _cb(c131); END_CONSTANTS +struct VertexInput +{ + float4 Position : POSITION; + float2 TexCoord : TEXCOORD; +}; + struct PixelInput { float4 Position : SV_POSITION; float2 TexCoord : TEXCOORD0; }; +PixelInput main_vs(VertexInput input) +{ + PixelInput output; + + output.Position = input.Position; + output.TexCoord = input.TexCoord; + + return output; +} + // Pixel Shader float3 FresnelSchlick(float cosTheta, float3 F0) @@ -74,61 +89,22 @@ float GeometrySmith(float3 N, float3 V, float3 L, float roughness) return ggx1 * ggx2; } -float3 ConvertCubeUVToXYZ(int index, float u, float v) -{ - float uc = 2.0 * u - 1.0; - float vc = 2.0 * v - 1.0; - - if (index == 0) { return float3(1.0, vc, -uc); } - if (index == 1) { return float3(-1.0, vc, uc); } - if (index == 2) { return float3(uc, 1.0, -vc); } - if (index == 3) { return float3(uc, -1.0, vc); } - if (index == 4) { return float3(uc, vc, -1.0); } - if (index == 5) { return float3(-uc, vc, 1.0); } - - return float3(1.0, 0.0, 0.5); -} - -float ComputeShadow(float4 positionLightSpace, int directionalLightIndex) +float ComputeShadow(float4 positionLightSpace) { float bias = 0.001; // maps to [-1, 1] float3 projectionCoords = positionLightSpace.xyz / positionLightSpace.w; - // map our UV sample coordinates to a cube map sample vector - float3 cubeMapSampleVector; - if (directionalLightIndex == 0) - { - cubeMapSampleVector = float3(1.0f, projectionCoords.y, -projectionCoords.x); - } - else if (directionalLightIndex == 1) - { - cubeMapSampleVector = float3(-1.0f, projectionCoords.y, projectionCoords.x); - } - else if (directionalLightIndex == 2) - { - cubeMapSampleVector = float3(projectionCoords.x, 1.0f, projectionCoords.y); - } - else if (directionalLightIndex == 3) - { - cubeMapSampleVector = float3(projectionCoords.x, -1.0f, -projectionCoords.y); - } - else if (directionalLightIndex == 4) - { - cubeMapSampleVector = float3(projectionCoords.x, projectionCoords.y, 1.0); - } - else - { - cubeMapSampleVector = float3(-projectionCoords.x, projectionCoords.y, -1.0); - } - - float closestDepth = SAMPLE_CUBEMAP(shadowMap, cubeMapSampleVector).r; + //transform to [0, 1] range + projectionCoords = projectionCoords * 0.5 + 0.5; + + float closestDepth = SAMPLE_TEXTURE(directionalShadowMap, positionLightSpace.xy).r; float currentDepth = projectionCoords.z; if (projectionCoords.z > 1.0) { return 0.0; } - float shadow = currentDepth > closestDepth ? 1.0 : 0.0; + float shadow = currentDepth - bias > closestDepth ? 1.0 : 0.0; return shadow; } @@ -179,7 +155,7 @@ float4 ComputeColor( float3 Lo = float3(0.0, 0.0, 0.0); - // point light + // point lights for (int i = 0; i < MAX_POINT_LIGHTS; i++) { float3 lightDir = PointLightPositions[i] - worldPosition; @@ -191,16 +167,13 @@ float4 ComputeColor( } // directional light - for (int i = 0; i < MAX_DIRECTIONAL_LIGHTS; i++) - { - float4 positionLightSpace = mul(float4(worldPosition, 1.0), DirectionalLightMatrices[i]); - float shadow = ComputeShadow(positionLightSpace, i); + float4 positionLightSpace = mul(float4(worldPosition, 1.0), DirectionalLightMatrix); + float shadow = ComputeShadow(positionLightSpace); - float3 lightDir = DirectionalLightDirections[i]; - float3 radiance = DirectionalLightColors[i]; + float3 lightDir = DirectionalLightDirection; + float3 radiance = DirectionalLightColor; - Lo += ComputeLight(lightDir, radiance, F0, V, N, albedo, metallic, roughness, (1.0 - shadow)); - } + Lo += ComputeLight(lightDir, radiance, F0, V, N, albedo, metallic, roughness, (1.0 - shadow)); float3 ambient = float3(0.03, 0.03, 0.03) * albedo; // * AO; float3 color = ambient + Lo; @@ -232,6 +205,7 @@ Technique DeferredPBR { Pass { + VertexShader = compile vs_3_0 main_vs(); PixelShader = compile ps_3_0 main_ps(); } } diff --git a/Effects/HLSL/Macros.fxh b/Effects/HLSL/Macros.fxh index 91d1702..5f080cd 100644 --- a/Effects/HLSL/Macros.fxh +++ b/Effects/HLSL/Macros.fxh @@ -52,6 +52,8 @@ sampler Name##Sampler : register(s##index) = sampler_state { Texture = (Name); }; #define SAMPLE_TEXTURE(Name, texCoord) tex2D(Name##Sampler, texCoord) +#define SAMPLE_TEXTURE_LOD(Name, texCoord) tex2Dlod(Name##Sampler, texCoord) +#define SAMPLE_VERTEX_TEXTURE(Name, texCoord) tex2Dlod(Name##Sampler, float4(texCoord, 0, 0)) #define SAMPLE_CUBEMAP(Name, texCoord) texCUBE(Name##Sampler, texCoord) #define SAMPLE_CUBEMAP_LOD(Name, texCoord) texCUBElod(Name##Sampler, texCoord) #endif diff --git a/Effects/HLSL/SimpleDepthEffect.fx b/Effects/HLSL/SimpleDepthEffect.fx index 787ea2a..f813bd7 100644 --- a/Effects/HLSL/SimpleDepthEffect.fx +++ b/Effects/HLSL/SimpleDepthEffect.fx @@ -3,8 +3,6 @@ BEGIN_CONSTANTS float4x4 ModelViewProjection _vs(c0) _cb(c0); - float near _vs(c4) _cb(c4); - float far _vs(c5) _cb(c5); MATRIX_CONSTANTS @@ -26,9 +24,7 @@ VertexShaderOutput main_vs(VertexShaderInput input) VertexShaderOutput output; output.Position = mul(input.Position, ModelViewProjection); - output.Depth = output.Position.z / output.Position.w; - output.Depth = (output.Depth * 0.5) + 0.5; return output; } diff --git a/Effects/SimpleDepthEffect.cs b/Effects/SimpleDepthEffect.cs index c821a6a..3594a7c 100644 --- a/Effects/SimpleDepthEffect.cs +++ b/Effects/SimpleDepthEffect.cs @@ -6,8 +6,6 @@ namespace Kav public class SimpleDepthEffect : Effect { EffectParameter modelViewProjectionParam; - EffectParameter nearParam; - EffectParameter farParam; Matrix model; Matrix view; @@ -45,9 +43,6 @@ namespace Kav } } - public float Near { get; set; } - public float Far { get; set; } - public SimpleDepthEffect(GraphicsDevice graphicsDevice) : base(graphicsDevice, Resources.SimpleDepthEffect) { CacheEffectParameters(); @@ -65,15 +60,11 @@ namespace Kav dirtyFlags &= ~EffectDirtyFlags.WorldViewProj; } - nearParam.SetValue(Near); - farParam.SetValue(Far); } private void CacheEffectParameters() { modelViewProjectionParam = Parameters["ModelViewProjection"]; - nearParam = Parameters["near"]; - farParam = Parameters["far"]; } } } diff --git a/Extensions/Vector3Extensions.cs b/Extensions/Vector3Extensions.cs new file mode 100644 index 0000000..cf6be15 --- /dev/null +++ b/Extensions/Vector3Extensions.cs @@ -0,0 +1,16 @@ +using Microsoft.Xna.Framework; + +namespace Kav.Extensions +{ + public static class Vector3Extensions + { + public static Vector3 Floor(this Vector3 input) + { + var x = (float)System.Math.Floor(input.X); + var y = (float)System.Math.Floor(input.Y); + var z = (float)System.Math.Floor(input.Z); + + return new Vector3(x, y, z); + } + } +} diff --git a/Kav.Core.csproj b/Kav.Core.csproj index 7957739..f337bb6 100644 --- a/Kav.Core.csproj +++ b/Kav.Core.csproj @@ -7,11 +7,13 @@ Evan Hemsley 2020 true Kav + true + diff --git a/Kav.Framework.csproj b/Kav.Framework.csproj index 0557675..5c246ad 100644 --- a/Kav.Framework.csproj +++ b/Kav.Framework.csproj @@ -7,11 +7,13 @@ Evan Hemsley 2020 true Kav + true + diff --git a/Lights/DirectionalLight.cs b/Lights/DirectionalLight.cs index 835587e..5bad9a0 100644 --- a/Lights/DirectionalLight.cs +++ b/Lights/DirectionalLight.cs @@ -8,22 +8,6 @@ namespace Kav public Color Color { get; } public float Intensity { get; } - public Matrix View - { - get - { - return Matrix.CreateLookAt((Direction * 5f), Vector3.Zero, Vector3.Up); - } - } - - public Matrix Projection - { - get - { - return Matrix.CreateOrthographic(20f, 20f, 1f, 7.5f); - } - } - public DirectionalLight(Vector3 direction, Color color, float intensity = 1f) { Direction = direction; diff --git a/Renderer.cs b/Renderer.cs index 9b52411..7489060 100644 --- a/Renderer.cs +++ b/Renderer.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Kav.Extensions; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -10,7 +11,7 @@ namespace Kav private int RenderDimensionsX { get; } private int RenderDimensionsY { get; } - private RenderTargetCube DirectionalLightDepthTarget { get; } + private RenderTarget2D DirectionalLightDepthTarget { get; } private SimpleDepthEffect SimpleDepthEffect { get; } private RenderTarget2D gPosition { get; } @@ -19,6 +20,8 @@ namespace Kav private RenderTarget2D gMetallicRoughness { get; } private RenderTarget2D deferredRenderTarget { get; } + private VertexBuffer fullscreenTriangle { get; } + private RenderTargetBinding[] GBuffer { get; } private DeferredPBREffect DeferredPBREffect { get; } @@ -31,9 +34,10 @@ namespace Kav RenderDimensionsX = renderDimensionsX; RenderDimensionsY = renderDimensionsY; - DirectionalLightDepthTarget = new RenderTargetCube( + DirectionalLightDepthTarget = new RenderTarget2D( GraphicsDevice, 1024, + 1024, false, SurfaceFormat.Single, DepthFormat.Depth24 @@ -91,16 +95,20 @@ namespace Kav SimpleDepthEffect = new SimpleDepthEffect(GraphicsDevice); DeferredPBREffect = new DeferredPBREffect(GraphicsDevice); + fullscreenTriangle = new VertexBuffer(GraphicsDevice, typeof(VertexPositionTexture), 3, BufferUsage.WriteOnly); + fullscreenTriangle.SetData(new VertexPositionTexture[3] { + new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 0)), + new VertexPositionTexture(new Vector3(-1, 3, 0), new Vector2(0, -2)), + new VertexPositionTexture(new Vector3(3, -1, 0), new Vector2(2, 0)) + }); + SpriteBatch = new SpriteBatch(GraphicsDevice); GraphicsDevice.SetRenderTarget(deferredRenderTarget); graphicsDevice.Clear(Color.White); - for (int i = 0; i < 6; i++) - { - GraphicsDevice.SetRenderTarget(DirectionalLightDepthTarget, (CubeMapFace) i); - GraphicsDevice.Clear(Color.White); - } + GraphicsDevice.SetRenderTarget(DirectionalLightDepthTarget); + GraphicsDevice.Clear(Color.White); GraphicsDevice.SetRenderTarget(null); } @@ -109,16 +117,15 @@ namespace Kav Camera camera, IEnumerable<(Model, Matrix)> modelTransforms, IEnumerable pointLights, - IEnumerable directionalLights + DirectionalLight directionalLight ) { - var directionalLightIndex = 0; + var cameraViewProjectionMatrix = camera.View * camera.Projection; - foreach (var directionalLight in directionalLights) - { - if (directionalLightIndex > 5) { break; } - ShadowMapRender(modelTransforms, directionalLight, (CubeMapFace) directionalLightIndex); - directionalLightIndex += 1; - } + ShadowMapRender( + modelTransforms, + directionalLight, + cameraViewProjectionMatrix + ); GraphicsDevice.SetRenderTargets(GBuffer); GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1f, 0); @@ -165,7 +172,6 @@ namespace Kav DeferredPBREffect.GAlbedo = gAlbedo; DeferredPBREffect.GNormal = gNormal; DeferredPBREffect.GMetallicRoughness = gMetallicRoughness; - DeferredPBREffect.DirectionalShadowMap = DirectionalLightDepthTarget; DeferredPBREffect.EyePosition = Matrix.Invert(camera.View).Translation; int i = 0; @@ -176,31 +182,53 @@ namespace Kav i++; } - i = 0; - foreach (var directionalLight in directionalLights) - { - if (i > DeferredPBREffect.MaxDirectionalLights) { break; } - DeferredPBREffect.DirectionalLights[i] = directionalLight; - i++; - } + DeferredPBREffect.DirectionalShadowMap = DirectionalLightDepthTarget; + DeferredPBREffect.DirectionalLightDirection = directionalLight.Direction; + DeferredPBREffect.DirectionalLightColor = directionalLight.Color.ToVector3() * directionalLight.Intensity; - SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, null, null, null, DeferredPBREffect); - SpriteBatch.Draw(deferredRenderTarget, Vector2.Zero, Color.White); - SpriteBatch.End(); + foreach (EffectPass pass in DeferredPBREffect.CurrentTechnique.Passes) + { + pass.Apply(); + GraphicsDevice.SetVertexBuffer(fullscreenTriangle); + GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1); + } } // for shadow mapping - public void ShadowMapRender(IEnumerable<(Model, Matrix)> modelTransforms, DirectionalLight directionalLight, CubeMapFace face) - { - GraphicsDevice.SetRenderTarget(DirectionalLightDepthTarget, face); + public void ShadowMapRender( + IEnumerable<(Model, Matrix)> modelTransforms, + DirectionalLight directionalLight, + Matrix cameraViewProjectionMatrix + ) { + GraphicsDevice.SetRenderTarget(DirectionalLightDepthTarget); GraphicsDevice.Clear(Color.White); GraphicsDevice.DepthStencilState = DepthStencilState.Default; GraphicsDevice.BlendState = BlendState.Opaque; - SimpleDepthEffect.View = directionalLight.View; - SimpleDepthEffect.Projection = directionalLight.Projection; - SimpleDepthEffect.Near = 0.1f; // FIXME: this is a kludge - SimpleDepthEffect.Far = 200f; + var right = Vector3.Cross(Vector3.Up, directionalLight.Direction); + var up = Vector3.Cross(directionalLight.Direction, right); + + var lightRotation = Matrix.CreateLookAt(Vector3.Zero, -directionalLight.Direction, up); + + var cameraBoundingFrustum = new BoundingFrustum(cameraViewProjectionMatrix); + + Vector3[] frustumCorners = cameraBoundingFrustum.GetCorners(); + for (var i = 0; i < frustumCorners.Length; i++) + { + frustumCorners[i] = Vector3.Transform(frustumCorners[i], lightRotation); + } + + BoundingBox lightBox = BoundingBox.CreateFromPoints(frustumCorners); + Vector3 boxSize = lightBox.Max - lightBox.Min; + Vector3 halfBoxSize = boxSize * 0.5f; + + Vector3 lightPosition = lightBox.Min + halfBoxSize; + lightPosition.Z = lightBox.Min.Z; + lightPosition = Vector3.Transform(lightPosition, Matrix.Invert(lightRotation)); + + SimpleDepthEffect.View = Matrix.CreateLookAt(lightPosition, lightPosition - directionalLight.Direction, up); + SimpleDepthEffect.Projection = Matrix.CreateOrthographic(boxSize.X, boxSize.Y, -boxSize.Z, boxSize.Z); + DeferredPBREffect.DirectionalLightMatrix = SimpleDepthEffect.View * SimpleDepthEffect.Projection; foreach (var (model, transform) in modelTransforms) {