sampler2D Texture1;

float3 lookup(float3 mappos, float3 offsetpos, float3 norm)
{
	float3 c = float3(0, 0, 0);
	float4 streetlightcell = tex2D( Texture1, offsetpos.xz+mappos.xz );
	if(streetlightcell.a > 0)
	{
		float3 lightvec = streetlightcell.rgb - mappos*1471;
		float dist = length(lightvec);
		lightvec=normalize(lightvec);
		c = streetlightcell.aaa * clamp(dot(lightvec,norm)*pow(dot(lightvec,float3(0,1,0)),1),0,1)*(150.001/max(dist*dist,150.001));
	}
	return c;
}

void gridlight_vp(float4 position        : POSITION,
                  float3 norm            : NORMAL,
                  float4 diffusein       : COLOR0,
                  out float4 oPosition   : POSITION,
                  out float3 posAsColour : TEXCOORD1,
                  out float4 diffuseout  : COLOR0,
                  out float3 oNormal     : TEXCOORD0,
                  uniform float4x4 worldViewProj,
                  uniform float4x4 world)
{
	oPosition = mul(worldViewProj, position);
	oNormal = mul(world, norm);
	posAsColour = (mul(world, position).xyz)*(1.0/1471);
	diffuseout = diffusein;
}

void gridlight_fp(
	float4 diffuse     : COLOR0,
	float3 posAsColour : TEXCOORD1,
	float3 norm        : TEXCOORD0,
	uniform float4 light,
	out float4 oColour : COLOR)
{
	float gridstep = 1.0 / 16.0;
	norm = normalize(norm);
	float3 lightvec = light.xyz - posAsColour*1471;
	float dist = length(lightvec);
	lightvec=normalize(lightvec);
	float ogrelight = clamp(dot(lightvec,norm),0,1)*(150.001/max(dist*dist,150.001));
	float3 gridlights = (
		lookup(posAsColour, float3(gridstep*-1,0,gridstep*-1),norm)+
		lookup(posAsColour, float3(gridstep*0, 0,gridstep*-1),norm)+
		lookup(posAsColour, float3(gridstep*1, 0,gridstep*-1),norm)+
		lookup(posAsColour, float3(gridstep*-1,0,gridstep*0 ),norm)+
		lookup(posAsColour, float3(gridstep*0, 0,gridstep*0 ),norm)+
		lookup(posAsColour, float3(gridstep*1, 0,gridstep*0 ),norm)+
		lookup(posAsColour, float3(gridstep*-1,0,gridstep*1 ),norm)+
		lookup(posAsColour, float3(gridstep*0, 0,gridstep*1 ),norm)+
		lookup(posAsColour, float3(gridstep*1, 0,gridstep*1 ),norm));
	oColour.rgb = float3(0.05,0.05,0.07) + diffuse.rgb * gridlights + float3(ogrelight,ogrelight,ogrelight*0.7);
	oColour.a = 1;
}

