Archive for the 'Physics' Category

Box pruning revisited - part 4 - sentinels

Tuesday, February 14th, 2017

Part 4 – sentinels

So we started optimizing the code, first modifying the two inner ‘while’ loops. That was a random place to start with, just the first thing that came to mind. But it was a good one, because as it turns out we’re not done with these two lines yet. Beyond the compiler-related issues, we can also optimize the algorithm itself here.

The two loops now look like this:

In both cases, the first comparisons (”RunningAddress<LastSorted”) are only here to ensure we don’t read past the end of the buffers. But they have no actual value for the algorithm itself. It’s scaffolding to support the actual “meat” of the algorithm. You would never mention that part in pseudocode to explain what the algorithm does. In other words: we could omit the first comparisons and provided it wouldn’t make the code crash, we’d still get the correct results out of the function. This wouldn’t be the same for the second comparisons: without them the algorithm would collapse entirely.

Identifying these “useless” bits is a classical part of optimization for me: I remember using this strategy a lot on the Atari ST to identify which instructions I could target first. That’s half of the battle. That gives you a goal: how do I get rid of them?

Once that goal is clearly expressed and identified, solutions come to mind more naturally and easily. In our case here, a classical solution is to use “sentinel” values, stored within PosList, to ensure that the second comparisons exit the loop when we reach the end of the buffers. This is a fairly standard strategy and I already explained it in the SAP document. So if you are not familiar with it, please take a moment to read about it there (it’s in Appendix B, page 24).

The implementation for the box-pruning function is straightforward. We allocate one more entry for the sentinel:

Then we fill up that buffer as usual for the first ‘nb’ entries. But we write one extra value (the sentinel) at the end of the buffer:

Afterwards it’s as easy as it gets, just remove the first comparisons in the inner loops:

The first comparisons can be removed because we guarantee that we will eventually fetch the sentinel value from PosList, and that value will always be greater than MinLimit and MaxLimit.

Thus this will be enough to exit the loop.

Now, as far as the disassembly is concerned, the changes are a bit hard to follow. The code got re-arranged (check out the position of “call operator delete” in versions 3 and 4 for example) and in its default form the disassembly is a bit obscure. Nonetheless, using the NOPS macro around the while instruction reveals that our change had the desired effect: one of the two comparisons clearly vanished.

More importantly, the benefits were not just theoretical. We also see the performance increase in practice:

Office PC:

Complete test (brute force): found 11811 intersections in 815456 K-cycles.
78703 K-cycles.
77667 K-cycles.
78142 K-cycles.
86118 K-cycles.
77456 K-cycles.
77916 K-cycles.
77156 K-cycles.
78100 K-cycles.
81364 K-cycles.
77259 K-cycles.
86848 K-cycles.
79394 K-cycles.
81877 K-cycles.
80809 K-cycles.
84473 K-cycles.
81347 K-cycles.
Complete test (box pruning): found 11811 intersections in 77156 K-cycles.

Home PC:

Complete test (brute force): found 11811 intersections in 781900 K-cycles.
82811 K-cycles.
81905 K-cycles.
82147 K-cycles.
81923 K-cycles.
82156 K-cycles.
81878 K-cycles.
82289 K-cycles.
82125 K-cycles.
82474 K-cycles.
82050 K-cycles.
81945 K-cycles.
82257 K-cycles.
81902 K-cycles.
81834 K-cycles.
82587 K-cycles.
82360 K-cycles.
Complete test (box pruning): found 11811 intersections in 81834 K-cycles.

The gains are summarized here:

Home PC

Timings (K-Cycles)

Delta (K-Cycles)

Speedup

Overall X factor

(Version1)

(101662)

Version2 - base

98822

0

0%

1.0

Version3

93138

~5600

~5%

~1.06

Version4

81834

~11000

~12%

~1.20

Office PC

Timings (K-Cycles)

Delta (K-Cycles)

Speedup

Overall X factor

(Version1)

(96203)

Version2 - base

92885

0

0%

1.0

Version3

88352

~4500

~5%

~1.05

Version4

77156

~11000

~12%

~1.20

Note that this optimization will only work if the input bounding boxes do not already contain our sentinel value - otherwise there would be no way to distinguish between the sentinel value and a regular value.

This is the first incidence of a rather common trend while optimizing code: the loss of genericity. Sometimes to make the code run faster, you need to accept some compromises or limitations compared to a fully “generic” implementation.

In this case, the limitation enforced by the optimization is that input bounding boxes cannot contain FLT_MAX. This is not a big problem in practice: usually only planes have infinite bounding boxes, and you can always make them use FLT_MAX/2 instead of FLT_MAX if needed. So this limitation is easy to accept. Sometimes they are a lot more debatable.

What we learnt:

Identify “useless” parts of the code that don’t contribute to the results, then eliminate them.

A less generic function can often run faster.

And that’s already it for this part, short and sweet.

GitHub code for part 4

Box pruning revisited - part 3 - don’t trust the compiler

Friday, February 10th, 2017

Part 3: don’t trust the compiler

We now look at the “CompleteBoxPruning” function for the first time. This is my code but since I wrote it 15 years ago, it’s pretty much the same for me as it is for you: I am looking at some foreign code I do not recognize much.

I suppose the first thing to do is to analyze it and get a feeling for what takes time. There is an allocation:

Then a loop to fill that buffer:

Then we sort this array:

And then the rest of the code is the main pruning loop that scans the array and does overlap tests:

After that we just free the array we allocated, and return:

Ok, so, we can forget the allocation: allocations are bad and should be avoided if possible, but on PC, in single-threaded code like this, one allocation is unlikely to be an issue - unless not much else is happening. That leaves us with basically two parts: the sorting, and the pruning. I suppose this makes total sense for an algorithm usually called either “sweep-and-prune” or “sort-and-sweep” – the “box pruning” term being again just how I call this specific variation on the theme: single sorting axis, direct results, no persistent data.

So first, let’s figure out how much time we spend in the sorting, and how much time in the pruning. We could use a profiler, or add extra rdtsc calls in there. Let’s try the rdtsc stuff. That would be an opportunity for me to tell you that the code in its current form will not compile for x64, because inline assembly is forbidden there. So the profiler functions for example do not compile:

This is easy to fix though: these days there is a __rdtsc() intrinsic that you can use instead, after including <intrin.h>. Let’s try that here. You can include the header and write something like this around the code you want to measure:

If we apply this to the different sections of the code, we get the following results:

Allocation:
time: 3
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1
time: 1

Remember that we looped several times over the “CompleteBoxPruning” function to get more stable results. Typically what happens then is that the first call is significantly more expensive than the other ones, because everything gets pulled in the cache (i.e. you get a lot more cache misses than usual). When optimizing a function, you need to decide if you want to optimize for the “best case”, the “average case”, or the “worst case”.

The best case is when everything is nicely in the cache, you don’t get much cache misses, and you can focus on things like decreasing the total number of instructions, using faster instructions, removing branches, using SIMD, etc.

The worst case is the first frame, when cache misses are unavoidable. To optimize this, you need to reduce the number of cache misses, i.e. decrease the size of your structures, use more cache-friendly access patterns, use prefetch calls judiciously, etc.

The average case is a fuzzy mix of both: in the real world you get a mixture of best & worst cases depending on what the app is doing, how often the function is called, etc, and at the end of the day, on average, everything matters. There is no right answer here, no hierarchy: although it is good practice to “optimize the worst case”, all of it can be equally important.

At this point the main thing is to be aware of these differences, and to know approximately if the optimization you’re working on will have an impact on the worst case or not. It is relatively common to work on a “best case” optimization that seems wonderful “in the lab”, in an isolated test app, and then realize that it doesn’t make any actual difference once put “in the field” (e.g. in a game), because the cost becomes dominated by cache misses there.

For now we are in the lab, so we will just be aware of these things, notice that the first frame is more expensive, and ignore it. If you think about it too much, you never even get started.

Sorting (static):
time: 686
time: 144
time: 139
time: 145
time: 138
time: 138
time: 138
time: 148
time: 139
time: 137
time: 138
time: 138
time: 137
time: 138
time: 146
time: 144

The sorting is at least 140 times more expensive than the allocation in our test. Thus, as expected, we’re just going to ignore the allocation for now. That was only a hunch before, but profiling confirms it was correct.

The first frame is almost 5 times more expensive than the subsequent frames, which seems a bit excessive. This comment explains why:

The code is using my old radix sort, which has a special trick to take advantage of temporal coherence. That is, if you keep sorting the same objects from one frame to the next, sometimes the resulting order will be the same. Think for example about particles being sorted along the view axis: their order is going to be roughly the same from one frame to the next, and that’s why e.g. a bubble-sort can work well in this case - it terminates early because there is not much work needed (or no work at all indeed) to get from the current ordering to the new ordering. The radix sort uses a similar idea: it starts sorting the input data using the sorted ranks from the previous call, then notices that the ranks are still valid (the order hasn’t changed), and immediately returns. So it actually skips all the radix passes. That’s why the first frame is so much more expensive: it’s the only frame actually doing the sorting!

To see the actual cost of sorting, we can remove the static keyword. That gives:

Sorting (non static):
time: 880
time: 467
time: 468
time: 471
time: 471
time: 470
time: 469
time: 469
time: 499
time: 471
time: 471
time: 490
time: 470
time: 471
time: 470
time: 469

That’s more like it. The first frame becomes more expensive for some reason (maybe because we now run the ctor/dtor inside that function, i.e. we allocate/deallocate memory), and then the subsequent frames reveal the real cost of radix-sorting the array. The first frame is now less than 2X slower, i.e. the cost of cache misses is not as high as we thought.

In any case, this is all irrelevant for now, because:

Pruning:
time: 93164
time: 94527
time: 95655
time: 93348
time: 94079
time: 93220
time: 93076
time: 94709
time: 93059
time: 92900
time: 93033
time: 94699
time: 94626
time: 94186
time: 92811
time: 95747

There it is. That’s what takes all the time. The noise (the variation) in the timings is already more expensive than the full non-static radix sorting. So we will just put back the static sorter and ignore it entirely for now. In this test, questions like “is radix sort the best choice here?” or “shouldn’t you use quick-sort instead?” are entirely irrelevant. At least for now, with that many boxes, and in this configuration (the conclusion might be different with less boxes, or with boxes that do not overlap each-other that much, etc), the sorting costs nothing compared to the pruning.

And then we can look at the last part:

Deallocation:
time: 4
time: 3
time: 3
time: 3
time: 6
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3
time: 3

Nothing to see here, it is interesting to note that the deallocation is more expensive than the allocation, but this is virtually free anyway.

So, analysis is done: we need to attack the pruning loop, everything else can wait.

Let’s look at the loop again:

There isn’t much code but since we have a lot of objects (10000), any little gain from any tiny optimization will also be multiplied by 10000 - and become measurable, if not significant.

If you look at the C++ code and you have no idea, you can often switch to the disassembly in search of inspiration. To make it more readable, I often use a NOP macro like this one:

And then I wrap the code I want to inspect between nops, like this for example:

It allows me to isolate the code in the assembly, which makes it a lot easier to read:

Note that the nops don’t prevent the compiler from reorganizing the instructions anyway, and sometimes an instruction you want to monitor can still move outside of the wrapped snippet. In this case you can use the alternative CPUID macro which puts a serializing cpuid instruction in the middle of the nops:

It puts more restrictions on generated code and makes it easier to analyze, but it also makes things very slow - in our case here it makes the optimized loop slower than the brute-force loop. It also sometimes changes the code too much compared to what it would be “for real”, so I usually just stick with nops, unless something looks a bit fishy and I want to double-check what is really happening.

Now, let’s look at the disassembly we got there.

While decorating the code with nops does not make everything magically obvious, there are still parts that are pretty clear right from the start: the cmp/jae is the first comparison (”while(RunningAddress2<LastSorted”) and the comiss/jb is the second one (”&& PosList[Index1 = *RunningAddress2++]<=list[Index0]->GetMax(Axis0))”).

Now the weird bit is that we first read something from memory and put it in xmm0 (”movss xmm0,dword ptr [eax+esi*4+0Ch]“), and then we compare this to some other value we read from memory (”comiss xmm0,dword ptr [eax+ebp*4]“). But in the C++ code, “list[Index0]->GetMax(Axis0)” is actually a constant for the whole loop. So why do we read it over and over from memory? It seems to me that the first movss is doing the “list[Index0]->GetMax(Axis0)”. It’s kind of obvious from the 0Ch offset in the indexing: we’re reading a “Max” value from the bounds, they start at offset 12 (since the mins are located first and they’re 4 bytes each), so that 0Ch must be related to it. And thus, it looks like the compiler decided to read that stuff from memory all the time instead of keeping it in a register.

Why? It might have something to do with aliasing. The pointers are not marked as restricted so maybe the compiler detected that there was a possibility for “list” to be modified within the loop, and thus for that limit value to change from one loop iteration to the next. Or maybe it is because “Index0″ and “Axis0″ are not const.

Or something else.

I briefly tried to use restricted pointers, to add const, to help the compiler see the light.

I failed.

At the end of the day, the same old advice remained: don’t trust the compiler. Never ever assume that it’s going to “see” the obvious. And even if yours does, there is no guarantee that another compiler on another platform will be as smart.

To be fair with compilers, they may actually be too smart. They might see something we don’t. They might see a perfectly valid (yet obscure and arcane) reason that prevents them from doing the optimization themselves.

In any case whatever the reason we reach the same conclusion: don’t rely on the compiler. Don’t assume the compiler will do it for you. Do it yourself. Write it this way:

And suddenly the disassembly makes sense:

The load with the +0Ch is now done before the loop, and the code between the nops became smaller. It is not perfect still: do you see the line that writes xmm0 to the stack ? (”movss dword ptr [esp+14h],xmm0″). You find it again a bit later like this:

So the compiler avoids the per-loop computation of MaxLimit (yay!) but instead of keeping it in one of the unused XMM registers (there are plenty: the code only uses one at this point), it writes it once to the stack and then reloads it from there, all the time (booh!).

Still, that’s enough for now. By moving the constant “MinLimit” and “MaxLimit” values out of the loops, in explicit const float local variables, we get the following timings:

Office PC:

Complete test (brute force): found 11811 intersections in 819967 K-cycles.
89037 K-cycles.
98463 K-cycles.
95177 K-cycles.
88952 K-cycles.
89091 K-cycles.
88540 K-cycles.
89151 K-cycles.
91734 K-cycles.
88352 K-cycles.
88395 K-cycles.
99091 K-cycles.
99361 K-cycles.
91971 K-cycles.
89706 K-cycles.
88949 K-cycles.
89276 K-cycles.
Complete test (box pruning): found 11811 intersections in 88352 K-cycles.

Home PC:

Complete test (brute force): found 11811 intersections in 781863 K-cycles.
96888 K-cycles.
93316 K-cycles.
93168 K-cycles.
93235 K-cycles.
93242 K-cycles.
93720 K-cycles.
93199 K-cycles.
93725 K-cycles.
93145 K-cycles.
93488 K-cycles.
93390 K-cycles.
93346 K-cycles.
93138 K-cycles.
93404 K-cycles.
93268 K-cycles.
93335 K-cycles.
Complete test (box pruning): found 11811 intersections in 93138 K-cycles.

The gains are summarized here:

Home PC

Timings (K-Cycles)

Delta (K-Cycles)

Speedup

Overall X factor

(Version1)

(101662)

Version2 - base

98822

0

0%

1.0

Version3

93138

~5600

~5%

~1.06

Office PC

Timings (K-Cycles)

Delta (K-Cycles)

Speedup

Overall X factor

(Version1)

(96203)

Version2 - base

92885

0

0%

1.0

Version3

88352

~4500

~5%

~1.05

“Delta” and “Speedup” are computed between current version and previous version. “Overall X factor” is computed between current version and the base version (version 2).

The base version is version2 to be fair, since version1 was the same code, just not using the proper compiler settings.

The code became faster. On the other hand the total number of instructions increased to 198. This is slightly irrelevant though: some dummy instructions are sometimes added just to align loops on 16-byte boundaries, reducing the number of instructions does not always make things faster, all instructions do not have the same cost (so multiple cheap instructions can be faster than one costly instruction), etc. It is however a good idea to keep an eye on the disassembly, and the number of instructions used in the inner loop still gives a hint about the current state of things, how much potential gains there are out there, whether an optimization had any effect on the generated code, and so on.

What we learnt:

Don’t trust the compiler.

Don’t assume it’s going to do it for you. Do it yourself if you can.

Always check the disassembly.

That’s enough for one post.

Next time we will stay focused on these ‘while’ lines and optimize them further.

GitHub code for part 3

Box pruning revisited - part 2 - compiler options

Friday, February 10th, 2017

Part 2 - compiler options

After converting the project, the default compiler options for the Release configuration are as follows (click to expand):

These are basically the only options affecting performance, if we ignore a few additional ones in the linker. After some years programming, you get a feeling for which ones of these options are important, and which ones are not.

So… what do you think, optimization experts?
Which one of these will make the most difference here?

For me, looking at that list, the suspicious ones that should be changed immediately are the following:

Inline Function Expansion: Default

Enable C++ Exceptions: Yes (/EHsc)

Enable Enhanced Instruction Set: Not Set

Floating Point Model: Precise (/fp:precise)

These guys are the usual suspects, as far as I’m concerned.

But let’s test this.

We first change the “Inline Function Expansion” option from “Default” to “Only __inline (/Ob1)

Results:

Complete test (brute force): found 11811 intersections in 837222 K-cycles.

Complete test (box pruning): found 11811 intersections in 96230 K-cycles.

In general, inlining has a strong impact on performance, and there would be a need for an entirely separate blog post about the art of inlining. But in this specific case, it does not make any difference: the “Default” setting works well enough. The disassembly is the same 202 instructions as before so it did not change anything.

Note that it does not mean nothing gets inlined. “Default” does not mean “no inlining“. If you really disable inlining with the “Disabled /Ob0” option, you get the following results:

Complete test (brute force): found 11811 intersections in 1155114 K-cycles.

Complete test (box pruning): found 11811 intersections in 174538 K-cycles.

That is quite a difference. So clearly, inlining is one of the important things to get right, and in this specific case the default option is already right.

Good.

Now, we switch inlining back to “Default” and move on to the next option.

—–

This time we disable exceptions (“Enable C++ Exceptions: No”).

Results:

Complete test (brute force): found 11811 intersections in 817837 K-cycles.

Complete test (box pruning): found 11811 intersections in 95789 K-cycles.

It appears that disabling exceptions has a noticeable effect on the brute-force implementation, but no clear effect on the box-pruning function.

The disassembly shows the same 202 instructions as before, so the small performance gain is not actually here, it’s just noise in the results. It is important to check the disassembly to confirm that the “optimization” actually changed something. Otherwise you can often see what you want to see in the results…

Well, exceptions usually add a tiny overhead for each function, and it can accumulate and add up to “a lot” (relatively speaking). But we don’t have a lot of functions here, and as we just saw before with inlining, the few functions we have are properly inlined. So it makes sense that disabling exceptions in this case does not change much.

Worth checking though. Don’t assume. Check and check and check.

—–

Next, we turn exceptions back on (to measure the effect of each option individually) and then we move on to this:

Enable Enhanced Instruction Set: Not Set

This one is interesting. The default is “Not Set” but if you look at the disassembly so far, it is clearly using some SSE registers (for example xmm0). So it turns out that by default, the compiler uses SSE instructions these days. Which explains why switching to /arch:SSE2 gives these results:

Complete test (brute force): found 11811 intersections in 829134 K-cycles.

Complete test (box pruning): found 11811 intersections in 96448 K-cycles.

Again it appears that the option has a small effect on the brute-force code (if this isn’t just noise), and no effect on the box-pruning code. And indeed, the disassembly shows the same 202 instructions as before.

Now, as an experiment, we can switch back to regular x87 code with the /arch:IA32 compiler flag (”Enable Enhanced Instruction Set : No Enhanced Instructions”). This gives the following results:

Complete test (brute force): found 11811 intersections in 921893 K-cycles.

Complete test (box pruning): found 11811 intersections in 110605 K-cycles.

Ok, so that makes more sense: using SSE2 does in fact have a clear impact on performance, it’s just that the default “Not Set” option was actually already using it. That’s a bit confusing, but at least the results now make sense.

While we are looking at these results, please note how enabling the SSE2 compiler flag only provides modest gains, from ~110000 to ~97000: that’s about a 10% speedup only. This is again why we didn’t enable that compile flag back in PhysX 2.x. Contrary to what naive users claimed online, using the flag does not magically make your code 4X faster.

—–

Finally, we focus our attention on the Floating Point Model, and switch it to /fp:fast. You might guess the results by now:

Complete test (brute force): found 11811 intersections in 825688 K-cycles.

Complete test (box pruning): found 11811 intersections in 96115 K-cycles.

And yes, the disassembly is exactly the same as before. Frustrating.

—–

At that point I got tired of what looked like a pointless experiment. I just quickly setup the remaining options with my usual settings, compiled, and…

…the code got measurably faster:

Complete test (brute force): found 11811 intersections in 817855 K-cycles.

Complete test (box pruning): found 11811 intersections in 93208 K-cycles.

Like, a 100% reproducible good 3000 K-Cycles faster.

And the speedup was not imaginary, it was indeed reflected in the disassembly: 192 instructions.

What…

After a short investigation I discovered that the only compiler option that made any difference, the one responsible for the speedup was “Omit Frame Pointers“.

…the hell?

So, experts, did you predict that? :)

I did not.

This was doubly surprising to me.

The first surprise is that /O2 (which was enabled by default in Release, right from the start) is supposed to include /Oy, i.e. the “Omit Frame Pointers” optimization.

But this link explains the problem:

“The /Ox (Full Optimization) and /O1, /O2 (Minimize Size, Maximize Speed) options imply /Oy. Specifying /Oy– after the /Ox, /O1, or /O2 option disables /Oy, whether it is explicit or implied.”

So, the issue is that the combo box in the compiler options exposes “No (/Oy-)”, which is an explicit “disable” command rather than a “use whatever is the default”. So as the MSDN says, it overrides and undoes the /O2 directive. Oops.

The second surprise for me was that it had such a measurable impact on performance: about 5%. Not bad for something that wasn’t even on my radar. To be fair this issue doesn’t exist with 64-bit builds (as far as I know), so maybe that’s why I never saw that one before. According to the MSDN /Oy frees up one more register, EBP, for storing frequently used variables and sub-expressions. Somehow I didn’t realize that before, and it certainly explains why things get faster.

—–

Ok!

Compiler options: checked!

Other than that, I removed some obsolete files from the project, but made no code changes. This version is now going to be our base version against which the next optimizations will be measured.

For reference, this was my best run on the office PC:

Complete test (brute force): found 11811 intersections in 819814 K-cycles.
102256 K-cycles.
93092 K-cycles.
92885 K-cycles.
99537 K-cycles.
93146 K-cycles.
93325 K-cycles.
95795 K-cycles.
97573 K-cycles.
97606 K-cycles.
98829 K-cycles.
97040 K-cycles.
95197 K-cycles.
98149 K-cycles.
93226 K-cycles.
93008 K-cycles.
95254 K-cycles.
Complete test (box pruning): found 11811 intersections in 92885 K-cycles.

And on the home PC:

Complete test (brute force): found 11811 intersections in 781996 K-cycles.
102578 K-cycles.
98972 K-cycles.
98898 K-cycles.
99183 K-cycles.
98920 K-cycles.
98823 K-cycles.
98948 K-cycles.
99047 K-cycles.
99132 K-cycles.
98822 K-cycles.
98975 K-cycles.
100701 K-cycles.
98892 K-cycles.
99025 K-cycles.
99294 K-cycles.
98981 K-cycles.
Complete test (box pruning): found 11811 intersections in 98822 K-cycles.

The progress will be captured in this table:

Home PC

Office PC

Version1

101662

96203

Version2 - base

98822

92885

What we learnt:

The default performance-related compiler options in Release mode are pretty good these days, but you can still do better if you go there and tweak them.

Next time, we will start looking at the code and investigate what we can modify. That is, we will start the proper optimizations.

GitHub code for part 2

Box pruning revisited - part1 - the setup

Friday, February 10th, 2017

Part 1 - The setup

Back in 2002 I released a small “box pruning” library on my website. Basically, this is a “broadphase” algorithm: given a set of input bounds (AABBs - for Axis Aligned Bounding Boxes), it finds the subset of overlapping bounds (reported as an array of overlapping pairs). There is also a “bipartite” version that finds overlapping boxes between two sets of input bounds. For more details about the basics of box pruning, please refer to this document.

Note that “box pruning” is not an official term. That’s just how I called it some 15 years ago.

Since then, the library has been used in a few projects, commercial or otherwise. It got benchmarked against alternative approaches: for example you could still find it back in Bullet 2.82’s “Extras\CDTestFramework” folder, tested against Bullet’s internal “dbVt” implementation. People asked questions. People sent suggestions. And up until recently, people sent me results showing how their own alternative broadphase implementation was faster than mine. The last time that happened, it was one of my coworkers, somebody sitting about a meter away from me in the office, who presented his hash-grid based broadphase which was “2 to 3 times faster” than my old box pruning code.

That’s when I knew I had to update this library. Because, of course, I’ve made that code quite a bit faster since then.

Even back in 2002, I didn’t praise that initial implementation for its performance. The comments in there mention the “sheer simplicity”, explicitly saying that it is “probably not faster” than the other competing algorithms from that time. This initial code was also not using optimizations that I wrote about later in the SAP document, e.g. the use of “sentinels” to simplify the inner loop. Thus, clearly, it was not optimal.

And then of course, again: it’s been 15 years. I learnt a few things since then. The code I write today is often significantly better and faster than the code I wrote 15 years ago. Even if my old self would have had a hard time accepting that.

So, I thought I could write a series of blog posts about how to optimize that old implementation from 2002, and make it a good deal faster. Like, I don’t know, let’s say an order of magnitude faster as a target.

Sounds good?

Ok, let’s start.

For this initial blog post I didn’t do any real changes, I am just setting up the project. The old version was compiled with VC6, which I unfortunately don’t have anymore. For this experiment I randomly picked VC11.

Here is a detailed list of what I did:

  • Converted the project from Visual Studio 6 to Visual Studio 2012. I used the automatic conversion and didn’t tweak any project settings. I used whatever was enabled after the conversion. We will investigate the compiler options in the next post.
  • Made it compile again. There were some missing loop indices in the radix code, because earlier versions of Visual Studio were notoriously not properly handling the scope in for loops (see /Zc::forScope). Other than that it compiled just fine.
  • Moved the files that will not change in these experiments to a shared folder outside of the project. That way I can have multiple Visual Studio projects capturing various stages of the experiment without copying all these files in each of them.
  • Added a new benchmark. In the old version there was a single test using the “CompleteBoxPruning” function, with a configuration that used 5000 boxes and returned 200 overlapping pairs. This is a bit too small to properly stress test the code, so I added a new test that uses 10000 boxes and returns 11811 intersections. That’s enough work to make our optimizations measurable. Otherwise they can be invisible and lost in the noise.
  • In this new test (”RunPerformanceTest” function) I loop multiple times over the “BruteForceCompleteBoxTest” and “CompleteBoxPruning” tests to get more stable results (recording the ‘min’). Reported timing values are divided by 1024 to get results in “K-Cycles”.
  • I also added a validity test (”RunValidityTest” function) to make sure that the two functions, brute-force and optimized, keep reporting the same pairs.

And that’s about it. There are no modifications to the code otherwise for now; it is the same code as in 2002.

The initial results are as follows, on my home PC and my office PC. The CPU-Z profiles for both machines are available here:

Home PC: pierre-pc

Office PC: pterdiman-dt

Note that they aren’t really “killer” machines. They are kind of old and not super fast. That’s by design. Optimizing things on the best & latest PC often hides issues that the rest of the world may suffer from. So you ship your code thinking it’s fast, and immediately get reports about performance problems from everybody. Not good. I do the opposite, and (try to) make the code run fast on old machines. That way there’s no bad surprises. For similar reasons I test the results on at least two machines, because sometimes one optimization only works on one, and not on the other. Ideally I could / should have used entirely different platforms here (maybe running the experiments on consoles), but I’m not sure how legal it is to publish benchmark results from a console, so, maybe next time.

Home PC:

Complete test (brute force): found 11811 intersections in 795407 K-cycles.
102583 K-cycles.
102048 K-cycles.
101721 K-cycles.
101906 K-cycles.
101881 K-cycles.
101662 K-cycles.
101768 K-cycles.
101693 K-cycles.
102094 K-cycles.
101924 K-cycles.
101696 K-cycles.
101964 K-cycles.
102000 K-cycles.
101789 K-cycles.
101982 K-cycles.
101917 K-cycles.
Complete test (box pruning): found 11811 intersections in 101662 K-cycles.

Office PC:

Complete test (brute force): found 11811 intersections in 814615 K-cycles.
106695 K-cycles.
96859 K-cycles.
97934 K-cycles.
99237 K-cycles.
97394 K-cycles.
97002 K-cycles.
96746 K-cycles.
96856 K-cycles.
98473 K-cycles.
97249 K-cycles.
96655 K-cycles.
102757 K-cycles.
96203 K-cycles.
96661 K-cycles.
107484 K-cycles.
104195 K-cycles.
Complete test (box pruning): found 11811 intersections in 96203 K-cycles.

The “brute force” version uses the unoptimized O(N^2) “BruteForceCompleteBoxTest” function, and it is mainly there to check the returned number of pairs is valid. I only report one performance number for this case - we don’t care about it.

The “box pruning” version uses the “CompleteBoxPruning” function, that we are going to optimize. As we can see here, this initial implementation offered quite decent speedups already - not bad for something that was about 50 lines of vanilla C++ code.

For the “complete box pruning case” I make the code run 16 times and record the minimum time. I am going to report the 16 numbers from the 16 runs though, to show how stable the machines are (i.e. do we get reproducible results or is it just random?), and to show the cost of the first run (which is usually more expensive than the subsequent runs, so it’s a worst-case figure).

These results are out-of-the-box after the automatic project conversion. Needless to say, this is compiled in Release mode.

If you want to replicate these numbers and get stable benchmark results from one run to the next, make sure your PC is properly setup for minimal interference. See for example the first paragraphs in this post .

For now I will only focus on the “CompleteBoxPruning” function, completely ignoring its “BipartiteBoxPruning” counterpart in my reports. All optimizations will be equally valid for the bipartite case, but there will be enough to say and report with just one function for now. The companion code might update and optimize the bipartite function along the way though - I’ll just not talk about it.

The initial disassembly for the function has 202 instructions. We are going to keep a close eye on the disassembly in this project.

That’s it for now.

Next time, we will play with the compiler options and see what kind of speedup we can get “for free”.

GitHub code for part 1

PhysX: bulldozer test (PhysX 3.4, CPU mode)

Tuesday, January 24th, 2017

Another quick test in PEEL 1.1.

PhysX tip: aggregates and MBP

Monday, January 23rd, 2017

This video shows 200 kinematic characters running around. There is no “physics” per-se in this scene - zero dynamic objects, everything is kinematic and controlled by the users’ code. But the scene still takes a lot of time in PhysX, because all these shapes have to be updated in the broadphase structure.

This is a worst-case scenario for the default broadphase (SAP): all objects move all the time, and they are all located at the same altitude. As a result, the projections of the objects’ AABBs overlap a lot on the Y axis, which creates a lot of “swaps” in the structure, and this takes a lot of time to update.

Of course this is an artificial scene, but it shows problems that do happen in real-world scenarios, in particular if we add all the extra bounds from the static environment. This is not shown in the video but there are other scenes in the combo box to test this case as well. The mockup static level looks like this:

So how do we make things run faster here? There are two main ways.

The first tip is to use “aggregates”. An aggregate is a collection of actors grouped together to form a single entry in the broadphase. In PhysX you should already be familiar with compound actors that group together multiple shapes within a single actor. It is the same idea: you can group together multiple actors within a single aggregate.

A typical use-case is a ragdoll / character, as shown in this video. In this example each character has 19 body parts, i.e. 19 actors. By default all these actors have a broadphase entry each. The body parts and their AABBs overlap each-other quite a lot all the time, and this puts a lot of stress on the SAP broadphase. But if you put each character in its own aggregate, it suddenly creates 19 times less entries in the broadphase, and an overlap is only registered when two characters touch each-other - i.e. when the white compound bounds shown in the video at 0:27 overlap each-other.

If self-collisions or character-vs-character collisions are needed, additional tests are performed after the broadphase to take care of those. The code becomes more complex, since there is now a two-level hierarchy in the broadphase module, but the results are faster overall than putting everything naïvely in the broadphase. Most notably, when self-collisions within an aggregate are not needed, the filtering is done by testing a single bit (at aggregate level) instead of doing this for each overlapping pair within the aggregate. Generally speaking it is always a good idea to use aggregates, provided you don’t put thousands of actors in each of them.

The second tip is to consider using “MBP” (for Multi Box Pruning). This is an alternative broadphase implementation that does not suffer from the same pitfalls as SAP, and it tends to be faster when a lot of objects are moving at the same time. On the other hand it is usually slower than SAP when few objects are moving, i.e. when the majority of the scene is sleeping. This implementation is based on my old box pruning code (but rewritten and much much faster), borrows ideas from the “multi-SAP” approach I described here, and then adds an additional layer of code to take care of sleeping objects. I wrote about it before and showed a demo of it, in a post where it was called “broadphase X”. Well, now you know, and you can grab the code on GitHub.

MBP currently works with user-defined regions, i.e. it is more tedious to setup than SAP - and that’s one main reason why it is not enabled by default. PEEL simply takes the scene’s global bounds and divides them into grid cells, which is usually a good default setup. A real game could do something more advanced, but it is not always needed. As you can see in the video, simply using a few default MBP grid cells has a large impact on performance: in this scene it is pretty much the same performance gain as using aggregates.

Then one can of course use both aggregates and MBP. But it does not always help. In this particular test case for example (200 kinematic characters alone, no mockup static level), combining both does not lead to additional gains compared to simply using one. The performance with the various options look like this:

YMMW and things will depend a lot on the scene’s configuration, the percentage of objects moving at any given time compared to the whole scene, etc.

In any case this post was just to introduce two options you can consider when broadphase performance becomes an issue: aggregates and MBP. Both of them have been used and shipped in AAA games, on PC as well as consoles like the PS4. They are viable options that you could experiment with.

PhysX tip: use the new Opcode2-based midphase structure

Friday, January 20th, 2017

PhysX 3.4 has a new mesh structure based on Opcode 2, which is used for the “midphase” queries (i.e. any collision query against a triangle mesh).

It is not enabled by default because it currently has some limitations compared to the previous midphase structure:

  • it does not support deformable meshes (i.e. it does not support PxTriangleMesh::getVerticesForModification() and PxTriangleMesh::refitBVH())
  • it is not implemented on all platforms. It is currently only available on platforms for which PX_INTEL_FAMILY is defined (that includes PCs but also consoles like the Xbox One and PS4).

To enable it, look up the comments for PxCookingParams::midphaseDesc and the PxMidphaseDesc class. Or check the PhysX manual. Or the PEEL code. Basically it will come down to simply adding this line to the cooking params before passing them to PxCreateCooking:

PxCookingParams Params;
Params.midphaseDesc.setToDefault(PxMeshMidPhase::eBVH34);

Overall, the new structure should be faster than the previous one. It is also much faster to build, so if for some reason you must cook triangle meshes at runtime, this new structure should help. Memory usage should be roughly the same as before.

You can see the results in PEEL 1.1. The new midphase structure is selected by default in PEEL, but you can go back to the old one using the “cooking” tab in the PhysX 3.4 plugin’s UI. Note that Opcode 2 used as a standalone library still provides significantly faster results (you can see that in PEEL as well), because PhysX has a larger per-query overhead for management, filtering, etc.

The midphase structure is also used in rigid body simulation, for dynamic objects colliding against triangle meshes (to fetch candidate triangles). So switching to the new structure might also give you performance gains there, even if you are not using scene queries.

PhysX tip: make sure debug visualization is really disabled

Friday, January 20th, 2017

In PhysX, debug visualization is enabled or disabled by this call:

PxScene::setVisualizationParameter(PxVisualizationParameter::eSCALE, Value);

With Value = 0.0 to disable it, and usually Value = 1.0 to enable it (but any non-zero value will enable it, and then be used as a scale factor for normals, etc).

Simply setting the PxVisualizationParameter::eSCALE to 1.0 does not render anything on its own. Users have to enable additional flags to tell the system which debug gizmos they want to see. For example here is the list I use in PEEL (but there’s more in the SDK):

  • PxVisualizationParameter::eSCALE,
  • PxVisualizationParameter::eBODY_AXES,
  • PxVisualizationParameter::eBODY_MASS_AXES,
  • PxVisualizationParameter::eBODY_LIN_VELOCITY,
  • PxVisualizationParameter::eBODY_ANG_VELOCITY,
  • PxVisualizationParameter::eCONTACT_POINT,
  • PxVisualizationParameter::eCONTACT_NORMAL,
  • PxVisualizationParameter::eACTOR_AXES,
  • PxVisualizationParameter::eCOLLISION_AABBS,
  • PxVisualizationParameter::eCOLLISION_SHAPES,
  • PxVisualizationParameter::eCOLLISION_AXES,
  • PxVisualizationParameter::eCOLLISION_COMPOUNDS,
  • PxVisualizationParameter::eCOLLISION_FNORMALS,
  • PxVisualizationParameter::eCOLLISION_EDGES,
  • PxVisualizationParameter::eCOLLISION_STATIC,
  • PxVisualizationParameter::eCOLLISION_DYNAMIC,
  • PxVisualizationParameter::eJOINT_LOCAL_FRAMES,
  • PxVisualizationParameter::eJOINT_LIMITS,
  • PxVisualizationParameter::eMBP_REGIONS,

Now there is a trap here.

The trap is that if you just set PxVisualizationParameter::eSCALE to 1.0 alone, nothing gets rendered but it still has a performance impact. And it can be invisible to users, until they use a profiler.

For example in PEEL, it means that this particular UI config has a clear negative impact on performance:

Debug viz options for PhysX in PEEL

And here’s the effect on performance in “ConvexGalore2″:

As you can see this is quite significant. The drop on the blue curve corresponds to the moment I unchecked “Enable debug visualization” in the UI. As soon as I did, performance went back to normal.

So, be aware of this, and make sure you don’t ship your game with PxVisualizationParameter::eSCALE still set to 1.0.

PhysX tip: use tight convex bounds

Thursday, January 19th, 2017

There is a new flag in PhysX 3.4 that tells the system to use tight bounds for convexes: PxConvexMeshGeometryFlag::eTIGHT_BOUNDS.

Use it.

Until now PhysX used a fast O(1) piece of code to update the AABB of a convex mesh, from its precomputed local AABB and the current world transform. That one’s a classic from the GD-Algorithms days, and I remember also spotting it in Charles Bloom’s public code years and years ago. If you want the details, see for example this file in the PEEL distro:

.\PEEL\Physics\Ice\APIs\Ice\IceMaths\IceAABB.h

And then look up the “Rotate” function, implemented there both for min/max and center/extents AABBs. This stuff is from 2000 or before, nothing new here.

There is no problem with this “Rotate” function: it’s great, we’ve been using it for more than a decade, and we’re still using it.

However, it obviously does not create the tightest possible AABB, since it only knows about the local un-transformed bounds, and it doesn’t know anything about the object contained within these bounds. That’s why for simple shapes like boxes or capsules we don’t use it: instead we directly recompute the sphere or capsule’s bounds from its data and current pose. This is just as fast, but also provides tighter bounds.

For convexes though, we never tried that, because computing tight bounds for them was more tedious. You either need to use brute-force and iterate over all vertices (which is a potentially expensive O(N) approach), or you need to do something more complex like maybe hill-climbing, etc: basically the same stuff as for GJK really, which has pros and cons I won’t go into right now.

Long story short: in PhysX 3.4 we tried the brute-force approach, and found that it significantly improves both performance and memory usage in scenes with piles of convex objects. The number of vertices in a convex is limited to 256 in PhysX, so there’s a limit to how expensive the computation can be, and we found it reasonable (iterating over vertices in a linear array is cache & SIMD friendly, so the worst case isn’t that bad).

Here are some results using PEEL’s “ConvexGalore2″ test scene. It’s a giant pile of convex objects falling, and it looks like this:

Here are the performance results with and without tight bounds. Blue is with the default PhysX settings, red is with PxConvexMeshGeometryFlag::eTIGHT_BOUNDS. There’s a pretty clear winner here:

It also improves memory usage, since the tighter bounds mean less candidate pairs are generated from the  broadphase, etc. This is again a clear win:

Granted: computing the bounds becomes more expensive, and if you have convex objects that don’t ever go close to other convex objects, using the flag might reduce performance overall. But I’d say that all things considered it’s one of these easy flags that you should just use all the time. It’s a small price to pay for potentially big gains. Visually the difference between the regular and tight bounds can be quite dramatic, as you can see for example here:

PhysX tip: cylinder shapes

Thursday, January 19th, 2017

PhysX does not support native, implicit cylinder shapes.

The initial technical reason behind this is clear, and goes back all the way to NovodeX 2.0 around 2003. I was the first NovodeX employee and my job was to implement everything related to collision detection in this engine: broad phase, narrow phase, contact generation, raycasts, etc. We didn’t have a lot of time for research or experimentation, so I only briefly tried GJK / EPA and quickly ran into a wall: these algorithms were just constantly failing for me. Accuracy issues, infinite loops, etc. At the time I was able to reproduce some of these issues in SOLID 3.5 itself, which made me give up: even the reference version was failing and I just had no time to spend on productizing my “research code” (you know… works in the lab, fails in the field).

So instead I went with what I was familiar with, and implemented contact generation using a mixture of SAT and distance tests, with a dedicated function for each possible pairs of shapes. So for example box-vs-box would use a dedicated function to generate box-vs-box contacts, sphere-vs-box would use another function, and so on. With this design the cost of adding a new shape type, such as a cylinder, is high. To support cylinder shapes, one needs to write and add several new contact generation functions: cylinder-vs-box, cylinder-vs-sphere, cylinder-vs-mesh, etc. And none of these functions are trivial, since a cylinder is not the most friendly shape to generate contacts for. On top of that, the same problem exists for “scene queries”, i.e. one needs to write explicit raycast, overlap and sweep queries for cylinders. It’s a lot of non-trivial work.

This basic design (the same as in the old ODE library for example) survived until PhysX 3, for which we finally got the time to pause, sit down and revisit everything (not just collision detection: everything). We started playing with GJK / EPA again, mainly because Havok had been using it since the beginning, and it seemed to give them an edge in performance. New people joined, new code got written. It took a while to iron everything out, but in PhysX 3.4 we were happy enough with the results and finally switched to the new implementation, “PCM” (for Persistent Contact Manifolds), as the default contact generation method. Which means that in theory adding support for cylinders should now be as easy as adding a “support function” for cylinders (a trivial task), and that would be it.

However in practice, as usual, it is not that easy. Because under the hood, our PCM codepath still relies on the previous non-PCM contact generation routines to create the initial contacts, when two shapes initially touch. We do this to avoid issues and artifacts traditionally coming with the PCM territory. There are other ways to deal with those, as explained in the past IIRC by Erwin (from Bullet) and Gino (from SOLID), but that’s again something that always felt a bit experimental / fragile to me. And in any case that’s more code that we currently don’t have and have no time to research at this point.

That isn’t the main problem though. Beyond these implementation details, adding a new shape type still increases the support burden, the amount of code and classes, the potential for bugs, the testing & maintenance cost, etc. The only way to justify that now would be to instead add a generic “user-defined” shape where users would simply define their own support function, and this could be reused not only for cylinders but also for most existing shapes, or new ones like cones, etc - any convex shape. That’s what several other engines do, so that’s a viable option, and that way at least we would get some more gains & benefit for the price we’d pay. But it would still introduce an inconsistency in the API, since these new shapes would only be supported in the PCM codepath. And it could come with a performance cost if we use virtual calls into users’ code to compute a supporting vertex. And we still wouldn’t have a great way to generate the initial contacts for these shapes. And… and… and this is starting to sound a lot like analysis paralysis, which might explain why user-defined shapes are still an item on our TODO list rather than an actual, current feature.

The final nail in the coffin though is simply that we already have a perfectly fine workaround: just use a convex mesh instead.

People often don’t like this suggestion: they object that a convex shape is not going to be smooth enough to roll convincingly, and/or that a convex mesh tessellated enough to roll nicely would create performance problems.

As far as I can tell, both of these claims are incorrect.

I created a few test scenes in PEEL 1.1 to investigate.

The first scene features a single cylinder starting on an inclined slope and rolling away. The test is configurable and users can select the amount of tessellation for the cylinder. At the same time, since it’s PEEL, you can run the same scene with an engine that features “proper” cylinders (like Bullet or Newton - the Havok case is more questionable, see e.g. here). That way you can directly compare the motions and see if the cylinder that uses a convex mesh rolls more or less convincingly than the real thing. For me, with about 60 vertices in the cylinder’s base circle, I cannot tell the difference. But download PEEL 1.1 and see for yourself. (Use “RollingCylinder”, test 27).

Rolling cylinder

Rolling cylinder

Another way to test this is to try one of the vehicle scenes, for example “ArticulatedVehicle” (test 76). In this test the wheels use convex meshes instead of “real” cylinders. You can change the tessellation level in the test’s UI, and see the effect on the motion. You have to pull the vehicle around with the mouse, as you cannot drive it in this test.

Articulated vehicle

Articulated vehicle

If you want to drive, try the “VehicleTest” scene (number 245). Here again the cylindrical wheels are convex meshes. Use the arrow keys to drive the car around. Do you feel that the tessellation produces a bumpy ride? I don’t.

Now, the performance issue. Yes, certainly, using a highly tessellated convex mesh is more expensive than using an implicit shape. But this is only visible within the same engine. Beyond that, in practice, a tessellated convex mesh in PhysX can be just as fast, or faster, than a “real” implicit cylinder in another engine. Again, don’t take my word for it: download PEEL and see for yourself. (for example with “CylinderStack”, test 28). There is no performance problem using a highly tessellated convex mesh for cylinders, because generally speaking there is no performance problem using highly tessellated convex meshes in PhysX.

Cylinder stack

Cylinder stack

Besides, even if there would be a performance issue with cylinders, it still would remain isolated and only affecting cylinders. Unless your game features cylinders exclusively, it would be unlikely to make a dent in the framerate. In an actual game, the extra cost would be lost in the noise. Remember that there’s a lot more than physics going on in a game. Physics may have maybe a CPU budget of 20% of the frame. And then only a limited part of the physics budget is eaten up by contact generation (there’s also the broad phase, the solver, scene queries, etc). And then only a limited part of that contact generation time will be dedicated to cylinders. So even if the support function for a convex mesh is 10 times slower than the support function for an implicit cylinder, at the end of the day it doesn’t make the whole game 10 times slower. The way it is now, the overall performance impact should be quite small.

So in theory, yeah, you have a point. In practice, no, this is just not an issue.

shopfr.org cialis