Exemplo n.º 1
0
def saveSel():
    myPrevSelected = []
    n = lx.eval("query sceneservice txLayer.N ?")  # Using all here is meaningless, as far as I know.
    for i in xrange(
        n
    ):  # xrange is faster for large numbers, and you don't have to specify a lower bound of 0 for range either - it will default to 0.
        if lx.eval1("query sceneservice txLayer.isSelected ? %s" % i):
            myID = lx.eval1("query sceneservice txLayer.id ? %s" % i)
            myPrevSelected.append(
                myID
            )  # Store the ID here, as the index may not point to the same thing if you've made changes.
            lx.eval("select.subItem %s remove" % myID)
    return myPrevSelected
    def basic_Execute(self, msg, flags):
        try:
            scn = modo.Scene()
            currScn = modo.scene.current()

            userSelection = scn.selected
            userSelectionCount = len(userSelection)

            currPath = currScn.filename

            if currPath is None:
                currPath = ""

            fbxExportType = lx.eval1('user.value sceneio.fbx.save.exportType ?')
            fbxTriangulate = False

            scnIndex = lx.eval('query sceneservice scene.index ? current')

            upAxis = lx.eval('pref.value units.upAxis ?')
            iUpAxis = upAxis

            userValues = self.query_User_Values()

            tbe = TilaBacthExport

            tbe.process_items(tbe(userSelection, userSelectionCount, scn, currScn, currPath, scnIndex, upAxis, iUpAxis, fbxExportType, fbxTriangulate, self.dyna_Bool(0), self.dyna_Bool(1), bool(userValues[2]), bool(userValues[3]), bool(userValues[4]), bool(userValues[5]), bool(userValues[6]), bool(userValues[7]), bool(userValues[8]), bool(userValues[9]), bool(userValues[10]), bool(userValues[11]), bool(userValues[12]), bool(userValues[13]), bool(userValues[14]), userValues[15], userValues[16], userValues[17], userValues[18], userValues[19], userValues[20], userValues[21], userValues[22], userValues[23], bool(userValues[24]), userValues[25], bool(userValues[26]), userValues[27], bool(userValues[28]), bool(userValues[29]), bool(userValues[30]), bool(userValues[31]), bool(userValues[32]), bool(userValues[33]), bool(userValues[34]), bool(userValues[35]), bool(userValues[36]), bool(userValues[37]), bool(userValues[38]), userValues[39], bool(userValues[40]), bool(userValues[41]), userValues[42]))
        except:
            lx.out(traceback.format_exc())
Exemplo n.º 3
0
    def __init__(self, cryexport_node):
        self.cryexport_node = cryexport_node
        self.scene_root = lx.eval1("query sceneservice scene.file ? current")
        if not self.scene_root:
            modo.dialogs.alert("Save File", "Please save file before exporting.")
            sys.exit()
        self.path = os.path.join(
            os.path.dirname(self.scene_root), self.collada_temp_path
        )
        self.wpos_matrix = modo.Matrix4(self.cryexport_node.channel("wposMatrix").get())
        self.submats = utils.get_submats_from_cryexport_node(self.cryexport_node)
        self.neat_name = self.cryexport_node.name.replace(_c.CRYEXPORTNODE_PREFIX, "")
        self.file_type = (
            "1"
            if self.cryexport_node.channel(_c.CHANNEL_FILETYPE_NAME) is None
            else self.cryexport_node.channel(_c.CHANNEL_FILETYPE_NAME).get()
        )
        self.exportable = (
            "1"
            if self.cryexport_node.channel(_c.CHANNEL_EXPORTABLE_NAME) is None
            else self.cryexport_node.channel(_c.CHANNEL_EXPORTABLE_NAME).get()
        )
        self.merge_objects = (
            "0"
            if self.cryexport_node.channel(_c.CHANNEL_MERGE_OBJECTS_NAME) is None
            else self.cryexport_node.channel(_c.CHANNEL_MERGE_OBJECTS_NAME).get()
        )

        self.groups = utils.get_groups_from_cryexport_node(self.cryexport_node)
    def batch_export(self):
        helper.check_selection_count(self)
        self.at_least_one_item_selected()

        dialog.begining_log(self)

        self.currPath = file.getLatestPath(t.config_export_path)

        path = os.path.join(self.currPath, os.path.splitext(self.scn.name)[0])
        dialog.init_dialog(
            "filesave", path,
            dialog.dialogFormatType[helper.get_first_export_type(self)])

        try:  # output folder dialog
            lx.eval('dialog.open')
        except:
            dialog.init_dialog('cancel', self.currPath)
        else:
            output_dir = lx.eval1('dialog.result ?')

            self.filename = os.path.splitext(os.path.split(output_dir)[1])[0]
            output_dir = os.path.split(output_dir)[0]

            file.updateExportPath(output_dir, '', '')

            self.batch_process(output_dir, self.filename)

            helper.revert_initial_parameter(self)

        helper.open_destination_folder(self, output_dir)
        dialog.ending_log(self)
Exemplo n.º 5
0
    def commander_execute(self, msg, flags):
        loops = self.commander_arg_value(0)

        if lx.eval1('tool.set poly.loopSlice ?') == 'on':
            lx.eval('tool.set poly.loopSlice off')

        lx.eval('tool.set poly.loopSlice on')
        lx.eval('tool.flag poly.loopSlice auto false')
        lx.eval('tool.attr poly.loopSlice count %s' % loops)
        lx.eval('tool.doApply')
        lx.eval('tool.set poly.loopSlice off')
Exemplo n.º 6
0
	def setIPackThatPath (self, ipackthat_exe_path):
		if self.validIPackThatPath (ipackthat_exe_path):
			try:
				lx.eval ('!!user.defNew name:ipackthat_path type:string life:config')
			except:
				pass

			try:
				lx.eval ('!!user.value ipackthat_path {%s}' % ipackthat_exe_path)
			except:
				pass
			
			return (lx.eval1 ('user.value ipackthat_path ?') == ipackthat_exe_path)
		return False
Exemplo n.º 7
0
	def findIPackThatPath (self):
		default_path = 'D:\\SteamLibrary\\steamapps\\common\\IPackThat\\IPackThat.exe'
		if self.setIPackThatPath (default_path):
			return True
		else:
			try:
				lx.eval ('dialog.setup fileOpen')
				lx.eval ('dialog.title "Select IPackThat executable file"')
				lx.eval ('dialog.fileTypeCustom format:exe username:{EXE} loadPattern:{*.exe} saveExtension:exe')
				if self.modo_ver == 801:
					lx.eval ('+dialog.open')
				else:
					lx.eval ('dialog.open')
				ipackthat_exe_path = lx.eval1 ('dialog.result ?')
			except:
				pass
			else:
				if self.setIPackThatPath (ipackthat_exe_path):
					return True

		lx.out ('Failed to define path to IPackThat.')
		return False
Exemplo n.º 8
0
        scene_svc.select("item", str(item))
        lx.eval('select.item {%s} set' % item)

        # get item type
        itemType = scene_svc.query("item.type")

        if itemType == 'locator':

            locators.append(item)

            # Ask if our locator has a default or custom shape:
            lx.eval('item.channel locator$drawShape ?')

            # This gives a result (default / custom)
            # Save that result into a variable:
            locatorShape = lx.eval1('item.channel locator$drawShape ?')

            if locatorShape == 'default':
                # Change size for standard default locator:
                lx.eval("item.channel locator$size " + str(mysize))

            elif locatorShape == 'custom':
                # Ask which is actual shape:
                lx.eval("item.channel locator$isShape ?")

                # This gives a result (box, pyramid, plane…)
                # Save that result into a variable:
                originalShape = lx.eval("item.channel locator$isShape ?")

                # Change size for standard default locator:
                lx.eval("item.channel locator$size " + str(mysize))
Exemplo n.º 9
0
    def basic_Execute(self, msg, flags):
        # Early out if no UV map is selected.
        selected_uv_name = lx.eval1('vertMap.list type:txuv ?')
        if selected_uv_name == '_____n_o_n_e_____':
            return

        # Early out if not in edge or polygon mode.
        selection_mode = lx.eval1('query layerservice selmode ?')
        if selection_mode != 'vertex' and selection_mode != 'edge' and selection_mode != 'polygon':
            return

        layer_svc = lx.service.Layer()
        layer_scan = lx.object.LayerScan(
            layer_svc.ScanAllocate(lx.symbol.f_LAYERSCAN_EDIT))
        if not layer_scan.test():
            return

        if self.dyna_IsSet(0):
            distance = self.attr_GetFlt(0)
        else:
            distance = 0.0000005  # This seems to be about the smallest you can get while having it reliably split.

        # Sort out mark modes we'll need.
        mesh_svc = lx.service.Mesh()

        mark_mode_selected = mesh_svc.ModeCompose(lx.symbol.sMARK_SELECT, None)

        mark_mode_moved = mesh_svc.ModeCompose('user4', None)
        mark_mode_clear_moved = mesh_svc.ModeCompose(None, 'user4')

        mark_mode_to_split = mesh_svc.ModeCompose('user3', None)
        mark_mode_clear_to_split = mesh_svc.ModeCompose(None, 'user3')

        for n in xrange(layer_scan.Count()):

            mesh_loc = lx.object.Mesh(layer_scan.MeshEdit(n))
            if not mesh_loc.test():
                continue

            polygon_count = mesh_loc.PolygonCount()
            if polygon_count == 0:  # Quick out if there are no polys in this layer.
                continue

            polygon_loc = lx.object.Polygon(mesh_loc.PolygonAccessor())
            if not polygon_loc.test():
                continue

            edge_loc = lx.object.Edge(mesh_loc.EdgeAccessor())
            if not edge_loc.test():
                continue

            point_loc = lx.object.Point(mesh_loc.PointAccessor())
            if not point_loc.test():
                continue

            meshmap_loc = lx.object.MeshMap(mesh_loc.MeshMapAccessor())
            if not meshmap_loc.test():
                continue

            # If selected UV map exists for this layer.
            try:
                meshmap_loc.SelectByName(lx.symbol.i_VMAP_TEXTUREUV,
                                         selected_uv_name)
            except:
                pass
            else:
                uvmap_ID = meshmap_loc.ID()

                # Clear existing marks.
                visitor = MarkEdges(edge_loc, mark_mode_clear_moved)
                edge_loc.Enumerate(mark_mode_moved, visitor, 0)

                visitor = MarkEdges(edge_loc, mark_mode_clear_to_split)
                edge_loc.Enumerate(mark_mode_to_split, visitor, 0)

                if selection_mode == 'vertex':
                    # Find and mark the edges that are on the border of the polygon selection.
                    visitor = MarkPointEdges(point_loc, edge_loc,
                                             mark_mode_to_split)
                    point_loc.Enumerate(mark_mode_selected, visitor, 0)

                elif selection_mode == 'edge':
                    # Find and mark the selected edges.
                    visitor = MarkEdges(edge_loc, mark_mode_to_split)
                    edge_loc.Enumerate(mark_mode_selected, visitor, 0)

                elif selection_mode == 'polygon':
                    # Find and mark the edges that are on the border of the polygon selection.
                    visitor = MarkPolyBorder(edge_loc, polygon_loc,
                                             mark_mode_selected,
                                             mark_mode_to_split)
                    edge_loc.Enumerate(lx.symbol.iMARK_ANY, visitor, 0)

                # Get the values to assign to split UVs.
                visitor = SplitEdges(edge_loc, point_loc, polygon_loc,
                                     uvmap_ID, mark_mode_to_split,
                                     mark_mode_moved, distance, selection_mode,
                                     mark_mode_selected)
                edge_loc.Enumerate(mark_mode_to_split, visitor, 0)

                # Split the UVs.
                # This has to be done in a second pass because, if it was done in the previous pass, the transform values would get distorted because of any previous edits we've made to the UVs at those verts.
                uv_value = lx.object.storage('f', 2)
                for polygon_ID, point_value in visitor.polygon_UV_values.iteritems(
                ):
                    polygon_loc.Select(polygon_ID)
                    for p in xrange(len(point_value)):
                        uv_value.set(point_value[p][1])
                        polygon_loc.SetMapValue(point_value[p][0], uvmap_ID,
                                                uv_value)

                # Clear the marks I made.
                visitor = MarkEdges(edge_loc, mark_mode_clear_moved)
                edge_loc.Enumerate(mark_mode_moved, visitor, 0)

                visitor = MarkEdges(edge_loc, mark_mode_clear_to_split)
                edge_loc.Enumerate(mark_mode_to_split, visitor, 0)

                layer_scan.SetMeshChange(
                    n, lx.symbol.f_MESHEDIT_MAP_UV
                    | lx.symbol.f_MESHEDIT_MAP_CONTINUITY)
        layer_scan.Apply()
def updateRenderOutput(listAllRO,existingRO,createFolder):
    """ Met a jour la list des render output
    cree, active ou desactive un render output et met a jour les information
    """
    global updateOnly       # on a selectionner des render output dans la scene et on veut les mettre a jour    
    global updateExistingOnly   # on fait la mise a jour seulement de ceux qui existe dans la scene
    global groupSelected    # un groupMask a ete selectionner et on va cree les nouveau dessous
    global osType
    global useRenderName    #Utilise le nom du render output
    global patternFile      #"[GROUPNAME]|[LAYERNAME]|[BASENAME]_[LAYERNAME]_[SUFFIXE]_"
    global RENDERCAMERA     # name of the actual render camera set in the scene
    
    separator="\\"
    if osType != "Windows":
        separator = "/"


    try:
        #on recuper la list des element existant
        existRO = []
        num = len(existingRO)
        if (num):
            for x in xrange(num):
                itemId = existingRO[x]
                lx.eval( "select.item {%s}" %itemId )
                existRO.append(lx.eval( "shader.setEffect ?" ))
                # si c'est la couche alpha on la laisse active et on efface son chemin au cas ou on enregistre pas la couche separer
                #if lx.eval( "shader.setEffect ?" ) == "shade.alpha" :
                #    lx.eval( "shader.setVisible %s %s" %(itemId,1) )
                #    lx.eval( r'item.channel renderOutput$filename ""' );
                #    lx.out(listAllRO)
                #    gammaFile = listAllRO[0]['gamma'] # 0 = (alpha)
                #    lx.eval( r'item.channel renderOutput$gamma %s' %gammaFile )
                    
            lx.out(existRO)
        

        #on update ou on cree les nouveau render pass
        targetPath = lx.eval('user.value rom_fileName ?')
        patternOutput = lx.eval('user.value rom_patternFile ?')
        motionRemap =  lx.eval('user.value rom_motionRemap ?')
        depthRemap = lx.eval('user.value rom_depthRemap ?')
        #nameFile = targetPath.rfind("\\")
        #lx.out(targetPath[0:nameFile])
        pathFile =""
        i = len(listAllRO)
        for x in xrange(i):
            itemRO = listAllRO[x]
            #si on met a jour on ne regarde pas si il est actif ou non
            if (itemRO['active'] == 1) or (updateOnly or updateExistingOnly):
                lx.out("YES")
                foundUpdate = False
                formatFile = itemRO['format']
                gammaFile = itemRO['gamma']
                aliasFile = itemRO['alias']
                # on verifie si il existe deja
                flag = 1
                
                if (num):
                    for xx in xrange(num):
                        lx.out("Check if exist:"+existRO[xx] +"-"+itemRO['name'])
                        if existRO[xx] == itemRO['name']:
                            #il existe deja pas besoin de le cree
                            lx.out("EXIST",itemId)
                            foundUpdate = True
                            flag = 0
                            itemId = existingRO[xx]
                            lx.eval( "select.item {%s}" %itemId )
                            lx.eval( r'item.channel renderOutput$gamma %s' %gammaFile )
                            lx.eval( r'item.channel renderOutput$antialias %s' %aliasFile )
                            lx.eval( r'item.tag string "ROMN:renderOutput" "%s"' %(targetPath+","+patternOutput))
                            #On ne le met pas a jour si il n'existe pas encore et qu'on ne force pas la mise a jour
                            testEmptyFilename = lx.eval( r'item.channel renderOutput$filename ?')
                            forceUpdate =  True #lx.eval('user.value rom_updateEmptyFilename ?')

                            lx.out("le cheminrecuperer est %s" %testEmptyFilename)
                            if targetPath !="" :
                                if testEmptyFilename != None or  forceUpdate:

                                    nameFile = targetPath.rfind(separator)
                                    baseFolder = targetPath[0:nameFile+1]
                                    BASENAME = targetPath[nameFile+1: len(targetPath)]
                                    RENDERNAME = format_filename(lx.eval('query sceneservice item.name ? %s' % itemId))
                                    TYPENAME= itemRO['suffixe']
                                    GROUP =""
                                    parentID = lx.eval('query sceneservice item.parent ? %s' % itemId)
                                    lx.out("PARENT_ID:"+parentID)
                                    if (parentID) and (lx.eval('query sceneservice item.type ? %s' % parentID) == "mask"):
                                        GROUP = lx.eval('query sceneservice item.name ? %s' % parentID)
                                        GROUP = GROUP.replace(" (Item)","")
                                        GROUP = GROUP.replace(" (Material)","")
                                        GROUP = format_filename(GROUP)
                                    else:
                                        GROUP ="" 
                                    

                                    nameFile = patternFile.replace("[GROUPNAME]",GROUP)
                                    nameFile = nameFile.replace("[CAMERA]",RENDERCAMERA)
                                    nameFile = nameFile.replace("[LAYERNAME]",RENDERNAME)
                                    nameFile = nameFile.replace("[BASENAME]",BASENAME)
                                    nameFile = nameFile.replace("[SUFFIXE]",TYPENAME)
                                    #nameFile = nameFile.replace("[PASSNAME]",PASSNAME)
                                    nameFile = nameFile.replace("|",separator)
                                    nameFile = baseFolder + nameFile
                                    nameFile = nameFile.replace(separator+separator+separator,separator)
                                    nameFile = nameFile.replace(separator+separator,separator)
                                    pathFile = os.path.dirname(nameFile)
                                    lx.out("LE FICHIER:"+nameFile)
                                    lx.eval( r'item.channel renderOutput$filename "%s"' %nameFile )
                                    lx.eval( r'item.channel renderOutput$format "%s"' %formatFile )

                                    #MakePath
                                    makes_path(pathFile,createFolder)
                            else:
                                lx.eval( r'item.channel renderOutput$filename ""'  )
                                lx.eval( r'item.channel renderOutput$format ""'  )
                                
                            lx.eval( "shader.setVisible %s %s" %(itemId,1) )
                            
                            # on demande si on veut mettre a jour les donner
                            
                            if itemRO['name'] == "occl.ambient" or itemRO['name'] == "depth" or itemRO['name'] == "motion" :
                                typeRender = itemRO['name']
                                typeRender.replace("occl.ambient","AO")
                                try:
                                    # set up the dialog
                                    lx.eval('dialog.setup yesNo')
                                    lx.eval('dialog.title {Do you want update ?}')
                                    lx.eval('dialog.msg {Do you want update %s values ?}' %typeRender)
                                    lx.eval('dialog.result ok')

                                    # Cree la structure des répértoire
                                    lx.eval('dialog.open')
                                    result = lx.eval("dialog.result ?")
                                    updateVal = True

                                except:
                                    # ON NE CREE PAS LA STRUCTURE AUTOMATIQUEMENT
                                    updateVal = False
                                
                                
                            # si c'est l'ambient on uptate les valeur ray et range
                            
                            if itemRO['name'] == "occl.ambient" and updateVal :
                                occRay = lx.eval('user.value rom_AORay ?')
                                occRange = lx.eval('user.value rom_AORange ?')


                                lx.eval( "item.channel renderOutput$occlRays %s" %occRay)
                                lx.eval( "item.channel renderOutput$occlRange %s" %occRange)
                            if itemRO['name'] == "depth" and updateVal:
                               
                                lx.eval("item.channel renderOutput$remap %s" %depthRemap)
                                if (depthRemap):
                                    depthRange = lx.eval('user.value rom_maximumDepth ?')
                                    lx.eval( "item.channel renderOutput$depthMax %s" %depthRange)
                                
                                    
                            if itemRO['name'] == "motion" and updateVal:
                               
                                lx.eval("item.channel renderOutput$remap %s" %motionRemap)
                                if (motionRemap):
                                    motionPixel = lx.eval('user.value rom_motionPixel ?')
                                    lx.eval( "item.channel renderOutput$motionMax %s" %motionPixel)
                        
                                
                
                # si il existe pas on le cree
                
                if (flag) and (not (updateOnly or updateExistingOnly)):
                    foundUpdate = True
                    lx.eval("select.itemType polyRender")
                    lx.eval("shader.create renderOutput")
                    lx.eval("shader.setEffect {%s}" %itemRO['name'] )
                    RenderSelect = lx.eval1('query sceneservice selection ? renderOutput')
                    
                    #est ce qu'on ajoute le prefix
                    addPrefix = ""
                    if (lx.eval('user.value rom_askPrefix ?') == True):
                        addPrefix = lx.eval('user.value rom_prefixName ?')
                    # est ce qu'on utilise le suffixe comme nom de layer
                    if (lx.eval('user.value rom_useSuffixe ?') == True):
                        NameRenderOutput = addPrefix + itemRO['suffixe']
                        
                    else:
                        NameRenderOutput = lx.eval('query sceneservice renderOutput.Name ? "%s"' %RenderSelect )
                        NameRenderOutput = addPrefix + NameRenderOutput
                        NameRenderOutput = NameRenderOutput.replace(" ", "_")
                        NameRenderOutput = NameRenderOutput.replace("_Output", "");
                        NameRenderOutput = NameRenderOutput.replace("_Shading", "");
                        NameRenderOutput = NameRenderOutput.replace("Shading_", "");
                        NameRenderOutput = NameRenderOutput.replace("(", "");
                        NameRenderOutput = NameRenderOutput.replace(")", "");
                    lx.eval('item.name "%s" renderOutput' %NameRenderOutput)
                    typeGroup = ""
               
                    if groupSelected:
                        groupSelectedName = lx.eval('query sceneservice item.name ? %s' % groupSelected)
                        groupSelectedName = groupSelectedName.replace(" (Item)","")
                        groupSelectedName = groupSelectedName.replace(" (Material)","")
                        groupSelectedName=format_filename(groupSelectedName)
                        typeGroup  = lx.eval('query sceneservice item.type ? %s' % groupSelected)
                        lx.eval("texture.parent %s -1" %groupSelected)
                    lx.eval( r'item.channel renderOutput$gamma %s' %gammaFile )
                    lx.eval( r'item.channel renderOutput$antialias %s' %aliasFile )
                    lx.eval( r'item.tag string "ROMN:renderOutput" "%s"' %(targetPath+","+patternOutput))
                    
                    # si c'est l'ambient on uptate les valeur ray et range
                    if itemRO['name'] == "occl.ambient" :
                        occRay = lx.eval('user.value rom_AORay ?')
                        occRange = lx.eval('user.value rom_AORange ?')
                        lx.eval( "item.channel renderOutput$occlRays %s" %occRay)
                        lx.eval( "item.channel renderOutput$occlRange %s" %occRange)
                    if itemRO['name'] == "depth" :
                        lx.eval("item.channel renderOutput$remap %s" %depthRemap)
                        if (depthRemap):
                            depthRange = lx.eval('user.value rom_maximumDepth ?')
                            lx.eval( "item.channel renderOutput$depthMax %s" %depthRange)            
                    if itemRO['name'] == "motion" : 
                        lx.eval("item.channel renderOutput$remap %s" %motionRemap)
                        if (motionRemap):
                            motionPixel = lx.eval('user.value rom_motionPixel ?')
                            lx.eval( "item.channel renderOutput$motionMax %s" %motionPixel)
                        

                    if targetPath !="" :


                        nameFile = targetPath.rfind(separator)
                        baseFolder = targetPath[0:nameFile+1]
                        BASENAME = targetPath[nameFile+1: len(targetPath)]
                        RENDERNAME = NameRenderOutput
                        TYPENAME= itemRO['suffixe']
                        GROUP =""
                        #on test si c'est bien un group et si on a choisi de creer un repertoir
                        if groupSelected and groupSelectedName and typeGroup=="mask":
                            GROUP = groupSelectedName
                            

                        nameFile = patternFile.replace("[GROUPNAME]",GROUP)
                        nameFile = nameFile.replace("[CAMERA]",RENDERCAMERA)
                        nameFile = nameFile.replace("[LAYERNAME]",RENDERNAME)
                        nameFile = nameFile.replace("[BASENAME]",BASENAME)
                        nameFile = nameFile.replace("[SUFFIXE]",TYPENAME)
                        #nameFile = nameFile.replace("[PASSNAME]",PASSNAME)
                        nameFile = nameFile.replace("|",separator)
                        nameFile = baseFolder + nameFile
                        nameFile = nameFile.replace(separator+separator+separator,separator)
                        nameFile = nameFile.replace(separator+separator,separator)
                        pathFile = os.path.dirname(nameFile)
                        lx.out("LE FICHIER:"+nameFile)
                        lx.eval( r'item.channel renderOutput$filename "%s"' %nameFile )
                        lx.eval( r'item.channel renderOutput$format "%s"' %formatFile )                            

                        #MakePath
                        makes_path(pathFile,createFolder)
                    else:
                        lx.eval( r'item.channel renderOutput$filename ""'  )
                        lx.eval( r'item.channel renderOutput$format ""'  )

            #si il est pas actif mais il existe on l'efface
            else:
                if (num):
                    for xx in xrange(num):
                        lx.out("Check if need to delete:"+existRO[xx] +"-"+itemRO['name'])
                        if existRO[xx] == itemRO['name']:
                            lx.out("Delete %s" %itemRO['name'])
                            itemId = existingRO[xx]
                            lx.eval( "select.item {%s}" %itemId )
                            lx.eval( "texture.delete")
    
    except: 
        lx.out( "Command failed with updateRenderOutput ", sys.exc_info() )
        
        return None
    def process_items(self):
        self.begining_log()

        if not self.exportFile_sw:  # Transform Selected
            if self.userSelectionCount == 0:  # No file Selected
                self.init_message('error', 'No item selected', 'Select at least one item')
                sys.exit()

            self.transform_loop()
            self.scn.select(self.userSelection)

        elif not self.scanFiles_sw:  # export selected mesh
            if self.userSelectionCount == 0:  # No file Selected
                self.init_message('error', 'No item selected', 'Select at least one item')
                sys.exit()

            if self.exportEach_sw:
                self.init_dialog("output")
            else:
                self.init_dialog("file_save")

            try:  # output folder dialog
                lx.eval('dialog.open')
            except:
                self.init_dialog('cancel')
            else:
                output_dir = lx.eval1('dialog.result ?')
                self.batch_export(output_dir)

        else:  # browse file to process
            self.init_dialog("input")
            try:  # mesh to process dialog
                lx.eval('dialog.open')
            except:
                self.init_dialog('cancel')
            else:
                files = lx.evalN('dialog.result ?')
                self.init_dialog("output")
                try:  # output folder dialog
                    lx.eval('dialog.open')
                except:
                    self.init_dialog('cancel')
                else:
                    output_dir = lx.eval1('dialog.result ?')

                    for f in files:
                        self.processing_log('.....................................   ' + os.path.basename(f) + '   .....................................')

                        lx.eval('!scene.open "%s" normal' % f)

                        # if ext == 'fbx'
                        lx.eval('select.itemType mesh')

                        scnIndex = lx.eval('query sceneservice scene.index ? current')
                        self.userSelection = self.scn.selected
                        self.userSelectionCount = len(self.userSelection)

                        self.print_log('.....................................   ' + str(self.userSelectionCount) + ' mesh item founded   .....................................')

                        self.batch_export(output_dir)
                        lx.eval('!scene.close')

                self.init_message('info', 'Done', 'Operation completed successfully !')

        if self.exportFile_sw:
            if self.openDestFolder_sw:
                if self.scanFiles_sw:
                    self.open_folder(output_dir)
                if self.exportEach_sw:
                    self.open_folder(output_dir)
                else:
                    self.open_folder(os.path.split(output_dir)[0])

        self.ending_log()
                lx.eval("item.channel locator$isAxis " + myaxis)
                lx.eval("item.channel locator$isAlign " + myalig)

                # Apply final form shape
                lx.eval("item.channel locator$isShape " + myform)

                # Finally, decide between default or custom shape
                # I introduce this final step to “store” shape dimensions
                # even if you create a Default locator and then you decide
                # to change to a custom shape
                lx.eval("item.channel locator$drawShape " + myshap)

                # ---------------------------------

                # get id of newly created locator
                locatorName = lx.eval1("query sceneservice selection ? all")

                # add locator to array
                locators.append(locatorName)

                # Select item by name
                lx.eval('select.subItem {%s}' % itemName)

                # Match position
                lx.eval('item.match item pos')

                # Match rotation
                lx.eval('item.match item rot')

        # select locators
        lx.eval("select.drop item")
def updateRenderOutput(listAllRO, existingRO, createFolder):
    """ Met a jour la list des render output
    cree, active ou desactive un render output et met a jour les information
    """
    global updateOnly  # on a selectionner des render output dans la scene et on veut les mettre a jour
    global updateExistingOnly  # on fait la mise a jour seulement de ceux qui existe dans la scene
    global groupSelected  # un groupMask a ete selectionner et on va cree les nouveau dessous
    global osType
    global useRenderName  #Utilise le nom du render output
    global patternFile  #"[GROUPNAME]|[LAYERNAME]|[BASENAME]_[LAYERNAME]_[SUFFIXE]_"
    global RENDERCAMERA  # name of the actual render camera set in the scene

    separator = "\\"
    if osType != "Windows":
        separator = "/"

    try:
        #on recuper la list des element existant
        existRO = []
        num = len(existingRO)
        if (num):
            for x in xrange(num):
                itemId = existingRO[x]
                lx.eval("select.item {%s}" % itemId)
                existRO.append(lx.eval("shader.setEffect ?"))
                # si c'est la couche alpha on la laisse active et on efface son chemin au cas ou on enregistre pas la couche separer
                #if lx.eval( "shader.setEffect ?" ) == "shade.alpha" :
                #    lx.eval( "shader.setVisible %s %s" %(itemId,1) )
                #    lx.eval( r'item.channel renderOutput$filename ""' );
                #    lx.out(listAllRO)
                #    gammaFile = listAllRO[0]['gamma'] # 0 = (alpha)
                #    lx.eval( r'item.channel renderOutput$gamma %s' %gammaFile )

            lx.out(existRO)

        #on update ou on cree les nouveau render pass
        targetPath = lx.eval('user.value rom_fileName ?')
        patternOutput = lx.eval('user.value rom_patternFile ?')
        motionRemap = lx.eval('user.value rom_motionRemap ?')
        depthRemap = lx.eval('user.value rom_depthRemap ?')
        #nameFile = targetPath.rfind("\\")
        #lx.out(targetPath[0:nameFile])
        pathFile = ""
        i = len(listAllRO)
        for x in xrange(i):
            itemRO = listAllRO[x]
            #si on met a jour on ne regarde pas si il est actif ou non
            if (itemRO['active'] == 1) or (updateOnly or updateExistingOnly):
                lx.out("YES")
                foundUpdate = False
                formatFile = itemRO['format']
                gammaFile = itemRO['gamma']
                aliasFile = itemRO['alias']
                # on verifie si il existe deja
                flag = 1

                if (num):
                    for xx in xrange(num):
                        lx.out("Check if exist:" + existRO[xx] + "-" +
                               itemRO['name'])
                        if existRO[xx] == itemRO['name']:
                            #il existe deja pas besoin de le cree
                            lx.out("EXIST", itemId)
                            foundUpdate = True
                            flag = 0
                            itemId = existingRO[xx]
                            lx.eval("select.item {%s}" % itemId)
                            lx.eval(r'item.channel renderOutput$gamma %s' %
                                    gammaFile)
                            lx.eval(r'item.channel renderOutput$antialias %s' %
                                    aliasFile)
                            lx.eval(
                                r'item.tag string "ROMN:renderOutput" "%s"' %
                                (targetPath + "," + patternOutput))
                            #On ne le met pas a jour si il n'existe pas encore et qu'on ne force pas la mise a jour
                            testEmptyFilename = lx.eval(
                                r'item.channel renderOutput$filename ?')
                            forceUpdate = True  #lx.eval('user.value rom_updateEmptyFilename ?')

                            lx.out("le cheminrecuperer est %s" %
                                   testEmptyFilename)
                            if targetPath != "":
                                if testEmptyFilename != None or forceUpdate:

                                    nameFile = targetPath.rfind(separator)
                                    baseFolder = targetPath[0:nameFile + 1]
                                    BASENAME = targetPath[nameFile +
                                                          1:len(targetPath)]
                                    RENDERNAME = format_filename(
                                        lx.eval(
                                            'query sceneservice item.name ? %s'
                                            % itemId))
                                    TYPENAME = itemRO['suffixe']
                                    GROUP = ""
                                    parentID = lx.eval(
                                        'query sceneservice item.parent ? %s' %
                                        itemId)
                                    lx.out("PARENT_ID:" + parentID)
                                    if (parentID) and (lx.eval(
                                            'query sceneservice item.type ? %s'
                                            % parentID) == "mask"):
                                        GROUP = lx.eval(
                                            'query sceneservice item.name ? %s'
                                            % parentID)
                                        GROUP = GROUP.replace(" (Item)", "")
                                        GROUP = GROUP.replace(
                                            " (Material)", "")
                                        GROUP = format_filename(GROUP)
                                    else:
                                        GROUP = ""

                                    nameFile = patternFile.replace(
                                        "[GROUPNAME]", GROUP)
                                    nameFile = nameFile.replace(
                                        "[CAMERA]", RENDERCAMERA)
                                    nameFile = nameFile.replace(
                                        "[LAYERNAME]", RENDERNAME)
                                    nameFile = nameFile.replace(
                                        "[BASENAME]", BASENAME)
                                    nameFile = nameFile.replace(
                                        "[SUFFIXE]", TYPENAME)
                                    nameFile = nameFile.replace("|", separator)
                                    nameFile = baseFolder + nameFile
                                    nameFile = nameFile.replace(
                                        separator + separator + separator,
                                        separator)
                                    nameFile = nameFile.replace(
                                        separator + separator, separator)
                                    pathFile = os.path.dirname(nameFile)
                                    lx.out("LE FICHIER:" + nameFile)
                                    lx.eval(
                                        r'item.channel renderOutput$filename "%s"'
                                        % nameFile)
                                    lx.eval(
                                        r'item.channel renderOutput$format "%s"'
                                        % formatFile)

                                    #MakePath
                                    makes_path(pathFile, createFolder)
                            else:
                                lx.eval(
                                    r'item.channel renderOutput$filename ""')
                                lx.eval(r'item.channel renderOutput$format ""')

                            lx.eval("shader.setVisible %s %s" % (itemId, 1))

                            # on demande si on veut mettre a jour les donner

                            if itemRO['name'] == "occl.ambient" or itemRO[
                                    'name'] == "depth" or itemRO[
                                        'name'] == "motion":
                                typeRender = itemRO['name']
                                typeRender.replace("occl.ambient", "AO")
                                try:
                                    # set up the dialog
                                    lx.eval('dialog.setup yesNo')
                                    lx.eval(
                                        'dialog.title {Do you want update ?}')
                                    lx.eval(
                                        'dialog.msg {Do you want update %s values ?}'
                                        % typeRender)
                                    lx.eval('dialog.result ok')

                                    # Cree la structure des répértoire
                                    lx.eval('dialog.open')
                                    result = lx.eval("dialog.result ?")
                                    updateVal = True

                                except:
                                    # ON NE CREE PAS LA STRUCTURE AUTOMATIQUEMENT
                                    updateVal = False

                            # si c'est l'ambient on uptate les valeur ray et range

                            if itemRO['name'] == "occl.ambient" and updateVal:
                                occRay = lx.eval('user.value rom_AORay ?')
                                occRange = lx.eval('user.value rom_AORange ?')

                                lx.eval(
                                    "item.channel renderOutput$occlRays %s" %
                                    occRay)
                                lx.eval(
                                    "item.channel renderOutput$occlRange %s" %
                                    occRange)
                            if itemRO['name'] == "depth" and updateVal:

                                lx.eval("item.channel renderOutput$remap %s" %
                                        depthRemap)
                                if (depthRemap):
                                    depthRange = lx.eval(
                                        'user.value rom_maximumDepth ?')
                                    lx.eval(
                                        "item.channel renderOutput$depthMax %s"
                                        % depthRange)

                            if itemRO['name'] == "motion" and updateVal:

                                lx.eval("item.channel renderOutput$remap %s" %
                                        motionRemap)
                                if (motionRemap):
                                    motionPixel = lx.eval(
                                        'user.value rom_motionPixel ?')
                                    lx.eval(
                                        "item.channel renderOutput$motionMax %s"
                                        % motionPixel)

                # si il existe pas on le cree

                if (flag) and (not (updateOnly or updateExistingOnly)):
                    foundUpdate = True
                    lx.eval("select.itemType polyRender")
                    lx.eval("shader.create renderOutput")
                    lx.eval("shader.setEffect {%s}" % itemRO['name'])
                    RenderSelect = lx.eval1(
                        'query sceneservice selection ? renderOutput')

                    #est ce qu'on ajoute le prefix
                    addPrefix = ""
                    if (lx.eval('user.value rom_askPrefix ?') == True):
                        addPrefix = lx.eval('user.value rom_prefixName ?')
                    # est ce qu'on utilise le suffixe comme nom de layer
                    if (lx.eval('user.value rom_useSuffixe ?') == True):
                        NameRenderOutput = addPrefix + itemRO['suffixe']

                    else:
                        NameRenderOutput = lx.eval(
                            'query sceneservice renderOutput.Name ? "%s"' %
                            RenderSelect)
                        NameRenderOutput = addPrefix + NameRenderOutput
                        NameRenderOutput = NameRenderOutput.replace(" ", "_")
                        NameRenderOutput = NameRenderOutput.replace(
                            "_Output", "")
                        NameRenderOutput = NameRenderOutput.replace(
                            "_Shading", "")
                        NameRenderOutput = NameRenderOutput.replace(
                            "Shading_", "")
                        NameRenderOutput = NameRenderOutput.replace("(", "")
                        NameRenderOutput = NameRenderOutput.replace(")", "")
                    lx.eval('item.name "%s" renderOutput' % NameRenderOutput)
                    typeGroup = ""

                    if groupSelected:
                        groupSelectedName = lx.eval(
                            'query sceneservice item.name ? %s' %
                            groupSelected)
                        groupSelectedName = groupSelectedName.replace(
                            " (Item)", "")
                        groupSelectedName = groupSelectedName.replace(
                            " (Material)", "")
                        groupSelectedName = format_filename(groupSelectedName)
                        typeGroup = lx.eval(
                            'query sceneservice item.type ? %s' %
                            groupSelected)
                        lx.eval("texture.parent %s -1" % groupSelected)
                    lx.eval(r'item.channel renderOutput$gamma %s' % gammaFile)
                    lx.eval(r'item.channel renderOutput$antialias %s' %
                            aliasFile)
                    lx.eval(r'item.tag string "ROMN:renderOutput" "%s"' %
                            (targetPath + "," + patternOutput))

                    # si c'est l'ambient on uptate les valeur ray et range
                    if itemRO['name'] == "occl.ambient":
                        occRay = lx.eval('user.value rom_AORay ?')
                        occRange = lx.eval('user.value rom_AORange ?')
                        lx.eval("item.channel renderOutput$occlRays %s" %
                                occRay)
                        lx.eval("item.channel renderOutput$occlRange %s" %
                                occRange)
                    if itemRO['name'] == "depth":
                        lx.eval("item.channel renderOutput$remap %s" %
                                depthRemap)
                        if (depthRemap):
                            depthRange = lx.eval(
                                'user.value rom_maximumDepth ?')
                            lx.eval("item.channel renderOutput$depthMax %s" %
                                    depthRange)
                    if itemRO['name'] == "motion":
                        lx.eval("item.channel renderOutput$remap %s" %
                                motionRemap)
                        if (motionRemap):
                            motionPixel = lx.eval(
                                'user.value rom_motionPixel ?')
                            lx.eval("item.channel renderOutput$motionMax %s" %
                                    motionPixel)

                    if targetPath != "":

                        nameFile = targetPath.rfind(separator)
                        baseFolder = targetPath[0:nameFile + 1]
                        BASENAME = targetPath[nameFile + 1:len(targetPath)]
                        RENDERNAME = NameRenderOutput
                        TYPENAME = itemRO['suffixe']
                        GROUP = ""
                        #on test si c'est bien un group et si on a choisi de creer un repertoir
                        if groupSelected and groupSelectedName and typeGroup == "mask":
                            GROUP = groupSelectedName

                        nameFile = patternFile.replace("[GROUPNAME]", GROUP)
                        nameFile = nameFile.replace("[CAMERA]", RENDERCAMERA)
                        nameFile = nameFile.replace("[LAYERNAME]", RENDERNAME)
                        nameFile = nameFile.replace("[BASENAME]", BASENAME)
                        nameFile = nameFile.replace("[SUFFIXE]", TYPENAME)
                        nameFile = nameFile.replace("|", separator)
                        nameFile = baseFolder + nameFile
                        nameFile = nameFile.replace(
                            separator + separator + separator, separator)
                        nameFile = nameFile.replace(separator + separator,
                                                    separator)
                        pathFile = os.path.dirname(nameFile)
                        lx.out("LE FICHIER:" + nameFile)
                        lx.eval(r'item.channel renderOutput$filename "%s"' %
                                nameFile)
                        lx.eval(r'item.channel renderOutput$format "%s"' %
                                formatFile)

                        #MakePath
                        makes_path(pathFile, createFolder)
                    else:
                        lx.eval(r'item.channel renderOutput$filename ""')
                        lx.eval(r'item.channel renderOutput$format ""')

            #si il est pas actif mais il existe on l'efface
            else:
                if (num):
                    for xx in xrange(num):
                        lx.out("Check if need to delete:" + existRO[xx] + "-" +
                               itemRO['name'])
                        if existRO[xx] == itemRO['name']:
                            lx.out("Delete %s" % itemRO['name'])
                            itemId = existingRO[xx]
                            lx.eval("select.item {%s}" % itemId)
                            lx.eval("texture.delete")

    except:
        lx.out("Command failed with updateRenderOutput ", sys.exc_info())

        return None
#python

import lx

def selectConectedUV():
	lx.eval('!!select.3DElementUnderMouse set')
	lx.eval('ffr.selectconnecteduv')

selType = lx.eval1('query layerservice selmode ?')

if selType == 'polygon':
	p_hover = lx.eval1('query view3dservice element.over ? poly')
	p_sel = lx.evalN('query layerservice uv ? selected')
	if isinstance(p_hover, str):
		selectConectedUV()
	else:
		if len(p_sel)>0:
			lx.eval('ffr.selectconnecteduv')
		else:
			lx.eval('select.all')

elif selType == 'edge':
	lx.eval('select.type polygon')
	e_hover = lx.eval1('query view3dservice element.over ? poly')
	if isinstance(e_hover, str):
		selectConectedUV()
	else:
		lx.eval('select.all')

elif selType == 'vertex':
	lx.eval('select.type polygon')
#python

import lx

selection = lx.evalN('query sceneservice selection ? mesh')
for mesh in selection:
    meshName = lx.eval('query sceneservice item.name ? {%s}' % mesh)
    lx.eval('select.item {%s} set' % mesh)
    numMat = lx.eval1('query layerservice material.N ?')
    for i in range(0, numMat):
        matID = lx.eval('query layerservice material.id ? {%s}' % i)
        matParent = lx.eval('query sceneservice item.parent ? {%s}' % matID)
        if i == 0:
            lx.eval('select.item {%s} set' % matParent)
        else:
            lx.eval('select.item {%s} add' % matParent)
    lx.eval('shader.group')
    lx.eval('item.name {%s (Materials)} mask' % meshName)
    lx.eval('select.drop item')
    def getBBOX(self, space):

        # Default to return until we get good values.
        bbox = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        # Only deal with visible and unlocked verts.
        mesh_svc = lx.service.Mesh()
        mode = mesh_svc.ModeCompose('select', 'hide lock')
        mode_selected_unhideunlock = mesh_svc.ModeCompose(
            'select', 'hide lock')

        # Grab the primary layer.
        layer_svc = lx.service.Layer()
        layer_scan = lx.object.LayerScan(
            layer_svc.ScanAllocate(lx.symbol.f_LAYERSCAN_PRIMARY
                                   | lx.symbol.f_LAYERSCAN_MARKALL))
        if not layer_scan.test():
            return bbox

        # Early out if there are no active layers.
        layer_count = layer_scan.Count()
        if layer_count == 0:
            return bbox

        # Get selection type.
        selType = lx.eval1('query layerservice selmode ?')

        # Grab the mesh.
        mesh = lx.object.Mesh(layer_scan.MeshBase(0))
        if not mesh.test():
            return bbox

        # Early out if there are no points in the active layer.
        point_count = mesh.PointCount()
        if point_count == 0:
            return bbox

        # Grab accessors.
        point = lx.object.Point(mesh.PointAccessor())
        edge = lx.object.Edge(mesh.EdgeAccessor())
        polygon = lx.object.Polygon(mesh.PolygonAccessor())
        if not point.test() or not edge.test() or not polygon.test():
            return bbox

        # Find the BBOX of selected verts.
        if selType == 'vertex':
            visitor = BBOXVerts(point)
            point.Enumerate(mode, visitor, 0)

        # Find the BBOX of selected edges.
        elif selType == 'edge':
            visitor = BBOXEdges(edge, point)
            edge.Enumerate(mode, visitor, 0)

        # Find the BBOX of selected polygons.
        elif selType == 'polygon':
            visitor = BBOXPolys(polygon, point)
            polygon.Enumerate(mode, visitor, 0)

        else:
            return

        # Make bbox.
        bbox = [minFloat, minFloat, minFloat, maxFloat, maxFloat, maxFloat]
        if space == 'world':
            item = lx.object.Item(layer_scan.MeshItem(0))
            lx.out('%s' % item.UniqueName())
            current_scene = item.Context()
            sel_svc = lx.service.Selection()
            chan_read = lx.object.ChannelRead(
                current_scene.Channels(None, sel_svc.GetTime()))
            matrix = lx.object.Matrix(
                chan_read.ValueObj(
                    item,
                    item.ChannelLookup(lx.symbol.sICHAN_XFRMCORE_WORLDMATRIX)))

            for pointPos in visitor.points:
                worldPos = matrix.MultiplyVector(pointPos)

                bbox[0] = max(bbox[0], worldPos[0])
                bbox[1] = max(bbox[1], worldPos[1])
                bbox[2] = max(bbox[2], worldPos[2])
                bbox[3] = min(bbox[3], worldPos[0])
                bbox[4] = min(bbox[4], worldPos[1])
                bbox[5] = min(bbox[5], worldPos[2])
        else:
            for pointPos in visitor.points:
                bbox[0] = max(bbox[0], pointPos[0])
                bbox[1] = max(bbox[1], pointPos[1])
                bbox[2] = max(bbox[2], pointPos[2])
                bbox[3] = min(bbox[3], pointPos[0])
                bbox[4] = min(bbox[4], pointPos[1])
                bbox[5] = min(bbox[5], pointPos[2])

        layer_scan.Apply()

        return bbox
Exemplo n.º 17
0
	def basic_Execute (self, msg, flags):

		# MODO version checks. Different versions have different FBX options.
		self.modo_ver = int(lx.eval ('query platformservice appversion ?'))
		if self.modo_ver < 801:
			lx.out ('Requires Modo 801 or newer.')
			return

		# Get the selected UV names.
		selected_uv_names = self.getUVSelection ()
		if len (selected_uv_names) == 0:
			lx.out ('No UV maps selected.')
			return

		# Grab the active layer.
		layer_svc = lx.service.Layer ()
		layer_scan = lx.object.LayerScan (layer_svc.ScanAllocate (lx.symbol.f_LAYERSCAN_ACTIVE))
		if not layer_scan.test ():
			lx.out ('Layerscan failed.')
			return

		# Early out if there are no active layers.
		layer_count = layer_scan.Count ()
		if layer_count <= 0:
			lx.out ('No active layers.')
			return

		# Grab the relevant meshes and UV maps.
		mesh_items = []
		mesh_uvs = []
		for layer_idx in xrange (layer_count):
			mesh_item = lx.object.Item (layer_scan.MeshItem (layer_idx))
			if not mesh_item.test ():
				lx.out ('Failed to get mesh item of layer %s.' % layer_idx)
				continue

			mesh_name = mesh_item.UniqueName ()
			
			mesh = lx.object.Mesh (layer_scan.MeshBase (layer_idx))
			if not mesh.test ():
				lx.out ('Failed to get mesh of %s.' % mesh_name)
				continue

			# Get the selected UV maps that exist on this model.
			meshmap = lx.object.MeshMap (mesh.MeshMapAccessor ())
			if not meshmap.test ():
				lx.out ('Failed to get meshmap accessor of %s.' % mesh_name)
				continue

			selected_uv_names_mesh = []
			for uv_map in selected_uv_names:
				try:
					meshmap.SelectByName (lx.symbol.i_VMAP_TEXTUREUV, uv_map)
				except:
					pass
				else:
					selected_uv_names_mesh.append (uv_map)

			if len (selected_uv_names_mesh) == 0:
				lx.out ('%s does not have any of the selected UV maps on it.' % mesh_name)
				continue
				
			mesh_items.append (mesh_item)
			mesh_uvs.append (selected_uv_names_mesh)

		layer_scan.Apply ()

		# Select the meshes.
		for x, mesh_item in enumerate(mesh_items):
			if x == 0:
				lx.eval ('select.subItem %s set mesh 0 0' % mesh_item.Ident ())
			else:
				lx.eval ('select.subItem %s add mesh 0 0' % mesh_item.Ident ())

		# Get IPackThat executable path.
		ipackthat_path = None
		try:
			ipackthat_path = lx.eval1 ('!!user.value ipackthat_path ?')
		except:
			if not self.findIPackThatPath ():
				return
		else:
			if not self.validIPackThatPath (ipackthat_path):
				if not self.findIPackThatPath ():
					return
				else:
					ipackthat_path = lx.eval1 ('!!user.value ipackthat_path ?')

		if ipackthat_path is None:
			lx.out ('Invalid IPackThat path.')
			return

		# Store user's FBX preferences for restoring later.
		fbxSettings = self.storeFBXSettings ()

		# Apply FBX settings we want to use for IPackThat.
		# Essentially disabling everything except geometry and setting export to selection.
		# Also picking FBX2013, just because that should ensure things export smoothly.
		lx.eval ('user.value sceneio.fbx.save.format 2')
		lx.eval ('user.value sceneio.fbx.save.exportType 1')
		lx.eval ('user.value sceneio.fbx.save.geometry 1')
		
		lx.eval ('user.value sceneio.fbx.save.exportToASCII 0')
		lx.eval ('user.value sceneio.fbx.save.animationOnly 0')
		lx.eval ('user.value sceneio.fbx.save.cameras 0')
		lx.eval ('user.value sceneio.fbx.save.lights 0')
		lx.eval ('user.value sceneio.fbx.save.materials 0')
		lx.eval ('user.value sceneio.fbx.save.polygonParts 0')
		lx.eval ('user.value sceneio.fbx.save.selectionSets 0')
		lx.eval ('user.value sceneio.fbx.save.smoothingGroups 0')
		lx.eval ('user.value sceneio.fbx.save.morphMaps 0')
		lx.eval ('user.value sceneio.fbx.save.animation 0')
		lx.eval ('user.value sceneio.fbx.save.sampleAnimation 0')
		if self.modo_ver > 900:
			try:
				lx.eval1 ('user.value sceneio.fbx.save.tangentsBitangents 0')
			except RuntimeError:
				pass
		if self.modo_ver > 1000 and self.modo_ver <= 1011:
			try:
				lx.eval ('user.value sceneio.fbx.save.triangulate 0')
				lx.eval ('user.value sceneio.fbx.save.meshSmoothing 0')
			except RuntimeError:
				pass
		if self.modo_ver >= 1012:
			try:
				lx.eval ('user.value sceneio.fbx.save.surfaceRefining 0')
			except RuntimeError:
				pass

		# Export the FBX.
		try:
			lx.eval ('dialog.setup fileSave')
			lx.eval ('dialog.title "Save FBX file for IPackThat"')
			lx.eval ('dialog.fileType scene2')
			lx.eval ('dialog.fileSaveFormat fbx format')
			if self.modo_ver == 801:
				lx.eval ('+dialog.open')
			else:
				lx.eval ('dialog.open')
			fbx_export_path = lx.eval1 ('dialog.result ?')
		except:
			lx.out ('Didn\'t save FBX for IPackThat.')
			return
		else:
			if fbx_export_path == None:
				lx.out ('Didn\'t save FBX for IPackThat.')
				return
			else:
				fbx_export_path = os.path.splitext (fbx_export_path)[0] + '.fbx'
				fbx_file_name = os.path.splitext (os.path.basename (fbx_export_path))[0]

		lx.eval ('scene.saveAs "%s" fbx true' % fbx_export_path)
		fbx_save_time = os.path.getmtime (fbx_export_path)

		# Restore the FBX preferences.
		self.restoreFBXSettings (fbxSettings)

		# Call IPackThat.
		proc = subprocess.Popen([ipackthat_path, fbx_export_path], stdout=subprocess.PIPE)
		stdout, stderr = proc.communicate()
		rc = proc.returncode

		if rc != 0:
			# IPackThat crashed or threw an error.
			lx.out ('IPackThat crashed.')
			lx.out ('Standard Output: %s' % stdout)
			lx.out ('Error Output: %s' % stderr)
		else:
			# Get the modified time of the export file.
			fbx_load_time = 0
			if os.path.lexists (fbx_export_path):
				fbx_load_time = os.path.getmtime (fbx_export_path)

			# User has likely saved over the old file.
			if fbx_load_time > fbx_save_time:
				if self.modo_ver > 1000:
					lx.eval ('!!loaderOptions.fbx mergeWithExistingItems:false loadGeometry:true loadNormals:false loadMeshSmoothing:false loadBlendShapes:false loadPolygonParts:false loadSelectionSets:false loadMaterials:false invertMatTranAmt:false useMatTranColAsTranAmt:false changeTextureEffect:false loadCameras:false loadLights:false loadAnimation:false loadSampleAnimation:false loadSampleAnimationRate:0 globalScalingFactor:1.0 importUnits:0')
				else:
					lx.eval ('!!loaderOptions.fbx mergeWithExistingItems:false loadGeometry:true loadNormals:false loadMeshSmoothing:false loadBlendShapes:false loadPolygonParts:false loadSelectionSets:false loadMaterials:false invertMatTranAmt:false useMatTranColAsTranAmt:false loadCameras:false loadLights:false loadAnimation:false loadSampleAnimation:false loadSampleAnimationRate:0')
				lx.eval ('!!scene.open "%s" import' % fbx_export_path)
			else:
				try:
					lx.eval ('dialog.setup fileOpen')
					lx.eval ('dialog.title "Load FBX file from IPackThat"')
					lx.eval ('dialog.fileType scene2')
					if self.modo_ver == 801:
						lx.eval ('+dialog.open')
					else:
						lx.eval ('dialog.open')
					fbx_import_path = lx.eval1 ('dialog.result ?')
				except:
					lx.out ('Failed to load scene with new UVs.')
					return
				else:
					if fbx_import_path == None:
						return
					else:
						fbx_file_name = os.path.splitext (os.path.basename (fbx_import_path))[0]
						if self.modo_ver > 1000:
							lx.eval ('!!loaderOptions.fbx mergeWithExistingItems:false loadGeometry:true loadNormals:false loadMeshSmoothing:false loadBlendShapes:false loadPolygonParts:false loadSelectionSets:false loadMaterials:false invertMatTranAmt:false useMatTranColAsTranAmt:false changeTextureEffect:false loadCameras:false loadLights:false loadAnimation:false loadSampleAnimation:false loadSampleAnimationRate:0 globalScalingFactor:1.0 importUnits:0')
						else:
							lx.eval ('!!loaderOptions.fbx mergeWithExistingItems:false loadGeometry:true loadNormals:false loadMeshSmoothing:false loadBlendShapes:false loadPolygonParts:false loadSelectionSets:false loadMaterials:false invertMatTranAmt:false useMatTranColAsTranAmt:false loadCameras:false loadLights:false loadAnimation:false loadSampleAnimation:false loadSampleAnimationRate:0')
						lx.eval ('!scene.open "%s" import' % fbx_import_path)

			scene = lxu.select.SceneSelection ().current ()
			scn_svc = lx.service.Scene ()
			group_type = scn_svc.ItemTypeLookup (lx.symbol.sITYPE_GROUPLOCATOR)

 			fbx_group_index = -2
			fbx_group = None
 			group_ident = None
 			item_ident = None
			
			# Find the newly imported FBX scene.
			group_count = scene.ItemCount (group_type)
			for i in reversed (xrange (group_count)):
				group = scene.ItemByIndex (group_type, i)
				if group.Name () == fbx_file_name:
					group_index = group.UniqueIndex ()
					if group_index > fbx_group_index:
						fbx_group_index = group_index
						fbx_group = group

			if fbx_group is not None:
				
				# Find the newly imported FBX versions of our original meshes.
				fbx_meshes = [None] * len(mesh_items)
				self.recurseToFindFBXMeshes (fbx_group, fbx_meshes, mesh_items)
				
				# Copy over the UVs.
				for fbx_mesh, mesh_item, mesh_uv in zip(fbx_meshes, mesh_items, mesh_uvs):
					if fbx_mesh is not None:
						fbx_ident = fbx_mesh.Ident ()
						mesh_ident = mesh_item.Ident ()
						for uv_map in mesh_uv:
							lx.eval ('select.subItem %s set mesh 0 0' % fbx_ident)
							
							try:
								lx.eval ('select.vertexMap %s txuv replace' % uv_map)
							except:
								continue
							else:
								try:
									lx.eval ('select.type polygon')
									lx.eval ('select.all')
									lx.eval ('uv.copy')

									lx.eval ('select.subItem %s set mesh 0 0' % mesh_ident)
									lx.eval ('select.vertexMap %s txuv replace' % uv_map)
								except:
									continue
								else:
									try:
										lx.eval ('select.type polygon')
										lx.eval ('select.all')
									
										if self.modo_ver > 801:
											lx.eval ('uv.paste selection')
										else:
											lx.eval ('uv.paste')
									except:
										continue

				# Delete the imported FBX scene.
				if self.modo_ver > 1009:
					lx.eval ('!!item.delete child:1 item:%s' % fbx_group.Ident())
				else:
					lx.eval ('select.subItem %s set groupLocator 0 0' % fbx_group.Ident ())
					lx.eval ('!!item.delete mask:groupLocator child:1')

				# Reselect the original mesh and UVs.
				for mesh_item in mesh_items:
					lx.eval ('select.subItem %s add mesh 0 0' % mesh_item.Ident ())
				for idx, uv_map in enumerate (selected_uv_names_mesh):
					if idx == 0:
						lx.eval ('select.vertexMap %s txuv replace' % uv_map)
					else:
						lx.eval ('select.vertexMap %s txuv add' % uv_map)
				lx.eval ('select.drop polygon')
				lx.eval("item.channel locator$isAxis " +myaxis)
				lx.eval("item.channel locator$isAlign " +myalig)
				
				# Apply final form shape
				lx.eval("item.channel locator$isShape " +myform)
				
				# Finally, decide between default or custom shape
				# I introduce this final step to “store” shape dimensions
				# even if you create a Default locator and then you decide
				# to change to a custom shape 
				lx.eval("item.channel locator$drawShape " +myshap)
				
				# ---------------------------------

				# get id of newly created locator
				locatorName = lx.eval1("query sceneservice selection ? all")

				# add locator to array
				locators.append(locatorName)
					
				# Select item by name
				lx.eval('select.subItem {%s}' % itemName)
				
				# Match position
				lx.eval('item.match item pos')
				
				# Match rotation
				lx.eval('item.match item rot')
	
		# select locators
		lx.eval("select.drop item")
Exemplo n.º 19
0
lx.eval("viewport.3dView showLights:true")

# convert selection to verts
lx.eval("select.convert vertex")

# query how many vertices selected
VertSelected = lx.evalN("query layerservice verts ? selected")

# we will create a bunch of Lights and need to add them to an array
lights = []

for MyEachVert in VertSelected:
    xVertPos = lx.eval("query layerservice vert.wpos ? {%s}" % MyEachVert)[0]
    yVertPos = lx.eval("query layerservice vert.wpos ? {%s}" % MyEachVert)[1]
    zVertPos = lx.eval("query layerservice vert.wpos ? {%s}" % MyEachVert)[2]
    lx.eval("item.create pointLight")
    lx.eval("item.channel locator$size 0.0")
    lx.eval("transform.channel pos.X {%s}" % xVertPos)
    lx.eval("transform.channel pos.Y {%s}" % yVertPos)
    lx.eval("transform.channel pos.Z {%s}" % zVertPos)

    # get id of newly created light
    lightName = lx.eval1("query sceneservice selection ? all")

    # add light to array
    lights.append(lightName)

# select lights
lx.eval("select.drop item")
for item in lights:
    lx.eval('select.item {%s} add' % item)
Exemplo n.º 20
0
# defines folder and string to strip
folder = '/home/ben/Documents/tests/modo/feather/cache/'
files = os.listdir(folder)
mddPrefix = 'blabla_pifpif_'

# get stripped mdd's 
mddList = []
for f in files:
    if f.endswith('mdd'):
        stripped = f.strip(mddPrefix).strip('.mdd')
        mddList.append(stripped)
        lx.out(mddList)

# get all items
n = lx.eval1('query sceneservice item.N ?')

# creates a list of meshes
itemList = []
for i in range(n):
    itemType = lx.eval('query sceneservice item.type ? %s' % i)
    if itemType == 'mesh':
        itemName = lx.eval('query sceneservice item.name ? %s' % i)
        itemList.append(itemName)

# assign the mdd to the corresponding mesh
compare = list(set(mddList).intersection(itemList))
for i in compare:
    lx.out(i)
    lx.eval('select.item item:%s' % i)
    fullPath = str(folder + mddPrefix + str(i) + '.mdd')
Exemplo n.º 21
0
    for point in sample_points:
        edge_sectors.append(tuple(int(math.ceil(x/y)-1) for x,y in izip(vecSub(layer_bounds[1],point), sector_range)))
    edge_sectors = set(edge_sectors)
    for sectors in edge_sectors:
        sector_vertices.extend(sector_space[sectors[0]][sectors[1]][sectors[2]])
    for vertex in sector_vertices:
        vec3 = lx.eval("query layerservice vert.pos ? " + str(vertex))

        #Check the vertex against the bounds of the edge
        if (vec3 != vec1 and vec3 != vec2) and \
           (vec3[0] > edge_bounds[0][0] and vec3[0] < edge_bounds[1][0]) and \
           (vec3[1] > edge_bounds[0][1] and vec3[1] < edge_bounds[1][1]) and \
           (vec3[2] > edge_bounds[0][2] and vec3[2] < edge_bounds[1][2]):
            vert_polys = set(lx.evalN("query layerservice vert.polyList ? " + str(vertex)))
            if not vert_polys:
                vert_polys = set([lx.eval1("query layerservice vert.polyList ? " + str(vertex))])
            edge_polys = set(lx.evalN("query layerservice edge.polyList ? " + str(edge)))
            if not edge_polys:
                edge_polys = set([lx.eval1("query layerservice edge.polyList ? " + str(edge))])
            
            if not edge_polys.intersection(vert_polys):         
                timer2 = time.clock()
                distance = vecDistanceAxis((vec1,vec2),vec3)
                try:
                    angle1 = vecAngle(vec1,vec2,vec1,vec3)
                except:
                    angle1 = 0
                try:
                    angle2 = vecAngle(vec2,vec1,vec2,vec3)
                except:
                    angle2 = 0
#python

import lx


def selectConectedUV():
    lx.eval('!!select.3DElementUnderMouse set')
    lx.eval('ffr.selectconnecteduv')


selType = lx.eval1('query layerservice selmode ?')

if selType == 'polygon':
    p_hover = lx.eval1('query view3dservice element.over ? poly')
    p_sel = lx.evalN('query layerservice uv ? selected')
    if isinstance(p_hover, str):
        selectConectedUV()
    else:
        if len(p_sel) > 0:
            lx.eval('ffr.selectconnecteduv')
        else:
            lx.eval('select.all')

elif selType == 'edge':
    lx.eval('select.type polygon')
    e_hover = lx.eval1('query view3dservice element.over ? poly')
    if isinstance(e_hover, str):
        selectConectedUV()
    else:
        lx.eval('select.all')
        scene_svc.select("item",str(item))
        lx.eval('select.item {%s} set' % item)

        # get item type
        itemType = scene_svc.query("item.type")

        if itemType == 'locator':

            locators.append(item)

            # Ask if our locator has a default or custom shape:
            lx.eval('item.channel locator$drawShape ?')

            # This gives a result (default / custom)
            # Save that result into a variable:
            locatorShape = lx.eval1('item.channel locator$drawShape ?')

            if locatorShape == 'default':
                # Change size for standard default locator:
                lx.eval("item.channel locator$size " +str(mysize))

            elif locatorShape == 'custom':
                # Ask which is actual shape:
                lx.eval("item.channel locator$isShape ?")

                # This gives a result (box, pyramid, plane…)
                # Save that result into a variable:
                originalShape = lx.eval("item.channel locator$isShape ?")

                # Change size for standard default locator:
                lx.eval("item.channel locator$size " +str(mysize))
Exemplo n.º 24
0
    def basic_Execute(self, msg, flags):

        try:

            # Some early checks and settings.

            # UV MAP SELECTED?
            # Early out if no UV map is selected.

            selected_uv_name = ''

            # We want to deal with the current selection, so we need a selection service.
            # This allows us to read and alter the current item/component selection as presented to the user.

            # We'll also deal with some accessors for a mesh a little further down - or rather, above here in the visitors code - which have a Select() method and these are unrelated to actual selection...
            # ...(for them it's more like "set yourself to return information about the component I've asked you to select").
            sel_svc = lx.service.Selection()

            # And we want to set up a vertex map packet translation object - these let us get information about selected vertex map "packets" that we get from the selection service.
            # We pass these packets into the translation object and it will give us information about the selected vertex map it represents.
            # In this instance, we want to know; it's type (to check it's a UV map) and it's name (so we know which UV map it is).
            # These also work in reverse - you can pass it a vertex map and it will return a packet. We can then pass that packet to the selection service to have it select (or deselect) it.
            vmap_pkt_trans = lx.object.VMapPacketTranslation(
                sel_svc.Allocate(lx.symbol.sSELTYP_VERTEXMAP))
            sel_type_vmap = sel_svc.LookupType(lx.symbol.sSELTYP_VERTEXMAP)

            # We want to select edges, so let's set that up using the selection service.
            # And we want to set up an edge packet translation object - these let us pass in edges and get a packet returned that we can give to the selection service.
            # This also works in reverse - we can get an edge packet from the selection service and pass it in to the translation to find out information about the edge it represents.
            edge_pkt_trans = lx.object.EdgePacketTranslation(
                sel_svc.Allocate(lx.symbol.sSELTYP_EDGE))
            sel_type_edge = sel_svc.LookupType(lx.symbol.sSELTYP_EDGE)

            # Go through all of the selected vertex maps.
            for i in xrange(sel_svc.Count(sel_type_vmap)):
                # Get a packet representing this map.
                pkt = sel_svc.ByIndex(sel_type_vmap, i)
                # If the type of this packet is UV...
                if vmap_pkt_trans.Type(pkt) == lx.symbol.i_VMAP_TEXTUREUV:
                    # ...get it's name and then break out of this loop.
                    selected_uv_name = vmap_pkt_trans.Name(pkt)
                    break
            else:
                # If we've got here, the for loop has terminated without breaking out, so we've not got a UV map selected.
                self.errorDialog('Please select a UV map to operate on.',
                                 'No UV Map Selected')
                return

            # Pull up the layer service, this will let us scan over the mesh layers.
            layer_svc = lx.service.Layer()

            # The layer_scan item will pull up the layers as determined in ScanAllocate.
            # In this case it's any ACTIVE layers, which means any layers that are editable at the moment (i.e. that are foreground layers).
            # The MARKALL flag also ensures that the elements' mark modes will be flagged so we can test against them.
            layer_scan = lx.object.LayerScan(
                layer_svc.ScanAllocate(lx.symbol.f_LAYERSCAN_ACTIVE
                                       | lx.symbol.f_LAYERSCAN_MARKALL))
            if not layer_scan.test():
                return

            # Get the number of layers the scan has found. If it's less than 1, then return - as there are no active layers.
            layer_count = layer_scan.Count()
            if layer_count < 1:
                return

            # Sort out mark modes we'll need. These are the flags for the elements, such as selected, hidden, locked and up to 8 custom ones.
            # We can use this mode when we run the visitor later, so it will only enumerate over elements that match these mark modes.
            # These are most easily generated by the mesh service, so start one up.
            mesh_svc = lx.service.Mesh()

            # The first paramater are modes that must be set, the second are modes that must not be set.
            # Here, we are specifying that they must not have hidden or locked modes set.
            # Mark modes are space separated strings.
            mark_mode_visible_unlocked = mesh_svc.ModeCompose(
                None, '%s %s' % (lx.symbol.sMARK_LOCK, lx.symbol.sMARK_HIDE))
            mark_mode_selected_visible_unlocked = mesh_svc.ModeCompose(
                lx.symbol.sMARK_SELECT,
                '%s %s' % (lx.symbol.sMARK_LOCK, lx.symbol.sMARK_HIDE))

            # Get current selection mode.
            current_sel_mode = lx.eval1('query layerservice selmode ?')

            # Get argument values.

            # AXIS

            # Get the axis argument value, if it's set.
            axis = 0
            if self.dyna_IsSet(0):
                axis = self.attr_GetInt(0)
                # Return if the axis value isn't valid. Again, we shouldn't get here, but it's good practice to handle these things.
                if axis < 0 or axis > 3:
                    self.errorDialog('Please specify a valid axis selection.',
                                     'No Valid Axis Set')
                    return
            else:
                # Otherwise return early. We shouldn't get here but it's good practise to handle these things.
                self.errorDialog('Please specify an axis.', 'No Axis Set')
                return

            # SELECTION MODE

            # Default to set selection.
            select_mode = 0
            if self.dyna_IsSet(1):
                select_mode = self.attr_GetInt(1)
                # Return if the select mode isn't valid. Again, we shouldn't get here, but it's good practice to handle these things.
                if select_mode < 0 or select_mode > 2:
                    self.errorDialog('Please specify a valid selection mode.',
                                     'No Valid Selection Mode Set')
                    return

            # IN SELECTION ONLY

            # Default to everything.
            in_selection_only = False
            if self.dyna_IsSet(2):
                in_selection_only = (self.attr_GetInt(2) == 1)

            # Set the mark mode to use for the edge visitor depending on whether we want to only alter edges which are currently selected and we're in edge mode.
            # This will mean that the visitor will only be called on edges that match this mark mode.
            # Or to use for the polygons inside the edge visitor depending on whether we want to only alter edges which are currently in selected polygons and we're in polygon mode.
            polygon_mark_mode = mark_mode_visible_unlocked
            edge_mark_mode = mark_mode_visible_unlocked
            if in_selection_only:
                if current_sel_mode == 'edge':
                    edge_mark_mode = mark_mode_selected_visible_unlocked
                elif current_sel_mode == 'polygon':
                    polygon_mark_mode = mark_mode_selected_visible_unlocked

            # TOLERANCE

            # Default tolerance to 5 degrees.
            tolerance = math.radians(5.0)
            if self.dyna_IsSet(3):
                # Although if it's defined in the arguments, use that instead.
                tolerance = self.attr_GetFlt(3)

            # ANGLE
            angles = ()
            if axis == 0:
                # If axis is 1 (i.e. U axis) set vector that points along the U axis.
                angles = ((1.0, 0.0), )
            elif axis == 1:
                # If axis is 1 (i.e. V axis) set vector that points along the V axis.
                angles = ((0.0, 1.0), )
            elif axis == 2:
                # If axis is 2 (i.e. custom) get the custom angle value.
                # Which is argument index 4.
                if self.dyna_IsSet(4):
                    # Here we use a bit of trig to construct a unit vector from the supplied angle.
                    angle = self.attr_GetFlt(4)
                    angles = ((-math.sin(angle), -math.cos(angle)), )
                else:
                    # Return if it's not set. Shouldn't get here, you know the drill.
                    self.errorDialog('Please specify a custom angle value.',
                                     'No Angle Value')
                    return
            elif axis == 3:
                # If axis is 3 (i.e. similar to selected edges) get the angles of the currently selected edges.
                # We can't just iterate over all selected layers here, because there might be discontinuous selections.
                # So we'll call upon the selection service to give us the currently selected edges and from that we can
                # ...work out the polygons the edge selection is attached to.
                # Once we have those details, we can get a list of the UV angles of those edges.
                # Which we'll add to this master list which contains all of the angles we've gathered from each layer.
                selected_edge_angles = []

                # Here we get the edge selection packets from the selection service.
                # And we pull out the information we need from them.
                selected_edge_count = sel_svc.Count(sel_type_edge)

                if selected_edge_count == 0:
                    # Return if there are no edges selected.
                    self.errorDialog(
                        'Please select some edges to get angles from.',
                        'No Edges Selected')
                    return

                selected_edges = []
                for i in xrange(selected_edge_count):
                    # Get a packet representing this edge.
                    pkt = sel_svc.ByIndex(sel_type_edge, i)
                    # Get it's verts IDs.
                    points = edge_pkt_trans.Vertices(pkt)
                    # Get it's polygon ID.
                    polygon = edge_pkt_trans.Polygon(pkt)
                    # Get it's mesh.
                    mesh = edge_pkt_trans.Mesh(pkt)

                    selected_edges.append((mesh, points, polygon))

                # This is a storage object, when passing arrays of information to/from MODO in the PythonAPI, these act as an intermediary between Python and MODO to store them in.
                # It holds 2 float values - which we'll use to hold UV coordinates. The arguments being 'f' for float ('float' will work fine, too) and 2 being the size of the array.
                uv_value = lx.object.storage('f', 2)

                # Now iterate over all of the layers the layerscan found.
                for n in xrange(layer_count):

                    # Get the mesh from the layer.
                    # This is the MeshBase - the original mesh in the scene - so we cannot edit the mesh itself from here. We would need to use MeshEdit (n) for that.
                    mesh_loc = lx.object.Mesh(layer_scan.MeshBase(n))
                    if not mesh_loc.test():
                        continue

        # Quick out if there are no polys in this layer.
                    polygon_count = mesh_loc.PolygonCount()
                    if polygon_count == 0:
                        continue

                    # Get a polygon accessor from the mesh.
                    polygon_loc = lx.object.Polygon(mesh_loc.PolygonAccessor())
                    if not polygon_loc.test():
                        continue

                    # Get an edge accessor from the mesh.
                    edge_loc = lx.object.Edge(mesh_loc.EdgeAccessor())
                    if not edge_loc.test():
                        continue

                    # Get a meshmap (i.e. vertex map) accessor from the mesh.
                    meshmap_loc = lx.object.MeshMap(mesh_loc.MeshMapAccessor())
                    if not meshmap_loc.test():
                        continue

                    # Check that the selected UV map exists for this mesh layer.
                    try:
                        meshmap_loc.SelectByName(lx.symbol.i_VMAP_TEXTUREUV,
                                                 selected_uv_name)
                    except:
                        # That check has asserted, so it has failed to select the UV map on this layer - meaning it doesn't have it.
                        continue
                    else:
                        # That check was a success, meaning this layer has the UV map and it's now selected by the meshmap accessor.

                        # Now get the internal ID of the UV map, which we will use to pull up the values from the elements later on.
                        uvmap_ID = meshmap_loc.ID()

                        # Now go over the list of selected edges we made earlier.
                        for selected_edge in selected_edges:
                            # If the mesh for that edge is the same as this one...
                            if mesh_loc.TestSameMesh(selected_edge[0]):
                                # Get a list of the polygon IDs we want to get UVs for.
                                polygon_IDs = []

                                if selected_edge[2] == 0:
                                    # Polygon ID is 0 - which means it's not a disco selection.
                                    # In that case, add each polygon this edge has.
                                    edge_loc.SelectEndpoints(
                                        selected_edge[1][0],
                                        selected_edge[1][1])
                                    for ep in xrange(edge_loc.PolygonCount()):
                                        polygon_IDs.append(
                                            edge_loc.PolygonByIndex(ep))
                                else:
                                    # Otherwise just use the polgyon ID of the disco selection.
                                    polygon_IDs.append(selected_edge[2])

                                # Now, for each polygon, get the UV values for the edge's points and work out, then store the angle.
                                for polygon_ID in polygon_IDs:
                                    polygon_loc.Select(polygon_ID)

                                    polygon_loc.MapEvaluate(
                                        uvmap_ID, selected_edge[1][0],
                                        uv_value)
                                    point_1_UV = uv_value.get()

                                    # Get the UV values for this polygon for edge point 2.
                                    polygon_loc.MapEvaluate(
                                        uvmap_ID, selected_edge[1][1],
                                        uv_value)
                                    point_2_UV = uv_value.get()

                                    # Get the vector for this UV edge and normalize it.
                                    # Store it only if it isn't zero length.
                                    uv_edge = (point_2_UV[0] - point_1_UV[0],
                                               point_2_UV[1] - point_1_UV[1])
                                    uv_edge_length = uv_edge[0]**2 + uv_edge[
                                        1]**2
                                    if uv_edge_length != 0.0:
                                        uv_edge_length = 1.0 / math.sqrt(
                                            uv_edge_length)
                                        uv_edge = (uv_edge[0] * uv_edge_length,
                                                   uv_edge[1] * uv_edge_length)
                                        selected_edge_angles.append(uv_edge)

                # Pass the angles of the selected UVs in as the angles value.
                angles = tuple(selected_edge_angles)

        # If we've got here, things are probably all set up right. Now to get on with the actual command.

        # Drop the current edge selection if selection mode is "set" (0).
            if select_mode == 0:
                sel_svc.Clear(sel_type_edge)

            # Figure out if we're deselecting rather than selecting.
            deselect = False
            if select_mode == 2:
                deselect = True

        # Iterate over all of the active layers the scan found.

            for n in xrange(layer_count):

                # Get the mesh from the layer.
                # This is the MeshBase - the original mesh in the scene - so we cannot edit the mesh itself from here. We would need to use MeshEdit (n) for that.
                mesh_loc = lx.object.Mesh(layer_scan.MeshBase(n))
                if not mesh_loc.test():
                    continue

    # Quick out if there are no polys in this layer.
                polygon_count = mesh_loc.PolygonCount()
                if polygon_count == 0:
                    continue

                # Get a polygon accessor from the mesh.
                polygon_loc = lx.object.Polygon(mesh_loc.PolygonAccessor())
                if not polygon_loc.test():
                    continue

                # Get an edge accessor from the mesh.
                edge_loc = lx.object.Edge(mesh_loc.EdgeAccessor())
                if not edge_loc.test():
                    continue

                # Get a meshmap (i.e. vertex map) accessor from the mesh.
                meshmap_loc = lx.object.MeshMap(mesh_loc.MeshMapAccessor())
                if not meshmap_loc.test():
                    continue

                # Check that the selected UV map exists for this mesh layer.
                try:
                    meshmap_loc.SelectByName(lx.symbol.i_VMAP_TEXTUREUV,
                                             selected_uv_name)
                except:
                    # That check has asserted, so it has failed to select the UV map on this layer - meaning it doesn't have it.
                    continue
                else:
                    # That check was a success, meaning this layer has the UV map and it's now selected by the meshmap accessor.

                    # Now get the internal ID of the UV map, which we will use to pull up the values from the elements later on.
                    uvmap_ID = meshmap_loc.ID()

                    # Run over the edges, enumerating over only the edges that match the given mark mode.
                    # The 0 here is where we can pass a monitor to log progress for very time intensive operations. But you can pass 0 just to leave out the monitor.
                    # We also pass in all the variables that the visitor will need to run.
                    visitor = SelectEdges(edge_loc, polygon_loc, uvmap_ID,
                                          angles, tolerance, polygon_mark_mode,
                                          sel_svc, sel_type_edge,
                                          edge_pkt_trans, mesh_loc, deselect)
                    edge_loc.Enumerate(edge_mark_mode, visitor, 0)
            # End the layerscan.
            layer_scan.Apply()

            # Drop us into edge mode if we weren't before.
            if current_sel_mode != 'edge':
                lx.eval('select.type edge')

        except:
            lx.out(traceback.format_exc())
Exemplo n.º 25
0
#python

import lx

selType = lx.eval1('query layerservice selmode ?')
if selType == 'item':
	lx.eval('layer.mergeMeshes true')

elif selType == 'polygon':
	lx.eval('poly.collapse')

elif selType == 'edge':
	lx.eval('edge.collapse')

elif selType == 'vertex':
	lx.eval('!vert.join true')
    def batch_folder(self):
        self.currPath = file.getLatestPath(t.config_browse_src_path)
        dialog.init_dialog("input_path", self.currPath)

        try:  # mesh to process dialog
            lx.eval('dialog.open')
        except:
            dialog.init_dialog('cancel', self.currPath)
        else:
            input_dir = lx.eval1('dialog.result ?')
            file.updateExportPath('', input_dir, '')
            self.currPath = file.getLatestPath(t.config_browse_dest_path)
            dialog.init_dialog("output", self.currPath)
            try:  # output folder dialog
                lx.eval('dialog.open')
            except:
                dialog.init_dialog('cancel', self.currPath)
            else:
                output_dir = lx.eval1('dialog.result ?')
                file.updateExportPath('', '', output_dir)

                if not self.processSubfolder_sw:
                    format = helper.filter_string(self.formatFilter,
                                                  t.compatibleImportFormat)
                    files = helper.get_files_of_type(input_dir, format)
                else:
                    input_subdir = helper.get_recursive_subdir(
                        [input_dir], self.subfolderDepth)
                    files = []
                    format = helper.filter_string(self.formatFilter,
                                                  t.compatibleImportFormat)
                    for subdir in input_subdir:
                        subfiles = helper.get_files_of_type(subdir, format)

                        for f in subfiles:
                            files.append(f)

                file_count = len(files)

                self.progress = dialog.init_progress_bar(
                    file_count, 'Exporting files...')

                self.progression[1] = file_count
                self.progression[0] = 0

                t.set_import_setting()

                for f in files:
                    dialog.processing_log(
                        '.....................................   ' +
                        os.path.basename(f) +
                        '   .....................................')

                    lx.eval('!scene.open "%s" normal' % f)

                    self.scnIndex = lx.eval(
                        'query sceneservice scene.index ? current')

                    helper.select_compatible_item_type()

                    self.userSelection = self.scn.selected
                    self.userSelectionCount = len(self.userSelection)

                    dialog.print_log(
                        '.....................................   ' +
                        str(self.userSelectionCount) +
                        ' mesh item founded   .....................................'
                    )

                    if self.at_least_one_item_selected(exit=False):
                        lx.eval('!scene.close')
                        continue

                    input_relative_dir_root = os.path.split(f)[0].split(
                        input_dir)[1][1:]
                    output_subdir = os.path.join(output_dir,
                                                 input_relative_dir_root)

                    helper.create_folder_if_necessary(output_subdir)

                    self.filename = os.path.splitext(os.path.basename(f))[0]

                    self.batch_process(output_subdir, self.filename)

                    dialog.increment_progress_bar(self, self.progress[0],
                                                  self.progression)

                    helper.revert_initial_parameter(self)

                    lx.eval('!scene.close')

                helper.reset_import_settings(self)

                #dialog.deallocate_dialog_svc(self.progress[1])

        dialog.init_message(
            'info', 'Done',
            'Operation completed successfully ! %s file(s) exported' %
            self.exportedFileCount)

        helper.open_destination_folder(self, output_dir)

        dialog.ending_log(self)
# set frame range and intialize counters
f=lx.args()
firstFrame = int(f[0])
lastFrame = int(f[1])
counter = firstFrame
counterRot = firstFrame * 3


#get the name of the character
sceneName = lx.eval("query sceneservice scene.name ? current")
scenePart = sceneName.split ('_')
character = scenePart[0]


# get all items
n = lx.eval1("query sceneservice item.N ?")

# get all items
allItems = pym.Scene_Get_Item_IDs_All()

# enable bke pass
for i in allItems:
    name = pym.Item_Name_Get(i)
    if name == 'bke':
        pym.Item_Select(i)
        lx.eval('layer.active %s type:pass' % i)

# select the render output
for i in range(n):
    itemType = lx.eval("query sceneservice item.type ? %s" % i)
    if(itemType == "renderOutput"):
    def getBBOX (self, space):

        # Default to return until we get good values.
        bbox = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

        # Only deal with visible and unlocked verts.
        mesh_svc = lx.service.Mesh ()
        mode = mesh_svc.ModeCompose ('select', 'hide lock')
        mode_selected_unhideunlock = mesh_svc.ModeCompose ('select', 'hide lock')

        # Grab the primary layer.
        layer_svc = lx.service.Layer ()
        layer_scan = lx.object.LayerScan (layer_svc.ScanAllocate (lx.symbol.f_LAYERSCAN_PRIMARY | lx.symbol.f_LAYERSCAN_MARKALL))
        if not layer_scan.test ():
            return bbox

        # Early out if there are no active layers.
        layer_count = layer_scan.Count ()
        if layer_count == 0:
            return bbox

        # Get selection type.
        selType = lx.eval1('query layerservice selmode ?')

        # Grab the mesh.
        mesh = lx.object.Mesh (layer_scan.MeshBase (0))
        if not mesh.test ():
            return bbox

        # Early out if there are no points in the active layer.
        point_count = mesh.PointCount ()
        if point_count == 0:
            return bbox

        # Grab accessors.
        point = lx.object.Point (mesh.PointAccessor ())
        edge = lx.object.Edge (mesh.EdgeAccessor ())
        polygon = lx.object.Polygon (mesh.PolygonAccessor ())
        if not point.test () or not edge.test () or not polygon.test ():
            return bbox

        # Find the BBOX of selected verts.
        if selType == 'vertex':
            visitor = BBOXVerts (point)
            point.Enumerate (mode, visitor, 0)

        # Find the BBOX of selected edges.
        elif selType == 'edge':
            visitor = BBOXEdges (edge, point)
            edge.Enumerate (mode, visitor, 0)

        # Find the BBOX of selected polygons.
        elif selType == 'polygon':
            visitor = BBOXPolys (polygon, point)
            polygon.Enumerate (mode, visitor, 0)

        else:
            return

        # Make bbox.
        bbox = [minFloat, minFloat, minFloat, maxFloat, maxFloat, maxFloat]
        if space == 'world':
            item = lx.object.Item (layer_scan.MeshItem (0))
            lx.out('%s' % item.UniqueName ())
            current_scene = item.Context ()
            sel_svc = lx.service.Selection()
            chan_read = lx.object.ChannelRead (current_scene.Channels (None, sel_svc.GetTime()))
            matrix = lx.object.Matrix (chan_read.ValueObj (item, item.ChannelLookup (lx.symbol.sICHAN_XFRMCORE_WORLDMATRIX)))

            for pointPos in visitor.points:
                worldPos = matrix.MultiplyVector (pointPos)

                bbox[0] = max (bbox[0], worldPos[0])
                bbox[1] = max (bbox[1], worldPos[1])
                bbox[2] = max (bbox[2], worldPos[2])
                bbox[3] = min (bbox[3], worldPos[0])
                bbox[4] = min (bbox[4], worldPos[1])
                bbox[5] = min (bbox[5], worldPos[2])
        else:
            for pointPos in visitor.points:
                bbox[0] = max (bbox[0], pointPos[0])
                bbox[1] = max (bbox[1], pointPos[1])
                bbox[2] = max (bbox[2], pointPos[2])
                bbox[3] = min (bbox[3], pointPos[0])
                bbox[4] = min (bbox[4], pointPos[1])
                bbox[5] = min (bbox[5], pointPos[2])

        layer_scan.Apply()

        return bbox
	def getSelectionMode(self):
		return lx.eval1 ('query layerservice selmode ?')
    def batch_files(self):
        self.currPath = file.getLatestPath(t.config_browse_src_path)
        dialog.init_dialog("input", self.currPath)

        try:  # mesh to process dialog
            lx.eval('dialog.open')
        except:
            dialog.init_dialog('cancel', self.currPath)
        else:
            files = lx.evalN('dialog.result ?')
            file.updateExportPath('', os.path.split(files[0])[0], '')
            self.currPath = file.getLatestPath(t.config_browse_dest_path)
            dialog.init_dialog("output", self.currPath)
            try:  # output folder dialog
                lx.eval('dialog.open')
            except:
                dialog.init_dialog('cancel', self.currPath)
            else:
                output_dir = lx.eval1('dialog.result ?')
                file.updateExportPath('', '', output_dir)

                file_count = len(files)

                self.progress = dialog.init_progress_bar(
                    file_count, 'Exporting files...')

                self.progression[1] = file_count
                self.progression[0] = 0

                t.set_import_setting()

                for f in files:
                    dialog.processing_log(
                        '.....................................   ' +
                        os.path.basename(f) +
                        '   .....................................')

                    lx.eval('!scene.open "%s" normal' % f)

                    self.scnIndex = lx.eval(
                        'query sceneservice scene.index ? current')

                    helper.select_compatible_item_type()

                    self.userSelection = self.scn.selected
                    self.userSelectionCount = len(self.userSelection)

                    dialog.print_log(
                        '.....................................   ' +
                        str(self.userSelectionCount) +
                        ' mesh item founded   .....................................'
                    )

                    if self.at_least_one_item_selected(exit=False):
                        lx.eval('!scene.close')
                        continue

                    self.filename = os.path.splitext(os.path.basename(f))[0]

                    self.batch_process(output_dir, self.filename)

                    dialog.increment_progress_bar(self, self.progress[0],
                                                  self.progression)

                    helper.revert_initial_parameter(self)

                    lx.eval('!scene.close')

                helper.reset_import_settings(self)

        dialog.init_message(
            'info', 'Done',
            'Operation completed successfully ! %s file(s) exported' %
            self.exportedFileCount)

        helper.open_destination_folder(self, output_dir)

        dialog.ending_log(self)