Quake III q_rsqrt

Quake III Arena, the first person shooter video game is renowned for heavy use of 3D graphics.

float fastInvSqrt(float x) {
  float xhalf = 0.5f * x;
  int i = *(int*)&x;         // evil floating point bit level hacking
  i = 0x5f3759df - (i >> 1);  // what the fuck?
  x = *(float*)&i;
  x = x*(1.5f-(xhalf*x*x));
  return x;
}

In order to implement physics and reflections in the game engine, it is important to compute normalized vectors. But the computing process needs to be very quick for the game to run smoothly. John Carmack developed an algorithm for this computation and it is called Fast Inverse Square Root (q_rsqrt)

The fast inverse square root is a clever algorithm that approximates 1/sqrt(x). It became famous when the Quake III source code was made public around 2005. While it was initially attributed to Carmack, he denied having written it. Its origins aren’t completely clear and they can be traced back way before Quake III was launched in 1999.

Inverse square roots are essential in video game graphics particularly in 3D game engines. Path finding, lighting, reflections and many other game programming techniques require vector normalization, which involves an inverse square root operation.

References:

  • If you are interested in Assembly
  • q_rsqrt

你可能感兴趣的:(Quake III q_rsqrt)