-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfast_inverse_square_root.h
48 lines (39 loc) · 1.33 KB
/
fast_inverse_square_root.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//
// Created by marc on 07/07/2021.
//
#ifndef RAYTRACING_RAYMARCHING_HYBRID_FAST_INVERSE_SQUARE_ROOT_H
#define RAYTRACING_RAYMARCHING_HYBRID_FAST_INVERSE_SQUARE_ROOT_H
// This has been copied straight out of quake 3 arena
inline
// https://github.com/id-Software/Quake-III-Arena/blob/master/code/game/q_math.c
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
// This has been adapted to work with doubles
inline
double Q_rsqrt( double number )
{
long long i;
double x2, y;
const double threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long long * ) &y; // evil floating point bit level hacking
i = 0x5fe6eb50c7b537a9 - ( i >> 1 ); // what the fuck?
y = * ( double * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
#endif //RAYTRACING_RAYMARCHING_HYBRID_FAST_INVERSE_SQUARE_ROOT_H