'/// Clusters2Objs 1.0 for XSI 3.5+
'/// By Homam Bahnassi - In|Framez 2004
'--------------------------------------

set oSelection = Application.Selection
Clusters2Objs oSelection

function Clusters2Objs(oObjects)
	Clusters2Objs = false
	'-- Check if the oObjects collection contains only polymeshs
	for each oObj in oObjects
		if oObj.type <> "polymsh" then
			logmessage "Clusters2Objs: " & oObj & " is not a poygonal mesh... Canceling..."
			exit function
		end if
	next

	'-- Creating the return object collection...
	set Clusters2Objs = CreateObject("XSI.Collection")
		
	'-- Extracting clusters...
	for each oObj in oObjects
		set oClusters = oObj.activeprimitive.geometry.Clusters
		for each oCluster in oClusters
			if oCluster.type = "poly" then
			
				'-- Creating new cluster object...
				set oResult = Duplicate (oObj,1,siDuplicateHistory,siSharedParent,siNoGrouping,siDuplicateProperties,siDuplicateAnimation,siDuplicateConstraints,siNoSelection,siGlobalXForm, , , , , , , , , , , 0)
				set oResCluster = oResult(0).activeprimitive.geometry.Clusters.item(oCluster.name)
				SetValue oResult(0) & ".Name", oCluster.name
				Clusters2Objs.Add oResult(0)
				
				'-- Preparing polygons for deleting...
				set oDelComp = CreateObject("XSI.Collection")
				set oAllFacets = oResult(0).activeprimitive.geometry.Facets
				for each oFacet in oAllFacets
					oDelComp.Add oFacet
				next
				
				set oClusterElements = oCluster.Elements
				aElements  = oClusterElements.Array
				for iElement=lbound(aElements,1) to ubound(aElements,1)
					oDelComp.Remove oAllFacets(aElements(iElement))
				next
				
				'-- Selecting polygons...
				ActivatePolygonSelTool
				DeselectAll
				for each oPoly in oDelComp
					AddToSelection oPoly
				next
				
				ParentObj oObj, oResult(0)
				ApplyTopoOp "DeleteComponent"
			end if
		next
	next
	Clusters2Objs = true
end function
