def PerlinNoiseFiller( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() Divisions = 15 Vmin = FMin Vmax = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to a random value weighted by the sum of its location for v in range(len(ObjectVerts)): loc = pm.xform( ObjectVerts[v], query=True, translation=True, worldSpace=True ) RawValue = PerlinNoise((loc[0]*200),(loc[1]*300),(loc[2]*250), Divisions) ModValue = math.fabs(math.cos(RawValue/10.0)) FValue = max(min(ModValue, Vmax), Vmin) pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def f3DNoise( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() min = FMin max = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) RandomVerts = list(ObjectVerts) random.shuffle(RandomVerts) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to a random value weighted by the sum of its location for v in range(len(ObjectVerts)): loc = pm.xform( RandomVerts[v], query=True, translation=True, worldSpace=True ) locValue = math.sqrt(abs(random.choice(loc))) RValue = random.uniform( min, max ) FValue = (locValue * RValue)/2 pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def doIt(obj): obj.createColorSet('edgeLength') colors = [] for i, vtx in enumerate(obj.vtx): #iterate through vertices #print vtx, vtx._range, vtx.getIndex(), vtx.getPosition() edgs = vtx.connectedEdges() totalLen=0 edgCnt=0 for edg in edgs: edgCnt += 1 #print edg #print "getting length" l = edg.getLength() #print "length", l totalLen += l avgLen=totalLen / edgCnt currColor = vtx.getColor() color = pm.dt.Color.black # only set blue if it has not been set before if currColor.b<=0.0: color.b = avgLen color.r = avgLen colors.append(color) print len(colors) obj.setColors( colors ) obj.updateSurface() pm.polyColorPerVertex( obj, e=1, colorDisplayOption=1 )
def bake_shape_to_vertex_normals(source_obj, dest_obj): ''' Stores blend shape information into the vertex normals between 2 objects. Given 2 objects with the same topology, gather all vertex offsets and bake the vector into the vertex normal Args: source_obj (PyNode): Maya scene object that is the blend shape target dest_obj (PyNode): Original maya scene object ''' source_vert_list = [ Vector(pm.xform(x, q=True, t=True, ws=True)) for x in source_obj.vtx ] dest_vert_list = [ Vector(pm.xform(x, q=True, t=True, ws=True)) for x in dest_obj.vtx ] rgb_vector_list, longest_length = v1_shared.shared_utils.bake_vertex_color_data( source_vert_list, dest_vert_list, False) for i, vtx in enumerate(dest_obj.vtx): r = Vector(list(rgb_vector_list[i])).length3D() / longest_length pm.polyColorPerVertex(vtx, rgb=[r, 0, 0]) pm.polyNormalPerVertex(vtx, xyz=list(rgb_vector_list[i])) print(longest_length / 10) pm.polyOptions(dest_obj, cs=True)
def set_color(*args): print('This will set the color by getting rgb value from slider') num = slider2.getRgbValue() print('slider numbers', num) for s in pm.ls(selection=True): print(s) pm.polyColorPerVertex(rgb=num, colorDisplayOption=True)
def clearLockedVerts(vtxList = [], disableColors = False): ''' clear mesh from having any locked vertices. ''' meshShape = pm.PyNode('{0}'.format(str(vtxList[0]).rpartition('.')[0])) pm.polyColorPerVertex(vtxList, rgb=(0, 0, 0), cdo = True) if disableColors: pm.setAttr('{0}.displayColors'.format(str(vtxList[0]).rpartition('.')[0]), False) checkAddReturnAttr(meshShape, vtxValue = [], attrName = 'lockedVtx', action = 'clear')
def makeVtxColorSet(obj): #???2????ColorSet?????m?F colSetLis = pm.polyColorSet(obj, query=1, allColorSets=1) if type(colSetLis) == list and u'colorSet_for_cartoonBlur' in pm.polyColorSet(obj, query=1, allColorSets=1): pm.polyColorSet( colorSet = 'colorSet_for_cartoonBlur', delete = 1) pm.confirmDialog( title="CartoonBlur", message="Vertex color set 'colorSet_for_cartoonBlur' is already exsist./Overwrited") pm.polyColorSet(obj, create = 1, rpt = "RGB", colorSet = 'colorSet_for_cartoonBlur') pm.polyColorPerVertex (obj, rgb = (1.0,1.0,1.0) ) pm.confirmDialog( title="CartoonBlur", message="???_?J???[?fcolorSet_for_cartoonBlur?f??????h??????????G?t?F?N?g???????????B\n?????x????????????????x???????????????????o?O????????")
def paint(selection, colour=None): """ Colour selection """ colour = colour or BASE_COLOUR if paint.last: try: pmc.polyColorPerVertex(paint.last, rgb=BASE_COLOUR, cdo=True) except pmc.MayaNodeError as e: print e pmc.polyColorPerVertex(selection, rgb=colour, cdo=True) paint.last = selection
def intersections(self, a, b): bDoutside = pm.duplicate(b, n="tmpBDoutside")[0] bDinside = pm.duplicate(b, n="tmpBDinside")[0] aCopyDupe = pm.duplicate(a, n="aCopyDupe")[0] dupes = [ bDoutside, bDinside, aCopyDupe, ] for dupe in dupes: dupe.setParent(w=True) self.polygonVolume(bDinside, -.005) pm.polyColorPerVertex(bDinside, r=1, g=0, b=0, a=1, cdo=1) pm.polyColorPerVertex(bDoutside, r=0, g=0, b=0, a=1, cdo=1) bColoured = pm.polyUnite(bDoutside, bDinside, ch=False)[0] bColoured.setParent(w=True) pm.delete(bColoured, ch=True) pm.transferAttributes(bColoured, aCopyDupe, sourceColorSet="colorSet1", targetColorSet="colorSet1", transferColors=True, sampleSpace=0, colorBorders=1) pm.delete(aCopyDupe, ch=True) pm.delete(bColoured) aVerts = [ str(a) + ".vtx[" + x.split("[")[-1].split("]")[0] + "]" for x in cmds.ls(str(aCopyDupe) + ".vtx[*]", fl=1) if cmds.polyColorPerVertex(x, q=1, rgb=1)[0] < .51 ] #bVerts = [str(b)+".vtx["+x.split("[")[-1].split("]")[0]+"]" for x in cmds.ls(str(bCopyDupe)+".vtx[*]",fl=1) if cmds.polyColorPerVertex(x,q=1,rgb=1)[0] < .51] pm.delete(aCopyDupe) sel = pm.select(aVerts) selVerts = pm.ls(sl=True) pm.select(a) Verts = pm.select(pm.polyListComponentConversion(tv=True)) allVerts = pm.ls(sl=True) pm.select(allVerts) pm.select(selVerts, d=True)
def setVtxColorFromArnoldAttr( attrName='color' ): if attrName.startswith('mtoa_constant_'): attrName = attrName[14:] for obj in pm.selected(): try: shp = obj.getShape() attr = 'mtoa_constant_'+attrName rgb = [] if shp.hasAttr( attr ): rgb = shp.getAttr( attr ) pm.polyColorPerVertex( obj, colorRGB=rgb, alpha=1, colorDisplayOption=True) except: continue
def lockVerts(vtxList = []): ''' "locks" verts from having influence values being manipulated by any weightUtility tool. locked = red ''' meshShape = pm.PyNode('{0}'.format(str(vtxList[0]).rpartition('.')[0])) vtxList = checkAddReturnAttr(meshShape, vtxValue = vtxList, attrName = 'lockedVtx', action = 'add') if not vtxList: pm.warning('Not verts provided.') return pm.polyColorPerVertex('{0}'.format(str(vtxList[0]).rpartition('.')[0]), rgb=(0, 0, 0), cdo = True) pm.polyColorPerVertex(vtxList, rgb=(1, 0, 0), cdo = True) pm.setAttr('{0}.displayColorChannel'.format(meshShape), 'Specular') return vtxList
def SetMiddleGrey( NObject ): NObjName = '%s' % NObject.name() # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to 0.5 Grey for v in range(len(ObjectVerts)): pm.polyColorPerVertex( ObjectVerts[v], colorRGB=(0.5,0.5,0.5), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def spawnEnemy( minSpawn, maxSpawn): colorRGBV = [1,1,0] rMax = maxSpawn rMin = minSpawn spawnMin = rMin + .01 spawnMax = rMax - .01 locX = random.uniform(spawnMin, spawnMax) locY = random.uniform(spawnMin, spawnMax) moveVectorX = random.uniform(-1.0,1.0) moveVectorY = random.uniform(-1.0,1.0) mayaObj = pm.polyCube( name="Enemy", w=1, h=1, d=1, cuv=0, ax=(0,1,0), sx=1, sy=1, sz=1 ) moveObj(mayaObj[0], locX, 0, locY) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() pVs = pm.ls( selection=True, fl=True ) pm.select( cl=True ) for v in range(len(pVs)): pm.polyColorPerVertex( pVs[v], colorRGB=colorRGBV, alpha=1.0, cdo=True, notUndoable=True ) return [mayaObj, moveVectorX, moveVectorY]
def makeVColorMask(obj,obj_v_len): #?J???[?Z?b?g??擾 pm.polyColorSet(obj, currentColorSet=True, colorSet= 'colorSet_for_cartoonBlur' ) temp = pm.polyColorSet( query=True, currentColorSet=True ) vColorMask = [ 1 - (sum(pm.polyColorPerVertex( obj.vtx[i],q=True,r=True,g=True,b=True ))/3 ) for i in range(0,obj_v_len) ] print(vColorMask) return vColorMask
def SimpleNoise( NObject, FMin, FMax ): # Set Local Variables NObjName = '%s' % NObject.name() min = FMin max = FMax # Select the Objects Vertices pm.selectMode( co=True ) pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() # List the Objects Vertices ObjectVerts = pm.ls( selection=True, fl=True ) pm.select( cl=True ) # For Every Vertex on the Object, Set its Vertex Color to 0.5 Grey for v in range(len(ObjectVerts)): FValue = random.uniform( min, max ) pm.polyColorPerVertex( ObjectVerts[v], colorRGB=( FValue, FValue, FValue ), alpha=1.0) # Release the Selection Constraints pm.polySelectConstraint( mode=0 ) pm.selectMode( o=True ) # Select the Object Again pm.select( NObjName )
def axisWidget(parentUnder=BLANK): ''' Makes colored object represent the 3 axes (as a child of the selection if possible). Can take an object to be the parent, or None for no parent. ''' sel = selected() info = { 'x': [[1, 0, 0], [1, 0, 0, 1]], 'y': [[0, 1, 0], [1, 1, 0, 1]], 'z': [[0, 0, 1], [0, 0, 1, 1]], } cyls = [] for name, (axis, color) in info.items(): cyl = polyCylinder(radius=.1, axis=axis)[0] cyl.t.set(axis) polyColorPerVertex(cyl, r=color[0], g=color[1], b=color[2]) cyl.displayColors.set(True) cyls.append(cyl) obj = polyUnite(cyls, ch=False)[0] if parentUnder is not None: try: if parentUnder is BLANK: if sel: obj.setParent(sel[0]) else: obj.setParent(parentUnder) obj.t.set(0, 0, 0) obj.r.set(0, 0, 0) except Exception: pass return obj
def makeColors(obj, freq=3, baseColor=[r.random(), r.random(), r.random()]): numVert = len(obj[0].vtx) print numVert mc.select(clear=1) for i in range(0, numVert): vtxName = obj[0] + ".vtx[%d]" % i mc.select(vtxName, add=1) mc.polyColorPerVertex(colorRGB=baseColor, colorDisplayOption=1) mc.select(clear=1) for i in range(0, numVert, freq): vtxName = obj[0] + ".vtx[%d]" % i mc.select(vtxName) mc.polyColorPerVertex(colorRGB=[r.random(), r.random(), r.random()], colorDisplayOption=1) mc.select(clear=1)
def run(): RawMovementVector = IntVector2( 0, 0 ) numEnemies = 15 playSpaceMinMaxX = 50 playSpaceMinMaxY = 50 enemyList = [] # Init SDL if sdl2.SDL_Init(sdl2.SDL_INIT_TIMER|sdl2.SDL_INIT_GAMECONTROLLER|sdl2.SDL_INIT_EVENTS) != 0: print(sdl2.SDL_GetError()) return -1 # Init Controller controller = sdl2.SDL_GameController() for i in range(sdl2.SDL_NumJoysticks()): if sdl2.SDL_IsGameController(i): controller = sdl2.SDL_GameControllerOpen(i) # Create SDL Window ctrlWindow = sdl2.SDL_CreateWindow( b"Control", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 200, 150, sdl2.SDL_WINDOW_INPUT_FOCUS|sdl2.SDL_WINDOW_HIDDEN ) if not ctrlWindow: print(sdl2.GetError()) return -1 # Init Player player = pm.polyCube( name="Player", w=1, h=1, d=1, cuv=0, ax=(0,1,0), sx=1, sy=1, sz=1 ) if player is None: print "ERROR! Player not created!" return -1 else: pm.selectType( pv=True ) pm.polySelectConstraint( type=0x0001, mode=3 ) pm.select() pVs = pm.ls( selection=True, fl=True ) pm.select( cl=True ) for v in range(len(pVs)): pm.polyColorPerVertex( pVs[v], colorRGB=(1.0,0.0,0.0), alpha=1.0, cdo=True, notUndoable=True ) pSpeed = 40.0 for i in range(numEnemies): thisE = spawnEnemy(-(playSpaceMinMaxX), playSpaceMinMaxX) enemyList.append(thisE) print enemyList # Start Ticks lastTime = 0 cTime = sdl2.SDL_GetTicks() activeEnemies = numEnemies playerScale = 1.0 # Start Game Loop running = True while running: # See if Yout Won achieved #print activeEnemies if activeEnemies < 1: sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() pm.select( all=True ) pm.delete() return "You Won!" #Calculate Delta Time lastTime = cTime cTime = sdl2.SDL_GetTicks() dTime = cTime - lastTime if dTime > 16: dTime = 16 deltaM = float(dTime)/float(1000) ButtonPressed = False # Process Input evnt = sdl2.SDL_Event() while sdl2.SDL_PollEvent(ctypes.byref(evnt)) != 0: if evnt.type == sdl2.SDL_QUIT: running = False break elif evnt.type == sdl2.SDL_CONTROLLERAXISMOTION: if evnt.caxis.axis == sdl2.SDL_CONTROLLER_AXIS_LEFTX: RawMovementVector.x = evnt.caxis.value break elif evnt.caxis.axis == sdl2.SDL_CONTROLLER_AXIS_LEFTY: RawMovementVector.y = evnt.caxis.value break elif evnt.type == sdl2.SDL_CONTROLLERBUTTONDOWN: if evnt.cbutton.button == sdl2.SDL_CONTROLLER_BUTTON_A: ButtonPressed = True break elif evnt.type == sdl2.SDL_CONTROLLERBUTTONUP: if evnt.cbutton.button == sdl2.SDL_CONTROLLER_BUTTON_A: ButtonPressed = False break elif evnt.type == sdl2.SDL_KEYDOWN: if evnt.key.keysym.sym == sdl2.SDLK_ESCAPE: sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() break #print RawMovementVector.x, RawMovementVector.y, ButtonPressed # Remap Raw Movement to -1 to 1 in float Movement = RemapMovement( RawMovementVector.x, RawMovementVector.y ) #print Movement.x, Movement.y pMoveX = Movement.x * (deltaM*pSpeed) pMoveY = Movement.y * (deltaM*pSpeed) moveObj( player[0], pMoveX, 0.0, pMoveY) for i in range(len(enemyList)): testList = enemyList testList[i] = updateEnemy( testList[i], playSpaceMinMaxX, playSpaceMinMaxY, deltaM ) if detectCollision( player[0], testList[i][0][0] ) == True: vis = pm.getAttr( testList[i][0][0]+'.visibility' ) if vis == True: pm.hide( enemyList[i][0][0] ) activeEnemies = activeEnemies - 1 playerScale = playerScale + 0.5 pm.xform( player[0], scale=[playerScale, playerScale, playerScale] ) # redraw viewport pm.refresh( cv=True ) sdl2.SDL_DestroyWindow(ctrlWindow) sdl2.SDL_Quit() return 0
def getVertexColor(): return py.polyColorPerVertex(query=True, colorRGB=True)
def exportSkin(meshes=None, path=None): """ Exports the given mesh nodes as a skyrim skin fbx. If no meshes are given the current selected meshes will be used. If no meshes are selected all meshes skinned to the root skeleton will be used. Args: meshes(list): A list of meshes to export. path(str): The destination fbx path. Returns: str: The exported file path. """ path = path or saveFbxDialog('Save Skin Dialog', dir=getSceneCharacterAssetDirectory()) # Get the root skeleton root = getRootJoint() if root is None: raise RootJointException('Export rig failed, could not find a root joint in the scene.') rootSkeleton = [root] + root.listRelatives(ad=True, type='joint') def getSkinnedMeshes(): clusters = set() for joint in rootSkeleton: for cluster in pmc.ls(pmc.listConnections(joint), type='skinCluster'): clusters.add(cluster) return [pmc.skinCluster(cluster, geometry=True, q=True)[0] for cluster in clusters] meshes = meshes or pmc.selected() or getSkinnedMeshes() meshes = getMeshes(meshes) if len(meshes) > 1: raise NotImplementedError('Multiple meshes selected for export. Currently we only support one mesh per skin.') # Check max influences for mesh in meshes: if not _checkMaxInfluences(mesh): raise MaxInfluenceException('Failed to export "%s". Skinning contains more than 4 influences.' % mesh) try: pmc.undoInfo(openChunk=True) # Set vertex colors to white for mesh in meshes: pmc.polyColorPerVertex(mesh, colorRGB=[1, 1, 1], a=1) # To fix certain issues with skinning we need to mess with the normals for mesh in meshes: pmc.bakePartialHistory(mesh, prePostDeformers=True) # Delete Non-deformer history pmc.polyNormalPerVertex(mesh, unFreezeNormal=True) # Unlock the normals pmc.polySoftEdge(mesh, a=180) # Soften the normals pmc.bakePartialHistory(mesh, prePostDeformers=True) # Delete Non-deformer history pmc.polyNormalPerVertex(mesh, freezeNormal=True) # Lock the normals pmc.polySoftEdge(mesh, a=0) # Harden the normals pmc.bakePartialHistory(mesh, prePostDeformers=True) # Delete Non-deformer history # Remove all joint constraints constraints = root.listRelatives(ad=True, type='constraint') if len(constraints) > 0: pmc.delete(constraints) # Disconnect message connections for joint in rootSkeleton: joint.message.disconnect() if not joint.hasAttr(MATCH_ATTR_NAME): continue for input in joint.attr(MATCH_ATTR_NAME).inputs(plugs=True): input.disconnect(joint.attr(MATCH_ATTR_NAME)) exportFbx(rootSkeleton + [mesh.getParent() for mesh in meshes], path=path) finally: pmc.undoInfo(closeChunk=True) pmc.undo() # Export nif ckcmd.importskin(path, os.path.dirname(path))
def erase(mesh): """ Clear / Prepare colour on mesh """ pmc.polyColorPerVertex(mesh.vtx, rgb=BASE_COLOUR) mesh.displayColors.set(0)
pm.setAttr('{0}.displayColors'.format(str(vtxList[0]).rpartition('.')[0]), False) checkAddReturnAttr(meshShape, vtxValue = [], attrName = 'lockedVtx', action = 'clear') mesh = pm.PyNode('pPlaneShape1') vertSphere = pm.PyNode('joint4_vtxSphere') jnt = pm.PyNode('joint4') srcJnt = pm.PyNode('joint1') skClstr = pm.PyNode('skinCluster1') createVertSphere() dist, wPosition = vSphereinfo(mesh, vertSphere) vtxFromPnt(mesh, minDist = 0, maxDist = dist, pntCenter = wPosition, selectVtx = True) selVerts = pm.cmds.ls(sl = True, fl = True) lockVerts(selVerts) lockedVerts = checkAddReturnAttr(mesh, vtxValue = [], attrName = 'lockedVtx', action = 'return') clearLockedVerts(vtxList = selVerts, disableColors = False) vtxToSkinWeights(mesh, vertSphere, jnt, srcJnt, fallOffRate = 5) pm.polyColorPerVertex(pm.selected()[0], query=True, g=True, b=True ) pm.getAttr('pPlaneShape2.displayColorChannel') pm.setAttr('pPlaneShape2.displayColorChannel', 'Specular' )
def setVertexColor(r=1, g=0, b=0): c = (r, g, b) py.polyColorPerVertex(colorRGB=c) return c