If command not working in the fragment shader

I’m fairly new to GLSL but all seems to work except one if. I’m trying to use the following code in the fragment shader:

[some code here]
void main (void)
if (enablelighting) {

            [some code here]

	for (int i=0; i<numused; i++)
	  if (lightposn[i].w != 0.0) {vec3 position = lightposn[i].xyz / lightposn[i].w ;}
	  vec3 direction = normalize (position - mypos) ;

              [some code here]
} else {
              [some code here]


Since it is a homework I’m not allowed to post complete codes, so I cut out the parts, which are not so important.
If I try to run it I get the “0:70(39): error: `position’ undeclared” error (though I’m sure lightposn[i].w is not zero). If I put “if (true)” I still get the same error :confused: What is really strange is that I have an if at the beggining which works perfectly. I also tried if (enablelighting) inside the for loop and still have the same error.

If I delete the if command the code works perfectly (but I need it, because I have to deal with lights having zero w component).

Why the if command works at the beggining at the code but not inside the for?

It’s a scope issue, you would get the same problem with:

{vec3 position = vec3(1,0,0);}
vec3 direction = normalize (position - mypos);

because “position” is only visible inside the code block surrounded by “{”+"}".
To be able to access “position” you need to declare it before the brackets:

vec3 position;
if (...) {position = ...;} else {position = ...;}
vec3 direction = normalize (position - mypos)

Thanks a lot!
Now my code works perfectly.

(I indeed got the same problem with only the brackets which should have made me think a little bit harder…)

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.