2
$\begingroup$

I am working on a 3D packing algorithm (MIT-licensed). The box and the cuboids it contains are displayed as a 2D projection. The order of drawing the cuboids (now represented as polygons) is important: a cuboid placed at the back of the box must not be drawn after the cuboids in the front row. I am currently using order by(cuboid.X + cuboid.Y + cuboid.Z) and it works around 99% of the time, but not always. Some aberrations do ocurr, as depicted below. I have tried multiplying the coordinates, and order by X then by Y then by z, and other combinations. Adding the coordinates is the one that gave the best result. POV-ordering has been suggested, but it won't work, as illustrated by the second diagram. Can someone enlighten me? enter image description here enter image description here

$\endgroup$
1
  • $\begingroup$ I assume that using a depth buffer is off the table, right? $\endgroup$ Commented Feb 10, 2022 at 17:29

1 Answer 1

3
$\begingroup$

Let's get our orientation straight first. When I speak of a direction, I mean the direction relative to our viewpoint. So the "front" face of a cuboid is the face nearest the camera; "back" means the face pointing away from the camera. The "left" face of a cuboid is the face pointing to the left from the camera's view.

A cuboid X is in front of cuboid Y if one of the following is true:

  • The back face of X is in front of the front face of Y
  • The left face of X is to the right of the right face of Y.

If either of these is true, then Y should be drawn before X. This is how you build your sort order. If one of the above is true, then Y should be "less than" X and thus come earlier in the sort.

Note that this algorithm assumes exact math is used to compute the faces of the cuboids for comparison purposes. If you're using floating-point math, you may encounter precision issues that cause problems.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.