[Tex/LaTex] Tikz: how to change the order of overlapping objects

tikz-pgf

I want to draw some overlapping rectangles, for example:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,backgrounds}
\begin{document}

\begin{tikzpicture}
\draw [fill=blue,ultra thick] (0.4,0.5) rectangle (0,1);
\draw [fill=red,ultra thick] (0,0.3) rectangle (1,1);
\draw [fill=green,ultra thick] (0,0) rectangle (0.5,0.5);
\end{tikzpicture}

\end{document}

But I want (in this example) the green rectangle under the red and the red under the blue. Is that possible (without changing the order of commands)?

More explanation: the latex commands are generated by a C++ program which computes coordinates of some rectangles. I want to draw them and they can overlap. The program computes the rectangles in some order and I want to show them in the reverse order. (It seems difficult to me to write the lines of C++ output to a file in reverse order.)

Here is what I have and what I want:

example

Best Answer

A simple sequence of \draw commands can also be reverted by TeX. In the following example, macro \reversedraws goes before the sequence of \draw commands, which should be reverted. It stores them in macro \collect@draws in reverse order. After the last \draw, the now reverted list is output:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes,backgrounds}

\usepackage{etoolbox}% provides \preto
\makeatletter
\newcommand*{\collect@draws}{}
\newcommand*{\reversedraws}{%
  \renewcommand*{\collect@draws}{}% initialize
  \look@for@draw
}
\newcommand*{\look@for@draw}{%
  \@ifnextchar\draw{%
    \catch@draw
  }{%
    \collect@draws % output the result
  }%
}
\def\catch@draw\draw#1;{%
  \preto\collect@draws{\draw#1;}%
  \look@for@draw
}
\makeatother

\begin{document}
  \begin{tikzpicture}
    \reversedraws
    \draw [fill=blue,ultra thick] (0.4,0.5) rectangle (0,1);
    \draw [fill=red,ultra thick] (0,0.3) rectangle (1,1);
    \draw [fill=green,ultra thick] (0,0) rectangle (0.5,0.5);
  \end{tikzpicture}
\end{document}

Result

Of course fixing the C++ tool program to output the correct order is the better approach and can be done more efficient in linear time there. In the example above, the run time behavior is quadratic.