# Which 3d rectangle to draw first

I'm trying to create an application that draws a set of rectangles in a 3d area. I want it to automatically calculate the rectangle that should be drawn first - it's very obvious for a human to know which side must be drawn first, but I have no idea how to actually determine this with mathematics.

This is what it currently does. This example consists of 5 rectangles, all with the same depth and attached to each other: Example

I should somehow calculate which rectangle is the closest to the middle point (0, 0, 0) - I just don't know where to start.

-
There's not always a complete solution -- it is possible to arrange three rectangles such that each one passes in front of one of the others. –  Henning Makholm Feb 2 '12 at 15:25
But those situations can be dealt with, by appropriately partitioning the rectangles. A rather elegant (and fairly efficient) solution to the whole problem is to construct a BSP-tree, see en.wikipedia.org/wiki/Binary_space_partitioning –  Martin Wanvik Feb 2 '12 at 15:38