Main
|
Resume
|
Showreel
|
Blog
|
Script
|
Contact
connexion
go to footer
expand all
|
collapse all
languages
class
All
JScript|XSI
Python|XSI
JScript|WEB
Python|Maya
All
Memo
learning
DDD
php
tool
keyboard tooltips
rig
Toogle joint draw style
- rig - felixlecha
# Toogle the joint draw style, None to joint to_toogle = mc.ls(type='joint') current_value = mc.getAttr(f"{to_toogle[0]}.drawStyle") value = 0 if current_value == 2 else 2 for item in to_toogle: mc.setAttr(f"{item}.drawStyle", value)
Freeze Vertex
- Memo - felixlecha
import maya.cmds as mc mc.polyMoveVertex(lt=[0, 0, 0], ch=False)
learn python 01
- learning - felixlecha
# 2012.11.21 - Learning Scripting Python/Maya session 03 # Create some PolyCube parented in beteween them or not. And Randomize their Transforms. With a UI to launch the Command. # Load Module import maya.cmds as mc import random as rand def create_Random_Object( inName, inType = 'Cube', inNbr = 10, inTrsStr = 10, inRotStr = 10, inParentMode=True ): ''' Create some PolyCube parented in beteween them. And Randomize their Transforms. Arguments : inName : string | The baseName object inType : string | Select the type of PolyMesh inNbr : integer | How many cube you want inTrsStr : float | What strength apply to random Translation inRotStr : float | What strength apply to random Rotation inMode : bolean | Parent Cube in beteween them or not ''' # Create Transform list lTrs = [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz' ] if inParentMode: # Create an empty Parent sParent = None # Create ProgressWindow mc.progressWindow( title='Create Object', progress=0, maxValue=inNbr, status='Create : ', isInterruptable=True ) for i in range( inNbr ): mc.progressWindow( edit=True, progress=i, status='Create : %s_%s_mesh' %(inName, (i+1)) ) # Create Object if inType == 'Sphere': sObj = mc.polySphere( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Cube': sObj = mc.polyCube( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Cylinder': sObj = mc.polyCylinder( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Cone': sObj = mc.polyCone( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Plane': sObj = mc.polyPlane( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Torus': sObj = mc.polyTorus( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Prism': sObj = mc.polyPrism( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Pyramid': sObj = mc.polyPyramid( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Pipe': sObj = mc.polyPipe( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Helix': sObj = mc.polyHelix( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Soccer_Ball': sObj = mc.polyPrimitive( n='%s_%s_mesh' %(inName, (i+1)) )[0] elif inType == 'Platonic_Solids': sObj = mc.polyPlatonicSolid( n='%s_%s_mesh' %(inName, (i+1)) )[0] else : sObj = mc.polyCube( n='%s_%s_mesh' %(inName, (i+1)) )[0] # Set Random Value in Transform for j in range(len(lTrs)): # For Translate : { -0.5, 0.5 } * Strength if j <= 2: mc.setAttr( '%s.%s' %(sObj, lTrs[j]), (rand.random()-0.5)*inTrsStr ) # For Rotate : { 0, 360 } else: mc.setAttr( '%s.%s' %(sObj, lTrs[j]), rand.random()*(36*inRotStr) ) if inParentMode: # If Parent is loaded : Parent to previous PolyCube if sParent: mc.parent( sObj, sParent, relative=False ) # Update Parent sParent = sObj mc.progressWindow( endProgress=True ) mc.warning( 'I create %i PoluCube. Bisous' %inNbr ) def create_Random_Object_Exe( *args ): ''' Execute the "create_Random_Object()" def with the value from "create_Random_Object_UI()" call : create_Random_Object() ''' # Get Values from UI cro_Name = mc.textField( 'cro_name', q=True, tx=True ) cro_Type = mc.optionMenuGrp( 'cro_object_type', q=True, v=True ) cro_Nbr = mc.intSliderGrp( 'cro_nbr', q=True, v=True ) cro_Trs_Str = mc.floatSliderGrp( 'cro_translation_strength', q=True, v=True ) cro_Rot_Str = mc.floatSliderGrp( 'cro_rotate_strength', q=True, v=True ) cro_Mode_P = mc.checkBox( 'cro_mode_parent', q=True, v=True ) create_Random_Object( inName = cro_Name, inType = cro_Type, inNbr = cro_Nbr, inTrsStr = cro_Trs_Str, inRotStr = cro_Rot_Str, inParentMode = cro_Mode_P ) def create_Random_Object_UI(): ''' Interface User to launchthe "create_Random_Object()" def call : create_Random_Object_UI() ''' # Define new Window name sWindow = 'tool' # Test if Window already existe, if is True Delete it if mc.window( sWindow, q=True, ex=True ): mc.deleteUI( sWindow ) # Create Window mc.window( sWindow, t='Create Randomized Objects' ) # Create Layout sLay = mc.columnLayout( columnAttach=('both', 5), rowSpacing=3, adj=True, p = sWindow ) # Create TextField mc.text( label='Base Name ', p=sLay ) mc.textField( 'cro_name', p=sLay, text='newObject', annotation='Define the Base Name of the Object' ) lPolyMesh = ['Sphere','Cube','Cylinder','Cone','Plane','Torus','Prism','Pyramid','Pipe','Helix','Soccer_Ball','Platonic_Solids' ] mc.optionMenuGrp( 'cro_object_type', label='Object Type', p=sLay ) for sPolyMesh in lPolyMesh: mc.menuItem( label = sPolyMesh ) mc.text( label='nObjects ', p=sLay ) mc.intSliderGrp( 'cro_nbr', field=True, minValue=1, value=10, p=sLay, annotation='Define how many objects you want to create' ) mc.separator( style='in' ) mc.text( label='Randomize Settings', p=sLay ) mc.separator( style='out' ) mc.text( label='Translation Strength ', p=sLay ) mc.floatSliderGrp( 'cro_translation_strength', min=-0, max=100, value=10, field=True, p=sLay, annotation='Define the random of the Translation' ) mc.text( label='Rotate Strength ', p=sLay ) mc.floatSliderGrp( 'cro_rotate_strength', min=-0, max=10, value=10, field=True, p=sLay, annotation='Define the random of the Rotate' ) # Create a CheckBox to check the Mode mc.checkBox( 'cro_mode_parent', label='Mode Parent', v=True, p=sLay, annotation='Check to parent in between Object or not' ) # Create Button mc.button( label='CREATE', h=40, w=180, p=sLay, c='create_Random_Object_Exe()', annotation='Create Randomized Objects' ) mc.separator( style='none', height=2 ) # Show Window mc.showWindow( sWindow ) create_Random_Object_UI()
Select shapes selected transforms to edit
- Memo - felixlecha
# Select shapes selected transforms to edit mc.select([item for item in mc.listRelatives(mc.ls(sl= True), s=True, fullPath=True, type='nurbsCurve') or list()])
reOpen
- tool - felixlecha
import maya.cmds as mc current = mc.file(q=True ,sn=True ) if current: mc.file(current, o=True ,f =True ,pmt=False)
display ihi node
- rig - felixlecha
to_skip = ['groupId','shadingEngine','transform', 'groupParts', 'unitConversion', 'objectSet', 'lightLinker'] # Get ihi nodes active hidden result = [item for item in mc.ls('*.ihi', o= True) if mc.getAttr(item +'.ihi') == 0 and not mc.nodeType(item) in to_skip ] # Reset ihi node state to visible for item in result: mc.setAttr('{0}.ihi'.format(item), 2)
MultiCopy Skin
- tool - felixlecha
# MultiCopy Skin import maya.cmds as mc # select all obj to skin like at last the source object selection = mc.ls(sl=True) source_mesh = selection[-1] meshs_to_skin = selection[0:-1] # - Get skinCluster source_skinCluster = mc.ls(mc.listHistory(source_mesh, pdo=1, gl=1), type='skinCluster') [0] # - Get skin joint lJnt = mc.skinCluster( source_skinCluster, query=True, inf=True ) for item in meshs_to_skin: target_skinCluster = mc.skinCluster( lJnt, item, dr=4, tsb=True, nw=1 )[0] mc.copySkinWeights( ss= source_skinCluster, ds= target_skinCluster, nm= False, ia='closestJoint', sa='closestPoint' ) print "done !"
Toogle Control Visibility
- keyboard tooltips - felixlecha
# Toogle Control Visibility import maya.cmds as mc # Get Panel with Focus panel = mc.getPanel( wf = True ) # Check Model Panel if not mc.modelPanel( panel, q = True, ex = True ): panel = mc.getPanel( type = 'modelPanel' )[0] curve_vis = mc.modelEditor( panel, q = True, nurbsCurves = True ) if curve_vis: curve_vis = False else: curve_vis = True mc.modelEditor( panel, e=True, nurbsCurves = curve_vis ) mc.modelEditor(panel, e=True, subdivSurfaces = curve_vis ) mc.modelEditor(panel, e=True, planes = curve_vis ) mc.modelEditor(panel, e=True,lights = curve_vis ) mc.modelEditor(panel, e=True,cameras = curve_vis ) mc.modelEditor(panel, e=True,controlVertices = curve_vis ) mc.modelEditor(panel, e=True,hulls = curve_vis ) mc.modelEditor(panel, e=True,joints = curve_vis ) mc.modelEditor(panel, e=True,ikHandles = curve_vis ) mc.modelEditor(panel, e=True,deformers = curve_vis ) mc.modelEditor(panel, e=True,dynamics = curve_vis ) mc.modelEditor(panel, e=True,fluids= curve_vis ) mc.modelEditor(panel, e=True,hairSystems= curve_vis ) mc.modelEditor(panel, e=True,follicles= curve_vis ) mc.modelEditor(panel, e=True,nCloths= curve_vis ) mc.modelEditor(panel, e=True,nParticles= curve_vis ) mc.modelEditor(panel, e=True,nRigids= curve_vis ) mc.modelEditor(panel, e=True,dynamicConstraints= curve_vis ) mc.modelEditor(panel, e=True,locators= curve_vis ) mc.modelEditor(panel, e=True,dimensions= curve_vis ) mc.modelEditor(panel, e=True,handles= curve_vis ) mc.modelEditor(panel, e=True,pivots= curve_vis ) mc.modelEditor(panel, e=True,textures= curve_vis ) mc.modelEditor(panel, e=True,strokes= curve_vis )
HUD_Camera_Speed
- tool - felixlecha
import maya.cmds as mc from functools import partial from math import sqrt def show_speed( cam_obj, *args ): ''' Calculate and return camera speed ''' if not cam_obj: cam_obj= 'persp' # - Get current time i_time = mc.currentTime( q=True ) # - Get Camera position pos_current= mc.getAttr( cam_obj +'.translate')[0] # at current frame pos_previous= mc.getAttr( cam_obj +'.translate', time= i_time-1)[0] # at previous frame # - Calculate distance delta= (pos_current[0] - pos_previous[0]) + (pos_current[1] - pos_previous[1]) + (pos_current[2] - pos_previous[2]) # - Convert to km/h delta= sqrt( delta **2 )* 86400 / 1000 return str(int(round( delta ))) + ' km/h' # - Create HUD sel= mc.ls( sl= True ) if sel: cam_select= sel[0] else: cam_select= None mc.headsUpDisplay( 'HUD_Camera_speed', section= 7, block=0, blockSize='medium', label= '', labelFontSize= 'large', command= partial( show_speed, cam_select ), event= 'timeChanged' ) # - Remove HUD mc.headsUpDisplay( 'HUD_Camera_speed', rem=True )
Demo Vector 2D Class
- learning - felixlecha
# Demo Vector 2D Class import maya.cmds as mc class Vector2D(): ''' Create and Manage 2d Vector ''' def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return str( [self.x, self.y ] ) def __repr__(self): return str( [self.x, self.y ] ) def __add__( self, b ): type_b = self.var_type( b ) if type_b == 'Vector2D': return vector2D( x=self.x + b.x, y= self.y + b.y ) elif type_b == 'Number': return vector2D( x=self.x + b, y= self.y + b ) else: return None def var_type(self, b): ''' get the input type ''' if type(b).__name__ == 'instance': if b.__class__.__name__ is 'Vector2D': return 'Vector2D' elif type(b).__name__ in ['float', 'int']: return 'Number' else: return 'Unsupport' def reset( self, mode= 'script' ): self.x = 0 self.y = 0 if mode == 'menu': mc.inViewMessage( msg= 'Your vector is
reset
now !!!', fade=2 ) # init Some vectors vA = vector2D( x=1, y=3 ) vB = vector2D( x=6, y=2 ) # Print print vA.x print vA.y # Add vector + vector vC = vA + vB # Add vector + integer vD = vA + 2 # Reset vC.reset() vD.reset( mode= 'menu' )
Remove Turtle node
- All - felixlecha
import maya.cmds as mc mc.lockNode( 'TurtleDefaultBakeLayer', lock=False ) mc.delete('TurtleDefaultBakeLayer')
unknowNodes_remove
- tool - felixlecha
import maya.cmds as mc def unknowNodes_remove(): ''' Remove unknow and noReferenced nodes :return: none ''' # --- Get unknow node unknown_node = mc.ls( type= [ 'unknown', 'unknownDag', 'unknownTransform'] ) # --- Delete only noReferenced node delete_node= list() for node in unknown_node: if mc.objExists( node ): if not mc.referenceQuery( node, isNodeReferenced= True ): delete_node.append( node ) mc.delete( node ) print str(len(delete_node)) +' Unknow node deleted :' + ' '.join(delete_node)
transfert_UV
- tool - felixlecha
import maya.cmds as mc #---------------------------------------------------------------------- def transfert_UV( source, target, sourceUvSpace= 'map1', targetUvSpace= 'map1' ): ''' Transfer UV from one Geo to a Other rigged or not, without add history ;) :param source: the object source UV name :type source: string :param target: the object target name :type target: string ''' # --- Get the Orig shape of target shapes= mc.listRelatives( target, s= True ) # --- Set the mode to No intermediate by default intermediate= False # --- If multiple shape search intermediate shape if len(shapes) > 1: if mc.getAttr( shapes[1] +'.intermediateObject' ) and 'Orig' in shapes[1]: # Turn intermediate mode Active intermediate= True # Overwrite target by this intermediate shape target= shapes[1] # Turn the Intermediate Object to False mc.setAttr( target +'.intermediateObject', False) else: return # --- Transfer UV mc.transferAttributes( source, target, transferPositions= False, transferNormals= False, transferUVs= 2, transferColors= 2, sampleSpace= 4, sourceUvSpace= sourceUvSpace, targetUvSpace= targetUvSpace, searchMethod= 3, flipUVs= False, colorBorders= True ) # --- Delete Construction History on target mc.delete( target, constructionHistory=True) # --- Toggle the Intermediate Object to True if intermediate: mc.setAttr( target +'.intermediateObject', True ) print ' > UV successfully transferred to target mesh' # --- Get selection selection = mc.ls(selection=True) transfert_UV( source= selection[0], target= selection[1] )
manage Set
- tool - felixlecha
#---------------------------------------------------------------------- def manageSet( mode ): ''' Manage Set Select object to manage and select last the set ''' # Get Selection and filter cSel = mc.ls(sl= True) set= cSel[-1] # Test if set is a set items= cSel[0:-1] if mode == 'REMOVE': # Remove object from a set mc.sets( items, rm= set ) elif mode == 'ADD': # Add to Set mc.sets( items, fe= set ) manageSet( mode= 'ADD' ) manageSet( mode= 'REMOVE' )
Get skin jnt and reBuild
- tool - felixlecha
lJnt = mc.skinCluster( 'cape_skinCluster', query=True, inf=True ) meshToSkin = mc.ls(sl=True)[0] mc.skinCluster( lJnt, meshToSkin, dr=4 )
Base Renamer
- tool - felixlecha
# --- Simple Renamer import maya.cmds as mc prefix = '' suffix = '_jnt' search = '' replace = '' cSelection = mc.ls(sl= True ) for item in cSelection: # - Get base name if '|' in item: name = item.split('|')[-1] else: name = item # - Search and Replace if search: name = name.replace( search, replace ) # - Prefix if prefix: name = prefix + name # - Suffix if suffix: name = name + suffix # - Cancel if new name already exist in scene if mc.objExists( name ): print name +' already exist. '+ item +" wasn't rename" continue # - Rename mc.rename( item, name )
create_orig_on_selected()
- tool - felixlecha
# ------------------------------------- # Create orig on selected objects # ------------------------------------- import maya.cmds as mc def create_orig_on_selected(): '''''' # Get Current selection cSelection = mc.ls( sl = True ) for sSel in cSelection: # Get Parent s_parent = mc.listRelatives( sSel, p= True ) if s_parent: s_parent= s_parent[0] # Get current Obj Transform lPos_Sel = mc.xform( sSel, q=True, t=True, ws=True ) lRot_Sel = mc.xform( sSel, q=True, ro=True, ws=True ) # Create a group sGroup = mc.group( em=True, name= sSel + '_orig' ) # Set in place mc.xform( sGroup, a=True, t=lPos_Sel, ro=lRot_Sel, s=[1,1,1] ) # Parent current to orig Group mc.parent( sSel, sGroup, relative= False ) # reParent group to original parent if s_parent: mc.parent( sGroup, s_parent, relative= False ) create_orig_on_selected()
DeletePropertyonSelectedGeometry()
- tool - felixlecha
function DeletePropertyonSelectedGeometry() { var cSel = GetValue("SelectionList"); var oProperty, sProperty, sLog; sProperty = "CrosswalkProps" sLog = "Log : " // Init ProgressBar var oProgressBar = XSIUIToolkit.progressbar; var iPBMax = cSel.count; var iProgress = 0; var iCountLoop = 0; oProgressBar.maximum = iPBMax; oProgressBar.visible = true; oProgressBar.caption = "Delete property on Selected Geometry"; for ( var i = 0; i < cSel.count && !oProgressBar.cancelpressed; i++ ) { // Round Progress Value iCountLoop ++; iProgress = Math.round( iCountLoop / iPBMax * 100 ); oProgressBar.statustext = oProgressBar.statustext = iProgress + "%"; oProgressBar.increment(); if( cSel(i).Type == "polymsh" ) { if( cSel(i).Properties( sProperty ) ) { oProperty = cSel(i).Properties( sProperty ); DeleteObj( oProperty ); sLog = sLog + "\n" + " Property deleted on " + cSel(i); } } else { // Do nothing } } // Hide ProgressBar oProgressBar.visible = false; LogMessage( sLog ); } DeletePropertyonSelectedGeometry();
refresh/collapse ouliner
- keyboard tooltips - felixlecha
import maya.cmds as mc outliner = 'outlinerPanel1' mc.outlinerEditor( outliner, edit=True, sortOrder='dagName' ) mc.evalDeferred( "mc.outlinerEditor( outliner, edit=True, sortOrder='none' )")
Add circle Shape
- tool - felixlecha
def add_circleShape( inJoint, size=1 ): ''' Add a circle shape on in Joint inJoint : string, the name of the joint size : float, define the size of the shape ''' lNCircle = mc.circle( nr=(1, 0, 0), r=size ) mc.delete( lNCircle, constructionHistory= True ) sShape = mc.listRelatives(lNCircle[0], s=True) mc.parent( sShape[0], inJoint, s=True, r=True ) mc.rename( sShape[0], '%sShape' %(inJoint) ) mc.delete( lNCircle[0] ) cSelection = mc.ls(sl=True) for sSel in cSelection: add_circleShape( sSel, size=1)
reset All
- keyboard tooltips - felixlecha
# Reset All Transform on selected Objects import maya.cmds as mc def ch4_ResetSelection(): ''' Reset All Transform on selected Objects ''' # Get Current selection cSelection = mc.ls( sl = True ) if not cSelection: return for sSel in cSelection: mc.xform( sSel, a=True, t=[0,0,0], ro=[0,0,0], s=[1,1,1] ) ch4_ResetSelection()
rivet
- tool - felixlecha
import maya.cmds as mc import re def ch4_rivet( name='rivet' ): ''' Launch build rivet for between given edges or on each given faces name : string > to define the rivet name ''' #--- Load needed plugin load_plugin( toLoad= ['rotateHelper', 'matrixNodes' ] ) #--- Get subComponent Selection sels = mc.ls(sl=True) #--- keep only edges and faces edges = mc.filterExpand(sels, sm=32) or [] faces = mc.filterExpand(sels, sm=34) or [] #--- Launch Build if len(edges) == 2 : #--- Create a rivet inbetween to edges ch4_build_rivet(name, edges[0], edges[1]) elif faces : for face in faces: #--- Create a rivet for each face selected edges = ch4_convert_face_to_edges(face) print(edges) ch4_build_rivet(name, edges[0], edges[1]) else: print('select 2 edges or faces to build rivet') def load_plugin( toLoad= list() ): ''' Check if the needed plugin already load. if not loaded, load and autoload check for the plugin :param toLoad: A list of the plugin name to load. :type toLoad: list ''' # Get the plugin already loaded plugin_loaded = mc.pluginInfo( query=True, listPlugins=True ) for plugin in toLoad: # Check if the plugin wasn't already load if not plugin in plugin_loaded: # Load plugin mc.loadPlugin( plugin ) # autoLoad plugin if not mc.pluginInfo( plugin, query=True, autoload=True ): mc.pluginInfo( plugin, edit=True, autoload=True ) def ch4_convert_face_to_edges(face): ''' For a given face return two uncontinus edges face : string > the full face name ''' #--- convert face to edges edges = mc.ls( mc.polyListComponentConversion( face, ff=True, te=True ), fl=True ) #--- For 3edges Faces return the 2 first edges if len(edges) == 3: return [edges[0], edges[1]] #--- Create a vertex set with the first edge setEdgeA = set(mc.ls(mc.polyListComponentConversion(edges[0], fe=True, tv=True), fl=True)) #--- Search an edge without commun vertex for i in range( 1, len(edges) ): setEdgeB = set(mc.ls(mc.polyListComponentConversion(edges[i], fe=True, tv=True), fl=True)) if not setEdgeA & setEdgeB: #--- return uncontinus edges return [edges[0], edges[i]] def ch4_build_rivet(name, edgeA, edgeB): ''' Build a rivet between two given edges Edges can be from different mesh returns the created rivet name name : string > to define the rivet name edgeA : string > the full edge name edgeB : string > the full edge name ''' #--- init objA = edgeA.split('.')[0] objB = edgeB.split('.')[0] #--- Create Locator Rivet rivet = mc.spaceLocator(n=name)[0] #--- Create nodes nodes = [] nodes.append( mc.createNode('curveFromMeshEdge', n= rivet + '_%s_Crv' %(objA)) ) # 0 nodes.append( mc.createNode('curveFromMeshEdge', n= rivet + '_%s_Crv' %(objB)) ) # 1 nodes.append( mc.createNode('loft', n= rivet + '_loft') ) # 2 nodes.append( mc.createNode('pointOnSurfaceInfo', n= rivet + 'pointOnSurfaceInfo') ) # 3 nodes.append( mc.createNode('rotateHelper', n= rivet + '_rotateHelper') ) # 4 nodes.append( mc.createNode('decomposeMatrix', n= rivet + '_decomposeMatrix') ) # 5 #--- Set Nodes Connections #- Crv 1 mc.setAttr( nodes[0] + '.ei[0]', int(re.findall('\d+', edgeA)[-1])) mc.connectAttr( objA + '.w', nodes[0] + '.im', f=True) #- Crv 2 mc.setAttr( nodes[1] + '.ei[0]', int(re.findall('\d+', edgeB)[-1])) mc.connectAttr( objB + '.w', nodes[1] + '.im', f=True) #- Loft mc.setAttr( nodes[2] + '.ic', size=2) mc.setAttr( nodes[2] + '.u', True) mc.setAttr( nodes[2] + '.rsn', True) mc.connectAttr( nodes[0] + '.oc', nodes[2] + '.ic[0]', f=True) # COnnect Crv 1 to Loft mc.connectAttr( nodes[1] + '.oc', nodes[2] + '.ic[1]', f=True) # COnnect Crv 2 to Loft #- Point on surface info mc.setAttr( nodes[3] + '.turnOnPercentage', True) mc.connectAttr( nodes[2] + '.os', nodes[3] + '.is', f=True) # Connect Loft to Point on Surface Info #- Get Rotate mc.connectAttr( nodes[3] + '.normal', nodes[4] + '.up' ) # Connect PtsOnSurface normal to rotateHelper mc.connectAttr( nodes[3] + '.tangentV', nodes[4] + '.forward' ) # Connect PtsOnSurface tangentv to rotateHelper mc.connectAttr( nodes[4] + '.rotateMatrix', nodes[5] + '.inputMatrix' ) # Connect rotateHelper to decomposeMatrix #--- Drive Rivet mc.connectAttr( nodes[3] + '.positionX', rivet + '.translateX' ) mc.connectAttr( nodes[3] + '.positionY', rivet + '.translateY' ) mc.connectAttr( nodes[3] + '.positionZ', rivet + '.translateZ' ) mc.connectAttr( nodes[5] + '.outputRotateX', rivet + '.rotateX' ) mc.connectAttr( nodes[5] + '.outputRotateY', rivet + '.rotateY' ) mc.connectAttr( nodes[5] + '.outputRotateZ', rivet + '.rotateZ' ) #--- Add Ctrl attributes to rivet mc.addAttr(rivet, ln='posU', at='float', min=.0, max=1.0, dv=.5, k=True) mc.addAttr(rivet, ln='posV', at='float', min=.0, max=1.0, dv=.5, k=True) mc.connectAttr( rivet + '.posU', nodes[3] + '.parameterU', f=True) mc.connectAttr( rivet + '.posV', nodes[3] + '.parameterV', f=True) #--- Historical intereset for node in nodes : mc.setAttr( node + '.ihi', 0) mc.setAttr( rivet + 'Shape.ihi', 0) #--- Clean for attr in ['t', 'r', 's'] : for axis in ['x', 'y', 'z'] : mc.setAttr('%s.%s%s' %(rivet, attr, axis), k=False) for axis in ['X', 'Y', 'Z'] : mc.setAttr('%sShape.localPosition%s' %(rivet, axis), k=False, cb=False) ch4_rivet()
ch4_Bake_Selected_UI()
- tool - felixlecha
import maya.cmds as mc ''' author : felixlechA - Bake selected object animation on a locator and reApply animation on object - Copy selected object animation on a locator and paste animation on object - Snapshot the current pose of selected obj on a locator ''' #------------------------------------------------------------------------------ # Commun def #------------------------------------------------------------------------------ def ch4_CheckCreate_Group( sName ): ''' Check if a group exist and Create it if not exist --- sGroupName : string | Define the name of Group to check existance ''' # Test if RIG_TRASH exist bRT_Exist = mc.objExists(sName) # If not Exist we create it if not bRT_Exist: mc.group( em=True, name=sName ) return sName def ch4_CreateLocator( sName=None, sParent=None, ws=False, lPos=[0,0,0], lRot=[0,0,0], lScl=[1,1,1] ): ''' Create Locator --- sName : string | The Locator Name sParent : string | The Parent name lPos : list | [0,0,0] A three input list define the Translation lRot : list | [0,0,0] A three input list define the Rotation lScl : list | [1,1,1] A three input list define the Scale ''' sCurrent = mc.spaceLocator() mc.xform( sCurrent, ws=ws, t=lPos, ro=lRot, s=lScl ) if sParent: mc.parent( sCurrent, sParent ) if sName: mc.rename(sCurrent, sName ) mc.setAttr( sName + '.v', lock=True, keyable=False, channelBox=False ) return sName def ch4_GetTransform( inObj ): ''' Get the transform of the input object and return Transform in a dictionnary ''' dDict = dict() dDict['pos'] = mc.xform( inObj, q=True, ws=True, t=True ) dDict['rot'] = mc.xform( inObj, q=True, ws=True, ro=True ) dDict['scl'] = mc.xform( inObj, q=True, s=True, r=True ) return dDict def ch4_SetTransform( inObj, ws=False, lPos=[0,0,0], lRot=[0,0,0], lScl=[1,1,1] ): ''' Set transform, by default reset Transform ''' mc.xform( inObj, ws=ws, t=lPos, ro=lRot, s=lScl ) return inObj def ch4_Match_To_Target( inObj, inTarget, ws=True, bTranslate=True, bRotate=True, bScale=True): ''' Match inObj to inTarget ''' dTrans_Target = ch4_GetTransform( inTarget ) if bTranslate: dTrans_Object = ch4_GetTransform( inObj ) ch4_SetTransform( inObj, ws=ws, lPos=dTrans_Target['pos'], lRot=dTrans_Object['rot'], lScl=dTrans_Object['scl'] ) if bRotate: dTrans_Object = ch4_GetTransform( inObj ) ch4_SetTransform( inObj, ws=ws, lPos=dTrans_Object['pos'], lRot=dTrans_Target['rot'], lScl=dTrans_Object['scl'] ) if bScale: dTrans_Object = ch4_GetTransform( inObj ) ch4_SetTransform( inObj, ws=ws, lPos=dTrans_Object['pos'], lRot=dTrans_Object['rot'], lScl=dTrans_Target['scl'] ) return inObj def ch4_SetKeyFrame( inObj, bTranslate=True, bRotate=True, bScale=True ): ''' Key Flag Transform ''' if bTranslate: mc.setKeyframe( inObj, at='translate' ) if bRotate: mc.setKeyframe( inObj, at='rotate' ) if bScale: mc.setKeyframe( inObj, at='scale' ) return inObj def ch4_Bake_Obj(obj, time=None, merge_anim=False): ''' bake given obeject over time. obj : list() time : (int, int) ''' #--- filter list to bake obj = list(set(obj)-set([None])) #--- get time range if not time : time = (mc.playbackOptions(q=True, min=True), mc.playbackOptions(q=True, max=True)) #ch4_Get_Selected_Anim_Range() all_layers = mc.ls(type = 'animLayer') or list() mc.refresh(su=True) if merge_anim : if len(all_layers)>1 : print '--- MERGE ANIM LAYER : %s'%all_layers mergeAnimLayers(items=all_layers) mc.bakeResults( obj, t=time, sampleBy=1 ,simulation=True , disableImplicitControl=True, preserveOutsideKeys=False, sparseAnimCurveBake=False, removeBakedAttributeFromLayer=False, bakeOnOverrideLayer=False, minimizeRotation=True,controlPoints=False,shape=True) mc.refresh(su=False) def ch4_copy_key( source, target, attribut=None ): ''' ''' if not attribut: mc.copyKey( source ) else: mc.copyKey( source, at=attribut ) mc.pasteKey( target, o='replace') #------------------------------------------------------------------------------ # Bake Animation in WS #------------------------------------------------------------------------------ def ch4_Animation_Bake_Copy_exe(*args): ''' Bake the animation of selected obj on a locator in WS ''' sLog = '[^^] Bake Selected' # Get Current selection cSelection = mc.ls( sl = True ) # If selection is empty abord if not cSelection: sLog = '[^^] Selection is empty !\n > Select some ctrls to bake on a locator' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Create a new group to Store the Objects sRoot = ch4_CheckCreate_Group( 'BAKE_ANIM_TRASH' ) for sSel in cSelection: # Rename to remove NameSpace sName = str(sSel).replace( ':', '_0_' ) # Create locator # Test if locator already exist bBake_Obj_Exist = mc.objExists('bake___' + sName ) # If not Exist we create it sLocator = 'bake___' + sName if not bBake_Obj_Exist: ch4_CreateLocator( sName=sLocator ,sParent = sRoot) else: mc.cutKey( sLocator ) # Create Cstr sScale_Cstr = mc.scaleConstraint( sSel, sLocator ) sParent_Cstr = mc.parentConstraint( sSel, sLocator ) # Bake Locator ch4_Bake_Obj( [sLocator] ) # Remove Cstr mc.delete( sScale_Cstr ) mc.delete( sParent_Cstr ) sLog = sLog + '\n > %s was bake on a locator' %(sSel) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) def ch4_Animation_Bake_Paste_call(*args): ''' ''' # Get Values from UI bBakeMode_T = mc.checkBox( 'cb_BakeMode_T', q=True, v=True ) bBakeMode_R = mc.checkBox( 'cb_BakeMode_R', q=True, v=True ) bBakeMode_S = mc.checkBox( 'cb_BakeMode_S', q=True, v=True ) ch4_Animation_Bake_Paste_exe( bT=bBakeMode_T, bR=bBakeMode_R, bS=bBakeMode_S ) def ch4_Animation_Bake_Paste_exe( bT=True, bR=True, bS=True ): ''' ''' sLog = '[^^] Reapply Bake on Object :' # Test if no Transform are checked if not bT and not bR and not bS: sLog = sLog + 'No transform checked' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Test if the group exist bBake_Grp_Exist = mc.objExists( 'BAKE_ANIM_TRASH' ) if not bBake_Grp_Exist: sLog = sLog + ' > No Object found to Bake' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return lBake_Locator = mc.listRelatives( 'BAKE_ANIM_TRASH', c=True, type='transform' ) lAttribute = [] if bT: lAttribute = lAttribute + [ 'translateX', 'translateY', 'translateZ' ] if bR: lAttribute = lAttribute + [ 'rotateX', 'rotateY', 'rotateZ' ] if bS: lAttribute = lAttribute + [ 'scaleX', 'scaleY', 'scaleZ' ] for sLocator in lBake_Locator: sName = sLocator sName = str(sName).replace( 'bake___', '' ) sName = str(sName).replace( '_0_', ':' ) # Test if the group exist bObj_Exist = mc.objExists( sName ) if not bObj_Exist or not 'bake___' in sLocator: if 'bake___' in sLocator: sLog = sLog + '\n > No object corresponding to %s was found' %(sName) pass else: mc.cutKey( sName , attribute = lAttribute, option='keys' ) # Create Cstr if bS: sScale_Cstr = mc.scaleConstraint( sLocator, sName ) if bT and bR: sParent_Cstr = mc.parentConstraint( sLocator, sName ) elif bT and not bR: sParent_Cstr = mc.parentConstraint( sLocator, sName, sr=['x','y','z'] ) elif not bT and bR: sParent_Cstr = mc.parentConstraint( sLocator, sName, st=['x','y','z'] ) # Bake Object ch4_Bake_Obj( [sName] ) # Remove Cstr if bS: mc.delete( sScale_Cstr ) if bT or bR: mc.delete( sParent_Cstr ) sLog = sLog + '\n > %s was bake based on the locator' %(sName) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) #------------------------------------------------------------------------------ # Copy Paste Animation #------------------------------------------------------------------------------ def ch4_Animation_Copy_exe(*args): ''' Copy the animation of selected obj on a locator ''' sLog = '[^^] Bake Selected' # Get Current selection cSelection = mc.ls( sl = True ) # If selection is empty abord if not cSelection: sLog = '[^^] Selection is empty !\n > Select some ctrls to Copy Animation on a locator' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Create a new group to Store the Objects sRoot = ch4_CheckCreate_Group( 'BAKE_ANIM_TRASH' ) for sSel in cSelection: # Rename to remove NameSpace sName = str(sSel).replace( ':', '_0_' ) # Create locator # Test if locator already exist bAnim_Obj_Exist = mc.objExists('anim___' + sName ) # If not Exist we create it sLocator = 'anim___' + sName if not bAnim_Obj_Exist: ch4_CreateLocator( sName=sLocator ,sParent = sRoot) else: mc.cutKey( sLocator ) #--- Copy Anim on Locator ch4_copy_key( source=sSel, target=sLocator ) sLog = sLog + '\n > %s animation was copy on a locator' %(sSel) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) def ch4_Animation_Paste_call(*args): ''' ''' # Get Values from UI bAnimMode_T = mc.checkBox( 'cb_AnimMode_T', q=True, v=True ) bAnimMode_R = mc.checkBox( 'cb_AnimMode_R', q=True, v=True ) bAnimMode_S = mc.checkBox( 'cb_AnimMode_S', q=True, v=True ) ch4_Animation_Paste_exe( bT=bAnimMode_T, bR=bAnimMode_R, bS=bAnimMode_S ) def ch4_Animation_Paste_exe( bT=True, bR=True, bS=True ): ''' ''' sLog = '[^^] Paste Animation on Object :' # Test if no Transform are checked if not bT and not bR and not bS: sLog = sLog + 'No transform checked' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Test if the group exist bBake_Grp_Exist = mc.objExists( 'BAKE_ANIM_TRASH' ) if not bBake_Grp_Exist: sLog = sLog + ' > No Object found to paste animation' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return lBake_Locator = mc.listRelatives( 'BAKE_ANIM_TRASH', c=True, type='transform' ) lAttribute = [] if bT: lAttribute = lAttribute + [ 'translateX', 'translateY', 'translateZ' ] if bR: lAttribute = lAttribute + [ 'rotateX', 'rotateY', 'rotateZ' ] if bS: lAttribute = lAttribute + [ 'scaleX', 'scaleY', 'scaleZ' ] for sLocator in lBake_Locator: sName = sLocator sName = str(sName).replace( 'anim___', '' ) sName = str(sName).replace( '_0_', ':' ) # Test if the obj exist bObj_Exist = mc.objExists( sName ) if not bObj_Exist or not 'anim___' in sLocator: if 'anim___' in sLocator: sLog = sLog + '\n > No object corresponding to %s was found' %(sName) pass else: print lAttribute mc.cutKey( sName , attribute = str(lAttribute), option='keys' ) print 'delete keys' ch4_copy_key( source=sLocator, target=sName, attribut=lAttribute ) sLog = sLog + '\n > %s animation was paste based on the locator' %(sName) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) #------------------------------------------------------------------------------ # SnapShot pose #------------------------------------------------------------------------------ def ch4_Pose_Copy_exe(*args): ''' Snapshot the current pose of selected obj on a locator ''' sLog = '[^^] SnapShot Pose Selected' # Get Current selection cSelection = mc.ls( sl = True ) # If selection is empty abord if not cSelection: sLog = '[^^] Selection is empty !\n > Select some ctrls to SnapShot Pose on a locator' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Create a new group to Store the Objects sRoot = ch4_CheckCreate_Group( 'BAKE_ANIM_TRASH' ) for sSel in cSelection: # Rename to remove NameSpace sName = str(sSel).replace( ':', '_0_' ) # Create locator # Test if locator already exist bPlot_Obj_Exist = mc.objExists('pose___%s' %(sName)) # If not Exist we create it sLocator = 'pose___%s' %(sName) if not bPlot_Obj_Exist: ch4_CreateLocator( sName=sLocator ,sParent = sRoot) else: mc.cutKey( sLocator ) # Create Cstr sScale_Cstr = mc.scaleConstraint( sSel, sLocator ) sParent_Cstr = mc.parentConstraint( sSel, sLocator ) # Key Locator mc.setKeyframe( sLocator ) # Remove Cstr mc.delete( sScale_Cstr ) mc.delete( sParent_Cstr ) sLog = sLog + '\n > %s pose was SnapShot on a locator' %(sSel) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) def ch4_Pose_Paste_call(*args): ''' ''' # Get Values from UI bPoseMode_T = mc.checkBox( 'cb_PoseMode_T', q=True, v=True ) bPoseMode_R = mc.checkBox( 'cb_PoseMode_R', q=True, v=True ) bPoseMode_S = mc.checkBox( 'cb_PoseMode_S', q=True, v=True ) ch4_Pose_Paste_exe( bT=bPoseMode_T, bR=bPoseMode_R, bS=bPoseMode_S ) def ch4_Pose_Paste_exe( bT=True, bR=True, bS=True ): ''' ''' sLog = '[^^] Reapply Pose on Object :' # Test if no Transform are checked if not bT and not bR and not bS: sLog = sLog + 'No transform checked' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return # Test if the group exist bBake_Grp_Exist = mc.objExists( 'BAKE_ANIM_TRASH' ) if not bBake_Grp_Exist: sLog = sLog + ' > No Object found to paste' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=2.0 ) return lPose_Locator = mc.listRelatives( 'BAKE_ANIM_TRASH', c=True, type='transform' ) lAttribute = [] if bT: lAttribute = lAttribute + [ 'translateX', 'translateY', 'translateZ' ] if bR: lAttribute = lAttribute + [ 'rotateX', 'rotateY', 'rotateZ' ] if bS: lAttribute = lAttribute + [ 'scaleX', 'scaleY', 'scaleZ' ] for sLocator in lPose_Locator: sName = sLocator sName = str(sName).replace( 'pose___', '' ) sName = str(sName).replace( '_0_', ':' ) # Test if the group exist bObj_Exist = mc.objExists( sName ) if not bObj_Exist or not 'pose___' in sLocator: if 'pose___' in sLocator: sLog = sLog + '\n > No object corresponding to %s was found' %(sName) pass else: # Match Object to Target ch4_Match_To_Target( sName, sLocator, ws=True, bTranslate=bT, bRotate=bR, bScale=bS) # Key Object ch4_SetKeyFrame( inObj=sName, bTranslate=bT, bRotate=bR, bScale=bS ) sLog = sLog + '\n > %s was key based on the locator' %(sName) # Print log print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) #------------------------------------------------------------------------------ # Clean System #------------------------------------------------------------------------------ def ch4_Clean_System_exe(*args): ''' Remove the Bake Anim Object to clean the scene ''' sLog = '[^^] Clean Bake System :' # Test if the group exist bBake_Grp_Exist = mc.objExists( 'BAKE_ANIM_TRASH' ) if bBake_Grp_Exist: mc.delete( 'BAKE_ANIM_TRASH' ) sLog = sLog + '\n > BAKE_ANIM_TRASH Remove' else: sLog = sLog + '\n > scene already clean :)' print( sLog ) mc.headsUpMessage( sLog, verticalOffset=350, time=5.0 ) #------------------------------------------------------------------------------ # UI #------------------------------------------------------------------------------ def ch4_Bake_Selected_UI(): ''' Interface UI ''' # Define new Window name sWindow = 'Bake_Animation_Tool' # Test if Window already existe, if is True Delete it if mc.window( sWindow, q=True, ex=True ): mc.deleteUI( sWindow ) # Create Window mc.window( sWindow, t='Bake Animation on Selected' ) # Create Layout sLay = mc.columnLayout( columnAttach=('both', 5), rowSpacing=3, adj=True, p = sWindow ) mc.frameLayout(bs='etchedIn', mh=5, mw=5, bgc=[0.26, 0.65, 0.24], l='Animation in WS', cll=True) mc.button( label='Bake', h=30, w=180, c=ch4_Animation_Bake_Copy_exe, annotation='Bake the animation of selected obj on a locator in WS' ) mc.rowLayout( numberOfColumns=3 ) mc.checkBox( 'cb_BakeMode_T', label='Translate', v=True ) mc.checkBox( 'cb_BakeMode_R', label='Rotate', v=True ) mc.checkBox( 'cb_BakeMode_S', label='Scale', v=True ) mc.setParent('..') mc.button( label='Apply', h=30, w=180, c=ch4_Animation_Bake_Paste_call, annotation='reApply locator baked animation on corresponding object in WS' ) mc.setParent('..') mc.separator( style='none', height=5 ) mc.frameLayout(bs='etchedIn', mh=5, mw=5, bgc=[0.26, 0.65, 0.24], l='Animation', cll=True, cl=True) mc.button( label='Copy', h=30, w=180, c=ch4_Animation_Copy_exe, annotation='Copy the animation of selected obj on a locator' ) mc.rowLayout( numberOfColumns=3 ) mc.checkBox( 'cb_AnimMode_T', label='Translate', v=True ) mc.checkBox( 'cb_AnimMode_R', label='Rotate', v=True ) mc.checkBox( 'cb_AnimMode_S', label='Scale', v=True ) mc.setParent('..') mc.button( label='Paste', h=30, w=180, c=ch4_Animation_Paste_call, annotation='reApply locator animation on corresponding object' ) mc.setParent('..') mc.separator( style='none', height=5 ) mc.frameLayout(bs='etchedIn', mh=5, mw=5, bgc=[0.9, 0.4, 0.1], l='Pose in WS', cll=True) mc.button( label='Copy', h=30, w=180, c=ch4_Pose_Copy_exe, annotation='Snapshot the current pose of selected obj on a locator in WS' ) mc.rowLayout( numberOfColumns=3 ) mc.checkBox( 'cb_PoseMode_T', label='Translate', v=True ) mc.checkBox( 'cb_PoseMode_R', label='Rotate', v=True ) mc.checkBox( 'cb_PoseMode_S', label='Scale', v=True ) mc.setParent('..') mc.button( label='Paste', h=30, w=180, c=ch4_Pose_Paste_call, annotation='reApply pose on corresponding object at the current frame in WS' ) mc.setParent('..') mc.separator( style='none', height=5 ) mc.button( label='Clean Scene', h=40, w=180, c=ch4_Clean_System_exe, annotation='Remove the Bake Anim Object to clean the scene' ) mc.separator( style='none', height=2 ) # Show Window mc.showWindow( sWindow ) ch4_Bake_Selected_UI()
DeleteAllClustersonSelectedGeometry()
- tool - felixlecha
function DeleteAllClustersonSelectedGeometry() { var cSel = GetValue("SelectionList"); var oClusters, iDelCls, sLog; sLog = "Log : " // Init ProgressBar var oProgressBar = XSIUIToolkit.progressbar; var iPBMax = cSel.count; var iProgress = 0; var iCountLoop = 0; oProgressBar.maximum = iPBMax; oProgressBar.visible = true; oProgressBar.caption = "Delete All Clusters on Selected Geometry"; for ( var i = 0; i < cSel.count && !oProgressBar.cancelpressed; i++ ) { // Round Progress Value iCountLoop ++; iProgress = Math.round( iCountLoop / iPBMax * 100 ); oProgressBar.statustext = oProgressBar.statustext = iProgress + "%"; oProgressBar.increment(); if( cSel(i).Type == "polymsh" ) { oClusters = cSel(i).ActivePrimitive.Geometry.Clusters; iDelCls = 0; for ( var j = 0; j < oClusters.count ; j++ ) { DeleteObj( cSel(i) + ".polymsh.cls." + oClusters(j).Name ); iDelCls++; } sLog = sLog + "\n" + iDelCls + " Cluster(s) deleted on " + cSel(i); } else { // Do nothing } } // Hide ProgressBar oProgressBar.visible = false; LogMessage( sLog ); } DeleteAllClustersonSelectedGeometry();
Softimage_CurrentVersion()
- All - felixlecha
function Softimage_CurrentVersion() { var sCurrentVersion = Application.Version().split(".") var sXSIversion = parseFloat(sCurrentVersion[0]+"."+sCurrentVersion[1]); if( sXSIversion >= 9.5 ) { LogMessage( "Current Version is : Softimage " + sXSIversion ); } else { LogMessage( "Current version is older than 2011.5" ); } }
NormalizeWeights
- All - felixlecha
NormalizeWeights(); function NormalizeWeights() { SetValue("preferences.scripting.cmdlog", false, null); var aSel = new Array(); aSel = getValue("SelectionList"); if( aSel.Count >= 1) { for( var i = 0; i < aSel.Count; i++ ) { var oRoot = Application.ActiveProject.ActiveScene.Root; var oNull = oRoot.AddNull( "null_TMP" ); // Add Null as new deformer ApplyFlexEnv( aSel(i).FullName + ";" + oNull.FullName, null, 0 ); // Set Weights to 0 SIModifyFlexEnvWght( aSel(i).FullName + ".cls.EnvelopWeightCls.Envelope_Weights", oNull.FullName, aSel(i).FullName + ".pnt[*]", 0, 0, true); // Remove Tmp Deformer RemoveFlexEnvDeformer( aSel(i).FullName + ";" + oNull.FullName, null); // Delete Tmp Null DeleteObj( oNull ); // Freeze Envelope Weight History FreezeObj( aSel(i).FullName + ".cls.EnvelopWeightCls.Envelope_Weights", null, null); LogMessage( aSel(i).FullName + " > Normalized" ); } } else { LogMessage( "Select a polymesh with an envelope" ); } }
ICE Track Particle
- All - felixlecha
#----------------------------------------------------------------------------------- # Update # Version 1.04 # Author: felixlechA.com # Date: 2011.08.23 # Do the same things of the pervious version, but link the scale too ;) # I add a null parent object and a group who group track null, and the possibility to name the track null (name root and group too) #------------------------------------------------------------------------- ---------- #get a null to follow a specific particle's position and orientation #Version 1.03 #Author: Julian Johnson (julian@exch.demon.co.uk) #Date: 13/03/2009 #multiple points can be tagged in multiple clouds. The positions are worked out #in global space and nulls are dumped at the scene root. import win32com.client from win32com.client import constants as c code = """ oTrans = XSIMath.CreateTransform() oTempS = XSIMath.CreateVector3() oTempP = XSIMath.CreateVector3() oTempR = XSIMath.CreateRotation() def TrackParticle_Update(ctx,Out,Inpointcloud,Intransform): oScl = Inpointcloud.Value.Geometry.GetICEAttributeFromName('Scale') oPos = Inpointcloud.Value.Geometry.GetICEAttributeFromName('PointPosition') oRot = Inpointcloud.Value.Geometry.GetICEAttributeFromName('orientation') ind = ctx.Operator.Parameters("Index").Value if oScl.IsConstant: s = oScl.DataArray[0] else: try: s = oScl.DataArray[ind] n except IndexError: s = oTempS if oPos.IsConstant: p = oPos.DataArray[0] else: try: p = oPos.DataArray[ind] except IndexError: p = oTempP if oRot.IsConstant: r = oRot.DataArray[0] else: try: r = oRot.DataArray[ind] except IndexError: r = oTempR oTrans.Scaling = s oTrans.Translation = p oTrans.Rotation = r oTrans2 = XSIMath.MapObjectPoseToWorldSpace(Intransform.Value.Transform,oTrans) Out.Value.Transform = oTrans2 return """ def main(): oRoot = Application.ActiveSceneRoot oSel = Application.Selection if oSel.Count <= 0: s = 'You must directly tag some points on the cloud' oMessage = XSIUIToolkit.Msgbox(s, c.siMsgOkOnly) return for x in oSel: if x.Type != 'pntSubComponent': s = 'You must directly tag some points on the cloud' oMessage = XSIUIToolkit.Msgbox(s, c.siMsgOkOnly) return if x.SubComponent. Parent3DObject.Type != 'pointcloud': s = 'You have tagged some regular geometry' oMessage = XSIUIToolkit.Msgbox(s, c.siMsgOkOnly) return oColl = XSIFactory.CreateObject('XSI.Collection') oColl.AddItems(oSel.GetAsText()) sName = Application.XSIInputBox( 'Define a Name for the null Root', 'Follow Null Name', 'Follow_Null' ) oGroup = oRoot.AddGroup() oGroup.Name = sName + '_Grp' oNullRoot = oRoot.AddNull( sName + '_Root') for x in oColl: for y in x.SubComponent.ElementArray: oPC = x.SubComponent.Parent3DObject oNull = oNullRoot.AddNull( sName + '_ID_%s' % y) oNull.primary_icon.value = 4 oNull.size.value = 0.15 oGroup.AddMember( oNull ) oOp = XSIFactory.CreateScriptedOp("TrackParticle", code, "Python") oOp.AddOutputPort(oNull.Kinematics.Local, "Out") oOp.AddInputPort(oPC.ActivePrimitive, "Inpointcloud") oOp.AddInputPort(oPC.Kinematics.Local, "Intransform") oOp.AddParameter(XSIFactory.CreateParamDef2("Index", 3,y)) oOp.debug = 0 oOp.alwaysevaluate = 1 oOp.Connect() main()
Obj_Duplicator_and_Cns_Direction()
- All - felixlecha
// Duplicate and Parent first picked object on Current selected object and Constrain in Direction to picked Target // Obj_Duplicator_and_Cns_Direction(); function Obj_Duplicator_and_Cns_Direction() { // Select Root For Anchors var aSel = new Array(); aSel = getValue("SelectionList"); // Pick the Object To Duplicate and Parent var rtn = PickObject( "Select Mesh", "Select Mesh" ); var oObj = rtn(2); // Pick the Target for the Constraint var rtn = PickObject( "Select Camera", "Select Camera" ); var oTarget = rtn(2); // Create new Group var oSceneRoot = Application.ActiveProject.ActiveScene.Root; var oGroup = oSceneRoot.AddGroup(); oGroup.Name = oObj.name + "_Group"; // Hide Command Log SetValue("preferences.scripting.cmdlog", false, null); var oProgressBar = XSIUIToolkit.progressbar; oProgressBar.maximum = aSel.count; oProgressBar.visible = true; oProgressBar.caption = "[ Duplicate, Parent and Cns Direction ]"; for( i = 0; i < aSel.count && !oProgressBar.cancelpressed; i++ ) { var oNewObj = SIDuplicate( oObj ); ParentObj(aSel(i), oNewObj); oNewObj = dictionary.getObject( oNewObj, false); oNewObj.kinematics.global.transform = oNewObj.parent.kinematics.global.transform; // Add new null to Group oGroup.AddMember( oNewObj, false ); // Add Cns Direction on Target oNewObj.kinematics.AddConstraint( "Direction", oTarget, 0); oNewObj.kinematics.dircns.dirx.value = 0; oNewObj.kinematics. dircns.diry.value = 1; oNewObj.kinematics.dircns.dirz.value = 0; oProgressBar.statustext = "[ " + oNewObj + " ] " + oProgressBar.increment() + " / " + oProgressBar.maximum; oProgressBar.increment(); } oProgressBar.visible = false; }
SearchAndReplace( inString, inSearch, inReplace, inCase )
- All - felixlecha
// Search and replace (use Condition Case) // INPUT : // inString (string) // inSearch (string) // inReplace (string) // inCase (boolean) // OUTPUT : // inString (string) function SearchAndReplace( inString, inSearch, inReplace, inCase ) { if(inCase){ var oReg = new RegExp(inSearch, "g"); } else{ var oReg = new RegExp(inSearch, "gi"); } var inString = inString.replace(oReg, inReplace); return inString; } // Test : // LogMessage( SearchAndReplace("felix likes chocolate, he eat Chocolate everyday.", "chocolate", "Code", 0 )); // LogMessage( SearchAndReplace("felix likes chocolate, he eat Chocolate everyday.", "chocolate", "Code", 1 ));
CurrentUser()
- All - felixlecha
// Log the Current User Name function CurrentUser() { LogMessage(XSIUtils.Environment.Item("USERNAME") ); } // note : // you can access to all environement variable // and create a new one from xsi // //XSIUtils.Environment.SetItem("MYVAR", 1 );
OpenFolder()
- All - felixlecha
// Open folder in Windows Explorer function OpenFolder() { var sFolderPath = "C:\\"; XSIUtils.LaunchProcess( "Explorer.exe " + sFolderPath, false, sFolderPath ); }
ListSceneColor()
- All - felixlecha
// Listing of Scene Color with value function ListSceneColor() { var colors = ActiveProject.ActiveScene.Colors; LogMessage( "Current values for " + colors + ": " ); for ( var i=0; i
KeyboardState()
- All - felixlecha
// Log the switch/modifier keyboard pressed // keyboard interaction : GetKeyboardState function KeyboardState() { var rtn = GetKeyboardState(); var iPressKey = rtn(1); var str = ""; if ( 1 & iPressKey ) { str = "Shift " } if ( 2 & iPressKey ) { str += "Ctrl " } if ( 4 & iPressKey ) { str += "Alt " } if ( str != "" ) { LogMessage( str + "pressed", siInfo ); } else { LogMessage( "No modifier key pressed.", siInfo ); } LogMessage("Press Key Value : "+ iPressKey); }
TestExpr( inExpr )
- All - felixlecha
// Test if an expression is valid or not. It try to apply expression in a known valid expression. function TestExpr( inExpr ) { // Create tmp property named : "Expression_Manager_Eval" var oEvalProp = ActiveSceneRoot.AddProperty("CustomProperty",false,"Expression_Manager_Eval"); var pEval = oEvalProp.AddParameter3( "fEval", siDouble, 0, -999999, 999999, true, false ); // Create a tmp Valid expression var tmpExpr = pEval.AddExpression("0"); var bReturn; try { // Try Apply Expr tmpExpr.definition.Value = inExpr; // Read Evaluate Value var fEvalValue = pEval.Value; // Log Value LogMessage( " Current Expression is valide.\n value : " + fEvalValue ); bReturn = 1; } catch(e) { LogMessage( "Current Expression Error :\n " + e.description ); bReturn = 0; } // Delete tmp Property DeleteObj( oEvalProp ); return bReturn; } // Test an expression // TestExpr( "Fc + 1 + A" );