I am having trouble figuring out the correct order of transformations to apply on elements in my app. The app has elements which have parent/child relations and each element has a transformation (each element is drawn in local space and then transformed).
What i want to archive is that if i transform the parent all its child should also get transformed (so if you rotate the parent, the child should rotate around the parent).
The code below does just that but the problem is when i rotate the parent and then want to move the child. It moves in the wrong direction (due to its parent transformation ). I've tried changing the sequence of the transformations but no luck (i know i should first translate and then transform but then the child is rotated around its own axis - instead of parents).
The code:
Element e;
AffineTransform t = new AffineTransform();
AffineTransform t3 = new AffineTransform();
for (i = 0; i < el.size(); i++)
{
e = el.get(i);
t3.setToIdentity();
t.setToIdentity();
tmp = e.getParent();
while(tmp != null)
{
t.translate(tmp.getX(), tmp.getY());
t3.rotate(Math.toRadians(tmp.getAngle()),tmp.getAnchorX(), tmp.getAnchorY());
tmp = tmp.getParent();
}
t.concatenate(t3);
t.translate(e.getX(), e.getY());
t.rotate(Math.toRadians(e.getAngle()),e.getAnchorX(), e.getAnchorY());
e.draw(g2d,t);
}
The problem: - given two elements (one child of other) - parent is rotate (by 40 degrees) - child is then move by 10px How can i concatenate transformations so that when i move the child it wont move in the rotated direction?
EDIT: The code that Torious posted (not working yet):
public AffineTransform getTransformTo(Element ancestor) {
AffineTransform t = (AffineTransform)getAffineTransform().clone();
Element parent = getParent();
while (parent != null && parent != ancestor) {
t.preConcatenate(parent.getAffineTransform());
parent = parent.getParent();
}
return t;
}
public void translateInAncestorSpace(Element ancestor, Point translation) {
AffineTransform fromAncestor = getTransformTo(ancestor); // to ancestor space
try
{
fromAncestor.invert();
} catch(Exception e)
{
e.printStackTrace();
}
translation = (Point)fromAncestor.transform(translation, new Point());
Transform t1 = new Transform();
t1.translate(translation.x,translation.y);
transform(t1);
}
Output of the code:
Moving by [x=1,y=1] old position [x=22,y=40]
Moved by [x=-21,y=-39] new position [x=1,y=1]
Moving by [x=2,y=2] old position [x=1,y=1]
Moved by [x=1,y=1] new position [x=2,y=2]
Moving by [x=4,y=3] old position [x=2,y=2]
Moved by [x=2,y=1] new position [x=4,y=3]