What is the way to get an instance path to the root given a Group/ComponentInstance?

The only thing I found close is InputPoint#instance_path, but it works only based on x,y coords which I think may return wrong results if the point that is used is shared by several instances

Using Make 2017

Every ComponentInstance / Group is contained in a parent ComponentDefinition (there is not a single parent instance, but all instances of the parent component definiition). If the parent is a Model, it has no further parent but it is the root.

The nested component instance hierarchy forms a tree. You can obtain possible instance paths by a recursive bottom-up search (from the leaves to root):

def collect_occurences(instance)
  instance_paths = []
  queue = [ [instance] ] # Queue containing the instance path of the leaf
  until queue.empty?
    path = *(queue.shift)
    outer = path.first
    # Parent is root: instance path is complete.
    if outer.parent.is_a?(Sketchup::Model)
      instance_paths << path
    # Parent is component definition:
    # Prepend preliminary instance path by all instances of parent ("brothers of father").
    else
      outer.parent.instances.each{ |uncle|
        queue << [uncle] + path
      }
    end
  end
  return instance_paths
end

instance_paths = collect_occurences(some_instance)
1 Like

As Andreas mentions, given an arbitrary instance or definition you cannot find a single path back to the model root. You can only obtain a path when traversing from the root and down the hierarchy.

Can you describe the scenario where you have an instance and you need a full path?

BUT,… if the instance is being edited than you CAN:

Sketchup::Model.active_path

2 Likes

This will return any instance that is part of any definition that holds the instance I’m interested in. I need to remove those instances that are not containers of ‘some_instance’

I’m not sure I understand what you are saying. It will return any instance path (array of nested instances) that contain some_instance as the last element (leaf).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.