This topic is now archived and is closed to further replies.

Diffuse lighting in a vertex shader

This topic is 5576 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey, I''m trying to get simple diffuse lighting from a point light to work in my Cg vertex shader. Anyone who has done vertex shaders in d3d should be able to help, as i think it might be how i''m transforming the light position into object space. Anyhow, here is my cg program:
struct appin : application2vertex
    float4 position;
    float4 normal;
	float4 color0;

struct vertout : vertex2fragment
    float4 position : POSITION;
    float4 color0   : COLOR0;

vertout main( appin IN, 
             uniform float4x4 modelViewProjection,
             uniform float4x4 modelView,
             uniform float4x4 modelViewInverse,
			 uniform float4 LightPos ) // light pos is in model space
    vertout OUT;

    OUT.position = mul( modelViewProjection, IN.position );

    float4 ambientColor = float4(1,1,1,1);

    // Get a direction vector from the vertex pos to the light pos
    float4 light_to_vert = normalize( IN.position - LightPos );

    // Get the angle between the vertex normal and the light direction
    float fAngle = dot (IN.normal, light_to_vert); 
    fAngle = (fAngle / 2) + 0.5f;

    OUT.color0 =  fAngle * ambientColor;
    OUT.color0.a = 1;

    return OUT;
It displays my cube in a constant pale green. >_< I''m thinking that my conversion of the lightpos from worldspace to object space is wrong:
HRESULT CMyD3DApplication::SetupLight ()
    D3DXVECTOR4     modelSpacePos;
    D3DXMATRIX      matInvWorld;

    // transform light into model space
    D3DXMatrixInverse (&matInvWorld, NULL, &m_matWorld);
    D3DXVec3Transform (&modelSpacePos, &m_lightPos, &matInvWorld);

    m_pVertexProgramLit->SetShaderConstant(m_pLightPosition_vsLit, modelSpacePos);

    return S_OK;
Whats wrong here? Thanks.

Share this post

Link to post
Share on other sites