as paulHK said:
One fundamental issue here is you're rotating in destination space rather than source space (e.g. apply the shear on source coordinates and output a rectangle). This way you can guarantee every pixel in the output is drawn once and only once and there are no gaps in between.
and the line that's causing the 180 problem is this line:
To reproduce the distortion in the image you would have to apply the model-view-projection matrix and then divide by $w$. If you use a projection matrix that flips $Z$ then you would get an inverted version. For more details on the transformations that occur for a perspective projection to happen see: