Question

I need an efficient glsl code that doesn't have if-else statement. Currently the algorithm is like this :

lowp float a;
if (a > 1.0) 
   a -= 1.0;
else if (a < 0.0) 
   a += 1.0;

It's similar with a floating point modulo operator :

a = mod(a,1.0);

only if a == 1, it should return 1, instead of 0.

How to do this without if-else though?

Thanks

Was it helpful?

Solution

Here is a mathematic representation that might do what you need - without using branching statements

For inputs between [-1, 2.0]

a = a + 1 - max(trunc(a), ceil(a))

Input   Output
0.3     0.3
-0.3    0.7
0.7     0.7
1.3     0.3
1.7     0.7
1       1.0

OTHER TIPS

value = (expression) ? (if true) : (if false);

example :

BOOL result = value ? YES : NO; 

I don't understand how your code relates to the floating point modulo operator that you mention. Such an operator converts floats to integers; your code does not.

If such a conversion is desired, use function modff from the standard library.

#include <math.h>
float a, dummy;
...
a = modff(a, &dummy);

If you don't want any such conversion, the answer of @devnull is a correct rewrite of your code. If in addition you want to "include the upper value" and, e.g. have 1 map to 1, then you're in a bit of trouble, as this would involve checking whether a floating point number is integer or not. To do this portably, I'd suggest again the use of modff.

SYNOPSIS

float modff(float x, float *iptr);

Link with -lm.

DESCRIPTION

The modf() function breaks the argument x into an integral part and a fractional part, each of which has the same sign as x. The integral part is stored in the location pointed to by iptr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top