I wrote a shader for creating shadows in my game.
As a parameter I pass a Vector4 list, which then becomes “float4 [] walls” in my shader.
normal code:
var _rectangles = effect.Parameters["RectangleList"];
_rectangles.SetValue(Game1.Map.WallsAsVec4List);
shader code:
#define MAXWALLS 105
float4 RectangleList[MAXWALLS];
In my MainPS function I then loop through all elements in that list to check if the current pixel’s position is behind a wall or not.
[loop]
for (int i = 0; i < WallCount; i++)
{
//linebox returns true if a line from x1, y1 to x2, y2 intersects with any border of the following rectangle
if (linebox(PlayerX, PlayerY, pixelposition.x, pixelposition.y, RectangleList[i].x, RectangleList[i].y,
RectangleList[i].z, RectangleList[i].w) == true)
{
color.rgb = color.r * 0.5f;
return color;//Returns a dark pixel because the line of sight to the player / light source is obstructed
}
}
I do this by checking whether an imaginary line from the pixel to my player position intersects one of the walls (so the player is the light source).
I used to use a float[] array instead of float4[]. It was surpisingly cheap to calculate but the shader now puts a lot more strain on the GPU, even though there are as many walls as before.
I have now found out that the problem arises when passing parameters into the linebox function. More precisely: It is because I use, for example, “RectangleList [i] .x, RectangleList [i] .y, …” and not “RectangleList [i], RectangleList [i + 1], …” as before.
Why is that and what can I do about it ? I’ve been struggling with that for a quite while now. Please help !