19

Does GLSL have any pre-defined constants for +/-infinity or NaN? I'm doing this as a workaround but I wonder if there is a cleaner way:

// GLSL FRAGMENT SHADER
#version 410

<snip>

const float infinity = 1. / 0.;

void main ()
{
    <snip>
}

I am aware of the isinf function but I need to assign infinity to a variable so that does not help me.

atb
  • 1,412
  • 1
  • 14
  • 30
  • 2
    Using infinity saves a lot of logic in my code: ` float t0 = (d >= 0.) ? t : infinity; float t1 = (d >= 0.) ? t : infinity; t = min (t0, t1); ` – atb May 03 '12 at 16:14
  • I believe choosing a large enough value (based on your application) should easily do the trick. Say for example `1e20` – Shahbaz May 03 '12 at 16:33
  • 1
    Using infinity seems to work fine, I was just wondering if there was a pre-defined constant for it. While I'm at it, are there constants for other things like FLT_MAX FLT_EPSILON etc the way there are in C? – atb May 03 '12 at 16:36

3 Answers3

14

Like Nicol mentioned, there are no pre-defined constants.

However, from OpenGL 4.1 on, your solution is at least guaranteed to work and correctly generate an infinite value.

See for example in glsl 4.4:

4.7.1 Range and Precision

...

However, dividing a non-zero by 0 results in the appropriately signed IEEE Inf: If both positive and negative zeros are implemented, the correctly signed Inf will be generated, otherwise positive Inf is generated.

Be careful when you use an older version of OpenGL though:

For example in glsl 4.0 it says:

4.1.4 Floats

...

Similarly, treatment of conditions such as divide by 0 may lead to an unspecified result, but in no case should such a condition lead to the interruption or termination of processing.

Community
  • 1
  • 1
Jan Rüegg
  • 9,587
  • 8
  • 63
  • 105
6

There are no pre-defined constants for it, but there is the isinf function to test if something is infinity.

While I'm at it, are there constants for other things like FLT_MAX FLT_EPSILON etc the way there are in C?

No, there are not.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
6

This might work?

const float pos_infinity = uintBitsToFloat(0x7F800000);
const float neg_infinity = uintBitsToFloat(0xFF800000);

"If the encoding of a floating point infinity is passed in parameter x, the resulting floating-point value is the corresponding (positive or negative) floating point infinity"

Chris
  • 61
  • 1
  • 1