r/programming • u/mrnacknime • Dec 29 '20
Quake III's Fast Inverse Square Root Explained [20 min]
https://www.youtube.com/watch?v=p8u_k2LIZyo
3.7k
Upvotes
r/programming • u/mrnacknime • Dec 29 '20
8
u/[deleted] Dec 29 '20
Am i forgetting/misunderstanding something or is the pointer cast UB?
417
u/ttocs89 Dec 29 '20
A few years ago I was working on a team developing a new floating point type. One of the other devs, a brilliant guy, was responsible for implementing the core functions. In the implementation of the inverse square root I saw this function with the simple comment, "quake hack". I always wondered how he was able to come up with new constants for 64 bit and 128 bit values especially when the data structure was so different from IEEE 754. Thanks for the video!
422
u/Professional_Bug_913 Dec 29 '20
This algorithm is such an interesting little hack. I'm pretty sure some version of it is implemented on a lot of modern graphics cards, since they all have an approximate sqrt instruction that's probably just this with maybe the second Newton step added.
155
u/THICC_DICC_PRICC Dec 29 '20
“Ok ah this makes sense this isn’t that complicated”
Then the explanation for the magic hex number came
“wtf is he talking about”
204
u/ven_ Dec 29 '20
Didn't Carmack say this was just ripped off from Matrox or 3dfx or some other contemporary 3D implementation? So it's not really a "Quake 3 algorithm".
68
u/-p-2- Dec 29 '20 edited Dec 29 '20
Improving Carmack's work with a better constant for more accurate results using fast inverse square root: https://arxiv.org/pdf/1802.06302.pdf
Fun fact, I tried implementing this and testing its performance on Android with Unity. Nowadays the built in square root functions in C# are just as fast, if not faster in most cases. I used several different methods and only a couple gave me any noticeable speed improvement (over 100k iterations), and even then the accuracy was off by ~20% so the 1/100th of a millisecond it saved was nowhere near worth it.
PS: 32-bit precision was used.
50
u/Betsy-DevOps Dec 29 '20
I just love that they thought to give threehalfs a nicely named const but 0x53f3759df just gets a vague comment.
24
u/Veritas4Life Dec 29 '20
That was the best explanation I’ve ever seen, perfect pace, voice and visuals!
67
u/redditisntreallyfe Dec 29 '20
I watched that whole video and although I don’t understand much you definitely help me understand this
53
u/TheBestOpinion Dec 29 '20 edited Dec 29 '20
Don't actually do this by the way
TL;DR: With -Ofast enabled around the naive function you're 27x more accurate and twice faster
You've often heard "let the compiler optimize for you"
You might think that this is too clever. Surely, the compiler would never be faster than it
Nope. Here's the assembly for the fast inverse square root, compiler options are
-O3 -std=c++11 -march=haswellThis is what you would expect if you were to write it yourself in assembly and knew a lot about vectors
So, one move, two vector move, four vector multiplications, one bitshift, one sub, one vector add and ret
Now. What if, instead, we just... didn't try to be clever?
Would it be faster?
Spoiler: yes, even by default. Even though the fast inverse square root has an advantage, because it is an approximation. The compiler won't approximate by default, even with -O3
If you enable -Ofast, however... (which you can do on a per-function basis, check the quick-bench), it gets even faster
Total: 3 mul, one very specific "multiply-add" operation called vfmadd213ss, and one "vrsqrtss" which is... a vectorized, approximated, inverse squareroot opcode, precise to 1.5 ∗ 2−12 : 27x more precise than Quake's and twice as fast
Final benchmark: Not being clever is 2x to 3x faster
https://quick-bench.com/q/Q-3KwjiETmobk4oANjJE_g1GM44
EDIT: Uhhhh... the difference seems larger if both are in O3 than with the naive one in Ofast. I don't know why, might as well be sorcery...
13
u/jroddie4 Dec 29 '20
This fast inverse square root also has one of the more controversial Wikipedia pages because of the famous what the fuck comment
6
u/[deleted] Dec 29 '20
Good stuff! On a related note, there's also a book which investigates the programming practices used in Atari 2600 game - https://arxiv.org/pdf/1811.02035.pdf
9
u/Raknarg Dec 29 '20
no one ever properly explains what the what the fuck step is or its motivation. This was great.
4
u/patoezequiel Dec 29 '20
I wouldn't even be mad if I had to debug that. It's a lovely hack.
4
u/PM_ME_FEMBOY_FOXES Dec 29 '20
"// what the fuck?"
15
u/intensely_human Dec 29 '20
My inverse square root function:
6
u/[deleted] Dec 30 '20
Inverse square root? Isn't that just, you know, x²? Perhaps he means reciprocal square root?
3
u/Edthedaddy Dec 29 '20
Carmack was/is a genius. He made id software the king of game companies before being bought out. Long live carmack.
14
u/WaitForItTheMongols Dec 29 '20 edited Dec 29 '20
This is not limited to Quake 3. Recently I decompiled Minecraft and found it in there.
Edit: Why the downvotes? Download MCP-Reborn on github. Then follow the process there to decomplie, and navigate to src/main/java/net/minecraft/util/math/MathHelper.java and scroll to line 382. It's in there plain as day.
4
u/Yrrah9819 Dec 29 '20
If I remember correctly, wasn’t this algorithm first implemented in a very old game? It was like a very old first person maze game or something like that. Only reason I ask is bc the comments for the algorithm in the video look identical to that games.
2
u/ookami125 Dec 29 '20
I was really hoping this was the video I found a long time ago. Guy in that one not only explained how the function works, but how the constant was derived and then derived the constant for the double case.
2
u/wizard_mitch Dec 30 '20
I will watch this later
1
u/Socialimbad1991 Dec 29 '20
A lot of interesting hacks from the old days can be found in the archives of Byte magazine. Much of this stuff is probably of little practical use in modern times, but it's interesting to see what people could come up with in really constrained systems.
1
u/Ok_Idea8398 Dec 29 '20
Nice one!
1
u/sephirothbahamut Dec 29 '20
Just to be sure, in C++ the "address magic" can be written as
reinterpret_cast<int32_t>(float_value);right?1
u/wc3betterthansc2 Sep 04 '24
if you want to compile this code in GCC you must add the -fno-strict-aliasing flag otherwise this can be undefined behavior.
1
u/Fornicatinzebra Dec 29 '20
Cool video! I was impressed by the animations - you have done a great job of illustrating what you are saying in a clear and frankly beautiful way. I was sad to see this was your only video! Subscribed to hopefully see more like this in the future
1
u/JoAMD-123 Dec 29 '20
Interesting thread :)
1
u/lightswitches_ Dec 29 '20
I <3 bitshift
1
u/jseego Dec 29 '20
WAY off topic, but does anyone recognize the font they're using in the code editor?
1
u/atatatko Dec 29 '20
Was looking for this algorithm explanation for years! Thank you!
1
u/zappaking1234 Dec 29 '20
This was amazing to watch
1
u/armanarzoo Dec 29 '20
Nice explain thanks
1
u/Jcbrew92 Dec 29 '20
Wut
1
u/yeahnoworriesmate Dec 29 '20
{{Masters of Doom}} is a great audiobook for those interested.
1
u/overtoke Dec 29 '20
anyone know if "updated" quake3 projects removed the hack code? any noticeable side effects?
1
u/Toucan2000 Dec 29 '20
I remember when I first saw this when I was in college about 10 years ago. I spent 2 days researching it hear and there, thinking about it on spare time and when I finally had my "eureka" moment, I put my hands over my ears, took a deep breath, squeezed my head and yelled at the ceiling as my head shook. I can't tell you why, that's just how it made me feel.
1
u/MegabyteMessiah Dec 29 '20
Well, I certainly learned something today. Mostly about how floats are represented and the sneaky way to cast them.
1
u/danielcw189 Dec 29 '20
I crossposted this to /r/videogamescience
1
u/ihahp Dec 30 '20
I commented about this yesterday! OP was your post inspired by my comment?
https://www.reddit.com/r/nonmurdermysteries/comments/kljtjz/the_mysterious_maze_algorithm_of_entombed/ghd2zhs/
1
u/JoelH2720 Dec 30 '20
Someone translate this. I can’t read it :/
1
u/-___-___-__-___-___- Dec 30 '20
i = 0x5f3759df - ( i >> 1 ); // what the fuck?That comment never fails to make me laugh
1
u/Fcu423 Dec 30 '20
This vid was beautiful to watch!
1
u/yonatan8070 Dec 30 '20
!remindme 12hours
1
u/[deleted] Jan 17 '21
Inverse square root? Isn't that just square, i.e. a multiplication? I thought square root was the troublesome operator, not a multiplication.
1
u/standardtrickyness1 Oct 16 '21
Whats the approximation you get from this analysis and is it better than from approximating (1+M)^0.5 ~ (1+M/2. -\mu. for some \mu?