Tuesday, January 15, 2008

Burned by the STL - again!

I have blogged about this before, but it just burned me again.

Vector is usually very fast, but it also makes it really easy to write something really slow.

How about this?
struct forest_goo {
vector stuff;
vector > more_stuff;
};
vector many_forests;

How fast is this?

for(vector::iterator i = many_forests.begin(); i != many_forests.end();)
if(okay_forest(*i)) ++i;
else i = many_forests.erase(i);

Here's a hint: not very. The problem is the mid-vector erase. Vector is a bit stupid - when you erase a vector item, it copies every one of them backward by one spot to close the hole. But copying a vector means allocating memory for the vector (and for a vector of vectors it's worse). So in our case erasing one forest_goo item mid-vector is horribly expensive as long as there is a lot more forest goo after it.

The solution is two-part:
  1. Specialize std::swap() for the forest_goo struct so that you can swap two of them and have them change places without allocating memory. (On most STLs, swap() of vectors is already specialized, so you just have to tell the compiler to swap all the pieces.)
  2. Rewrite the algorithm to swap the to-be-killed forest_goo structs to the end of the vector. The swap is a no-mem-alloc operation. When done, you can then chop the entire end off of the array with clear, which won't require moving forest_goo structs around.

Saturday, January 12, 2008

X-Principles

I was reading about the history of X11 on Wikipedia while trying to fix Linux bugs and I stumbled across the principles of X. There are three I'd like to focus on, two of which I feel apply very well to X-Plane and one which does not.

The only thing worse than generalizing from one example is generalizing from no examples at all.

This is true, and in terms of X-Plane, I think this comes down to "don't add features that aren't needed." When you look at the "cost" of X-Plane in terms of how hard it is to write new code (and in some ways you could say Laminar Research does business by adding new code to X-Plane) our cost goes up with the number of existing features already in place that we have to keep working while we change things.

If a problem is not completely understood, it is probably best to provide no solution at all.

This also is very true for X-Plane. We want to provide long-term compatibility for X-Plane as a platform for airplanes, scenery and plugins. The risk of putting in solutions to problems that we don't understand is that two months later we'll go "ah drat, our APIs aren't quite right" but by that time third parties will be depending on the existing broken behavior.

Provide mechanism rather than policy. In particular, place user interface policy in the clients' hands.

I am critical of X, but you could deflect my criticism by pointing out that it stems from how X is used, which perhaps goes against its original intention. My issues, all stemming from the use of X as the lowest level of window management are:
  1. By making remote-desktop capabilities a core part of the spec, X11 introduces a complexity cost to desktop UI programming that isn't necessary a lot of the time.
  2. X is not a complete solution to a desktop environment layer.
The first criticism is open to debate - who am I to say what needs to be core and what doesn't? I will only say that if I have to sit down wih the Carbon or Win32 APIs and write UI interaction code, the specification of APIs in terms of blocking and non-blocking makes UI development a lot easier than the specification of APIs in terms of two streams of asynchronous RPCs/events. So I would argue the cost is real, but whether it's worth it, well, that depends on how you use X. (I am focusing perhaps too narrowly on those who hope Linux will becomea viable desktop platform.)

The second criticism isn't even remotely fair at all - X isn't a complete solution, and it's meant to have stuff on top of it. I suppose my issue here is: X11 is pretty ubiquitous as the base layer in the Unix world, but what goes on top is open for debate.

And this goes to this third principle. If X11 is only the "bottom half" of a complete UI framework, it makes sense to provide mechanism and omit policy. But....is the bottom half of a complete UI framework useful to clients? It's the lack of policy, encoded in a simple, ubiquitous API that makes simple things easy and hard things possible, that frustrates me about coding on Linux.

So when it comes to X-Plane, I take a very different approach - I treat all of my SDK code as policy work. That is, we try to make it easy to do things we want authors to do and impossible to do things we don't want authors to do. In my experience this is the only reasonably option...given an open platform, users will do, well, everything possible.

Is it fair to be so heavy handed? Call me a techno-fascist but I think it's essential. At the end of the day, third parties count on us to keep the platform stable so that they don't have to waste time updating previous finished products each time we post a new patch to X-Plane. The wider the array of weird behavior that we tolerate, the wider the array of weird behavior we have to treat as backward compatibility cases later. By using technical limitations to require authors to conform to specs the first time, we can avoid compatibility breaks later.

Monday, January 07, 2008

OpenGL and Threads: What's Wrong

So what's wrong with this code? The answer is that OpenGL is asynchronous, so traditional threading models tend to blow up with OpenGL for reasons that are hard to see (because the APIs look synchronous and act close enough to easily forget that they aren't).

Here's the fine print:
  • Calls to OpenGL from the same thread on the same context are executed in-order.
  • Calls from multiple contexts (and multiple threads always means multiple contexts) can execute out of order from the order they were issued.
  • All calls before a flush are executed before all calls after a flush, even across contexts, as long as the renderer is the same. (At least I think this is true.)
In the first example, a worker thread is preparing VBOs (buffers of geometry) and queueing them to a rendering thread that inserts them into the scene graph every now and then. But remember that both the VBO create and use are asynchronous and happen on other threads.

What ends up happening is that the VBO create code is rendered after the VBO draw code, because in-order execution is not guaranteed! This usually causes the driver to complain that the VBO isn't fully built. The solution is to flush after the VBO is created, which forces VBO creation to happen before any future calls.

In the second example, a PBO (buffer of imag data) is filled on the rendering thread, then sent to a worker thread to extract and process. We have the same problem: because we're across threads, the OpenGL extract operation can execute before the fill operation. Once again, flushing after the first thread-op synchronizes us.

Generally speaking, OpenGL isn't a great API for threading. It has very few options for synchronization - glFlush has real (and often quite negative) performance implications and it's a real blunt tool.

There is a 'fence' operation that allows a thread to block until part of the command-stream has
finished but it isn't real useful because:
  • It's vendor specific (all Macs, NV PCs) so it's not everywhere. It's not fun to use two threading models in an app because the threading primitives only exist in one.
  • It's not cross-thread! The fence is not shared between contexts, so we can't block a worker thread based on completion in a rendering thread - we have to block the renderer itself, which sucks.
In X-Plane we work around these things by trying to use deferred renderings, e.g...

while(1)
{
draw_a_lot();
read_old_async_data();
queue_new_async_data();
}

Teh result is that async queries (PBO framebuffer readbacks, occlusion queries) have a full frame before we ask for them, which helps prevent blocking.

Friday, December 21, 2007

What's Wrong With This Code

What's wrong with this code, which uses a second thread to build new nodes in a scene graph while the main thread renders and periodically picks up finished work?
thread 2:
create mesh geo in memory
glBufferData to create a vbo
send msg to thread 1 with VBO ID
thread 1:
while(1)
{
if we get a msg
insert VBO into scene graph
draw scene graph
}

Or how about this logic, which uses threads and PBOs to asynchronously capture full screen to disk?

thread 1:
render frame
bind pbo
glReadPixels
unbind pbo
send msg to thread 2

thread 2:
wait for message
bind pbo
get pbo data
unbind pbo
write data to disk


Hint: the answer is the same!

Updated OpenGL Performance Lore

Performance Lore (e.g. "I did X on my app and it got faster so you should do Y") is inherently dangerous in that performance tuning without performance analysis is a bad idea. With that in mind, it does have a use, I think, in at least pointing out possible areas of exploration.

With that in mind, some notes on X-Plane 9 performance:
  • It doesn't take a very complex pixel shader to become fill-rate bound! In version 8 (shaders were almost like the fixed function pipeline) X-Plane was almost always limited by the CPU and our ability to find and emit batches, even at high FSAA. With X-Plane 9, even on high end cards, even modest sized shaders are the limiting factor. Never underestimate the cost of doing something ten or twenty million times!
  • Overdraw is bad! As soon as you get into shaders, you become fill-rate bound and then overdraw becomes so expensive. So using blending and glPolygonOffset to composite into the frame buffer becomes a bad idea.
  • Geometry performance: putting index buffers into VBOs gained us some speed.
  • Optimizing down the number of vertices by more aggressively using indexing gained some speed, and never hurt, even if the mesh was a bit out of order, even on older hardware.
  • Using 16-bit indices on Mac made no difference - perhaps they're not natively supported?
  • Using the "static" VBO hint instead of "stream" for non-repeating geometry gave a tiny framerate improvement in a few cases, but mostly caused massive performance failures.
A note on this last point: the driver essentially has to guess a resource usage pattern from your API calls. A lot of them will use a most-recently-used purge scheme, that is, once you run out of VRAM you throw out the most recent thing you used and replace it. If we used a real FIFO, we'd guarantee the worst case: we would flush and reload every resource into VRAM every frame, so MRU makes sense.

The stream vs. static VBO hint will usually get your VBO into VRAM (static) or simply use it by mapping via AGP memory (stream). If your total working set is larger than VRAM (something's going to go over the bus) and a VBO is used only once, stream is the best choice; save VRAM for things that are used repeatedly, like repeating meshes and textures.

So when I tried jamming everything into VRAM, we ran out of VRAM in a big way and started to thrash...MRU works well when we're over budget by a tiny amount, but for a huge shortfall we just end up with thrash.

None of this is really surprising; people have been telling us we'd be shader-bound for years...it just took us a while to get there.

Thursday, December 20, 2007

Vtune - where's the stack?

I used VTune the other day to look at some performance problems on my PC. (Turns out the performance problem is the PC.) There's one thing about VTune I don't quite get:
  • When you're using the adaptive sampling profiler (system-timer-driven sampling) you only get function names.
  • To get a stack crawl you need to instrument the application (invasive profiling).
Now I don't like invasive profiling at all for a few reasons...
  • It changes the performance characteristics of the application.
  • It's not really compatible with inlining.
When sampling with Shark on the Mac, you get the stack history of each sample, not just the function itself. This is pretty important when leaf functions are bottlenecks from certain directions. For example, it's one thing to know you're spending all your time in glDrawElements (duh). But who is calling it? The OBJ engine? The mesh engine? Something else?

Friday, September 07, 2007

How does COM know?

If you call an a non-blocking method on a COM object that's in a different apartment and you need to receive callbacks, you need to sit in a message pump of some kind. That fact is written in a few different blogs, but what I didn't understand until today is: why does that work? How is COM connected to the message pump?

First let's pull apart that statement with some basics:
  • Single-Threaded Apartment (STA) basically puts boundaries around sets of objects that are similar to the boundaries around a process. When calling between the apartments (sets of COM objects) we use an RPC mechanism instead of a direct function call.
  • There is a 1:1 correspondence between threads and apartments, and a 1:1 correspondence between threads and their message queues. Thus there is an appropriate message queue for each apartment, and posting to that queue will assure which thread gets the message.
  • RPCs are thus implemented by posting messages to the queue of the thread we're trying to reach. We then poll our own message queue until we get some kind of "reply" indicating the RPC has done. This looks like a blocking function call to client code.
In order for this to work, the thread in the apartment we are calling into must itself be waiting on a message queue. This would be the case if it is either (1) really bored and just querying the message queue or (2) it is itself blocked on a method call into another apartment, and is thus polling its queue to find out if its own RPC is done.

If this all seems like insanity to you, well, it is.

Now when I say "non-blocking" method call, what I really mean is: a method call that returns really fast but starts some work to be completed later.

Normally when a thread is blocked because it made an RPC into another apartment, that apartment can call right back because the same polling of the message queue to discover that the RPC is over allows other methods to be called. This simply means that the flow of code between COM objects can ignore STA when all method calls are "blocking".

But as soon as we have a non-blocking call, there is no guarantee that the client code is actually listening for method calls into its apartment. (By the rules of STA, if the thread is doing stuff, no calls CAN happen, because one thread per apartment.)

Typically client code will make the async call, maybe make a few, and then do some kind of blocking until we're done..for example, we might call WaitForMultipleObjects.

In this case the right thing to do is MsgWaitForMultipleObjects (followed by GetMessage/DispatchMessage if we get woken up for a message). This way while our thread is doing nothing, other apartments can call us back.

This works because the thread, message queue, and apartment are all 1:1 relationships. So to say "this thread needs to be open to COM RPCs" all we need to say is "this thread needs to block on its own message queue", which is done with GetMessage.