public Matrix TransformationMatrixToSpace(DisplayObject targetSpace)
{
DisplayObject currentObject;
Matrix selfMatrix;
Matrix targetMatrix;
if (targetSpace == this)
{
Matrix identity = Matrix.Create();
identity.Identity();
return identity;
}
else if (targetSpace == _parent || (targetSpace == null && _parent == null))
{
Matrix transformationMatrix = Matrix.Create();
transformationMatrix.CopyFromMatrix(TransformationMatrix);
return transformationMatrix;
}
else if (targetSpace == null || targetSpace == Root)
{
// targetSpace 'null' represents the target coordinate of the base object.
// -> move up from this to base
selfMatrix = Matrix.Create();
selfMatrix.Identity();
currentObject = this;
while (currentObject != targetSpace)
{
selfMatrix.AppendMatrix(currentObject.TransformationMatrix);
currentObject = currentObject.Parent;
}
return selfMatrix;
}
else if (targetSpace.Parent == this)
{
targetMatrix = Matrix.Create();
targetMatrix.CopyFromMatrix(targetSpace.TransformationMatrix);
targetMatrix.Invert();
return targetMatrix;
}
// 1.: Find a common parent of this and the target coordinate space.
List<DisplayObject> ancestors = new List<DisplayObject>();
int count = 0;
DisplayObject commonParent = null;
currentObject = this;
while (currentObject != null && count < MAX_DISPLAY_TREE_DEPTH)
{
ancestors.Add(currentObject);
currentObject = currentObject.Parent;
count++;
}
currentObject = targetSpace;
while (currentObject != null && commonParent == null)
{
for (int i = 0; i < count; ++i)
{
if (currentObject == ancestors[i])
{
commonParent = ancestors[i];
break;
}
}
currentObject = currentObject.Parent;
}
if (commonParent == null)
{
throw new Exception("Object not connected to target");
}
// 2.: Move up from this to common parent
selfMatrix = Matrix.Create();
selfMatrix.Identity();
currentObject = this;
while (currentObject != commonParent)
{
selfMatrix.AppendMatrix(currentObject.TransformationMatrix);
currentObject = currentObject.Parent;
}
// 3.: Now move up from target until we reach the common parent
targetMatrix = Matrix.Create();
targetMatrix.Identity();
currentObject = targetSpace;
while (currentObject != null && currentObject != commonParent)
{
targetMatrix.AppendMatrix(currentObject.TransformationMatrix);
currentObject = currentObject.Parent;
}
// 4.: Combine the two matrices
targetMatrix.Invert();
selfMatrix.AppendMatrix(targetMatrix);
return selfMatrix;
}