PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Rotation (sort of)

Quick question: I have a problem that keeps recurring. It looks like this: I have a set of sprite frames (say, 32) for an opponent in my game. Each frame represents a possible orientation. When the enemy walks south, I display frame 16, east is 8, west is 24.

Anyway, when this enemy changes it's direction from east to north, it needs to rotate clockwise, since that is the shortest path.

Now, suppose it rotates from frame 30 to frame 2. It can easily be seen that rotating clockwise is best here, and at 32 there's a wrap-around.

However, catching this in code is tricky. I would like to have an efficient function that takes two orientations, both in the range 0..31, and calculates the shortest path between them.

The best thing I could come up with is this:

Code:

int dist32( int x, int y )
{
int d=y-x;
if(d>16) d=y-(x+32);
if (d<-16) d=(y+32)-x;
return d;
}


But that's two conditionals, and I need to use signed ints. I'm quite sure there must be a better way. :)

Anyone?

- Jacco.[/code]
I took a look at my code in Varium, and that's exactly the algorithm I came up with as well.

Dan East
Regarding the signed ints, just mask your values to keep them within 0..31.

x&=(32-1);
y&=(32-1);

Dan East
I don't know exactly if this is what you search, but would this work?


Code:

d=(x-y)&31;
if (d>15) d=32-d;
Ehm yeah that matches my explanation. I explained it incorrect though. :) What I forgot to mention is that in case of a rotation from frame 2 to 30 (4 frames to the left) I would like to have a distance of -4 returned.
Phantom wrote:Ehm yeah that matches my explanation. I explained it incorrect though. :) What I forgot to mention is that in case of a rotation from frame 2 to 30 (4 frames to the left) I would like to have a distance of -4 returned.


I see :)

no ideas then, the only "trick" you could abuse would be making something like this


Code:

d=(x-y)&63;
switch ((d>>3)&3) // use bits 3 and 4 to know the next operation, 4 is the sign, 3 the most significant bit of the substraction
{
case (0): d=d; break; // the result is the same
case (1): d=d-32; break;
case (2): d=d-32; break;
case (3): d=64-d; break;
}



but I doubt it'd be better than the initial one as if done correctly by the compiler you'd need two jumps except for the "0 case" which would need only one, but maybe this gives some ideas to somebody (the code is probably wrong but I hope you get the idea)
Slightly tested:
Code:
diff=x-y
xor=(diff+16)&32 // if it's >limit or -ve then the bit is set and we must kill/add some bits
// (otherwise xor is 0 and the next line leaves things untouched)
diff^=-xor


I make it about 5 cycles in ARM with no branch.
(I only did a small test case from 0 to 7 in my head 'cos I've had a week from hell, it's late and I'm knackered... hope it helps/works :P ).
Nice trick refractor. Unless I made a mistake somewhere, it only differs from the posted code where you're exactly half the range (16) away, and I don't think that really matters.

Code:

#include <iostream>
#include <vector>

using namespace std;

int dist32( int x, int y )
{
int d=y-x;
if(d>16) d=y-(x+32);
if (d<-16) d=(y+32)-x;
return d;
}

int test_dist32(int x, int y) {
int diff=x-y;
int xor=(diff+16)&32; // if it's >limit or -ve then the bit is set and we must kill/add some bits

// (otherwise xor is 0 and the next line leaves things untouched)
diff^=-xor;

return -diff;
}

struct PAIR {
int x, y;
};

int main() {
unsigned failure = 0,
fail = 0,
success = 0,
mismatch = 0;

vector<PAIR> fail_pairs;
vector<PAIR> mismatch_pairs;

for(unsigned f1 = 0; f1 < 32; ++f1) {
for(unsigned f2 = 0; f2 < 32; ++f2) {
if(dist32(f1,f2) == test_dist32(f1, f2)) {
success++;
} else if(dist32(f1,f2) == -test_dist32(f1, f2)) {
mismatch++;
PAIR p = { f1, f2 };
mismatch_pairs.push_back(p);
} else {
failure = (f1 << 5) + f2;
PAIR p = { f1, f2 };
fail_pairs.push_back(p);
fail++;
}
}
}


cout<<"successes: "<<success<<endl;

cout<<"failures: "<<fail<<endl;
for(unsigned i = 0; i < fail_pairs.size(); ++i)
cout<<"\t* <"<<fail_pairs[i].x<<","<<fail_pairs[i].y<<">\n";

cout<<"mismatchs: "<<mismatch<<endl;
for(i = 0; i < mismatch_pairs.size(); ++i)
cout<<"\t* <"<<mismatch_pairs[i].x<<","<<mismatch_pairs[i].y<<">\n";

if(failure) {
cout<<"last failure: <"<<int(failure>>5)<<","<<(failure & 0x1F)<<">"<<endl;
cout<<"dist32(30,31): "<<dist32(30,31)<<endl;
cout<<"test_dist32(30,31): "<<test_dist32(30,31)<<endl;
}

return 0;
}
Andy wrote:
Code:

using namespace std;


Heresy!
For my next trick, I'll use "#include <iostream.h>".
It is only modula arithmetic we are talking about.
If your are fine with the following change:

if(d>16) d=y-(x+32);

into:

if(d>=16) d=y-(x+32);

then your question is only a matter of a sign extension of bit 4, which is the same as casting a signed 5 bit number to a signed 32 bit number. Since such cast does not exist in C/C++, i do it "manually" :)

The fastest code is therefore (hopefully)

Code:

int dist32( int x, int y ) {
return ((y-x)<<27)>>27;
}


Tala
Phantom wrote:
The best thing I could come up with is this:

Code:

int dist32( int x, int y )
{
int d=y-x;
if(d>16) d=y-(x+32);
if (d<-16) d=(y+32)-x;
return d;
}



Look at the d=y-(x+32) and d=(y+32)-x - it's the same.

Specifically I think this is what you are after:

d=((y-x+16)&31)-16;
Dave,

Correct me if I'm wrong, but I think your formula is not correct. If I feed it x=30, y=2, I get:

((2-30+16)&31)-16 = (-12&31)-16, which equals -4.

For x=2, y=30 I get:

((30-2+16)&31)-16 = (44&31)-16, which equals -4 (should have been 4).

This could probably be corrected by xor'ing the sign bit of the (x+y+16) part. That's pretty much what refractor does. Great solution! Mind if I use it in a game? :) I'm glad my instincts where right: It's branchless...

Tala: Also correct me if I'm wrong, but if x=30 and y=2, your formula gives -28 (should have been 4).

- Jacco.
Hi Jacco,

I'm curious, how many times are you calling this function per frame? If you're going to the trouble to worry about branches, is this bit of code a currently a bottleneck in your game?

For sake of discussion, let's say this code executed in one cycle - how much faster would it allow your game to run compared to the original implementation posted at the beginning of this thread? Would the user even notice it?
Tala's code is cleanest and cheapest.

Tala: Also correct me if I'm wrong, but if x=30 and y=2, your formula gives -28 (should have been 4).


Code:
((y-x)<<27)>>27
= ((2 - 30)<<27)>>27
= ((-28)<<27)>>27
= ((binary 11111111111111111111111111100100)<<27)>>27
= (binary 00100000000000000000000000000000)>>27
= (binary 00000000000000000000000000000100)
= 4


The shift by 27 means that you can only ever get a number in the range -16 to 15 inclusive:
Code:
11111111111111111111111111110000
to
00000000000000000000000000001111
Ehm.. Nope, it's absolutely not important. It was just an interesting problem.
Phantom wrote:Dave,

Correct me if I'm wrong, but I think your formula is not correct. If I feed it x=30, y=2, I get:

((2-30+16)&31)-16 = (-12&31)-16, which equals -4.


No it doesn't, it equals +4
((2-30+16)&31)-16 = ((-12)&31)-16

-12 is basically 0xfffffff4. ANDing that with 31 gives you
0xfffffff4 & 0x0000001f = 0x14 = 20 decimal

So
((2-30+16)&31)-16 = ((-12)&31)-16 = 20-16 = +4

See - it works!

Phantom wrote:
That's pretty much what refractor does. Great solution! Mind if I use it in a game? :)


No problem, go for it.... before the US Patent Office gets it's greasy mitts on it :wink:

By the way, do you understand why it works?
ANDing with a power of 2 obviously clips a value to that range, so &31 clips to 0-31. Values wrap after 32 (just like the rotation values).
However since you want to find a relative (shortest) rotation between -16 and +15, you want to clip to a range which is 16 values lower than 0-31. So if you do ((x+16)&31)-16 you get it.

The final part is comparing a and b. To find the rotation to get from x to y it's y-x. But this value isn't yet clipped between -16 and +15, e.g. if it was x=1 and y=31 you'd have 30 (which is the clockwise rotation).
Putting it all together you get ((y-x+16)&31)-16

((31-1+16)&31)-16 = (46&31)-16 = 14-16 = -2

So the shortest from 1 to 31 is -2, which is correct.
Voila!
You're right, it works.

Anyway, it's funny how you often just code something that works, while at the same time there's a much better solution. It's not a big deal (especially not in this case), but I think it's an interesting challenge nevertheless.

Thanks for joining in. :)
I fail to see how

Code:
d=((y-x+16)&31)-16


is faster than

Code:
d=((y-x)<<27)>>27


Infact since ARM has a 1 clock barrel shifter my version results in 3 clocks, while fdaves suggestion takes 4 clocks.

Tala
Well I think your solution does not give the correct result: The shortest distance between 2 and 30 is -2, while your solution gives 28.
Well I think your solution does not give the correct result: The shortest distance between 2 and 30 is -2, while your solution gives 28.


First my algorith can not possibly result in 28. Also the shortest distance between 2 and 30 should be -4.
I guess you do not grasp the concept behind the sign expansion trick.

y = 30; x = 2;
y-x = 28 = 0x0000001c
((y-x)<<27)>>27 = 0xfffffffc = -4

Tala
You're right, it is correct. I was blinded by the y-x part.
Hi Guyz,

Great solution!
But this whole problem reminds me of another recurring problem: The dreaded 'Modulo Flip'


Every programmer typically uses stuff like this:

Code:

myVar &= 15;


to make sure that whatever value you get is clipped into the region of 0-15


now sometimes you want to clip a value to a non 2power like for instance 0-20. So the naive solution would be:

Code:

myVar %= 20;


but oh no! this solution has a major problem. The moment if the value crosses the 0 boundary into minus values, the answer all of a sudden 'flips' into negative answers.

To illustrate: Lets assume we want to clip between 0-4 we do this with an "AND" and a "MODULO" approach.
Code:

value - &3 - %4

5 - 1 - 1
4 - 0 - 0
3 - 3 - 3
2 - 2 - 2
1 - 1 - 1
0 - 0 - 0
-1 - 3 - -1
-2 - 2 - -2
-3 - 1 - -3


as you can see, the modulo approach gives crap answers with negative amounts.

so what is the trick to get sensible answers?

One trick I sometimes use is this:
Before using the modulo, add a huge value which is divisible by the amount you want to modulo it by, and then apply the modulo. This way you make sure the value is not negative.

so:
Code:

modVal = (myVal + ((MAXINT/4)/MODULO))%MODULO);


luckily the compiler will take out the extra divisions so it is not as bad as this seems.

anyone has a better solution?

Rhino

p.s. the reason I add maxint/4 is to add a really big number, but to try and not overflow the amount
Rhino123 wrote:Hi Guyz,
but oh no! this solution has a major problem. The moment if the value crosses the 0 boundary into minus values, the answer all of a sudden 'flips' into negative answers.


IMO, the major problem is that it requires division, which takes hundreds of times longer to execute than bitwise AND.

Dan East
The expression ((MAXINT/4)/MODULO) does not evaluate into multiples of MODULO, but i guess its just a typo.

Strictly speaking ARM here, i think a better solution would be

modVal = myVal%MODULO;
if (modVal<0) modVal += MODULO;

rationale:
On ARM the compiler will use the conditional execution option instead of a dynamic branch. This makes the resulting code executing only 1 clock longer than the original code. Given the inefficiency of the % operator on ARM (which requires division), this is not a big tradeoff. On the bright side, the programmer does not have to be concerned about overflows and argument range.

IMO, the major problem is that it requires division, which takes hundreds of times longer to execute than bitwise AND


That was exactly, what i was thinking :) Now its not exactly hundreds of times...but its considerably slower.

Tala

ps. I see no good way to avoid % at all in the general case. Sometimes there is no trick for an operation than just doing the operation.
Typically you would be performing modulo with static divisor - or at least a divisor which seldom changes (for example keeping an object within a 240x320 screen in an Asteroids style game). In that case you should create a lookup table for each divisor and use that.

Dan East
Here's another implementation, which could be faster than true modulo if your divisor is not many times larger than your dividend. Typically, your divisor is a value that is already within range, and you apply some delta to it. So if your delta isn't extremely large (and realistically why would it ever be many times larger than your dividend?), this would be very efficient.

Code:

int modulo(int divisor, int dividend) {
while (divisor>=dividend)
divisor-=dividend;
while (divisor<0)
divisor+=dividend;
return divisor;
}


As Rhino123 mentioned, this isn't true modulo, but gives the same result as masking via bitwise AND, which is what he was looking for.

Dan East
Hi Dan,

you are right that modulo should be avoided since it is dead slow... but occasionally you just need it.

I agree that the latter solution of yours is a nice one, given that the values are not too way off the range.

Cheers!

R
refractor · 24 May 2005, 16:18 UTC — In an "I told you so" kinda mood.
You're right, it is correct. I was blinded by the y-x part.
Also blinded from reading my post on the previous page which contained a work-through of the example you gave. :mrgreen: Ho hum.
Code:
while (divisor>=dividend)
divisor-=dividend;


Well, that certainly is not the way one would like to implement that in the general case, due to its exponential worst case runtime in the number of bits. The average runtime is surely somewhat faster and only in corner cases (when divisor and dividend are not that much off) really acceptable.

A similar algorithm with linear runtime (in the number of bits) would be the algorithm we all learned in school :

Code:

for (n=...;n>=0;n--) {
if (divisor >= dividend<<n)
divisor -= dividend<<n;
}


This example is for positive numbers.

Btw both algorithm can directly be used to perform division instead of just modulo.


ps. For division i prefer Newton-Raphson though.
I must have missed some things in school. :)
Tala wrote:ot the way one would like to implement that in the general case, due to its exponential worst case runtime in the number of bits. The average runtime is surely somewhat faster and only in corner cases (when divisor and dividend are not that much off) really acceptable.


I thought I made it clear the algorithm I presented was for use in specific cases. The "corner cases" you refer to actually represent the norm in game engines. My personal use of modulo is almost always to keep a value within some range. For example keeping a sprite within the limits of the display, or keeping Euler rotations within [0,2*PI). In those cases the values typically exceed the divisor by small amounts (if they didn't then the game would exhibit almost random behavior, as objects vastly out of range are "snapped" into range each frame).

So in my experience, while your algorithm is better suited for completely generic uses typically not applicable to game design (such as feeding completely random numbers to the algorithm), it would perform many times slower than the algorithm I presented in most real-world gaming scenarios.

A better generic algorithm would first check to see which specific algorithm it should utilize, based on the size of the divisor compared to the dividend.

However the core of the issue is that a game should be designed to not require actual modulo - instead using binary operators, or simply using smaller unsigned types that can just overflow.

Dan East
Tala: very clever trick with the shifting!

Dan: I hate to use modulo too since it is a division. Most of the time I can get around using AND's or your bordertrick. But for the other cases Tala's solution is very elegant!
OK, another one. Have a look at this code:

Code:

int CalcDir( int x1, int y1, int x2, int y2 )
{
int dx = x2 - x1, dy = y2 - y1;
int _dx = abs( dx ), _dy = abs( dy ), r = 0;
if (dx < 0) r = 8, dy = -dy;
if (dy > 0) { r += 4; int h = _dx; _dx = _dy; _dy = h; }
if (_dx < _dy) { if ((_dx * 2) > _dy) r++; }
else { r += 2; if ((_dy * 2) < _dx) r++; }
return r;
}


This code takes two positions and calculates in which direction (x2,y2) is relative to (x1,y1), on a 0..15 scale. Or, in what half-octant of (x1,y1) the point (x2,y2) is. This is useful to make a gun aim at an enemy. The above code is obviously quite a bit faster than the usual approach, which involves an atan.

I have tried to generalize this approach to larger ranges; but the 0..31 is already quite complex. Might have something to do with the constraint that the areas are numbered in clockwise order, perhaps it's better to have a different numbering and then use a lookup table to get the final answer. Did anyone implement something like this?

- Jacco.[/code]
Phantom wrote:
I have tried to generalize this approach to larger ranges; but the 0..31 is already quite complex.


My quicky angle maker is similar, I split the signs and find which d is larger to make 8 sectors. But I get a large range by dividing the smaller d over the larger d.

EG Approx=Sector<<10 +or-(small*1024/large)
Approx angle does map to a real angle.

Fastest code is affected by what you need to do elsewhere. For me distance is already found before I work out interaction so I know the objects interact. From that I get a unity vector for dx dy which can be used as cos(angle) sin(angle) without having to know angle. Following code is killa for unity angles think killa(1024*cos(ang),1024*sin(ang)), if ang=given*PI/1024 and int given ranges from 0-2047 then killa should give back the angle but because its approx it has error. The average error I get is 6 and the max 10. killb takes what you throw at it without standardising and if I used it would need a lookup for the division. Currently error is 10 average and 16 max. the 272* would be 256 to be pure, but by beefing up the number you compensate an error source. 256 would be 15 average and 24 max.

Code:
int killa(int ux,int uy) {
int s;
int f=0;
if(ux<0) {ux=-ux;f^=1+8;}
if(uy<0) {uy=-uy;f^=2+8;}
if(uy>ux) {
s=(ux*1448)>>12;
f^=4+8;
} else {
s=(uy*1448)>>12;
}
int d=(0xf588)>>((f&7)*2);
d=((d&3)<<9);
if(f&8) d-=s; else d+=s;
d=d&2047;
return(d);
}
int killb(int ux,int uy) {
int ans,s=0;
int f=0;
if(ux<0) {ux=-ux;f^=1+8;}
if(uy<0) {uy=-uy;f^=2+8;}
if(uy>ux) {
if(uy>0) s=(272*ux)/uy;
f^=4+8;
} else {
if(ux>0) s=(272*uy)/ux;
}

int d=(0xf588)>>((f&7)*2);
d=((d&3)<<9);
if(f&8) d-=s; else d+=s;
d=d&2047;
return(d);
}
This is a fun thread.

Does ARM have an absolute-value instruction? If not, would the abs(dx)/abs(dy) require conditionals? And if so, would something like this be better?

_dx = dx;

if (dx < 0) {
...
_dx = -dx;
}
Andy wrote:Does ARM have an absolute-value instruction?


It doesn't have an abs and your conclusion is sound.

Thinking about an ARM version replacing killa's 1448>>12 thing with s=(ux>>2)+(ux>>3)-(ux>>5) would save a register and some cycles with an average error of 3 and a max error of 8.
You can also change that last else... So the whole thing looks something like:
Code:

int CalcDir( int x1, int y1, int x2, int y2 )
{
int dx = x2 - x1, dy = y2 - y1, r = 0;
int _dx = (dx < 0) ? -dx : dx;
int _dy = (dy < 0) ? -dy : dy;
if (dx < 0) r = 8, dy = -dy;
if (dy > 0) { r += 4; int h = _dx; _dx = _dy; _dy = h; }
if (_dx < _dy) { if ((_dx * 2) > _dy) r++; }
else { r += ((_dy * 2) < _dx) ? 3 : 2; }
return r;
}
@Phantom

Your algorithm idea would give correct results if you would restrict yourself to a quantization of 0..7 since tan(pi/4)==1.
However tan(pi/8 ) != 1/2. So i guess you are fine with the approximation?

For a more general approach i suggest looking into the CORDIC algorithm. It does some micro rotations pi, pi/2, pi/4, pi/8, pi/16 and gains precision every iteration. CORDIC is widely used in (fixed point) DSP programming, where trigonometric functions are not available.
Hi Guyz,

Since this topic has changed a bit into 'smart code snippets' I was wondering about this one too: Everyone knows that if you do a 64bit int multiplication in C for the Arm you are better of writing a small inline assembly or small assembly source for it since it is a lot faster then the routines the compiler comes up with.

Since the ARM doesn't support division(32 bit or 64bit), is there also a smart (assembly) way to do this instead of relying on system functions?

I know, divisions should be avoided anyhow, but somehow they are hard to avoid when doing 3d stuff.

cheers,

Reinier
Rhino123 wrote:Since the ARM doesn't support division(32 bit or 64bit), is there also a smart (assembly) way to do this instead of relying on system functions?


hmmm after some searching I found this which seems pretty smart:
http://www.peter-teichmann.de/adiv1e.html

and a great page about the fastest squareroots in efficient Arm:
http://www.finesse.demon.co.uk/steven/sqrt.html
Page 2 of this thread has a fast fixed point division routine in ASM.
http://www.pocketmatrix.com/forums/view ... hp?t=11940

The result is 16.16 fixed point.

Dan East
Great tip! thanks


By the way... how does one test if the processor is an XScale? (So that one can switch to an alternative divide function)

cheers,

R
0-7, octants:
Code:

int CalcDir( int x1, int y1, int x2, int y2 )
{
int dx = x2 - x1, dy = y2 - y1;
int adx = (dx<0)?-dx:dx, ady = (dy<0)?-dy:dy, r;
r=(dy>0?8:0)+(dx>0?4:0)+(adx>ady?2:0);
r=(int []){2,3,1,0,5,4,6,7}[r];
}

0-15, half-octants:
Code:

int CalcDir( int x1, int y1, int x2, int y2 )
{
int dx = x2 - x1, dy = y2 - y1;
int adx = (dx<0)?-dx:dx, ady = (dy<0)?-dy:dy, r;
r=(dy>0?8:0)+(dx>0?4:0)+(adx>ady?2:0)+((adx>ady*2)|(ady>adx*2));
r=(int []){5,4,6,7,2,3,1,0,10,11,9,8,13,12,14,15}[r];
}


extending for quarter octants is trivial, would take about 10 minutes.
of course, the array lookup is redundant if youre just picking a frame/sprite, better to just put them in the "right" order.
Shouldn't line 3 of the 8-way version read:

Code:

r=(dy>0?8:0)+(dx>0?4:0)+(adx>ady?2:0);


?

In that case, a 32-way version would be:

Code:

int CalcDir( int x1, int y1, int x2, int y2 )
{
int dx = x2 - x1, dy = y2 - y1;
int adx = (dx<0)?-dx:dx, ady = (dy<0)?-dy:dy, r;
r=(dy>0?16:0)+(dx>0?8:0)+(adx>ady?4:0)+2*((adx>ady*2)|(ady>adx*2))+((adx>ady*4)|(ady>adx*4));
r=(int []){5,4,6,7,2,3,1,0,10,11,9,8,13,12,14,15,21,20,22,23,18,19,17,16,26,27,25,24,29,28,30,31}[r];
}


The ordering of the array is probably not correct, I'm still analysing the pattern in that one.