def render(*args): global size, material_dir, textures_dir size = pm.intSliderGrp("baker_size", q=True, v=True) material_dir = pm.textField("baker_mat_dir", q=True, tx=True) textures_dir = pm.textField("baker_out_dir", tx=True, q=True) redshift_dir = os.path.join(pm.workspace(fn=True), "images") os.chdir(textures_dir) settings() selected = pm.selected(type="transform") or pm.ls(type="transform") selected = [sl for sl in selected if sl.listRelatives(type="mesh")] names = [mesh.name().split("|")[-1] for mesh in selected] pm.showHidden(selected) if pm.checkBox("baker_id", q=True, v=True): for mesh, mesh_name in zip(selected, names): bakeID(mesh, mesh_name + "_id") if pm.checkBox("baker_ao", q=True, v=True): pm.select(pm.ls(type="mesh")) pm.hyperShade(a="ao_material") for mesh, mesh_name in zip(selected, names): bake(mesh, mesh_name + "_ao.png") if pm.checkBox("baker_shadow", q=True, v=True): pm.select(pm.ls(type="mesh")) pm.hyperShade(a="shadow_material") for mesh, mesh_name in zip(selected, names): bake(mesh, mesh_name + "_shadow.png") if pm.checkBox("baker_mat", q=True, v=True): for mesh_name in names: bakeMaterials(mesh_name) pm.warning("finished")
def exportCameras(self, cacheFolder, log): perspCameras = pm.listCameras(o=0, p=1) userCameras = [] for cam in perspCameras: if 'persp' not in cam: userCameras.append(cam) self.userCameras = userCameras for cam in userCameras: startTime = pm.playbackOptions(query=True, minTime=True) endTime = pm.playbackOptions(query=True, maxTime=True) pm.select(cam) fileName = cam + '.abc' fileName = os.path.join(cacheFolder, fileName).replace('\\', '/') jobstring = "AbcExport " jobstring += "-j \" -fr %d %d -worldSpace" % (startTime, endTime) jobstring += ' -root ' + cam jobstring += ' -file ' + fileName jobstring += '\"' print jobstring try: pm.hide(all=True) pm.select(cam) pm.showHidden(above=True) pm.mel.eval(jobstring) except: pm.warning('Could not export %s cam' % cam)
def _createNode(self): try: cam = pm.ls(sl=True, type="camera")[0] except: raise AttributeError("Please select a camera shape!") node = pm.nodetypes.ImagePlane() # adapted from cameraImagePlaneUpdate.mel node.message.connect(cam.imagePlane, nextAvailable=True) cam.horizontalFilmAperture.connect(node.sizeX) cam.verticalFilmAperture.connect(node.sizeY) cam.orthographicWidth.connect(node.width) cam.orthographicWidth.connect(node.height) node.attr("center").set(cam.getWorldCenterOfInterest()) for item in pm.listRelatives(cam, parent=True): pm.showHidden(item, below=True) for modelPanel in pm.getPanel(type="modelPanel"): modelCamera = pm.modelPanel(modelPanel, query=True) if modelCamera != "": for shape in pm.listRelatives(modelCamera, shapes=True): if shape == cam: editor = pm.modelPanel(modelPanel, query=True, modelEditor=True) pm.modelEditor(editor, edit=True, updateColorMode=True) break return node
def reapplyNoise(self, cmd=''): self.control = self.getAssociatedLocator() pc.showHidden(self.control) self.reconnectAnimationCurves(self.camera, self.control) target = pc.listRelatives(self.control, c=True, typ='transform')[0] pc.parent(self.camera, target) self.zeroTransforms(self.camera) self.connectOffsetAttributes() pc.select(self.control) self.closeUI()
def ToggleHairCtrlVis(state='switch'): hairCtrlsGroup = pm.ls('HairCtrlGroup')[0] if not hairCtrlsGroup: return if state == 'switch': pass elif state == 'show': pm.showHidden(hairCtrlsGroup, below=True) elif state == 'hide': pm.hide([ctrl.getChildren() for ctrl in hairCtrlsGroup.getChildren()])
def end(cls): for obj in cls.controlsToHide: showHidden(obj.getParent(), obj.getParent().getParent()) cls.controlsToHide = [] if cls.hideMain: showHidden(cls.mainShapes) if not cls.mainShapes[0].isVisible(): plug = cls.mainShapes[0].visibility.listConnections(s=True, p=True) if plug: plug[0].set(1)
def matchMesh(self, btn): """ This function can execute all functions related to creating a match mesh Args: None Returns (None) """ smoothMesh = self.get_smooth_mesh() skinMesh = self.get_skin_mesh() pm.hide(skinMesh) pm.showHidden(smoothMesh) print smoothMesh print 'YOU DID IT NOW MATCH THAT MESH!'
def hideShowCurves(flag): sel = pc.ls(sl=True) try: if flag: pc.select(pc.ls(type=pc.nt.NurbsCurve)) pc.Mel.eval('HideSelectedObjects') else: pc.select(pc.ls(type=pc.nt.NurbsCurve)) pc.showHidden(b=True) except: pass pc.select(sel)
def shaderSwitch(pRenderStyle, *Args): skinMat = getMaterial('Eyelashes') fillMat = getMaterial('blocker') if pRenderStyle == 'Normal': applyMatToSelection(skinMat, ['Body_%s' % (globalGender[0]), 'Eyes']) pm.hide('Eyes', 'blocker', 'IconRenderer') pm.showHidden('Eyelashes') if pRenderStyle == 'Flat': applyMatToSelection(fillMat, ['Body_%s' % (globalGender[0]), 'Eyes']) pm.showHidden('Eyes', 'blocker', 'IconRenderer') pm.hide('Eyelashes')
def save_icon(object, filename, imageFormat): """ Take picture of object, render using playblast for later use as a QT Button icon. """ path = os.path.join(save_folder, "{}.png".format(filename)) # Store all hidden items items = pm.hide(allObjects=True, returnHidden=True) # Show only object we want to focus on and fit view pm.showHidden(object) pm.viewFit() # PNG is 32 in the imageFormat enum. pm.setAttr("defaultRenderGlobals.imageFormat", imageFormat) pm.playblast(completeFilename=path, forceOverwrite=True, format='image', width=200, height=200, showOrnaments=False, startTime=1, endTime=1, viewer=False) # Show all the items we hid a while back. pm.showHidden(items) # Return camera to previous view. pm.viewSet(previousView=True)
def createWriteNodes(shadingMixNode, shadingGroupNode, blendReturned): for i in blendReturned: attr = i + '.output' if pm.getAttr(attr, type=True) == 'float3': # VECTOR typeAttr = 'vector' nodeToConnect = pm.createNode( 'aiWriteColor' , n='aiWriteColor_AOV') else: # FLOAT typeAttr = 'float' nodeToConnect = pm.createNode( 'aiWriteFloat' , n='aiWriteFloat_AOV') AOV_name = i.name().split('_')[1] attrToConnect = nodeToConnect.listAttr(st='input') attrName = nodeToConnect.listAttr(st='aovName') pm.setAttr(attrName[0], AOV_name) pm.connectAttr(attr, attrToConnect[0]) inConnect = shadingGroupNode.listConnections(d=False, t=['alLayer', 'aiWriteColor', 'aiWriteFloat'], p=True)[0] pm.connectAttr(inConnect, nodeToConnect.listAttr(st='beauty')[0]) pm.connectAttr(nodeToConnect.listAttr(st='outColor')[0], shadingGroupNode.listAttr(st='surfaceShader')[0], f=True) selectionList = [] for i in shadingGroupNode.listConnections(): if i.nodeType() == "transform": selectionList.append(i) pm.select(selectionList) pm.showHidden() folder_to_save = os.path.join(folder_to_save_base, shadingMixNode.name()) s = pm.ls(sl=True) nameTr = shadingMixNode.name() if (len(s) != 1): pm.polyUnite(s, n=nameTr) #cmds.arnoldRenderToTexture(folder=folder_to_save, enable_aovs=True, resolution=2048, all_udims=True) pm.select(cl=True)
def exportAlembic(self, namespace, cacheFolder, log): print 'actually exporting' geoSuffix = pm.optionVar.get('geoString', 'REN') meshes = [ mesh.fullPath() for mesh in pm.ls(namespace + ':*' + geoSuffix, type='transform') ] startTime = pm.playbackOptions(query=True, minTime=True) endTime = pm.playbackOptions(query=True, maxTime=True) log.writelines('Exporting %s, path %s \n' % (namespace, cacheFolder)) if meshes: pm.select(meshes) log.writelines('Exporting meshes %s \n' % (', '.join(meshes))) fileName = namespace + '.abc' fileName = os.path.join(cacheFolder, fileName).replace('\\', '/') print fileName jobstring = "AbcExport " jobstring += "-j \" -fr %d %d -uvWrite" % (startTime, endTime) for mesh in meshes: jobstring += ' -root ' + mesh jobstring += ' -file ' + fileName jobstring += '\"' try: pm.hide(all=True) pm.select(meshes) pm.showHidden(above=True) pm.mel.eval(jobstring) except: pm.warning('Could not export %s rig' % namespace)
def show_group(shown_group): group_image = {'up_eye_locator_grp': 'thumb_upeye.png', 'low_eye_locator_grp': 'thumb_loweye.png', 'up_lip_locator_grp': 'thumb_upmouth.png', 'low_lip_locator_grp': 'thumb_lowmouth.png', 'head_locator_grp': 'thumb_jaw_head.png', 'cheek_locator_grp': 'thumb_cheek.png'} if shown_group == 'all': py.showHidden('up_eye_locator_grp', 'low_eye_locator_grp', 'up_lip_locator_grp', 'low_lip_locator_grp', 'head_locator_grp', 'cheek_locator_grp') else: py.hide('up_eye_locator_grp', 'low_eye_locator_grp', 'up_lip_locator_grp', 'low_lip_locator_grp', 'head_locator_grp', 'cheek_locator_grp') py.showHidden(shown_group) guide_gui(group_image[shown_group])
def showOrients(): showHidden(fossil_card.getArrows())
import os import sys import pymel.core as pm import maya.cmds as mc pm.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer') pm.hide('ground:Ground00_MSH') pm.duplicate('BG_RL', n='BG_GROUND_RL', ic=1) pm.editRenderLayerGlobals(currentRenderLayer='BG_GROUND_RL') pm.select('ground:Ground00_MSH', r=1) pm.showHidden(a=1) try: pm.hide('ANB:BackyardVampirinaWeddingMess:Wedding_Ground00_MSH') except: print('CARI GROUND!!!!!!!!!!!!!') pm.editRenderLayerAdjustment("vraySettings.renderMaskMode") pm.setAttr("vraySettings.renderMaskMode", 3) pm.editRenderLayerAdjustment("vraySettings.renderMaskObjectIDs") pm.setAttr('vraySettings.renderMaskObjectIDs', "3001", type="string") pm.select('ground:Ground00_MSH', r=1) mc.vray("addAttributesFromGroup", "ground:Ground00_MSH", "vray_objectID", 1) pm.editRenderLayerAdjustment("ground:Ground00_MSH.vrayObjectID") pm.setAttr("ground:Ground00_MSH.vrayObjectID", 3001) mc.sets('ground:Ground00_MSH', edit=1, forceElement='VOP_Set')
def eyesCallback(*Args): pm.showHidden('Eyes') pm.select('mixamorig:RightEye', 'mixamorig:LeftEye')
def buildIkChain(start, end, pvLen=None, stretchDefault=1, endOrientType=util.EndOrient.TRUE_ZERO, twists={}, makeBendable=False, name='', groupName='', controlSpec={}): ''' :param int pvLen: How far from the center joint to be, defaults to half the length of the chain. .. todo:: * Have fk build as rotate only if not stretchy :param dict twists: Indicates how many twists each section has, ex {1: 2} means joint[1] has 2 twists, which means a 3 joint arm chain becomes shoulder, elbow, twist1, twist2, wrist ''' chain = util.getChain(start, end) # Simplify the names controlChain = util.dupChain(start, end) for j, orig in zip(controlChain, chain): j.rename(util.trimName(orig) + '_proxy') mainJointCount = len(chain) - sum(twists.values()) # Take the linear chain and figure out what are the "main ik", and which # are the twist joints. Also parent the mainArmature as a solo chain for ik application. mainArmature = [] subTwists = {} cur = 0 for i in range(mainJointCount): mainArmature.append(controlChain[cur]) if len( mainArmature ) > 1: # Need to reparent so the 'pivot' joints are independent of the twists if mainArmature[-1].getParent() != mainArmature[ -2]: # ... unless this section has no twists and is already parented. mainArmature[-1].setParent(mainArmature[-2]) cur += 1 if i in twists: subTwists[mainArmature[-1]] = [] for ti in range(twists[i]): subTwists[mainArmature[-1]].append(controlChain[cur]) controlChain[cur].setParent( w=True ) # This ends up being temporary so the ik is applied properly cur += 1 # actual ik node mainIk = ikHandle(sol='ikRPsolver', sj=mainArmature[0], ee=mainArmature[-1])[0] # NOT using Spring because it acts odd. If the pelvis turns, the poleVectors follow it. # Make as RP first so the ik doesn't flip around #PyNode('ikSpringSolver').message >> mainIk.ikSolver # Build the main ik control hide(mainIk) hide(controlChain) if not name: name = util.trimName(start) ctrl = controllerShape.build(name + '_Ik', controlSpec['main'], type=controllerShape.ControlType.IK) container = group(n=name + '_grp') container.setParent(node.mainGroup()) pdil.dagObj.moveTo(ctrl, end) pdil.dagObj.zero(ctrl).setParent(container) # Orient the main ik control if endOrientType == util.EndOrient.TRUE_ZERO: util.trueZeroSetup(end, ctrl) elif endOrientType == util.EndOrient.TRUE_ZERO_FOOT: util.trueZeroFloorPlane(end, ctrl) elif endOrientType == util.EndOrient.JOINT: pdil.dagObj.matchTo(ctrl, end) ctrl.rx.set(util.shortestAxis(ctrl.rx.get())) ctrl.ry.set(util.shortestAxis(ctrl.ry.get())) ctrl.rz.set(util.shortestAxis(ctrl.rz.get())) pdil.dagObj.zero(ctrl) elif endOrientType == util.EndOrient.WORLD: # Do nothing, it's built world oriented pass pdil.dagObj.lock(ctrl, 's') mainIk.setParent(ctrl) # I think orientTarget is for matching fk to ik orientTarget = duplicate(end, po=True)[0] orientTarget.setParent(ctrl) pdil.dagObj.lock(orientTarget) orientConstraint(orientTarget, mainArmature[-1]) hide(orientTarget) pdil.dagObj.lock(mainIk) attr, jointLenMultiplier, nodes = util.makeStretchyNonSpline( ctrl, mainIk, stretchDefault) # &&& Need to do the math for all the # Make the offset joints and setup all the parenting of twists subArmature = [] rotationOffsetCtrls = [] bendCtrls = [] for i, j in enumerate( mainArmature[:-1] ): # [:-1] Since last joint can't logically have twists if makeBendable: j.drawStyle.set( 2 ) # Probably should make groups but not drawing bones works for now. offset = duplicate(j, po=True)[0] offset.setParent(j) offset.rename(pdil.simpleName(j, '{}_Twist')) #subArmature.append(offset) ### OLD if True: ### NEW if not makeBendable: subArmature.append(offset) else: if i == 0: subArmature.append(offset) else: offsetCtrl = controllerShape.build( 'Bend%i' % (len(bendCtrls) + 1), { 'shape': 'band', 'size': 10, 'color': 'green 0.22', 'align': 'x' }) pdil.dagObj.matchTo(offsetCtrl, offset) offsetCtrl.setParent(offset) showHidden(offsetCtrl, a=True) subArmature.append(offsetCtrl) bendCtrls.append(offsetCtrl) rotationOffsetCtrls.append(offset) # &&& Deprectated? attrName = pdil.simpleName(j, '{}_Twist') ctrl.addAttr(attrName, at='double', k=True) ctrl.attr(attrName) >> offset.rx if i in twists: for subTwist in subTwists[j]: subTwist.setParent(j) #subArmature.append(subTwist) ### NEW comment out attrName = pdil.simpleName(subTwist) ctrl.addAttr(attrName, at='double', k=True) ctrl.attr(attrName) >> subTwist.rx if not makeBendable: subArmature.append(subTwist) else: if True: ### NEW offsetCtrl = controllerShape.build( 'Bend%i' % (len(bendCtrls) + 1), { 'shape': 'band', 'size': 10, 'color': 'green 0.22', 'align': 'x' }) pdil.dagObj.matchTo(offsetCtrl, subTwist) offsetCtrl.setParent(subTwist) subTwist.drawStyle.set( 2 ) # Probably should make groups but not drawing bones works fine for now. showHidden(offsetCtrl, a=True) subArmature.append(offsetCtrl) bendCtrls.append(offsetCtrl) #offset.rename( simpleName(j, '{0}_0ffset') ) #for mainJoint, (startSegment, endSegment) in zip( mainArmature, zip( rotationOffsetCtrls, rotationOffsetCtrls[1:] + [mainArmature[-1]] )): # if mainJoint in subTwists: # twistSetup(subTwists[mainJoint], startSegment, endSegment) # Since we don't want twists affecting eachother, base them off the mainArmature if False: ### SKipping this new stuff and resurrecting the old twists for startSegment, endSegment in zip(mainArmature, mainArmature[1:]): #print( 'HAS SUB TWISTS', startSegment in subTwists ) if startSegment in subTwists: twistSetup(ctrl, subTwists[startSegment], startSegment, endSegment, jointLenMultiplier) ''' # Build the groups to hold the twist controls groups = [] for i, (j, nextJ) in enumerate(zip(mainArmature[:-1], mainArmature[1:])): g = group(em=True) parentConstraint(j, g) g.rename( pdil.dagObj.simpleName(g, '{0}_grp') ) groups.append(g) g.setParent(container) if j in subTwists: #totalDist = pdil.dagObj.distanceBetween(j, nextJ) for subTwist in subTwists[j]: dist = pdil.dagObj.distanceBetween(j, subTwist) #disc = 'disc'() disc = controllerShape.build('Twist', {'shape': 'disc', 'align': 'x', 'size': 3}) disc.setParent(g) disc.t.set( 0, 0, 0 ) disc.r.set( 0, 0, 0 ) pdil.dagObj.lock(disc) disc.rx.unlock() disc.tx.unlock() # Manage the lengths of the twist joints and their controls mult = pdil.math.multiply( dist, jointLenMultiplier) mult >> disc.tx mult >> subTwist.tx disc.rx >> subTwist.rx ''' constraints = util.constrainAtoB(chain, subArmature + [mainArmature[-1]]) # PoleVector if not pvLen or pvLen < 0: pvLen = util.chainLength(mainArmature) * 0.5 out = util.calcOutVector(mainArmature[0], mainArmature[1], mainArmature[-1]) pvPos = out * pvLen + dt.Vector( xform(mainArmature[1], q=True, ws=True, t=True)) pvCtrl = controllerShape.build(name + '_pv', controlSpec['pv'], type=controllerShape.ControlType.POLEVECTOR) pdil.dagObj.lock(pvCtrl, 'r s') xform(pvCtrl, ws=True, t=pvPos) controllerShape.connectingLine(pvCtrl, mainArmature[1]) poleVectorConstraint(pvCtrl, mainIk) pdil.dagObj.zero(pvCtrl).setParent(container) # Socket offset control socketOffset = controllerShape.build( name + '_socket', controlSpec['socket'], type=controllerShape.ControlType.TRANSLATE) socketContainer = util.parentGroup(start) socketContainer.setParent(container) pdil.dagObj.moveTo(socketOffset, start) pdil.dagObj.zero(socketOffset).setParent(socketContainer) pdil.dagObj.lock(socketOffset, 'r s') pointConstraint(socketOffset, mainArmature[0]) # Reuse the socketOffset container for the controlling chain mainArmature[0].setParent(socketContainer) # hide( mainArmature[0] ) ''' Currently unable to get this to update, maybe order of operations needs to be enforced? # Add switch to reverse the direction of the bend reverseAngle = controlChain[1].jointOrient.get()[1] * -1.1 ctrl.addAttr( 'reverse', at='short', min=0, max=1, dv=0, k=True ) preferredAngle = pdil.math.condition( ctrl.reverse, '=', 0, 0, reverseAngle ) twist = pdil.math.condition( ctrl.reverse, '=', 0, 0, -180) preferredAngle >> controlChain[1].preferredAngleY twist >> mainIk.twist pdil.math.condition( mainIk.twist, '!=', 0, 0, 1 ) >> mainIk.twistType # Force updating?? ''' if True: # &&& LOCKABLE endToMidDist, g1 = pdil.dagObj.measure(ctrl, pvCtrl, 'end_to_mid') startToMidDist, g2 = pdil.dagObj.measure(socketOffset, pvCtrl, 'start_to_mid') parent(endToMidDist, g1, startToMidDist, g2, container) #ctrl.addAttr( 'lockPV', at='double', min=0.0, dv=0.0, max=1.0, k=True ) #switcher.input[0].set(1) #print('--'* 20) #print(mainArmature) for jnt, dist in zip(mainArmature[1:], [startToMidDist, endToMidDist]): axis = util.identifyAxis(jnt) lockSwitch = jnt.attr('t' + axis).listConnections(s=True, d=False)[0] if jnt.attr('t' + axis).get() < 0: pdil.math.multiply(dist.distance, -1) >> lockSwitch.input[1] else: dist.distance >> lockSwitch.input[1] util.drive(ctrl, 'lockPV', lockSwitch.attributesBlender, 0, 1) """ axis = identifyAxis(mainArmature[-1]) lockSwitchA = mainArmature[-1].attr('t' + axis).listConnections(s=True, d=False)[0] if mainArmature[-1].attr('t' + axis).get() < 0: pdil.math.multiply( endToMidDist.distance, -1) >> lockSwitchA.input[1] else: endToMidDist.distance, -1 >> lockSwitchA.input[1] lockSwitchB = mainArmature[-2].attr('t' + axis).listConnections(s=True, d=False)[0] startToMidDist.distance >> lockSwitchB.input[1] #print(lockSwitchA, lockSwitchB, '-'* 20) drive(ctrl, 'lockPV', lockSwitchA.attributesBlender, 0, 1) drive(ctrl, 'lockPV', lockSwitchB.attributesBlender, 0, 1) """ # Register all the parts of the control for easy identification at other times. ctrl = pdil.nodeApi.RigController.convert(ctrl) ctrl.container = container ctrl.subControl['socket'] = socketOffset for i, bend in enumerate(bendCtrls): ctrl.subControl['bend%i' % i] = bend ctrl.subControl['pv'] = pvCtrl # Add default spaces space.addMain(pvCtrl) #space.add( pvCtrl, ctrl, spaceName=shortName(ctrl, '{0}_posOnly') ) #space.add( pvCtrl, ctrl, spaceName=shortName(ctrl, '{0}_posOnly'), mode=space.TRANSLATE) space.add(pvCtrl, ctrl) space.add(pvCtrl, ctrl, mode=space.Mode.TRANSLATE) return ctrl, constraints
def referenceLines(*pArgs): boolChk = pm.checkBox('GuidesVisible', value=True, query=True) if boolChk == True: pm.showHidden('Trace') if boolChk == False: pm.hide('Trace')
def make_offset_groups(**kwargs): py.showHidden('baseoffset') py.hide('master_locator_grp') delete_bool = kwargs.setdefault('delete', False) if delete_bool is True: for key in cl.EcGroup.group_offset_dict: for i in range(0, len(cl.EcGroup.group_offset_dict[key])): try: print 'deleting %s' % key py.delete(cl.EcGroup.group_offset_dict[key][i].group_name) except: print 'Tried to delete %s' % key py.delete('cn_head_jnt', 'low_jaw_grp') py.showHidden('master_locator_grp') py.hide('baseoffset') locator_placement_gui() else: master_jaw_grp = cl.EcGroup(groupName='low_jaw_grp').set_parent(operation='offset', parent='master_offset_grp')\ .match(DriveObject='cn_head_low_jaw_jnt').match(DrivenObject='master_offset_grp', DriveObject='cn_head_jnt', type='parent', maintainOffset=True)\ .match(DrivenObject='follicles_grp', DriveObject='cn_head_jnt', type='parent', maintainOffset=True) for key in cl.EcGroup.loc_name_pos_dict: num = 2 parent = 'master_offset_grp' side = ['rt_', 'lf_'] if key == 'head_low_jaw' or key == 'head': main_offset = [None] elif key == 'mouth_center_up': main_offset = [] main_offset.append(cl.EcGroup(groupName='cn_'+key+'_m_grp')) offset_group = cl.EcGroup(groupName='cn_'+key+'_offset_grp') main_offset[0].set_parent(operation='offset', parent=parent)\ .match(DriveObject='cn_'+key+'_jnt') offset_group.set_parent(operation='offset', parent=main_offset[0].group_name)\ .match(DriveObject='cn_'+key+'_jnt')\ .match(DriveObject='cn_'+key+'_f', deleteConstraint=False, maintainOffset=True) offset = cl.EcOffset(key, 'cn_', offset_group.group_name) elif 'mouth' in key: if 'low' in key: if key == 'mouth_center_low': side = ['cn_'] num = 1 parent = 'low_jaw_grp' else: parent = 'low_jaw_grp' main_offset = [] for i in range(0, num): main_offset.append(cl.EcGroup(groupName=side[i]+key+'_m_grp')) offset_group = cl.EcGroup(groupName=side[i]+key+'_offset_grp') main_offset[i].set_parent(operation='offset', parent=parent)\ .match(DriveObject=side[i]+key+'_jnt') offset_group.set_parent(operation='offset', parent=main_offset[i].group_name)\ .match(DriveObject=side[i]+key+'_jnt')\ .match(DriveObject=side[i]+key+'_f', deleteConstraint=False, maintainOffset=True) rotate_offset = cl.EcGroup(groupName=side[i]+key+'_rotate_grp')\ .set_parent(operation='offset', parent=offset_group.group_name) if 'low' in key: rotate_offset.match(DriveObject='cn_head_low_jaw_jnt', deleteConstraint=False, type='parent') offset = cl.EcOffset(key, side[i], rotate_offset.group_name).freeze() else: main_offset = [] for i in range(0, num): main_offset.append(cl.EcGroup(groupName=side[i]+key+'_m_grp')) offset_group = cl.EcGroup(groupName=side[i]+key+'_offset_grp') main_offset[i].set_parent(operation='offset', parent=parent)\ .match(DriveObject=side[i]+key+'_jnt') offset_group.set_parent(operation='offset', parent=main_offset[i].group_name)\ .match(DriveObject=side[i]+key+'_jnt')\ .match(DriveObject=side[i]+key+'_f', deleteConstraint=False, maintainOffset=True) offset = cl.EcOffset(key, side[i], offset_group.group_name) cl.EcGroup.group_offset_dict[key] = main_offset py.hide('baseoffset') offset_gui()
if not "{lod}" in args[1]: parser.error("OUTPUT must contain {lod}") sys.stderr.write("inputs are " + str(options) + " " + str(args)) import pymel.core as pm pm.openFile(args[0], loadReferenceDepth="none", force=True) details = [] for transform in pm.listTransforms(): try: lod = transform.resolution_export.get() if len(lod): path = args[1].format(lod=lod) pm.showHidden(transform) pm.select(transform) # unparent, otherwise the top node is also exported pm.parent(transform, world=True) pm.exportSelected(path, preserveReferences=True, force=True) details.append({"element": {"path": path}, "context": {"LOD": lod}}) except AttributeError: pass # pass outputs back print "begin-json details" print json.dumps(details, indent=4) print "====" # flush stdout, as os._exit does not do so
def orientsToggle(self): if self.ui.actionCard_Orients_2.isChecked(): showHidden(fossil_card.getArrows()) else: hide(fossil_card.getArrows())
def show(self): pm.showHidden('%s' % (self.light))
def makeHairMesh(name="HairMesh#", mat="", cSet="hairCrease", reverse=False, lengthDivs=7, widthDivs=4, Segments=4, width=1, curveDel=False, cShape='triangle'): '''Create a Hair Tube From Select Curve line or Edge or IsoPram''' sel = pm.selected() if not sel: print "Select some Curves or Edges or isopram" return if type(sel[0]) == pm.general.MeshEdge: pm.runtime.CreateCurveFromPoly() pathTransform = pm.selected()[0] elif type(sel[0]) == pm.general.NurbsSurfaceIsoparm: pm.runtime.DuplicateCurve() pathTransform = pm.selected()[0] pathTransform = [ t for t in pm.selected() if type(t) == pm.nodetypes.Transform ] pm.select(pathTransform, r=1) pathShape = pm.listRelatives(shapes=True) if type(pathShape[0]) == pm.nodetypes.NurbsCurve: minscale = [0.001, 0.001, 0.001] pathCurve = [(i, pathShape[pathTransform.index(i)]) for i in pathTransform] if pm.objExists("HairBaseProfileCurve"): profileCurve = pm.ls("HairBaseProfileCurve")[0] #print profileCurve.listRelatives()[0].listConnections()[0] profileCurve.listRelatives()[0].listConnections()[0].setRadius( width) pm.showHidden(profileCurve, a=1) else: shapeType = { 'circle': (3, 8), 'triangle': (1, 3), 'square': (1, 4) } profileCurve = pm.circle(c=(0, 0, 0), nr=(0, 1, 0), sw=360, r=width, d=shapeType[cShape][0], ut=0, tol=5.77201e-008, s=shapeType[cShape][1], ch=1, name="HairBaseProfileCurve") for a in [('overrideEnabled', 1), ('overrideRGBColors', 1), ('overrideColorRGB', (0.2, 0.5, 0.2))]: profileCurve[0].getShape().attr(a[0]).set(a[1]) pm.select(d=1) for crv in pathCurve: print crv pm.rebuildCurve(crv[0], kep=1) if reverse: pm.reverseCurve(crv[0]) #profileInstance = instance(profileCurve,n="pCrv_instance"+string(pathCurve.index(crv))) if pm.objExists("HairCtrlGroup"): hairOncsGroup = pm.ls("HairCtrlGroup")[0] else: hairOncsGroup = pm.group(name="HairCtrlGroup") #pm.parent(hairOncGroup,crv[0]) mPath = pm.pathAnimation(profileCurve, crv[0], fa='y', ua='x', stu=1, etu=Segments * 10, b=1) HairProfile = [] hairOncGroup = pm.group(name="HairCtrls#") pm.parent(hairOncGroup, hairOncsGroup, r=1) for u in range(Segments + 1): pm.currentTime(u * 10) profileInstance = pm.duplicate(profileCurve, n=(crv[0] + "HairProFileCrv_" + str(u)), rr=1)[0] pm.parent(profileInstance, hairOncGroup, r=1) HairProfile.append(profileInstance) if u == 0 or u == Segments: pm.scale(profileInstance, minscale, a=1, os=1) HairMesh = createHairMesh(HairProfile, name=name, cSet=cSet, mat=mat, lengthDivs=lengthDivs, widthDivs=widthDivs) pm.rename(hairOncGroup, hairOncGroup.name() + HairMesh[0].name()) pm.delete(profileCurve, mp=1) pm.delete(profileCurve) pm.xform(hairOncsGroup, ws=1, piv=pm.xform(hairOncsGroup.getChildren()[-1], q=1, ws=1, piv=1)[:3]) if curveDel: pm.delete(pathTransform, hi=1)
def checkAiShaderSurface(shader_node, shadingGroupNode): for i in shadingGroupNode.listConnections(): if i.nodeType() == "transform": selectionList.append(i) if selectionList: # DISABLE ALL AOVS for aov in listOfAovsEnabled: pm.setAttr(aov + ".enabled", 0) listConnected = pm.listConnections(shader_node, p=True, d=False) # CREATE FOLDER TO SAVE (AOV) folder_to_save = os.path.join(folder_to_save_base, shader_node.name()) if not os.path.exists(folder_to_save): os.makedirs(folder_to_save) # add .txt file with information of parametrs in shader fileName = os.path.join(folder_to_save, shader_node.name() + '.txt') preferencesFile = open(fileName, 'w+') for i in pm.listAttr(shader_node): value = pm.getAttr(shader_node.name() + '.' + i) try: preferencesFile.write(i) preferencesFile.write(" " + str(value)) except: pass preferencesFile.write("\n") preferencesFile.close() aovExistsV = shader_node.listConnections(s=False, t='aiWriteColor') aovExistsF = shader_node.listConnections(s=False, t='aiWriteFloat') if (len(aovExistsV)==0 and len(aovExistsF)==0): # DID NOT CREATE AOVS NODE for plug in listConnected: if "float3" in plug.type(): # VECTOR typeAttr = 'vector' nodeToConnect = pm.createNode( 'aiWriteColor' , n='aiWriteColor_AOV') else: # FLOAT typeAttr = 'float' nodeToConnect = pm.createNode( 'aiWriteFloat' , n='aiWriteFloat_AOV') attrToConnect = nodeToConnect.listAttr(st='input') attrName = nodeToConnect.listAttr(st='aovName') AOV_name = plug.outputs(p=True)[0].name().split('.')[1] pm.setAttr(attrName[0], AOV_name) if (typeAttr, AOV_name) not in listofAOVS: listofAOVS.append((typeAttr, AOV_name)) if (AOV_name != "inputs[7]"): if (AOV_name != "layer2a"): pm.setAttr("aiAOV_" + AOV_name + ".enabled", 1) else: pass pm.connectAttr(plug, attrToConnect[0]) inConnect = shadingGroupNode.listConnections(d=False, t=['aiStandardSurface', 'aiWriteColor', 'aiWriteFloat'], p=True)[0] pm.connectAttr(inConnect, nodeToConnect.listAttr(st='beauty')[0]) pm.connectAttr(nodeToConnect.listAttr(st='outColor')[0], shadingGroupNode.listAttr(st='surfaceShader')[0], f=True) pm.select(selectionList) pm.showHidden() s = pm.ls(sl=True) nameTr = shader_node.name() if shader_node.name() != "krissVector_black_part26_nl_shd_aiss": if (len(s) != 1): pm.polyUnite(s, n=nameTr) cmds.arnoldRenderToTexture(folder=folder_to_save, enable_aovs=True, resolution=2048, all_udims=True) pm.select(cl=True) else: # ALREADY CREATED AOVS NODE print "BAKED WAS ALREADY DONE TO %s shader" % shader_node.name() else: print "NO OBJECTS ASSIGN TO %s shader" % shader_node.name()
def connectorDisplayToggle(val): if val: showHidden(fossil_card.getConnectors()) else: hide(fossil_card.getConnectors())
def bdExportAlambic(self, ns, cachePath): meshes = [ mesh.fullPath() for mesh in pm.ls(ns + ':*REN', type='transform') ] if 'scene' in ns: print ns bananaMeshes = [ mesh.fullPath() for mesh in pm.ls(ns + ':banana*:*REN', type='transform') ] signMeshes = [ mesh.fullPath() for mesh in pm.ls(ns + ':sign*:*REN', type='transform') ] meshes = bananaMeshes + signMeshes try: poleCtrl = pm.ls(ns + ':sign_GEO:poleSign_ctrl', type='transform')[0] if not poleCtrl.rotateY.isConnected(): startTime = pm.playbackOptions(query=True, minTime=True) rotateY = poleCtrl.rotateY.get() poleCtrl.rotateY.setKey(t=startTime, v=rotateY) poleCtrl.rotateY.setKey(t=startTime + 1, v=rotateY + 0.001) except: pm.warning('Didnt find the sign') elif 'truck' in ns: truckAnim = pm.ls(ns + ':Main_CTRL')[0] self.truckActive = truckAnim.attr('Geometry').get() elif 'snail' in ns: try: self.branchesActive = pm.getAttr(ns + ':moveScaleRotate.branches') except: pm.warning('%s snail has no branches' % ns) startTime = pm.playbackOptions(query=True, minTime=True) endTime = pm.playbackOptions(query=True, maxTime=True) if meshes: pm.select(meshes) fileName = ns + '.abc' jobstring = "AbcExport " jobstring += "-j \" -fr %d %d -uvWrite" % (startTime, endTime) for mesh in meshes: jobstring += ' -root ' + mesh if os.path.isdir(projectPath + self.cachePath): jobstring += ' -file ' + projectPath + self.cachePath + fileName jobstring += '\"' print jobstring else: newDir = os.makedirs(projectPath + self.cachePath) print newDir jobstring += ' -file ' + projectPath + self.cachePath + fileName jobstring += '\"' print jobstring try: pm.hide(all=True) pm.select(meshes) pm.showHidden(above=True) print meshes pm.mel.eval(jobstring) except: pm.warning('Could not export %s rig' % ns)
def generateReposer(cards=None, placeholder=False, progress=None): ''' If no cards are specificed, a new reposer is build, otherwise it rebuilds/adds reposers for the specified cards. Args: cards placeholder progress: Optional `progressWindow` that will be `.update()`'d twice for each card, MUST be preconfigured (in case several things are updating) &&& TODO Verify the cards can be built in any order ''' global jointMapping # global'd for debugging suffix = '_placeholder' if placeholder else '' rJoints = [] rCards = [] unlock = {} # <repose joint or card>: <list of attrs to be re-locked> jointMapping = {} # Lazy "bi-directional mapping" of bpj <-> reposeJoint, both are added as keys to eachother # Build all the cards and joints if not cards: cards = find.blueprintCards() # Delete previous roots for oldRoot in getReposeRoots(): oldRoot.deleteAttr('reposeRoot') # Otherwise populate the containers with the existing reposer to build/add new stuff. else: #allExistingRCards = set( cmds.ls( '*.bpCard', o=True, r=True, l=True ) ) allExistingRJoints = set( cmds.ls( '*.bpj', o=True, r=True, l=True ) ) for oldRoot in getReposeRoots(): joints = cmds.listRelatives( str(oldRoot), f=True, ad=True, type='joint' ) joints = [PyNode(c) for c in allExistingRJoints.intersection(joints)] for rj in joints: bpj = rj.bpj.listConnections()[0] jointMapping[rj] = bpj jointMapping[bpj] = rj for card in cards: if progress: progress.update() rCard = duplicate(card, po=0)[0] showHidden(rCard) pdil.dagObj.unlock(rCard) stripReposerCard(rCard) targetName = simpleName(card, '{}_repose' + suffix) previous, attrs = reposeLink(card, rCard, 'bpCard') if not placeholder else (None, []) unlock[rCard] = attrs renameReposeObj(rCard, targetName, previous) for child in rCard.listRelatives(): if not child.type() == 'nurbsSurface': delete(child) rCards.append(rCard) makeIdentity(rCard, t=False, r=False, s=True, apply=True) pdil.dagObj.lock( rCard, 's' ) for jnt in card.joints: reposeJoint = joint(None) targetName = simpleName(jnt, '{}_repose' + suffix) previous, attrs = reposeLink(jnt, reposeJoint, 'bpj') if not placeholder else (None, []) unlock[reposeJoint] = attrs renameReposeObj(reposeJoint, targetName, previous) pdil.dagObj.matchTo(reposeJoint, jnt) #assert jnt.info.get('options', {}).get('mirroredSide', False) is False, 'parent to mirrored joints not supported yet' jointMapping[jnt] = reposeJoint jointMapping[reposeJoint] = jnt rJoints.append(reposeJoint) # Set their parents for reposeJoint in rJoints: parent = jointMapping[reposeJoint].parent if parent in jointMapping: # Check against joint mapping in case only a few selected cards a being tposed reposeJoint.setParent( jointMapping[parent] ) reposeContainer = getReposeContainer() # Put under cards, card pivot to lead joint for rCard, card in zip(rCards, cards): if progress: progress.update() bpj = card.parentCardJoint #print('BPJ - - - - ', bpj, bpj in jointMapping) if bpj in jointMapping: start = card.start() if card.joints else bpj #rCard.setParent( getRJoint(bpj) ) pdil.dagObj.unlock(rCard) #firstBpj = card.joints[0] #return isMirrored = card.isCardMirrored() mirroredSide = card.joints[0].info.get('options', {}).get('mirroredSide') #print('rCard.mirror', rCard.mirror, 'info:', mirroredSide) #if rCard.mirror is False and mirroredSide: if isMirrored is False and card.mirror is False and mirroredSide: #print('opposite mirror') rCard.setParent( makeMirrored( jointMapping[bpj] ) ) else: #print('regular side stuff') rCard.setParent( jointMapping[bpj] ) #cmds.parent(str(rCard), str(jointMapping[bpj])) xform(rCard, ws=True, piv=xform(start, q=True, t=True, ws=True) ) pdil.dagObj.lock(rCard, 't') else: if not placeholder: rCard.addAttr('reposeRoot', at='message') rCard.setParent( reposeContainer ) addVector(rCard, 'origRot', rCard.r.get()) addVector(rCard, 'origTrans', rCard.t.get()) #start = getRJoint(card.start()) start = jointMapping[card.start()] start.setParent( rCard ) pdil.dagObj.lock( start, 't s' ) if rCard in unlock: for attr in unlock[rCard]: rCard.attr(attr).unlock() rCard.attr(attr).showInChannelBox(True) for reposeJoint in rJoints: pdil.dagObj.lock(reposeJoint, 'ry rz') pdil.dagObj.lock(reposeJoint, 't s') # I can't see why I wasn't locking t/s already. Possible exception, `freeform` if reposeJoint in unlock: for attr in unlock[reposeJoint]: reposeJoint.attr(attr).unlock() reposeJoint.attr(attr).showInChannelBox(True) addVector(reposeJoint, 'origRot', reposeJoint.r.get()) addVector(reposeJoint, 'origTrans', reposeJoint.t.get()) '''
def connectorDisplayToggle(self): if self.ui.actionConnectors.isChecked(): showHidden(fossil_card.getConnectors()) else: hide(fossil_card.getConnectors())
def showFaceUi(): sel = pc.ls(sl=True) pc.select(pc.ls(regex='(?i).*:?UI_grp')) pc.showHidden(b=True) pc.select(sel)