Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
uber

Angle calculation in source code

Recommended Posts

I'm not really sure if this would be the right category for a question like this, but I figured it's more appropriate in here than in doom editing.

 

I'm having a bit of trouble understanding the way the game calculates angle deviations for weapons like the fists, pistol, shotgun, etc. in the

angle += (P_Random()-P_Random())<<18;

line, since I don't have any C experience, or any sort of programming experience at all really. I'm pretty sure I get the basic idea, in that it takes two (I assume consecutive, since otherwise it'd always return zero) random numbers from the list in m_random.c and substracts the second one from the first. Then it shifts the bits 18 times to the left, multiplying it by 2^18 or 262144 and returning the final angle that would be added to the current view angle of the player, if I'm not mistaken.

 

What stumps me is the way the result gets turned into an actual angle. I read the wiki page on the binary angular measurement used in doom, and what I understand is that it divides a full circle between 0x00000000, that being 0º, and 0xFFFFFFFF, which is almost 360º. So, since doom uses unsigned 32 bit integers, that means the maximum value would be 2^32, or 4294967296. Does that mean it's pretty much 360 degrees divided in 4294967296 parts?

 

And lastly, I don't really get how negative values are calculated for this, such as if I get 109 - 220 for the numbers. Does it overflow, since it's dealing with unsigned integers, and return a really high number?

 

I'd really appreciate some help in this matter!

Share this post


Link to post
5 hours ago, uber² said:

Does that mean it's pretty much 360 degrees divided in 4294967296 parts?

Yes that's right.

 

It is a lot like how radians and degrees both measure angles, where 180 degrees is Pi radians.  With 32-bit math, 2^31 is 180 degrees, 2^30 is 90 degrees, etc...

 

Negative values work fairly normally here, you need to understand "two's complement" which is how negative numbers are represented in a group of bits.  As a very rough guide, a small negative number in 32 bits has most of the upper bits as 1s.  After a shift left 18 times, there are still 1s in the highest bits, so technically the number is still negative, and when you add it to an angle it does the right thing (a subtraction).

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×