def particlesToLocator(par=None, locGrp=None): '''{'path':'Dynamics/Particles/Crowd/particlesToLocator( )ONLYSE', 'icon':':/locator.svg', 'tip':'每个粒子创建一个locator', 'usage':""" #在每一个粒子的位置上创建一个locator $fun( par="nParticle1" )""", } ''' par = checkArg(par, nodeType='nParticle', tryToShape=True) if not par: raise IOError('Select a particles node!') parId = cmds.getParticleAttr(par, a=True, at='particleId') if not parId: return pos = cmds.getParticleAttr(par, a=True, at='position') locGrp = locGrp if locGrp else par + '_locGrp' if not cmds.objExists(locGrp): locGrp = cmds.group(name=par + '_locGrp', empty=True) for i, id in enumerate(parId): locName = '|%s|%s_loc_id_%d' % (locGrp, par, id) if not cmds.objExists(locName): loc = cmds.spaceLocator(name='%s_loc_id_%d' % (par, id))[0] cmds.parent(loc, locGrp) cmds.setAttr(locName + '.t', pos[i * 3], pos[i * 3 + 1], pos[i * 3 + 2], type='double3')
def particlesToCurve(par=None, reset=False, curvesGrp=None): '''{'path':'Dynamics/Particles/particlesToCurve( )ONLYSE', 'icon':':/curveCV.png', 'tip':'粒子拖尾曲线', 'usage':""" #粒子拖尾出曲线: #reset:将曲线重置 #下面这个例子:从1到100帧,第隔5帧创建一个曲线点 #-------------------------- $fun( "nParticle1",reset=True ) start = 1 end = 100 step = 5 for i in range( start, end, step): cmds.currentTime( i, e=True) $fun( "nParticle1" )""", } ''' par = checkArg(par, nodeType='nParticle', tryToShape=True) if not par: raise IOError('Select a particles node!') curGrp = curvesGrp if curvesGrp else par + '_curGrp' if reset and cmds.objExists(curGrp): curs = cmds.listRelatives(curGrp, type='nurbsCurve', ad=True, f=True) for c in curs: if cmds.getAttr(c + '.spans') > 1: #cmds.curve( c, a=True, p=[(0,0,0)] ) cmds.curve(c, r=True, d=3, p=[(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)]) else: parId = cmds.getParticleAttr(par, a=True, at='particleId') if not parId: return pos = cmds.getParticleAttr(par, a=True, at='position') if not cmds.objExists(curGrp): curGrp = cmds.group(name=curGrp, empty=True) for i, id in enumerate(parId): curName = '|%s|%s_cur_id_%d' % (curGrp, par, id) tpos = (pos[i * 3], pos[i * 3 + 1], pos[i * 3 + 2]) if not cmds.objExists(curName): cur = cmds.curve(d=3, p=[tpos, tpos, tpos, tpos]) #cur = cmds.createNode( 'nurbsCurve', parent=curGrp ) newName = cmds.rename(cur, '%s_cur_id_%d' % (par, id)) cmds.parent(newName, curGrp) elif cmds.getAttr(curName + '.spans') < 2: cmds.curve(curName, r=True, p=[tpos, tpos, tpos, tpos]) #else: cmds.curve(curName, a=True, p=[tpos])
def parToLocMesh(mesh, particles): trinode = mc.polyTriangulate(mesh, ch=True) #count the particles count = mc.getAttr(particles + '.count') #create a group for the locators locGroup = mc.group(em=True) newCount = 0 for p in range(count): pos = mc.getParticleAttr(('%s.pt[%d]' % (particles, p)), at='worldPosition') point = (pos[0], pos[1], pos[2]) direction = (0.0, 1.0, 0.0) if rayIntersect(mesh, point, direction): loc = mc.spaceLocator() mc.move(pos[0], pos[1], pos[2], loc, a=True) mc.scale(0.1, 0.1, 0.1, loc, a=True, p=(pos[0], pos[1], pos[2])) mc.parent(loc, locGroup) newCount = newCount + 1 locGroup = mc.rename(locGroup, 'loc_%d_GRP' % (newCount)) mc.delete(trinode) return locGroup
def mesh_uvToWorld(): '''{'path':'Polygons/EditMesh/mesh_uvToWorld( )ONLYSE', 'icon':':/mesh.svg', 'usage':""" #选择两个mesh物体,将第一个按uv匹配到第二个 $fun( )""", } ''' fromObj = cmds.ls(sl=True)[0] #'pPlane1' toObj = cmds.ls(sl=True)[1] #'pPlane2' iterVertex = om.MItMeshVertex(nameToNode(fromObj, old=True)) try: uv_util = om.MScriptUtil() uv_ptr = uv_util.asFloat2Ptr() uArray, vArray = [], [] posArray = [] while not iterVertex.isDone(): posArray.append(tuple(iterVertex.position(om.MSpace.kWorld))[:3]) iterVertex.getUV(uv_ptr) uArray.append(uv_util.getFloat2ArrayItem(uv_ptr, 0, 0)) vArray.append(uv_util.getFloat2ArrayItem(uv_ptr, 0, 1)) iterVertex.next() parName = cmds.particle()[1] cmds.goal(parName, g=toObj, w=1) cmds.setAttr(parName + '.goalSmoothness', 0) cmds.setAttr(parName + ".conserve", 0) startFrame = cmds.playbackOptions(q=True, min=True) cmds.setAttr(parName + ".startFrame", startFrame) cmds.currentTime(startFrame, e=True) parName = qm.qsEmit(object=parName, position=posArray, attributes=[("goalU", "floatValue", uArray), ("goalV", "floatValue", vArray)]) #cmds.setAttr(parName+".collide", 0) #cmds.setAttr(parName+".ignoreSolverGravity", 1) #cmds.setAttr(parName+".ignoreSolverWind", 1) #cmds.setAttr(parName+".drag", 0) #nculeus = cmds.listConnections(parName + '.nextState')[0] #startFrame = cmds.getAttr( nculeus+".startFrame") cmds.currentTime(startFrame, e=True) cmds.currentTime(int(startFrame + 1), e=True) targetPos = cmds.getParticleAttr(parName, at='position', array=True) targetPos = [ newom.MPoint(targetPos[i], targetPos[i + 1], targetPos[i + 2]) for i in range(0, len(targetPos), 3) ] fromMesh = newom.MFnMesh(nameToNode(fromObj)) fromMesh.setPoints(targetPos, newom.MSpace.kWorld) except: cmds.delete(cmds.listRelatives(parName, parent=True)) raise IOError('Got a error!') cmds.delete(cmds.listRelatives(parName, parent=True))
def particleToLocator(particles): #count the particles count = mc.getAttr( particles + '.count' ) #create a group for the locators locGroup = mc.group( em=True, name='loc_%d_GRP' % (count) ) for p in range(count): pos = mc.getParticleAttr( ('%s.pt[%d]'%(particles, p)), at='worldPosition' ) loc = mc.spaceLocator( ) mc.move( pos[0] , pos[1] , pos[2], loc, a = True ) mc.scale( 0.1, 0.1, 0.1, loc, a = True, p = ( pos[0] , pos[1] , pos[2] )) mc.parent(loc, locGroup) return locGroup
def particleToLocator(particles): #count the particles count = mc.getAttr(particles + '.count') #create a group for the locators locGroup = mc.group(em=True, name='loc_%d_GRP' % (count)) for p in range(count): pos = mc.getParticleAttr(('%s.pt[%d]' % (particles, p)), at='worldPosition') loc = mc.spaceLocator() mc.move(pos[0], pos[1], pos[2], loc, a=True) mc.scale(0.1, 0.1, 0.1, loc, a=True, p=(pos[0], pos[1], pos[2])) mc.parent(loc, locGroup) return locGroup
def createCurveFromParticles(parObj, replace=False, disCVOnly=True): '''{'del_path':'Dynamics/Particles/createCurveFromParticles( cmds.ls(sl=True)[0], replace=False, disCVOnly=True )', 'usage':'$fun( cmds.ls(sl=True)[0] )', 'icon':':/menuIconCurves.png', 'tip':'在每个位置上创建一根曲线', } ''' #parObj='nParticle2' if cmds.objectType(parObj) == 'transform': if cmds.listRelatives(parObj, shapes=True, type=('particle', 'nParticle')) == None: raise IOError('%s is not particle or nParticle' % (parObj)) elif cmds.objectType(parObj) != 'particle' and cmds.objectType( parObj) != 'nParticle': raise IOError('%s is not particle or nParticle' % (parObj)) cvPos = [] parPos = cmds.getParticleAttr(parObj, at='position', array=True) for i in range(0, len(parPos), 3): cvPos.append((parPos[i], parPos[i + 1], parPos[i + 2])) curveName = parObj + '_01' if replace == True: if cmds.objExists(curveName) == False: curveNode = cmds.curve(name=curveName, d=1, p=([0, 0, 0])) curveShape = cmds.listRelatives(curveNode, shapes=True)[0] else: curveNode = cmds.curve(name=curveName, d=1, p=([0, 0, 0])) curveShape = cmds.listRelatives(curveNode, shapes=True)[0] cmds.curve(curveNode, r=True, p=cvPos) if disCVOnly: cmds.setAttr(curveShape + '.dispCV', 1) cmds.setAttr(curveShape + '.dispGeometry', 0) cmds.select(curveNode, r=True) return curveNode
def parToLocMesh(mesh, particles): trinode = mc.polyTriangulate(mesh, ch = True) #count the particles count = mc.getAttr( particles + '.count' ) #create a group for the locators locGroup = mc.group( em=True ) newCount = 0 for p in range(count): pos = mc.getParticleAttr( ('%s.pt[%d]'%(particles, p)), at='worldPosition' ) point = (pos[0] , pos[1] , pos[2]) direction=(0.0, 1.0, 0.0) if rayIntersect(mesh, point , direction): loc = mc.spaceLocator( ) mc.move( pos[0] , pos[1] , pos[2], loc, a = True ) mc.scale( 0.1, 0.1, 0.1, loc, a = True, p = ( pos[0] , pos[1] , pos[2] )) mc.parent(loc, locGroup) newCount = newCount + 1 locGroup = mc.rename(locGroup , 'loc_%d_GRP' % (newCount) ) mc.delete (trinode) return locGroup
def w06_doBake(self, parNode=None, instancerNode=None, startFrame=None, endFrame=None, exclusiveAttrs=[], otherParAttr=[], renameChild=True, dup_connect=False, dup_instance=False, ): #import random temp = self.w06_getParShape(parNode) parPapa= temp[0] parShape = temp[1] insNode = instancerNode #if insNode!=None: # insNode = insNode[0] poolGrp = '%s_ins_baked'%(parPapa) if cmds.objExists(poolGrp)==False: poolGrp = cmds.group(name=poolGrp, em=True) else: temp = cmds.listRelatives(poolGrp) if temp: cmds.delete(temp) grpLoc = '%s_loc_dup'%(parShape) if cmds.objExists(grpLoc)==False: grpLoc = cmds.group(name=grpLoc, em=True) oriObjs = mel.eval('particleInstancer -name %s -q -object %s'%(insNode, parShape) ) #cmds.particleInstancer(parShape, name=insNode, q=True, object=True) poolObjs = [] if cmds.listRelatives( poolGrp, f=True )==None else cmds.listRelatives( poolGrp, f=True ) attrsData = {'position':['double3', ['tx','ty','tz'] ],\ 'rotation':['double3', ['rx','ry','rz'] ],\ 'scale':['double3', ['sx','sy','sz'] ],\ 'aimDirection':['double3',['target[0].targetTranslate'] ], \ 'aimPosition':['double3',['target[0].targetTranslate'] ],\ 'aimAxis':['double3',['aimVector'] ],\ 'aimUpAxis':['double3',['upVector'] ],\ 'aimWorldUp':['double3',['worldUpVector'] ]\ } if 'position' in exclusiveAttrs and 'rotation' in exclusiveAttrs: attrsData.pop('position') if 'rotation' in exclusiveAttrs: for attr in ('rotation', 'aimDirection', 'aimPosition', 'aimAxis','aimUpAxis', 'aimWorldUp'): if attr in attrsData.keys(): attrsData.pop(attr) if 'scale' in exclusiveAttrs: attrsData.pop('scale') for attr in attrsData.keys(): parAttr = mel.eval('particleInstancer -n "%s" -q -%s "%s"'%(insNode, attr, parShape) ) if parAttr==None: attrsData.pop(attr) else: attrType = cmds.getAttr('%s.%s'%(parShape,parAttr), type=True) if attrType=='doubleArray': dataType='double' else:#dataType is vectorAttry dataType='double3' attrsData[attr].extend( (dataType,parAttr,'') ) aimConstraint=False if 'rotation' in attrsData.keys(): for attr in ('aimDirection', 'aimPosition', 'aimAxis','aimUpAxis', 'aimWorldUp'): if attr in attrsData.keys(): attrsData.pop(attr) elif 'aimDirection' in attrsData.keys() or 'aimPosition' in attrsData.keys() or\ 'aimAxis' in attrsData.keys() or 'aimWorldUp' in attrsData.keys() : aimConstraint=True aimCon = cmds.createNode('aimConstraint', name='%s_instanceAimConstraint'%(parPapa) ) aimAttrs = [] if 'aimDirection' in attrsData.keys() and 'aimPosition' in attrsData.keys(): attrsData.pop('aimPosition') for attr in ('aimDirection', 'aimPosition', 'aimAxis','aimUpAxis', 'aimWorldUp'): if attr in attrsData.keys(): aimAttrs.append(attr) notKeyAttrs = ['aimDirection', 'aimPosition', 'aimAxis','aimUpAxis', 'aimWorldUp'] notKeyAttrs.extend(exclusiveAttrs) newAttrs = {} if otherParAttr: for attr in otherParAttr: attrType = 'double3' if str( cmds.getAttr('%s.%s'%(parShape,attr), type=True) )=='vectorArray' else 'double' if attrType=='double3': subAttrs = [attr+'X', attr+'Y', attr+'Z'] else: subAttrs = [attr] newAttrs[attr] = [attrType, subAttrs, attrType, attr, ''] keyModel = True curObjs = {} #startFrame = 1 #endFrame = 100 objectIndexAttr = mel.eval('particleInstancer -n "%s" -q -objectIndex "%s"'%(insNode, parShape) ) #print attrsData for curF in range( startFrame, endFrame+1 ): objsVis = {} import time startTime = time.time() cmds.currentTime(curF, e=True) ids = cmds.getParticleAttr(parShape, at='particleId', array=True) ids = [] if ids ==None else ids print '\n\nFrame: '+str(curF) if ids: if objectIndexAttr: objsIndex = [int(i) for i in cmds.getParticleAttr(parShape, at=objectIndexAttr, array=True)] else: #objsIndex = [i for i in range(len(ids)) ] objsIndex = [0 for i in range(len(ids)) ] #Get born particles #print 'poolObjs:', poolObjs for pId in ids: pId = int(pId) #Get last frame born particles if pId not in curObjs.keys(): attrIndex = ids.index(pId) #print poolObjs objIndex = objsIndex[attrIndex] oriObj = oriObjs[objIndex] #renameChild=True, dup_connect=False, dup_instance=False newObj = cmds.duplicate(oriObj, name='%s_ins_%05d'%(parPapa,pId), rr=True, rc=renameChild, ic=dup_connect, ilf=dup_instance )[0] cmds.parent( newObj, poolGrp) for newAttr in newAttrs.values(): if newAttr[0] == 'double3': cmds.addAttr(newObj, ln=newAttr[3], at=newAttr[2]) for newAttrName in newAttr[1]: cmds.addAttr(newObj, ln=newAttrName, p=newAttr[3], at='double',keyable=True) else:#newAttr=='double' cmds.addAttr(newObj, ln=newAttr[1][0], at='double', keyable=True) #Create new attributes curObjs[pId] = newObj cmds.setKeyframe(newObj, at='visibility', t=curF-1, v=False) cmds.setKeyframe(newObj, at='visibility', v=True) #Get die particles diedList = [] #print str(i), ': ', ids #print 'beforeFramesIds: ', curObjs.keys() for pId in curObjs.keys(): if pId not in ids: diedList.append( pId ) cmds.setKeyframe(curObjs[pId], at='visibility', v=False) #Remove died particles from curObjs dictionary #print 'Before: ', curObjs #print 'diedList', diedList for pId in diedList: tempObj = curObjs[pId] curObjs.pop(pId) #Get particles data for bake #print attrsData if ids: for key, value in attrsData.iteritems(): #if key=='rotation' and value[3]=='aimConstraint': #for aimAttr in aimAttrs.iteritems(): #pass #else: if value[0]==value[2]: attrsData[key][4]= cmds.getParticleAttr(parShape, at=value[3], array=True) elif value[0]=='double3' and value[2]=='double': temp = [] for i in cmds.getParticleAttr(parShape, at=value[3], array=True): temp.extend( (i,i,i) ) attrsData[key][4] = temp elif value[0]=='double' and value[2]=='double3': temp=[] tempData = cmds.getParticleAttr(parShape, at=value[3], array=True) attrsData[key][4] = [tempData[i] for i in range(0, len(tempData), 3) ] else: raise IOError() #print attrsData['aimDirection'][4]!='' if attrsData.has_key('aimDirection') and attrsData['aimDirection'][4]!='': temp = [] #temp = [ attrsData['aimDirection'][4][aimi] + attrsData['position'][4][aimi]\ #for aimi in range( len(attrsData['aimDirection'][4]) ) ] #attrsData['aimDirection'][4] = temp[:] for aimi in range( len(attrsData['aimDirection'][4]) ): temp.append( attrsData['aimDirection'][4][aimi] + attrsData['position'][4][aimi] ) attrsData['aimDirection'][4] = temp[:] #Get rotate attribute data if aimConstraint: rotTemp = [] dataIndex = 0 for pId in ids: cmds.setAttr('%s.constraintTranslate'%(aimCon),\ attrsData['position'][4][dataIndex],attrsData['position'][4][dataIndex+1],\ attrsData['position'][4][dataIndex+2], type='double3') for aimAttr in aimAttrs: value = attrsData[aimAttr] cmds.setAttr('%s.%s'%(aimCon, value[1][0]), value[4][dataIndex], value[4][dataIndex+1], value[4][dataIndex+2], type='double3') rotTemp.extend( cmds.getAttr(aimCon+'.constraintRotate')[0] ) dataIndex = dataIndex+3 #rotateData= ['double3', ['rx', 'ry', 'rz'], 'double3', 'aimConstraint', ''] for key, value in newAttrs.iteritems(): newAttrs[key][4] = cmds.getParticleAttr(parShape, at=value[3], array=True) #Combine attrsData with newAttrs together tempData = newAttrs.copy() if aimConstraint: tempData['rotation'] = ['double3', ['rx', 'ry', 'rz'], 'double3', 'aimConstraint', rotTemp] for key, value in attrsData.iteritems(): if key not in notKeyAttrs: tempData[key] = value for key, value in tempData.iteritems(): dataIndex = 0 for pId in ids: obj=curObjs[pId] for attr in value[1]: cmds.setKeyframe(obj, at=attr, v=value[4][dataIndex]) dataIndex = dataIndex+1 print 'Current particle count: %s\nUsed Times: %s'\ %( len(ids), time.time()-startTime ) #if cmds.memory(freeMemory=True)[0]<800: #cmds.flushUndo() if aimConstraint: cmds.delete(aimCon) cmds.delete( grpLoc ) cmds.flushUndo()
def loadShotPoints(sector, *args): '''This function will load the generated point cloud in Maya via Houdini Engine. It will then copy each point and their attribute to a new point cloud to get rid of Houdini Engine.''' # Load Houdini Engine if loadHoudiniEngine() == False: return # Check if point bgeo file exists # currentWorkspace = os.path.abspath(cmds.workspace(sn=True,q=True)) # currentShot = str(os.path.split(currentWorkspace)[1]) # bgeoPath = '//Merlin/3d4/skid/05_shot/%s/geo/fileCache/%s_instancerPts.bgeo.sc'%(currentShot,currentShot) bgeoPath = '//Merlin/3d4/skid/04_asset/set/setForest/geo/pointCloud_sector%s.bgeo.sc' % sector # Set persp far clip plane cmds.setAttr('perspShape.farClipPlane', 1000000) # Set current time to first frame fstart = cmds.playbackOptions(ast=True, q=True) cmds.currentTime(fstart) # Load the bgeo importer toolBgeoToMaya = os.path.abspath( '//merlin/3d4/skid/04_asset/hda/toolBgeoToMaya_v2.hdanc') cmds.houdiniAsset(la=[toolBgeoToMaya, 'Object/toolBgeoToMaya']) # Set file path to shot points cmds.setAttr('toolBgeoToMaya1.houdiniAssetParm.houdiniAssetParm_file', bgeoPath, type="string") # Sync asset # cmds.evalDeferred('cmds.houdiniAsset(syn="toolBgeoToMaya1")') cmds.houdiniAsset(syn="toolBgeoToMaya1") # Duplicate point cloud to get rid of houdini engine pointCloud = 'file_bgeoToMaya_0' pointCloud_s = pointCloud + 'Shape' # Get particle count nbPart = cmds.particle(pointCloud, q=True, ct=True) # Create new particle system with suffix tmp = cmds.particle(n=pointCloud + '_dupli') dupliPartXf = tmp[0] dupliPartShp = tmp[1] cmds.setAttr(dupliPartShp + '.isDynamic', False) # Create rgbPP attribute on the new system cmds.addAttr(dupliPartShp, ln='rgbPP', dt='vectorArray') cmds.addAttr(dupliPartShp, ln='rgbPP0', dt='vectorArray') # Create radiusPP attribute cmds.addAttr(dupliPartShp, ln='radiusPP', dt='doubleArray') cmds.addAttr(dupliPartShp, ln='radiusPP0', dt='doubleArray') # Create index attribute cmds.addAttr(dupliPartShp, ln='index', dt='doubleArray') cmds.addAttr(dupliPartShp, ln='index0', dt='doubleArray') # Fill new particle system with positions for i in range(nbPart): wPos = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i), at='position', array=True) cmds.emit(o=dupliPartXf, pos=[wPos[0], wPos[1], wPos[2]]) # Transfer rgbPP for i in range(nbPart): attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i), at='rgbPP', array=True) cmds.particle(e=True, at='rgbPP', order=i, vectorValue=[attrValue[0], attrValue[1], attrValue[2]]) # Transfer radiusPP for i in range(nbPart): attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i), at='radiusPP', array=True) cmds.particle(e=True, at='radiusPP', order=i, floatValue=attrValue[0]) # Transfer index for i in range(nbPart): attrValue = cmds.getParticleAttr('%s.pt[%s]' % (pointCloud_s, i), at='index', array=True) cmds.particle(e=True, at='index', order=i, floatValue=attrValue[0]) # Delete unwanted nodes cmds.delete('toolBgeoToMaya1') # Rename particle system and group newname = 'forest_instancing_pc' cmds.rename(tmp[0], newname) masterGRP = 'FOREST_INSTANCING_GRP' try: cmds.select(masterGRP, r=True) except ValueError: cmds.group(newname, name=masterGRP) else: cmds.parent(newname, masterGRP) # Set nucleus (yes we have to keep it for some reason) cmds.setAttr('nucleus1.startFrame', fstart) cmds.parent('nucleus1', masterGRP)
def printParticleInBoundingbox(start, end, parName, once=True): '''{'path':'Dynamics/Particles/printParticleInBoundingbox()ONLYSE', 'icon':':/particle.png', 'tip':'和物体穿插的粒子', 'usage':""" #返回在指定的时间断内和选择的物体的boundingbox相穿插的粒子的id. #在outline中选择,例如选择每个动画角色的组。 $fun( 1, 48, "nParticle1", once=True) #start: # 开始帧 #end: # 结束帧 #parName: # 粒子节点的名字 #once: # 每次穿插都返回,还是每个粒子最多返回一次 """, 'help':"""<pre> 返回在指定的时间断内和选择的物体的boundingbox相穿插的粒子的id. 在outline中选择,例如选择每个动画角色的组。 start: 开始帧 end: 结束帧 parName: 粒子节点的名字 once: 每次穿插都返回,还是每个粒子最多返回一次 """, } ''' import maya.api.OpenMaya as newom objects = cmds.ls(sl=True, type='transform') allIds = set() allDatas = [] end = end + 1 for curF in range(start, end): cmds.currentTime(curF, e=True) parIds = cmds.getParticleAttr(parName, at='particleId', array=True) if not parIds: continue parIds = [int(id) for id in parIds] bboxes = [] for obj in objects: bbox = cmds.exactWorldBoundingBox(obj, ii=True) bboxes.append((obj, newom.MBoundingBox(newom.MPoint(bbox[:3]), newom.MPoint(bbox[3:])))) parPos = cmds.getParticleAttr(parName, at='position', array=True) parIdWithPos = [(parIds[i], newom.MPoint(parPos[i * 3], parPos[i * 3 + 1], parPos[i * 3 + 2])) for i in range(len(parIds))] curFrameContainedIds = set() objsWithIds = [] for obj, bbox in bboxes: curObjContained = [] for id, pos, in parIdWithPos: if bbox.contains(pos): if once and id in allIds: continue curObjContained.append(id) if curObjContained: objsWithIds.append((obj, curObjContained)) curFrameContainedIds = curFrameContainedIds.union( curObjContained) if objsWithIds: allIds = allIds.union(curFrameContainedIds) allDatas.append((curF, tuple(curFrameContainedIds), objsWithIds)) #allDatas.sort() ttCount = 0 dataStr = 'All ParticleId:%s\n' % (str(tuple(allIds))) for data in allDatas: dataStr += 'Frame:%s\n\t%s\n' % (data[0], data[1]) ttCount += len(data[0]) #infoFile = open( '.txt', 'w') #infoFile.write( dataStr ) #os.startfile( '.txt' ) print dataStr
import math import maya.cmds as cmds selectPop = cmds.ls(type=['PopulationToolLocator']) if cmds.objExists(selectPop[0]) and cmds.attributeQuery( 'numberParticlesPlaced', node=selectPop[0], exists=True): popCount = cmds.getAttr(selectPop[0] + '.numberParticlesPlaced') tornadoPos = cmds.xform('Tornado', q=True, translation=True, worldSpace=True) particlesPos = cmds.getParticleAttr( 'particleShape1.pt[0:{num}]'.format( num=popCount), attribute='position', array=True) sort = [] while len(particlesPos) > 3: one = tuple(particlesPos[:3]) sort.append(one) particlesPos = particlesPos[3:] sort.append(particlesPos) del sort[-1] particlesPos = sort vectorF = [] for p, pos in enumerate(particlesPos): deltaX = tornadoPos[0] - pos[0] deltaZ = tornadoPos[2] - pos[2] rotD = math.atan2(deltaX, deltaZ) #math.degrees( z = math.sin(rotD) x = math.cos(rotD) one = (x, 0.0, z) vectorF.append(one)
def particleExport(filepath, startFrame, endFrame, inc,particleTuple, userveca="",uservecb="",userfloa="",userflob=""): pTransform = particleTuple[0] pshape = particleTuple[1] if cmds.objectType( pshape ) == "particle" or cmds.objectType( pshape ) == "nParticle": cmds.runup( maxFrame=startFrame) arad=1 if cmds.objExists(pshape+".radiusPP") else 0 arot=1 if cmds.objExists(pshape+".rot") else 0 avel=1 if cmds.objExists(pshape+".velocity") else 0 aid=1 if cmds.objExists(pshape+".id") else 0 alife=1 if cmds.objExists(pshape+".lifespanPP") else 0 aage=1 if cmds.objExists(pshape+".age") else 0 argb=1 if cmds.objExists(pshape+".rgbPP") else 0 aopacity=1 if cmds.objExists(pshape+".opacityPP") else 0 amass=1 if cmds.objExists(pshape+".mass") else 0 auserveca=1 if cmds.objExists(pshape+"."+userveca) else 0 auservecb=1 if cmds.objExists(pshape+"."+uservecb) else 0 auserfloa=1 if cmds.objExists(pshape+"."+userfloa) else 0 auserflob=1 if cmds.objExists(pshape+"."+userflob) else 0 attrNum = arad + arot + avel + aid + alife + aage + argb + aopacity + amass + auserveca + auservecb + auserfloa + auserflob; svel = "v 3 vector 0 0 0 \n" if avel else "" srad = "pscale 1 float 1 \n" if arad else "" srot = "rot 3 vector 0 0 0 \n" if arot else "" sid = "id 1 float 1 \n" if aid else "" slife = "life 1 float 1 \n" if alife else "" sage = "age 1 float 1 \n" if aage else "" srgb = "Cd 3 vector 0 0 0 \n" if argb else "" sopacity = "opacity 1 float 1 \n" if aopacity else "" smass = "mass 1 float 1 \n" if amass else "" suserveca = (userveca +" 3 vector 0 0 0 \n") if auserveca else "" suservecb = (uservecb +" 3 vector 0 0 0 \n") if auservecb else "" suserfloa = (userfloa +" 1 float 1 \n") if auserfloa else "" suserflob = (userflob +" 1 float 1 \n") if auserflob else "" (difName,basename) = getDirFromParh(filepath) particleCount = cmds.particle(pTransform,q=1, count=1) for frame in xrange(startFrame,endFrame+1):#in order to start at desired frame cmds.currentTime( frame, edit=True ) finalFilePath = difName+"/"+basename+"."+str(frame).zfill(5)+".geo" particleFile = open(finalFilePath, 'w') particleFile.write("PGEOMETRY V5 \nNPoints " + str(cmds.particle(pTransform,q=1, count=1)) + " NPrims 0 \nNPointGroups 0 NPrimGroups 0 \nNPointAttrib "+str(attrNum)+" NVertexAttrib 0 NPrimAttrib 0 NAttrib 1 \nPointAttrib \n"+svel+srad+srot+sid+slife+sage+srgb+sopacity+smass+suserveca+suservecb+suserfloa+suserflob); for fr in range(cmds.particle(pTransform,q=1, count=1)) : posb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'worldPosition') if avel:velb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'velocity') if arad:scaleb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'radiusPP') if arot:rotb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'rot') if aid:idb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'id') if alife:lifeb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'lifespanPP') if aage:ageb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'age') if argb:rgbb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'rgbPP') if aopacity:opacityb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'opacityPP') if amass:massb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = 'mass') if auserveca:uservecab = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = userveca) if auservecb:uservecbb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = uservecb) if auserfloa:userfloab = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = userfloa) if auserflob:userflobb = cmds.getParticleAttr(pshape+".pt"+"["+str(fr)+"]",attribute = userflob) fvel = str(velb[0]) +" "+ str(velb[1])+" "+str(velb[2])+" " if avel else "" frad = str(scaleb[0])+" " if arad else "" frot = str(rotb[0]) +" "+ str(rotb[1])+" "+str(rotb[2])+" " if arot else "" fid = str(idb[0])+" " if aid else "" flife = str(lifeb[0])+" " if alife else "" fage = str(ageb[0])+" " if aage else "" frgb = str(rgbb[0]) +" "+ str(rgbb[1])+" "+str(rgbb[2])+" " if argb else "" fopacity = str(opacityb[0])+" " if aopacity else "" fmass = str(massb[0])+" " if amass else "" fuserveca = str(uservecab[0]) +" "+ str(uservecab[1])+" "+str(uservecab[2])+" " if auserveca else "" fuservecb = str(uservecbb[0]) +" "+ str(uservecbb[1])+" "+str(uservecbb[2])+" " if auservecb else "" fuserfloa = str(userfloab[0])+" " if auserfloa else "" fuserflob = str(userflobb[0])+" " if auserflob else "" if cmds.particle(pTransform,q=1, count=1) != 0: particleFile.write(str(posb[0]) + " " + str(posb[1]) + " " + str(posb[2]) + " 1 (" + fvel + frad + frot + fid + flife + fage + frgb + fopacity + fmass + fuserveca + fuservecb + fuserfloa + fuserflob +") \n") particleFile.write("DetailAttrib \nvarmap 1 index 1 \"v -> v\" \n (0) \nbeginExtra \nendExtra") particleFile.close() else: print "Select particles first...."
def particleExport(filepath, startFrame, endFrame, inc, particleTuple, userveca="", uservecb="", userfloa="", userflob=""): pTransform = particleTuple[0] pshape = particleTuple[1] if cmds.objectType(pshape) == "particle" or cmds.objectType( pshape) == "nParticle": cmds.runup(maxFrame=startFrame) arad = 1 if cmds.objExists(pshape + ".radiusPP") else 0 arot = 1 if cmds.objExists(pshape + ".rot") else 0 avel = 1 if cmds.objExists(pshape + ".velocity") else 0 aid = 1 if cmds.objExists(pshape + ".id") else 0 alife = 1 if cmds.objExists(pshape + ".lifespanPP") else 0 aage = 1 if cmds.objExists(pshape + ".age") else 0 argb = 1 if cmds.objExists(pshape + ".rgbPP") else 0 aopacity = 1 if cmds.objExists(pshape + ".opacityPP") else 0 amass = 1 if cmds.objExists(pshape + ".mass") else 0 auserveca = 1 if cmds.objExists(pshape + "." + userveca) else 0 auservecb = 1 if cmds.objExists(pshape + "." + uservecb) else 0 auserfloa = 1 if cmds.objExists(pshape + "." + userfloa) else 0 auserflob = 1 if cmds.objExists(pshape + "." + userflob) else 0 attrNum = arad + arot + avel + aid + alife + aage + argb + aopacity + amass + auserveca + auservecb + auserfloa + auserflob svel = "v 3 vector 0 0 0 \n" if avel else "" srad = "pscale 1 float 1 \n" if arad else "" srot = "rot 3 vector 0 0 0 \n" if arot else "" sid = "id 1 float 1 \n" if aid else "" slife = "life 1 float 1 \n" if alife else "" sage = "age 1 float 1 \n" if aage else "" srgb = "Cd 3 vector 0 0 0 \n" if argb else "" sopacity = "opacity 1 float 1 \n" if aopacity else "" smass = "mass 1 float 1 \n" if amass else "" suserveca = (userveca + " 3 vector 0 0 0 \n") if auserveca else "" suservecb = (uservecb + " 3 vector 0 0 0 \n") if auservecb else "" suserfloa = (userfloa + " 1 float 1 \n") if auserfloa else "" suserflob = (userflob + " 1 float 1 \n") if auserflob else "" (difName, basename) = getDirFromParh(filepath) particleCount = cmds.particle(pTransform, q=1, count=1) for frame in xrange(startFrame, endFrame + 1): #in order to start at desired frame cmds.currentTime(frame, edit=True) finalFilePath = difName + "/" + basename + "." + str(frame).zfill( 5) + ".geo" particleFile = open(finalFilePath, 'w') particleFile.write( "PGEOMETRY V5 \nNPoints " + str(cmds.particle(pTransform, q=1, count=1)) + " NPrims 0 \nNPointGroups 0 NPrimGroups 0 \nNPointAttrib " + str(attrNum) + " NVertexAttrib 0 NPrimAttrib 0 NAttrib 1 \nPointAttrib \n" + svel + srad + srot + sid + slife + sage + srgb + sopacity + smass + suserveca + suservecb + suserfloa + suserflob) for fr in range(cmds.particle(pTransform, q=1, count=1)): posb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='worldPosition') if avel: velb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='velocity') if arad: scaleb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='radiusPP') if arot: rotb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='rot') if aid: idb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='id') if alife: lifeb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='lifespanPP') if aage: ageb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='age') if argb: rgbb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='rgbPP') if aopacity: opacityb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='opacityPP') if amass: massb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute='mass') if auserveca: uservecab = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute=userveca) if auservecb: uservecbb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute=uservecb) if auserfloa: userfloab = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute=userfloa) if auserflob: userflobb = cmds.getParticleAttr(pshape + ".pt" + "[" + str(fr) + "]", attribute=userflob) fvel = str(velb[0]) + " " + str(velb[1]) + " " + str( velb[2]) + " " if avel else "" frad = str(scaleb[0]) + " " if arad else "" frot = str(rotb[0]) + " " + str(rotb[1]) + " " + str( rotb[2]) + " " if arot else "" fid = str(idb[0]) + " " if aid else "" flife = str(lifeb[0]) + " " if alife else "" fage = str(ageb[0]) + " " if aage else "" frgb = str(rgbb[0]) + " " + str(rgbb[1]) + " " + str( rgbb[2]) + " " if argb else "" fopacity = str(opacityb[0]) + " " if aopacity else "" fmass = str(massb[0]) + " " if amass else "" fuserveca = str(uservecab[0]) + " " + str( uservecab[1]) + " " + str( uservecab[2]) + " " if auserveca else "" fuservecb = str(uservecbb[0]) + " " + str( uservecbb[1]) + " " + str( uservecbb[2]) + " " if auservecb else "" fuserfloa = str(userfloab[0]) + " " if auserfloa else "" fuserflob = str(userflobb[0]) + " " if auserflob else "" if cmds.particle(pTransform, q=1, count=1) != 0: particleFile.write( str(posb[0]) + " " + str(posb[1]) + " " + str(posb[2]) + " 1 (" + fvel + frad + frot + fid + flife + fage + frgb + fopacity + fmass + fuserveca + fuservecb + fuserfloa + fuserflob + ") \n") particleFile.write( "DetailAttrib \nvarmap 1 index 1 \"v -> v\" \n (0) \nbeginExtra \nendExtra" ) particleFile.close() else: print "Select particles first...."
# Particle Mover import maya.cmds as cmds particleList = cmds.filterExpand( sm=47 ) particleEmitter = particleList.split('.')[0] particleShape = cmds.listRelatives( particleEmitter, shapes=True )[0] particleIds = cmds.getParticleAttr( particleList, attribute='id', array=True ) particlePos = cmds.getParticleAttr( particleList, attribute='worldPosition', array=True ) locatorPos = cmds.getParticleAttr( particleList, attribute='worldPosition' ) locator = cmds.spaceLocator( position=(locatorPos[0], locatorPos[1], locatorPos[2]) )[0] def moveParticles(): $gPos = $positions; $gIds = $ids; string $window = `window -menuBar true -title "Move Particles"`; columnLayout -adjustableColumn true; button -label "Apply" -command moveParticles; button -label "Reset" -command ("setToZero(\""+$loc[0]+"\")"); button -label "Finish" -command ("delete "+$loc[0]+"; deleteUI -window "+$window+"; select -r "+stringArrayToString($particles," "));