Corrupting of the view if far from world center

Started by
11 comments, last by BlackJoker 9 years, 5 months ago

My vertex shader code is:


struct VertexInputType
{
    float4 position : SV_POSITION;
	float3 normal : NORMAL;
	float2 tex : TEXCOORD0;
	
};

struct PixelInputType
{
    float4 position : SV_POSITION;
 	float3 normal : NORMAL;
	float2 tex : TEXCOORD0;
	float3 viewDirection: TEXCOORD1;
};


////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output;
	
	// Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;
	// Calculate the position of the vertex against the world, view, and projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix); 
    output.position = mul(output.position, projectionMatrix); 
	
	output.position.z = log(zNear*output.position.z + 1) / log(zNear*zFar + 1) * output.position.w;

	// Store the texture coordinates for the pixel shader.
	output.tex = input.tex;
    
	// Calculate the normal vector against the world matrix only.
	  
	output.normal = mul(input.normal, (float3x3)worldMatrix);
	// Normalize the normal vector.
    output.normal = normalize(output.normal);

	float4 posWorld = mul(input.position, worldMatrix);
	output.viewDirection = float4(cameraPosition,0) - posWorld;
    

    return output;
}
Advertisement
output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix); 
    output.position = mul(output.position, projectionMatrix);
Here, you're transforming positions from model space to world space to view space to projection space.
As others have pointed out, world space coordinates are too large for you, so you're losing precision.

Instead, multiply worldMatrix and viewMatrix together on the CPU side ahead of time to produce worldViewMatrix.
Then in your shader, you'll be able to go from model space straight to view space (without making a stop via world space).

Thanks to all.

I guess that I will stop at keep camera in center suggestion. This seems to be the easiest and cleanest way to workaround such issues.

This topic is closed to new replies.

Advertisement