Having trouble projecting a ShadowMap on to a surface - c#

So I am having trouble rendering a shadow map in a shader I'm kind of new to shader coding(roughly 3 months), I'll talk you through what I am doing(well what I think I am doing).
So to start off by creating a script(ShadowCopy.cs) which copies the shadow map then passes it to a global variable(_MyShadowMap). Now the shader(ShadowMapping.shader), then I create getShadowCoord which calculates the shadowMap then applies the getCascadeWeights() to the shadow Coordinates(for Optimal reasons).
Then I create computeCameraSpacePosFromDepthAndInvProjMat() which computes the camera space position based from depth and inverse projection matrix. Now the frag function which renders the pixels
making it visible in the Application, but overall its just Screen-Space-Shadows.
So the problem I am facing are the Projection Values which I honestly don't know how to fix. You can see the Problem in the picture.
enter image description here
The Material Settings for ShadowMapping.shader.
enter image description here
ShadowCopy.cs
using UnityEngine;
using UnityEngine.Rendering;
public class ShadowCopy : MonoBehaviour
{
public Light m_Light;
RenderTexture m_ShadowmapCopy;
public int TextureSize = 512;
void Start()
{
RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;
m_ShadowmapCopy = new RenderTexture(TextureSize, TextureSize, 16, RenderTextureFormat.ARGB32);
m_ShadowmapCopy.filterMode = FilterMode.Point;
CommandBuffer cb = new CommandBuffer();
cb.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);
cb.Blit(shadowmap, new RenderTargetIdentifier(m_ShadowmapCopy));
cb.SetGlobalTexture("_MyShadowMap", shadowmap);
m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, cb);
}
void OnGUI()
{
if (m_ShadowmapCopy != null)
{
GUI.DrawTextureWithTexCoords(new Rect(0, 20, 150, 150), m_ShadowmapCopy, new Rect(0, 0, 1, 1), false);
}
}
ShadowMapping.shader
Shader "Custom/ShadowMapping" {
Properties {
_Color("Main Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGBA)", 2D) = "white" {}
}
SubShader {
Pass {
Tags { "RenderType"="Opaque" }
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0
#include "UnityCG.cginc"
#include "AutoLight.cginc"
uniform float4 _Color;
uniform sampler2D _MyShadowMap;
//UNITY_DECLARE_SHADOWMAP(_MyShadowMap);
uniform sampler2D _MainTex;
float4 LowResDepth_TexelSize;
float4 _ShadowMapTexture_TexelSize;
#define SHADOWMAPSAMPLER_AND_TEXELSIZE_DEFINED
#define UNITY_USE_CASCADE_BLENDING 0
#define UNITY_CASCADE_BLEND_DISTANCE 0.1
struct appdata {
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
#ifdef UNITY_STEREO_INSTANCING_ENABLED
float3 ray0 : TEXCOORD1;
float3 ray1 : TEXCOORD2;
#else
float3 ray : TEXCOORD1;
#endif
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f {
float4 pos : SV_POSITION;
// xy uv / zw screenpos
float4 uv : TEXCOORD0;
// View space ray, for perspective case
float3 ray : TEXCOORD1;
// Orthographic view space positions (need xy as well for oblique matrices)
float3 orthoPosNear : TEXCOORD2;
float3 orthoPosFar : TEXCOORD3;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
v2f vert (appdata v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
float4 clipPos = UnityObjectToClipPos(v.vertex);
o.pos = clipPos;
o.uv.xy = v.texcoord;
o.uv.zw = ComputeNonStereoScreenPos(clipPos);
clipPos.y *= _ProjectionParams.x;
float3 orthoPosNear = mul(unity_CameraInvProjection, float4(clipPos.x,clipPos.y,-1,1)).xyz;
float3 orthoPosFar = mul(unity_CameraInvProjection, float4(clipPos.x,clipPos.y, 1,1)).xyz;
orthoPosNear.z *= -1;
orthoPosFar.z *= -1;
o.orthoPosNear = orthoPosNear;
o.orthoPosFar = orthoPosFar;
return o;
}
UNITY_DECLARE_DEPTH_TEXTURE(_CameraDepthTexture);
inline fixed4 getCascadeWeights(float3 wpos, float z)
{
fixed4 zNear = float4( z >= _LightSplitsNear );
fixed4 zFar = float4( z < _LightSplitsFar );
fixed4 weights = zNear * zFar;
return weights;
}
inline float4 getShadowCoord( float4 wpos, fixed4 cascadeWeights )
{
float3 sc0 = mul (unity_WorldToShadow[0], wpos).xyz;
float3 sc1 = mul (unity_WorldToShadow[1], wpos).xyz;
float3 sc2 = mul (unity_WorldToShadow[2], wpos).xyz;
float3 sc3 = mul (unity_WorldToShadow[3], wpos).xyz;
float4 shadowMapCoordinate = float4(sc0 * cascadeWeights[0] + sc1 * cascadeWeights[1] + sc2 * cascadeWeights[2] + sc3 * cascadeWeights[3], 1);
#if defined(UNITY_REVERSED_Z)
float noCascadeWeights = 1 - dot(cascadeWeights, float4(1, 1, 1, 1));
shadowMapCoordinate.z += noCascadeWeights;
#endif
return shadowMapCoordinate;
}
inline float3 computeCameraSpacePosFromDepthAndInvProjMat(v2f i)
{
float zdepth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv.xy);
#if defined(UNITY_REVERSED_Z)
zdepth = 1 - zdepth;
#endif
float4 clipPos = float4(i.uv.zw, zdepth, 1.0);
clipPos.xyz = 2.0f * clipPos.xyz - 1.0f;
float4 camPos = mul(unity_CameraInvProjection, clipPos);
camPos.xyz /= camPos.w;
camPos.z *= -1;
return camPos.xyz;
}
half4 frag(v2f i) : COLOR
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
float3 vpos = computeCameraSpacePosFromDepthAndInvProjMat(i);
float4 wpos = mul (unity_CameraToWorld, float4(vpos,1));
fixed4 cascadeWeights = getCascadeWeights (wpos, vpos.z);
float4 shadowCoord = getShadowCoord(wpos, cascadeWeights);
float shadow = tex2D(_MyShadowMap, shadowCoord);
shadow = lerp(_LightShadowData.r, 1.0, shadow);
fixed4 res = shadow;
return shadow * tex2D(_MainTex, i.uv) * _Color;
}
ENDCG
}
}
}

A few items that jump out at me:
Change: cb.SetGlobalTexture("_MyShadowMap", shadowmap); to cb.SetGlobalTexture("_MyShadowMap", m_ShadowmapCopy);
Change: uniform sampler2D _MyShadowMap; to UNITY_DECLARE_SHADOWMAP(_MyShadowMap);
Change float shadow = tex2D(_MyShadowMap, shadowCoord); to float shadow = UNITY_SAMPLE_SHADOW(_MyShadowMap, shadowCoord);

Related

Using custom shader results in black image

I use unity 2018.3.5f1. I would like to overlay a custom shader while rendering an image. Following is my onRenderImage Function.
void OnRenderImage(RenderTexture src, RenderTexture dest) {
// shaderMaterial renders the image with Barrel distortion and disparity effect
Graphics.Blit(camTextureHolder.mainTexture, nullRenderTexture, shaderMaterial);
// measure average frames per second
m_FpsAccumulator++;
if (Time.realtimeSinceStartup > m_FpsNextPeriod) {
m_CurrentFps = (int)(m_FpsAccumulator / fpsMeasurePeriod);
m_FpsAccumulator = 0;
m_FpsNextPeriod += fpsMeasurePeriod;
}
}
The issue is that the entire screen appears to be black while I'm trying to do so. May I know how do I fix this issue?
Update:
This is the code for the shader that I'm using
Shader "Custom/FakeAR"
{
Properties{
_MainTex("", 2D) = "white" {}
[HideInInspector]_FOV("FOV", Range(1, 2)) = 1.6
[HideInInspector]_Disparity("Disparity", Range(0, 0.3)) = 0.1
[HideInInspector]_Alpha("Alpha", Range(0, 2.0)) = 1.0
}
SubShader{
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct v2f {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
};
// Default Vertex Shader
v2f vert(appdata_img v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = MultiplyUV(UNITY_MATRIX_TEXTURE0, v.texcoord.xy);
return o;
}
// Parameters
sampler2D _MainTex;
float _FOV;
// Alpha is the ratio of pixel density: width to height
float _Alpha;
// Disparity is the portion to separate
// larger disparity cause closer stereovision
float _Disparity;
// Fragment Shader: Remap the texture coordinates to combine
// barrel distortion and disparity video display
fixed4 frag(v2f i) : COLOR {
float2 uv1, uv2, uv3;
float t1, t2;
float offset;
// uv1 is the remap of left and right screen to a full screen
uv1 = i.uv - 0.5;
uv1.x = uv1.x * 2 - 0.5 + sign(i.uv.x < 0.5);
t1 = sqrt(1.0 - uv1.x * uv1.x - uv1.y * uv1.y);
t2 = 1.0 / (t1 * tan(_FOV * 0.5));
// uv2 is the remap of side screen with barrel distortion
uv2 = uv1 * t2 + 0.5;
// black color for out-of-range pixels
if (uv2.x >= 1 || uv2.y >= 1 || uv2.x <= 0 || uv2.y <= 0) {
return fixed4(0, 0, 0, 1);
}
else {
offset = 0.5 - _Alpha * 0.5 + _Disparity * 0.5 - _Disparity * sign(i.uv.x < 0.5);
// uv3 is the remap of image texture
uv3 = uv2;
uv3.x = uv2.x * _Alpha + offset;
return tex2D(_MainTex, uv3);
}
}
ENDCG
}
}
FallBack "Diffuse"
}
Is it because of the shader?
Well I think it's working it's just that the shader has nothing to render meaning it goes for black. You might want the shader to use the excisting camera texture. So maybe this?
void OnRenderImage(RenderTexture src, RenderTexture dest) {
// shaderMaterial renders the image with Barrel distortion and disparity effect
Graphics.Blit(src, dst, shaderMaterial);
// measure average frames per second
m_FpsAccumulator++;
if (Time.realtimeSinceStartup > m_FpsNextPeriod) {
m_CurrentFps = (int)(m_FpsAccumulator / fpsMeasurePeriod);
m_FpsAccumulator = 0;
m_FpsNextPeriod += fpsMeasurePeriod;
}
}
Try making the shader really default and see if it renders something. So try a shader that looks like this:
Shader "Examples/ExampleDisplacement"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
float4 frag (v2f i) : SV_Target
{
float4 col = tex2D(_MainTex, i.uv);
return col;
}
ENDCG
}
}
}

Unity Scanlines Shader not working

I was working on this scanlines shader but it doesn't work.
What i try to do is to set every pixel to black if the y position is a multiple of 2. but it doesn't work. Nothing is changing on the screen.
The color inversion test (by changing return col to return 1 - col works totally fine, so the shader actually affects the image.
Does anyone know what's the problem?
Thanks.
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
float4 position : TEXCOORD1;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
o.uv = v.uv;
o.position = ComputeScreenPos(o.vertex);
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
if (i.uv.y % 2 == 0)
col -= col;
return col;
}
ENDCG
}
Edit: I'm using Unity 5.5.1f1 and my build setting is Standalone Windows/MacOSX/Linux.
First i.uv has values from 0 to 1. If this is a post process effect and you want window y position that is i.uv.y * _ScreenParams.y, or you can use i.vertex.y.
Second someFloat % 2 returns a float in the range 0..2 (see HLSL modulus operator)
so the if statement should be:
if (i.uv.y * _ScreenParams.y % 2 < 1)
col -= col;
But here you can use the step function instead.
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
float ypos = i.uv.y * _ScreenParams.y;
float ymod = ypos % 2;
col.rgb *= step(1, ymod);
return col;
}

How to blend cubemaps in Unity Shader Language

Hi fellow Unity devs,
I have been trying to modify the built in Unity shader for Skybox/Cubemap, such that it takes a second cubemap, and has a blend factor between the two.
I have attempted the following shader script, however it does not produce the intended result, is anybody who knows more about shader code than me please able to assist in my learning/results? I am finding it very difficult to learn how to use shader code, only been using Unity for about 2-3 months.
Shader "RenderFX/Skybox2" {
Properties {
_Tint ("Tint Color", Color) = (.5, .5, .5, .5)
[Gamma] _Exposure ("Exposure", Range(0, 8)) = 1.0
_Rotation ("Rotation", Range(0, 360)) = 0
_Rotation2 ("Rotation 2", Range(0, 360)) = 0
_Blend ("Blend", Range (0, 1) ) = 0.5
[NoScaleOffset] _Tex ("Cubemap (HDR)", Cube) = "grey" {}
_Skybox2 ("Skybox two", Cube) = ""
}
SubShader {
Tags { "Queue"="Background" "RenderType"="Background" "PreviewType"="Skybox" }
Cull Off ZWrite Off
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
samplerCUBE _Tex;
half4 _Tex_HDR;
half4 _Tint;
half _Exposure;
float _Rotation;
float3 RotateAroundYInDegrees (float3 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float3(mul(m, vertex.xz), vertex.y).xzy;
}
struct appdata_t {
float4 vertex : POSITION;
};
struct v2f {
float4 vertex : SV_POSITION;
float3 texcoord : TEXCOORD0;
};
v2f vert (appdata_t v)
{
v2f o;
float3 rotated = RotateAroundYInDegrees(v.vertex, _Rotation);
o.vertex = UnityObjectToClipPos(rotated);
o.texcoord = v.vertex.xyz;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half4 tex = texCUBE (_Tex, i.texcoord);
half3 c = DecodeHDR (tex, _Tex_HDR);
c = c * _Tint.rgb * unity_ColorSpaceDouble.rgb;
c *= _Exposure;
return half4(c, 1);
}
ENDCG
}
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 2.0
#include "UnityCG.cginc"
samplerCUBE _Skybox2;
half4 _Skybox2_HDR;
half4 _Tint;
half _Exposure;
float _Rotation2;
float _Blend;
float3 RotateAroundYInDegrees (float3 vertex, float degrees)
{
float alpha = degrees * UNITY_PI / 180.0;
float sina, cosa;
sincos(alpha, sina, cosa);
float2x2 m = float2x2(cosa, -sina, sina, cosa);
return float3(mul(m, vertex.xz), vertex.y).xzy;
}
struct appdata_t {
float4 vertex : POSITION;
};
struct v2f {
float4 vertex : SV_POSITION;
float3 texcoord : TEXCOORD0;
};
v2f vert (appdata_t v)
{
v2f o;
float3 rotated = RotateAroundYInDegrees(v.vertex, _Rotation2);
o.vertex = UnityObjectToClipPos(rotated);
o.texcoord = v.vertex.xyz;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
half4 tex = texCUBE (_Skybox2, i.texcoord);
half3 c2 = DecodeHDR (tex, _Skybox2_HDR);
c2 = c2 * _Tint.rgb * unity_ColorSpaceDouble.rgb;
c2 *= _Exposure;
return half4(c2, 1);
}
ENDCG
}
Pass {
SetTexture[c]
SetTexture[c2] {
ConstantColor (0,0,0, [_Blend])
Combine texture Lerp(constant) previous
}
}
}
Fallback Off
}
The result is a grey view, and I don't think I am passing the c/c2 variables properly, or even if they CAN be passed like that. I am really stumped as to how I might achieve this effect.
The blend pass works fine for just the plain textures, but I need it to maintain the rotation values, not just the textures.
Thank you in advance to you shader/Unity experts out there! I hope one day to join your ranks.

Problems with my unity shader

I have began to create some shaders for my university group project however I have ran into a bit of a snag with my water shader. I am trying to create one which utilises two overlapping normal maps.
Whilst everything looks okay in the editor, when I then publish to the webplayer, the scene looks like its unlit.
Heres my code for the shader:
//
// Filename : WaterShader.shader
// Version : 2.0
// Date : 1st March 2014
//
Shader "Flight/WaterShader/2.0"
{
// Set up variables so we can access them in inspector mode
Properties
{
// Variable to control the colour tint
_Color ("Base Color", Color) = (1, 1, 1, 1)
// Variables for specular
_SpecularColor ("Specular Color", Color) = (1, 1, 1, 1)
_SpecularAmount ("Shininess", Float) = 10
// Variable for setting the base texture
_MainTex ("Water Texture", 2D) = "white" { }
// Variables to set the normal map 1
_BumpMapA ("Normal Map", 2D) = "bump" { }
_BumpDepthA ("Depth", Range(0.25, 10.0)) = 1
// Variables to set the normal map 2
_BumpMapB ("Normal Map", 2D) = "bump" { }
_BumpDepthB ("Depth", Range(0.25, 10.0)) = 1
}
SubShader
{
pass
{
Tags { "RenderType" = "Opaque" }
Lighting On
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers flash
// Variables
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _BumpMapA;
float4 _BumpMapA_ST;
float _BumpDepthA;
sampler2D _BumpMapB;
float4 _BumpMapB_ST;
float _BumpDepthB;
float4 _Color;
float4 _SpecularColor;
float _SpecularAmount;
float4 _LightColor0;
struct vertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 texcoord : TEXCOORD0;
float4 tangent : TANGENT;
};
struct vertexOutput
{
float4 pos : SV_POSITION;
float4 tex : TEXCOORD0;
float4 posWorld : TEXCOORD1;
float3 normalWorld : TEXCOORD2;
float3 tangentWorld : TEXCOORD3;
float3 binormalWorld : TEXCOORD4;
};
vertexOutput vert(vertexInput input)
{
vertexOutput output;
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
output.tex = input.texcoord;
output.posWorld = mul(_Object2World, input.vertex);
output.normalWorld = normalize( mul( float4( input.normal, 0.0f ), _World2Object ).xyz );
output.tangentWorld = normalize( mul( _Object2World, input.tangent ).xyz );
output.binormalWorld = normalize( cross( output.normalWorld, output.tangentWorld) * input.tangent.w );
return output;
}
float4 frag(vertexOutput input) : COLOR
{
// Set up variables
float3 viewDirection;
float3 lightDirection;
float3 normalDirection;
float lightIntensity;
float4 normalColorA;
float4 normalColorB;
float4 normalColor;
float3 normalLocalA;
float3 normalLocalB;
float3 normalLocal;
float3x3 normalWorld;
float4 textureColor;
float3 diffuseColor;
float3 specularColor;
float3 lightColor;
float4 finalColor;
// Begin calculations
// Calculate the angle we are looking at the pixel
viewDirection = normalize(_WorldSpaceCameraPos.xyz - input.posWorld.xyz );
if(_WorldSpaceLightPos0.w == 0.0)
{
lightIntensity = 1.0;
lightDirection = normalize(_WorldSpaceLightPos0.xyz);
}
else
{
float3 fragmentToLightSource = _WorldSpaceLightPos0.xyz - input.posWorld.xyz;
float distance = length(fragmentToLightSource);
lightIntensity = 1.0 / distance;
lightDirection = normalize(fragmentToLightSource);
}
// Sample the textures
textureColor = tex2D(_MainTex, input.tex.xy * _MainTex_ST.xy + _MainTex_ST.zw);
normalColorA = tex2D(_BumpMapA, input.tex.xy * _BumpMapA_ST.xy + _BumpMapA_ST.zw);
normalColorB = tex2D(_BumpMapB, input.tex.xy * _BumpMapB_ST.xy + _BumpMapB_ST.zw);
// Expand the normals and set the intensity of the normal map
normalLocalA = float3(2.0 * normalColorA.ag - float2(1.0, 1.0), 0.0);
normalLocalA.z = _BumpDepthA;
normalLocalB = float3(2.0 * normalColorB.ag - float2(1.0, 1.0), 0.0);
normalLocalB.z = _BumpDepthB;
// Combine the two normals
normalLocal = normalize(normalLocalA + normalLocalB);
// Calculate the normal in the world
normalWorld = float3x3( input.tangentWorld, input.binormalWorld, input.normalWorld );
normalDirection = normalize( mul( normalLocal, normalWorld ) );
// Calculate lighting
diffuseColor = lightIntensity * _LightColor0.xyz * saturate( dot(normalDirection, lightDirection) );
specularColor = diffuseColor * _SpecularColor.xyz * pow( saturate( dot( reflect(-lightDirection, normalDirection), viewDirection) ), _SpecularAmount );
// Combine lighting
lightColor = UNITY_LIGHTMODEL_AMBIENT.xyz + diffuseColor + specularColor;
// Apply lighting to the texture color
textureColor = float4( textureColor.xyz * lightColor * _Color.xyz, 1.0);
return textureColor;
}
ENDCG
}
}
FallBack "Specular"
}
In the editor it looks like this:
Where as in the webplayer it looks like this:
Anyone able to help me see where I have gone wrong? :)
You need a separate pass of pixel light in the scene for the web player. Replace your current SubShader Parameters with
SubShader
{
Tags {"RenderType" = "Opaque"}
Pass
{
Tags {"LightMode" = "ForwardAdd"}
}
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma exclude_renderers flash

HLSL Shader throws error when I try to use value

So I'm trying to learn myself some HLSL, but I am stumped. I'm writing a custom shader that has ambient lighting and a simple point-light color thing.
Here is the shader code:
`float4x4 World;
float4x4 View;
float4x4 Projection;
// TODO: add effect parameters here.
float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.5;
float4 DiffuseColor = float4(1, 1, 1, 1);
float3 LightPosition = float3(32, 32, 64);
float4 LightDiffuseColor = float4(0.3, 0.05, 0, 1); // intensity multiplier
float4 LightSpecularColor = float4(1, 1, 1, 1); // intensity multiplier
float LightDistance = 50;
texture Texture;
sampler2D textureSampler = sampler_state {
Texture = (Texture);
MinFilter = Point;
MagFilter = Point;
AddressU = Wrap;
AddressV = Wrap;
};
struct VertexShaderInput
{
float4 Pos: POSITION;
float2 TexCoords : TEXCOORD0;
float4 Normal : NORMAL0;
};
struct VertexShaderOutput
{
float4 PosOut : POSITION;
float2 TextureCoordinate : TEXCOORD0;
float3 Normal : TEXCOORD1;
};
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;
float4 worldPosition = mul(input.Pos, World);
float4 viewPosition = mul(worldPosition, View);
output.PosOut= mul(viewPosition, Projection);
output.TextureCoordinate = input.TexCoords;
output.Normal = mul(input.Normal, World);
return output;
}
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
float attenuation = saturate(1.0f - (length(input.PosOut - LightPosition) / LightDistance));
float4 textureColor = tex2D(textureSampler, input.TextureCoordinate);
textureColor.a = 1;
float4 lightCol =
//LightDiffuseColor;
mul(LightDiffuseColor, attenuation);
float4 ambient = (AmbientColor * AmbientIntensity);
ambient.a = 1;
return saturate(textureColor * ambient + lightCol);
}
technique Textured
{
pass Pass1
{
// TODO: set renderstates here.
VertexShader = compile vs_2_0 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
`
The problem has been narrowed down to this section in the pixel shader:
float attenuation = saturate(1.0f - (length(input.PosOut - LightPosition) / LightDistance));
...
float4 lightCol =
//LightDiffuseColor;
mul(LightDiffuseColor, attenuation);
return saturate(textureColor * ambient + lightCol);
It will work fine if i use just the LightDiffuseColor, but as soon as I try to multiply it, it throws this error:
GameContentShadersSimpleTexture.fx(35,21) error X4502 invalid ps_2_0 input semantic 'POSITION'
I'm using XNA for the engine. I'm kinda stumped here. Can anyone help me?
Thanks,
Doodles.
Edit:
Mkay, so I've narrowed it down to a pretty precise spot. It's when the length function is called for (input.PosOut - LightPosition)
All right, so I have a solution for this. Instead of using per-pixel lighting for point lights, I should be using vertex lighting instead. The position semantic is not supported for pixel shader inputs, as seen here. But position still needs to be an ouput for the vertex shader, so it's included in the pixel shader input, but it cannot be used. My updated code is shown below:
float4x4 World;
float4x4 View;
float4x4 Projection;
// TODO: add effect parameters here.
float4 AmbientColor = float4(1, 1, 1, 1);
float AmbientIntensity = 0.5;
float4 DiffuseColor = float4(1, 1, 1, 1);
float3 LightPosition = float3(32, 32, 48);
float4 LightDiffuseColor = float4(0.3, 0.05, 0, 1);
float4 LightSpecularColor = float4(1, 1, 1, 1); // intensity multiplier
float LightDistance = 100;
texture Texture;
sampler2D textureSampler = sampler_state {
Texture = (Texture);
MinFilter = Point;
MagFilter = Point;
AddressU = Wrap;
AddressV = Wrap;
};
struct VertexShaderInput
{
float4 Position : POSITION0;
float4 Normal : NORMAL0;
float2 TextureCoordinate : TEXCOORD0;
};
struct PixelShaderInput
{
float4 Position : POSITION0;
float4 Color : COLOR1;
float3 Normal : TEXCOORD0;
float2 TextureCoordinate : TEXCOORD1;
};
PixelShaderInput VertexShaderFunction(VertexShaderInput input)
{
PixelShaderInput output;
float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);
output.Position= mul(viewPosition, Projection);
output.Color = mul(LightDiffuseColor,saturate(1.0f - (length(mul(input.Position, World) - LightPosition) / LightDistance)));
output.TextureCoordinate = input.TextureCoordinate;
output.Normal = mul(input.Normal, World);
return output;
}
float4 PixelShaderFunction(PixelShaderInput input) : COLOR0
{
float4 textureColor = tex2D(textureSampler, input.TextureCoordinate);
textureColor.a = 1;
float4 ambient = (AmbientColor * AmbientIntensity);
ambient.a = 1;
return saturate(textureColor * ambient + input.Color);
}
technique Textured
{
pass Pass1
{
// TODO: set renderstates here.
VertexShader = compile vs_1_1 VertexShaderFunction();
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}

Categories

Resources