[SOLVED] How To Duplicate Layer with complete hierarchy (sub-layers and nodes)

I though I share this one, since it gave me a hard time to figure it out and I think it's pretty useful.

Basically it takes a given layer and clones it completely with same hierarchy and all contained nodes.
All child layers get duplicated in the same hierarchy and all assigned nodes get duplicated as instance and reassigned to the new layer structure copy.

Only the layers get a new unique name. The node instances will have the same name. (for my case this is more conveniant, than the stupidely incremented 3dsMax style numbers as suffix.)

There is a funky part in the code, where I am checking in a while loop to creating a new unique name, since uniquename(layer.name) is always returning Layer001, even though it already exists. I have no clue how I could do this differently. So if someone has any hint? Much appreciated!

fn duplicateNodesWithSameName nodes cloneType:#instance = ( maxOps.cloneNodes nodes cloneType:cloneType newNodes:&nnl for i = 1 to nnl.count do ( nnl[i].name = nodes[i].name ) select nnl return nnl ) fn duplicateLayer layer parentLayer: recursive:true cloneType:#instance = ( -- DUPLICATE THE LAYER layerCopy = layermanager.newLayerFromName (layer.name + ((random 0 9999999999999999999) as string)) -- ASSIGN UNIQUE NAME BASED ON OLD LAYER NAME counter = 0 newName = layer.name + "_" + (formattedprint counter format:"02d") -- setName returns true on succes, as long its not possible to rename, increment the counter, until its possible while (not (layerCopy.setName newName)) do ( counter += 1 newName = layer.name + "_" + (formattedprint counter format:"02d") ) -- REPARENT IF PARENT IS GIVEN if parentLayer != unsupplied do layerCopy.setParent parentLayer -- COPY NODES ON LAYER AND REASSIGN THEM TO NEW LAYER -- clean up the reference variable to prevent errors -- get all nodes on this layer layer.nodes &theNodes -- collect only the visible nodes in the layer visibleNodes = for n in theNodes where n.ishidden == false collect n -- duplicate visible nodes with same name and pass on parameters for cloneType duplicatedNodes = duplicateNodesWithSameName visibleNodes cloneType:cloneType -- go through all duplicated nodes for i = 1 to duplicatedNodes.count do ( -- add it to the layerCopy layerCopy.addNode duplicatedNodes[i] ) -- RECURSIVE PART if (recursive) do ( -- ITERATE ALL CHILDS layerChildCount = layer.getNumChildren() -- if so go through them if layerChildCount > 0 do ( for i = 1 to layerChildCount do ( c = layer.getChild i -- CALL ITSELF ON EACH CHILD duplicateLayer c parentLayer:layerCopy --but this time pass on the parentlayer reference, so each child gets assigned the correct parent ) ) ) ) -- TEST: duplicate the currently active layer with all its content and sub-layers duplicateLayer layermanager.current