Welcome to Fractal Forums

Fractal Software => Fragmentarium => Topic started by: Patryk Kizny on August 24, 2015, 12:50:52 PM




Title: Quick question about initializing variables
Post by: Patryk Kizny on August 24, 2015, 12:50:52 PM
Hey,
In most of the included frags there's a structure that passes init() function down to the main scene file and also #providesinit statement.

What is a practical difference between initializing variables and doing some 'free' calculations 'inline' vs within init() function? Is there anything that really matters besides convenience having this in one place in the code?

For examples take this:
Code:
qtrot = rotationMatrix3(normalize(qtRotVector), qtRotAngle);
which defines a rotation matrix for the quaternion fractal.
It could be done inline or it coud sit within init() function.

Thanks


Title: Re: Quick question about initializing variables
Post by: _revers_ on August 24, 2015, 02:47:16 PM
The init() function is called only once per shader invocation. If you would put initialization for example in DE() function it would be called many times.
Consider Mandelbulb.frag: init() is called only once in the main() function in 3D.frag, but DE() function from Mandelbulb.frag is called in the DEF() function in DE-Raytracer.frag, which is called in many loops in the same file.


Title: Re: Quick question about initializing variables
Post by: Patryk Kizny on August 24, 2015, 03:29:52 PM
Yeah, but the question is what would be the difference between putting "float myVariable = 3.14529" within init() or outside of it as a 'free' line in the code, so outside of the body of any functions.


Title: Re: Quick question about initializing variables
Post by: _revers_ on August 24, 2015, 04:02:31 PM
Well I think it is due to a fact that you can do more in functions than in global scope. Consider the following:
Code:
struct MyStruct {
vec3 pos;
vec3 col;
};
MyStruct array[2];

// This won't work in global scope:
array[0].pos = vec3(0.0);
array[0].col = vec3(1.0);
array[1].pos = vec3(0.0);
array[1].col = vec3(1.0);

// This will work:
void init() {
    array[0].pos = vec3(0.0);
    array[0].col = vec3(1.0);
    array[1].pos = vec3(0.0);
    array[1].col = vec3(1.0);
}

You can do a workaround:
Code:
MyStruct array[] = MyStruct[2](MyStruct(vec3(0.0), vec3(1.0)), MyStruct(vec3(0.0), vec3(1.0)));
But for larger arrays it might be more readable to put initialization in the init() function. Apart from above example I don't think there is much difference.


Title: Re: Quick question about initializing variables
Post by: Patryk Kizny on August 24, 2015, 07:50:12 PM
Thanks, makes sense.