clone method

Node clone({
  1. bool recursive = true,
})

Creates a copy of this node.

If recursive is true, the copy will include all child nodes.

Implementation

Node clone({bool recursive = true}) {
  // First, clone the node tree and collect any skins that need to be re-bound.
  List<Skin> clonedSkins = [];
  Node result = _cloneAndCollectSkins(recursive, clonedSkins);

  // Then, re-bind the skins to the cloned node tree.

  // Each of the clonedSkins currently have joint references in the old tree.
  for (var clonedSkin in clonedSkins) {
    for (
      int jointIndex = 0;
      jointIndex < clonedSkin.joints.length;
      jointIndex++
    ) {
      Node? joint = clonedSkin.joints[jointIndex];
      if (joint == null) {
        clonedSkin.joints[jointIndex] = null;
        continue;
      }

      Node? newJoint;

      // Get the index path from this node to the joint.
      Iterable<int>? nodeIndexPath = Node.getIndexPath(this, joint);
      if (nodeIndexPath != null) {
        // Then, replay the path on the cloned node tree to find the cloned
        // joint reference.
        newJoint = result.getChildByIndexPath(nodeIndexPath);
      }

      // Inline replace the joint reference with the cloned joint.
      // If the joint isn't found, a null placeholder is added.
      clonedSkin.joints[jointIndex] = newJoint;
    }
  }

  return result;
}