def nmManipulator_world(): ''' this function will set all the transform tools to world space. ''' cmds.manipMoveContext('Move', e=True, mode=2) cmds.manipRotateContext('Rotate', e=True, mode=1) try: cmds.manipScaleContext('Scale', e=True, mode=2) except: pass # line nmGUI_func.nmGUI_runCheck( 'complete', 'Manipulator tools have been set to world space.')
def scaleTool(self): try: if Cache.keyOffset == 0: cmds.manipScaleContext('myScale', edit=True, mode=2) # world mode Cache.currentContext = 'myScale' self.setAttributes() else: cmds.manipScaleContext('myScale', edit=True, mode=0) # object mode Cache.currentContext = 'myScale' self.setAttributes() except: if Cache.keyOffset == 0: cmds.manipScaleContext('myScale', mode=2) # world mode Cache.currentContext = 'myScale' self.setAttributes() else: cmds.manipScaleContext('myScale', mode=0) # object mode Cache.currentContext = 'myScale' self.setAttributes() cmds.setToolTo(Cache.currentContext) # #Tool = Tools()
def set_commands(node_type='transform', pre_func=str, post_func=str): mc.manipMoveContext('Move', e=True, preDragCommand=[pre_func, node_type]) mc.manipMoveContext('Move', e=True, postDragCommand=[post_func, node_type]) mc.manipRotateContext('Rotate', e=True, preDragCommand=[pre_func, node_type]) mc.manipRotateContext('Rotate', e=True, postDragCommand=[post_func, node_type]) mc.manipScaleContext('Scale', e=True, preDragCommand=[pre_func, node_type]) mc.manipScaleContext('Scale', e=True, postDragCommand=[post_func, node_type]) # the drag commands are only active on reentering the context mc.setToolTo(mc.currentCtx())
def flatten(component, script_job=False): if script_job: cmds.select(selected.cmdslist()) else: cmds.select(component.cmdslist()) center = list(component.bbox.center)[:3] origin = get_average_vert_normal(component.normals, component.indices) # Perform scale cmds.manipScaleContext('Scale', e=True, mode=6, alignAlong=origin) radians = cmds.manipScaleContext('Scale', q=True, orientAxes=True) t = [math.degrees(r) for r in radians] cmds.scale(0, 1, 1, r=True, oa=t, p=center)
def setManipCommands(nodeType='transform', preFunc=str, postFunc=str): mc.manipMoveContext('Move', e=True, preDragCommand=[preFunc, nodeType]) mc.manipMoveContext('Move', e=True, postDragCommand=[postFunc, nodeType]) mc.manipRotateContext('Rotate', e=True, preDragCommand=[preFunc, nodeType]) mc.manipRotateContext('Rotate', e=True, postDragCommand=[postFunc, nodeType]) mc.manipScaleContext('Scale', e=True, preDragCommand=[preFunc, nodeType]) mc.manipScaleContext('Scale', e=True, postDragCommand=[postFunc, nodeType]) # the drag commands are only active on reentering the context currentCtx = mc.currentCtx() if currentCtx in [ 'moveSuperContext', 'RotateSuperContext', 'scaleSuperContext' ]: # only set context if needed mc.setToolTo(currentCtx)
def setManip(): manip = cmds.radioButtonGrp('manip', q=True, sl=True) # Setting to World Space if (manip == 1): cmds.manipMoveContext('Move', e=True, mode=2) cmds.manipRotateContext('Rotate', e=True, mode=1) cmds.manipScaleContext('Scale', e=True, mode=2) # Setting to Object Space elif (manip == 2): cmds.manipMoveContext('Move', e=True, mode=0) cmds.manipRotateContext('Rotate', e=True, mode=0) cmds.manipScaleContext('Scale', e=True, mode=0) maya.mel.eval('SelectToolOptionsMarkingMenu; MarkingMenuPopDown;' ) # Changing Tool to selection
def scriptJobCmds(self): mc.manipScaleContext('Scale', e=True, mode=6) mc.manipRotateContext('Rotate', e=True, mode=3) mc.manipMoveContext('Move', e=True, mode=6) #fix: isolateSelection viewSelectedSets = mc.ls('*ViewSelectedSet', type='objectSet') isolatedObjs = [] panelName = '' for set in viewSelectedSets: isolatedObjs = mc.sets(set, q=True) if (len(isolatedObjs) == 0): continue panelName = set.split('ViewSelectedSet')[0] mc.isolateSelect(panelName, s=False) mc.isolateSelect(panelName, s=True) break
def manipScaleContext(*args, **kwargs): if len(args): doPassSelf = kwargs.pop('passSelf', False) else: doPassSelf = False for key in ['pod', 'postCommand', 'postDragCommand', 'prc', 'prd', 'preCommand', 'preDragCommand', 'psc']: try: cb = kwargs[key] if callable(cb): kwargs[key] = _factories.makeUICallback(cb, args, doPassSelf) except KeyError: pass res = cmds.manipScaleContext(*args, **kwargs) return res
def alignPivot(move = True, scale = False, fix = False): normal = getFaceNormals() if fix: up = pm.dt.Vector(0.0, 1.0, 0.0) if up == normal: up = pm.dt.Vector(1.0, 0.0, 0.0) y_axis = normal.cross(up) x_axis = y_axis.cross(normal) rot = computeFrame(normal, x_axis, y_axis) if move: if fix: cmds.manipMoveContext("Move", edit=True, mode=6, orientAxes=[rot[0], rot[1], rot[2]]) else: cmds.manipMoveContext("Move", edit=True, mode=6, alignAlong=[normal.x, normal.y, normal.z]) if scale: if fix: cmds.manipScaleContext("Scale", edit=True, mode=6, orientAxes=[rot[0], rot[1], rot[2]]) else: cmds.manipScaleContext("Scale", edit=True, mode=6, alignAlong=[normal.x, normal.y, normal.z]) cmds.refresh(currentView=True)
def testScaleUSD(self): '''Scale USD object, read through the Transform3d interface.''' # Select Ball_35 to scale it. ball35Path = ufe.Path([ mayaUtils.createUfePathSegment("|world|transform1|proxyShape1"), usdUtils.createUfePathSegment("/Room_set/Props/Ball_35") ]) ball35Item = ufe.Hierarchy.createItem(ball35Path) ufe.GlobalSelection.get().append(ball35Item) # Create a Transform3d interface for it. transform3d = ufe.Transform3d.transform3d(ball35Item) # We compare the UFE scale with the USD run-time scale. To # obtain the full scale of Ball_35, we need to add the USD # scale to the Maya proxy shape scale. proxyShapeXformObj = om.MSelectionList().add('transform1').getDagPath( 0).node() proxyShapeXformFn = om.MFnTransform(proxyShapeXformObj) def ball35Scale(): ball35Prim = usdUtils.getPrimFromSceneItem(ball35Item) if not ball35Prim.HasAttribute('xformOp:scale'): return proxyShapeXformFn.scale() else: return combineScales( proxyShapeXformFn.scale(), ball35Prim.GetAttribute('xformOp:scale').Get()) # Set up the callables that will retrieve the scale. self.runTimeScale = ball35Scale self.ufeScale = partial(transform3dScale, transform3d) # Save the initial position to the memento list. expected = ball35Scale() # MAYA-96058: unfortunately, scale command currently requires a scale # manipulator to be created to update the UFE object. manipCtx = cmds.manipScaleContext() cmds.setToolTo(manipCtx) self.runTestScale(expected)
def scaleTool(self): try: if Cache.keyOffset == 0: cmds.manipScaleContext('myScale', edit = True, mode = 2) # world mode Cache.currentContext = 'myScale' self.setAttributes() else: cmds.manipScaleContext('myScale', edit = True, mode = 0) # object mode Cache.currentContext = 'myScale' self.setAttributes() except: if Cache.keyOffset == 0: cmds.manipScaleContext( 'myScale', mode = 2 ) # world mode Cache.currentContext = 'myScale' self.setAttributes() else: cmds.manipScaleContext('myScale', mode = 0) # object mode Cache.currentContext = 'myScale' self.setAttributes() cmds.setToolTo( Cache.currentContext ) # #Tool = Tools()
def scaleModePress(self): cmds.ScaleToolWithSnapMarkingMenu() mode = int(cmds.manipScaleContext('Scale', q=True, mode=True)) if self.tool == 'scaleSuperContext': if mode == 1: # 0 = Object, 1 = Local, 2 = World cmds.manipScaleContext('Scale', e=True, mode=2) self.printMode('World', changed=True) elif mode == 2: cmds.manipScaleContext('Scale', e=True, mode=0) self.printMode('Object', changed=True) elif mode == 0: cmds.manipScaleContext('Scale', e=True, mode=1) self.printMode('Local', changed=True) elif mode == 0: self.printMode('Object') elif mode == 2: self.printMode('World') elif mode == 1: self.printMode('Local')
def cus(): cmds.manipMoveContext("Move", e=True, m=6) cmds.manipScaleContext("Scale", e=True, m=6) cmds.manipRotateContext("Rotate", e=True, m=6)
def degToRad(xDeg, yDeg, zDeg, relativeOpt, applyFor): """ This function sets degree values and converts them to radians within 'Custom axis orientation'. """ # Retrieve degrees data from floatSliderGrp xDegVal = cmds.floatSliderGrp(xDeg, query=True, value=True) yDegVal = cmds.floatSliderGrp(yDeg, query=True, value=True) zDegVal = cmds.floatSliderGrp(zDeg, query=True, value=True) # Convert data to radians xRadVal = math.radians(xDegVal) yRadVal = math.radians(yDegVal) zRadVal = math.radians(zDegVal) # Find out what boxes were checked and assign those states to variables relativeState = cmds.checkBoxGrp(relativeOpt, query=True, value1=True) # Relative checkbox moveState = cmds.checkBoxGrp(applyFor, query=True, value1=True) # Move checkbox rotateState = cmds.checkBoxGrp(applyFor, query=True, value2=True) # Rotate checkbox scaleState = cmds.checkBoxGrp(applyFor, query=True, value3=True) # Scale checkbox # Execute if moveState == True: # If Relative checkbox - Checked if relativeState == True: # Retrieve current radian values from Move 'Custom axis orientation' curMoveVal = cmds.manipMoveContext('Move', query=True, orientAxes=True) # Add new values to current ones xRadMoveVal = xRadVal + curMoveVal[0] yRadMoveVal = yRadVal + curMoveVal[1] zRadMoveVal = zRadVal + curMoveVal[2] cmds.manipMoveContext('Move', e=True, mode=6, oa=(xRadMoveVal, yRadMoveVal, zRadMoveVal)) cmds.setToolTo('moveSuperContext') # If Relative checkbox - Unchecked else: cmds.manipMoveContext('Move', e=True, mode=6, oa=(xRadVal, yRadVal, zRadVal)) cmds.setToolTo('moveSuperContext') if rotateState == True: pass # future code for rotate [RotateSuperContext] if scaleState == True: # If Relative checkbox - Checked if relativeState == True: # Retrieve current radian values from Scale 'Custom axis orientation' curScaleVal = cmds.manipScaleContext('Scale', query=True, orientAxes=True) # Add new values to current ones xRadScaleVal = xRadVal + curScaleVal[0] yRadScaleVal = yRadVal + curScaleVal[1] zRadScaleVal = zRadVal + curScaleVal[2] cmds.manipScaleContext('Scale', e=True, mode=6, oa=(xRadScaleVal, yRadScaleVal, zRadScaleVal)) cmds.setToolTo('scaleSuperContext') # If Relative checkbox - Unchecked else: cmds.manipScaleContext('Scale', e=True, mode=6, oa=(xRadVal, yRadVal, zRadVal)) cmds.setToolTo('scaleSuperContext')
def caoidWindow(): """ This function creates a Maya window. """ caoid = 'caoid' # Name of the window # Check if window already exists. If it exists, delete it. if cmds.window(caoid, ex=True): cmds.deleteUI(caoid, window=True) # Build window cmds.window(caoid, title='Custom axis orientation in degrees', wh=(580, 370), retain=False) mainContainer = cmds.frameLayout(labelVisible=False, borderVisible=False, marginHeight=6, marginWidth=6) # This subContainer prevetns frameLayout children to scale in height subContainer = cmds.columnLayout(adjustableColumn=True, rowSpacing=4) # SUBCONTAINER CHILDREN : DESCRIPTION FRAME, CURRENT VALUES FRAME, SETTINGS FRAME # DESCRIPTION FRAME cmds.frameLayout(label="Description", borderStyle="etchedIn", marginHeight=3, labelIndent=5) cmds.columnLayout(columnAttach=("left", 18)) cmds.text( l= "This tool is setting up values in degrees for 'Custom axis orientation'.", align='left') cmds.setParent(subContainer) # CURRENT VALUES FRAME cmds.frameLayout(label="Current values in degrees", borderStyle="etchedIn", marginHeight=6, labelIndent=5) cmds.columnLayout(adjustableColumn=True, rowSpacing=4, columnAttach=("left", 18)) # Retrieve current radian values from Move and Scale 'Custom axis orientation' curMoveVal = cmds.manipMoveContext('Move', query=True, orientAxes=True) curScaleVal = cmds.manipScaleContext('Scale', query=True, orientAxes=True) # Create a new list with converted values (Rad -> Deg) curMoveDegVal = [] for i in curMoveVal: curMoveDegVal.append(math.degrees(i)) curScaleDegVal = [] for i in curScaleVal: curScaleDegVal.append(math.degrees(i)) cmds.text(l='{0:>18} {1:>13} {2:>13}'.format('X', 'Y', 'Z'), align='left') cmds.text(l='Move: {0:>10.3f} {1:>10.3f} {2:>10.3f}'.format( curMoveDegVal[0], curMoveDegVal[1], curMoveDegVal[2]), align='left') cmds.text(l='Scale: {0:>10.3f} {1:>10.3f} {2:>10.3f}'.format( curScaleDegVal[0], curScaleDegVal[1], curScaleDegVal[2]), align='left') cmds.setParent(subContainer) # SETTINGS FRAME cmds.frameLayout(label='Settings', borderStyle='etchedIn', marginHeight=3, labelIndent=5) cmds.columnLayout(adjustableColumn=True) xDeg = cmds.floatSliderGrp(l='X axis (deg):', field=True, minValue=-360, maxValue=360, fieldMinValue=-360, fieldMaxValue=360, columnAttach3=('right', 'both', 'left'), columnOffset3=(6, 0, 0)) yDeg = cmds.floatSliderGrp(l='Y axis (deg):', field=True, minValue=-360, maxValue=360, fieldMinValue=-360, fieldMaxValue=360, columnAttach3=('right', 'both', 'left'), columnOffset3=(6, 0, 0)) zDeg = cmds.floatSliderGrp(l='Z axis (deg):', field=True, minValue=-360, maxValue=360, fieldMinValue=-360, fieldMaxValue=360, columnAttach3=('right', 'both', 'left'), columnOffset3=(6, 0, 0)) relativeOpt = cmds.checkBoxGrp( label='', numberOfCheckBoxes=1, label1='Relative', annotation="""When checked, add to or subtract from current seted values of X, Y or Z in 'Custom axis orientation.'""") cmds.separator(height=10, style='in') applyFor = cmds.checkBoxGrp( label='Apply for:', numberOfCheckBoxes=3, vertical=True, columnAttach2=('right', 'left'), columnOffset2=(6, 2), labelArray3=('Move', 'Rotate', 'Scale'), enable2=False) # disable Rotate for the time being cmds.setParent(mainContainer) # BUTTONS SECTION form = cmds.formLayout(numberOfDivisions=100) def clickCmd(buttonValue): degToRad(xDeg, yDeg, zDeg, relativeOpt, applyFor) applyButton = cmds.button(l='Apply', height=26, c=clickCmd) closeCmd = 'cmds.deleteUI("%s", window=True)' % caoid closeButton = cmds.button(l='Close', height=26, c=closeCmd) cmds.formLayout(form, edit=True, attachForm=((applyButton, 'bottom', 0), (applyButton, 'left', 0), (closeButton, 'bottom', 0), (closeButton, 'right', 0)), attachPosition=((applyButton, 'right', 2, 50), (closeButton, 'left', 2, 50))) cmds.showWindow(caoid)
def setCustomAxisOrientation(): ''' TENTATIVE DE PATH DE L ISOLATE SELECTION ---- #fix: isolateSelection part1 viewSelectedSets = mc.ls( '*ViewSelectedSet' , type = 'objectSet' ) isolatedObjs = [] panelName = '' for set in viewSelectedSets: isolatedObjs = mc.sets( set , q = True ) if( len(isolatedObjs) == 0 ): continue panelName = set.split( 'ViewSelectedSet' )[0] break #fix: isolateSelection part1 ''' selection = mc.ls(sl=True) locators = buildLocator.buildLocator() if (len(locators) > 1): mc.delete(locators) mc.error('marche pas avec plusieurs obj') rot = [0, 0, 0] rotRad = [0, 0, 0] rot[0] = mc.getAttr(locators[0] + '.rotateX') rot[1] = mc.getAttr(locators[0] + '.rotateY') rot[2] = mc.getAttr(locators[0] + '.rotateZ') rotRad[0] = math.radians(rot[0]) rotRad[1] = math.radians(rot[1]) rotRad[2] = math.radians(rot[2]) mc.delete(locators) mc.select(selection) if (len(selection) == 0): return 0 if ('.' in selection[0]): i = selection[0].index('.') selection[0] = selection[0][0:i] #changement orientation mel.eval('changeSelectMode -component;') mc.hilite(selection[0], r=True) mc.manipScaleContext('Scale', e=True, mode=6, orientAxes=rotRad) mc.manipRotateContext('Rotate', e=True, mode=3, orientAxes=rotRad) mc.manipMoveContext('Move', e=True, mode=6, orientAxes=rotRad) #fix gizmo au centre du monde mc.setToolTo('RotateSuperContext') mc.setToolTo('scaleSuperContext') mc.setToolTo('moveSuperContext') ''' TENTATIVE DE PATH DE L ISOLATE SELECTION ---- #fix: isolateSelection part2 print( isolatedObjs ) print( panelName ) mc.refresh() if( len( isolatedObjs ) > 0 ): mc.isolateSelect( panelName , s = False ) for obj in isolatedObjs: mc.isolateSelect( panelName , ado = obj ) mc.isolateSelect( panelName , rdo = '|polySurface115.f[58]') mc.isolateSelect( panelName , u = True ) mc.isolateSelect( panelName , s = True ) ''' #fix: scriptJob pour les changement de selection exec('maintainCustomOrientationSJW = scriptJobWindow()') in globals() exec('maintainCustomOrientationSJW.UI()') in globals() return 1
def get_matrix(): global SYM_AVOIDANCE global sb from . import sisidebar_main as sb #print '-------------get Matrix---------------- :' #print 'select obj :', cmds.ls(sl=True) #current_tool = cmds.currentCtx() #print 'current tool ;', current_tool #cmds.setToolTo('selectSuperContext') #cmds.setToolTo(current_tool) if SYM_AVOIDANCE: SYM_AVOIDANCE = False return #ロックの有無をチェック try: sb.window.attribute_lock_state(mode=3, check_only=True) except Exception as e: print e.message pass try: #2018up2以降の不具合対応 sid = sb.space_group.checkedId() except Exception as e: print e.message return #一旦スケールX値をリセットしてメインウィンドウクラスに変更をお知らせする #sb.set_temp_text('change') sb.set_active_mute() scale = ['', '', ''] rot = ['', '', ''] trans = ['', '', ''] if cmds.selectMode(q=True, o=True): selection = cmds.ls(sl=True, type='transform') if selection: try: s_list, r_list, t_list = get_srt(selection) except Exception as e: print e.message return #print 'get matrix :', s_list, r_list, t_list for i in range(3): s_list = [ map(lambda a: round(float(a), view_decimal), xyz) for xyz in s_list ] r_list = [ map(lambda a: round(float(a), view_decimal), xyz) for xyz in r_list ] t_list = [ map(lambda a: round(float(a), view_decimal), xyz) for xyz in t_list ] if not all(s[i] == s_list[0][i] for s in s_list): #print 'not same' scale[i] = '' else: #print 'same' scale[i] = str(s_list[0][i]) if not all(r[i] == r_list[0][i] for r in r_list): #print 'not same', r_list rot[i] = '' else: #print 'same', r_list rot[i] = str(r_list[0][i]) if not all(t[i] == t_list[0][i] for t in t_list): trans[i] = '' else: trans[i] = str(t_list[0][i]) #sb.check_key_anim() if np_flag: sb.view_np_time(culc_time='- Numpy Calculation Mode -') else: sb.view_np_time(culc_time='- Usual Calculation Mode -') selection = cmds.ls(sl=True, type='float3') #カーブもとっておく cv_selection = cmds.ls(sl=True, type='double3', fl=True) #print cv_selection if selection or cv_selection: #ラティスポイント他すべてを有効にする sel_str = str(selection + cv_selection) ''' if '.vtx[' in sel_str: cmds.selectType(polymeshVertex=True) #cmds.selectType(particle=True) ''' if '.cv[' in sel_str: cmds.selectType(cv=True) cmds.selectMode(co=True) if '.pt[' in sel_str: cmds.selectType(latticePoint=True) cmds.selectMode(co=True) #オブジェクトモードでもコンポーネント選択がある場合は強制的にモード変更する components = cmds.polyListComponentConversion(selection, tv=True) + cv_selection #print components #if not components: s_list, r_list, t_list = get_srt(components, mode='component') start = dt.datetime.now() #計測開始 #マニプ情報取得に必要な情報を集める sym = cmds.symmetricModelling(q=True, symmetry=True) current_tool = cmds.currentCtx() tools_list = [ 'scaleSuperContext', 'RotateSuperContext', 'moveSuperContext' ] if sym: axis_list = ['x', 'y', 'z'] sym_axis = cmds.symmetricModelling(q=True, ax=True) axis_id = axis_list.index(sym_axis) meshes = cmds.ls(hl=True, l=True) #マニプが有効でない場合はシンメトリ座標を取得できないので自前計算 if not current_tool in tools_list: for i, value in enumerate(t_list): if i % 3 == axis_id: value = math.sqrt(value**2) t_list[i] = value if np_flag: #print 'culc in numpy' s_list = np.reshape(s_list, (len(s_list) / 3, 3)) scale = np.average(s_list, axis=0).tolist() r_list = np.reshape(r_list, (len(r_list) / 3, 3)) rot = np.average(r_list, axis=0).tolist() t_list = np.reshape(t_list, (len(t_list) / 3, 3)) trans = np.average(t_list, axis=0).tolist() else: #print 'culc in math' srt_list = [0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(0, len(s_list), 3): srt_list[0] += s_list[i + 0] srt_list[1] += s_list[i + 1] srt_list[2] += s_list[i + 2] scale = map(lambda a: a / (len(s_list) / 3), srt_list[0:3]) for i in range(0, len(r_list), 3): srt_list[3] += r_list[i + 0] srt_list[4] += r_list[i + 1] srt_list[5] += r_list[i + 2] rot = map(lambda a: a / (len(r_list) / 3), srt_list[3:6]) for i in range(0, len(t_list), 3): srt_list[6] += t_list[i + 0] srt_list[7] += t_list[i + 1] srt_list[8] += t_list[i + 2] trans = map(lambda a: a / (len(t_list) / 3), srt_list[6:9]) #シンメトリのときとワールド座標の場合の処理 #ワールド空間のときもMayaのマニピュレータ位置とあわせる if sym or sid == 0 or sid == 4: if current_tool in tools_list: if current_tool == 'moveSuperContext': trans = cmds.manipMoveContext('Move', q=True, p=True) elif current_tool == 'RotateSuperContext': trans = cmds.manipRotateContext('Rotate', q=True, p=True) elif current_tool == 'scaleSuperContext': trans = cmds.manipScaleContext('Scale', q=True, p=True) #ワールド空間でない且つ選択オブジェクトが1つの場合はマトリクス計算で座標を求める if sid != 0 and sid != 4 and len(meshes) == 1: scale = cmds.xform(meshes[0], q=True, s=True, ws=True) #scale = [1.0]*3 if len(meshes) == 1: pos = trans + [1] #行列掛けるようの位置配列、末尾に1つけとく if np_flag: #マトリクス計算で座標求める matrix = cmds.xform(meshes[0], q=True, m=True, ws=True) matrix = np.reshape(matrix, (4, 4)) rev_matrix = np.linalg.inv(matrix) #逆行列 #print 'get mesh matrix :', matrix, meshes[0] #print 'get rev matrix np:', rev_matrix mul_matrix_trans = np.dot(pos, matrix) mul_rev_matrix_trans = np.dot(pos, rev_matrix) #print 'mul matrix :', mul_matrix_trans #print 'mul rev matrix :', mul_rev_matrix_trans trans = scale * mul_rev_matrix_trans[:3] #print 'Local trans np:', trans else: #Numpy使わない処理 matrix = cmds.xform(meshes[0], q=True, m=True, ws=True) rev_matrix = pm.ls( meshes[0])[0].transformationMatrix().inverse() #print 'get rev matrix :', rev_matrix pos = [pos] #行列掛けるようの位置配列、末尾に1つけとく #print matrix #print rev_matrix mul_rev_matrix_trans = mm.dot(pos, rev_matrix)[0] #print mul_rev_matrix_trans trans = mm.mul(mul_rev_matrix_trans[:3], scale) #print 'Local trans :', trans #print 'sym pos :', trans, meshes, sid #print 'trans :', trans end = dt.datetime.now() culc_time = end - start sb.view_np_time(culc_time='Culc Time ' + str(culc_time)) #表示桁数を調整する try: scale = map(lambda a: round(float(a), view_decimal) if a != '' else '', scale) rot = map(lambda a: round(float(a), view_decimal) if a != '' else '', rot) trans = map(lambda a: round(float(a), view_decimal) if a != '' else '', trans) #念のため0のマイナス符号を除去、main側のセットでもやってるんで一旦ミュート #print rot #scale = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, scale) #rot = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, rot) #trans = map(lambda a : float(str(a).replace('-0.0', '0.0')) if a=='-0.0' else a, trans) #print rot sb.set_pre_transform(trans, rot, scale) sb.set_srt_text(scale, rot, trans) except: sb.set_pre_transform(trans, rot, scale) sb.set_srt_text(scale, rot, trans)
def wrd(): cmds.manipMoveContext("Move", e=True, m=2) cmds.manipScaleContext("Scale", e=True, m=2) cmds.manipRotateContext("Rotate", e=True, m=1)
def bakePivot(ob, pos=1, ori=1): currentCtx = mc.currentCtx() contextList = [ "moveSuperContext", "manipMoveContext", "RotateSuperContext", "manipRotateContext", "scaleSuperContext", "manipScaleContext" ] if currentCtx not in contextList: mc.error("m_bakeCustomToolPivot.kWrongToolError") return None # Check 3) must be in custom orientation mode customOri = [] pivotModeActive = 0 customModeActive = 0 if currentCtx == "moveSuperContext" or currentCtx == "manipMoveContext": customOri = mc.manipMoveContext('Move', q=1, orientAxes=1) pivotModeActive = mc.manipMoveContext('Move', q=1, editPivotMode=1) customModeActive = mc.manipMoveContext('Move', q=1, mode=1) / 6 elif ( currentCtx == "RotateSuperContext" or currentCtx == "manipRotateContext" ): customOri = mc.manipRotateContext('Rotate', q=1, orientAxes=1) pivotModeActive = mc.manipRotateContext('Rotate', q=1, editPivotMode=1) customModeActive = mc.manipRotateContext('Rotate', q=1, mode=1) / 3 elif ( currentCtx == "scaleSuperContext" or currentCtx == "manipScaleContext" ): customOri = mc.manipScaleContext('Scale', q=1, orientAxes=1) pivotModeActive = mc.manipScaleContext('Scale', q=1, editPivotMode=1) customModeActive = mc.manipScaleContext('Scale', q=1, mode=1) / 6 if ori and not pos and not customModeActive: mc.error("m_bakeCustomToolPivot.kWrongAxisOriModeError") return None # Get custom orientation if ori and customModeActive: customOri[0] = mel.eval('rad_to_deg({})'.format(customOri[0])) customOri[1] = mel.eval('rad_to_deg({})'.format(customOri[1])) customOri[2] = mel.eval('rad_to_deg({})'.format(customOri[2])) # Set object(s) rotation to the custom one # (preserving child transform positions and geometry positions) mc.rotate( customOri[0], customOri[1], customOri[2], ob, a=1, pcp=1, pgp=1, ws=1, fo=1 ) if pos: # Get pivot in parent space # object = 'pSphere4' old = [0, 0, 0] m = mc.xform(ob, q=1, m=1) p = mc.xform(ob, q=1, os=1, sp=1) old[0] = (p[0] * m[0] + p[1] * m[4] + p[2] * m[8] + m[12]) old[1] = (p[0] * m[1] + p[1] * m[5] + p[2] * m[9] + m[13]) old[2] = (p[0] * m[2] + p[1] * m[6] + p[2] * m[10] + m[14]) # Zero out pivots mc.xform(ob, zeroTransformPivots=1) # Translate object(s) back to previous pivot # (preserving child transform positions and geometry positions) new = mc.getAttr(ob + ".translate")[0] mc.move( (old[0] - new[0]), (old[1] - new[1]), (old[2] - new[2]), ob, pcp=1, pgp=1, ls=1, r=1 ) # Exit pivot mode if pivotModeActive: mel.eval('ctxEditMode;') # Set the axis orientation mode back to object if ori and customModeActive: if ( currentCtx == "moveSuperContext" or currentCtx == "manipMoveContext" ): mc.manipMoveContext('Move', e=1, mode=0) elif ( currentCtx == "RotateSuperContext" or currentCtx == "manipRotateContext" ): mc.manipRotateContext('Rotate', e=True, mode=0) elif ( currentCtx == "scaleSuperContext" or currentCtx == "manipScaleContext" ): mc.manipScaleContext('Scale', e=1, mode=0)
def _testMultiSelectScaleUSD(self): '''Scale multiple USD objects, read through Transform3d interface.''' # Select multiple balls to scale them. proxyShapePathSegment = mayaUtils.createUfePathSegment( "|world|transform1|proxyShape1") # Test passes for a single item. # balls = ['Ball_33'] balls = ['Ball_33', 'Ball_34'] ballPaths = [ ufe.Path([ proxyShapePathSegment, usdUtils.createUfePathSegment('/Room_set/Props/' + ball) ]) for ball in balls ] ballItems = [ ufe.Hierarchy.createItem(ballPath) for ballPath in ballPaths ] for ballItem in ballItems: ufe.GlobalSelection.get().append(ballItem) # We compare the UFE scale with the USD run-time scale. To # obtain the full scale of USD scene items, we need to add the USD # scale to the Maya proxy shape scale. proxyShapeXformObj = om.MSelectionList().add('transform1').getDagPath( 0).node() proxyShapeXformFn = om.MFnTransform(proxyShapeXformObj) def usdSceneItemScale(item): prim = usdUtils.getPrimFromSceneItem(ball35Item) if not prim.HasAttribute('xformOp:scale'): return proxyShapeXformFn.scale() else: return combineScales(proxyShapeXformFn.scale(), prim.GetAttribute('xformOp:scale').Get()) def ufeSceneItemScale(item): return transform3dScale(ufe.Transform3d.transform3d(item)) # Set up the callables that will retrieve the scale. self.runTimeScale = usdSceneItemScale self.ufeScale = ufeSceneItemScale # Give the tail item in the selection an initial scale that # is different, to catch bugs where the relative scale # incorrectly squashes any existing scale. backItem = ballItems[-1] backT3d = ufe.Transform3d.transform3d(backItem) initialScale = [1.1, 2.2, 3.3] backT3d.scale(*initialScale) self.assertVectorAlmostEqual(initialScale, usdSceneItemScale(backItem)) # Save the initial positions to the memento list. expected = [usdSceneItemScale(ballItem) for ballItem in ballItems] # MAYA-96058: unfortunately, scale command currently requires a scale # manipulator to be created to update the UFE object. manipCtx = cmds.manipScaleContext() cmds.setToolTo(manipCtx) #Temporarily disabling undo redo until we fix it for PR 94 self.runMultiSelectTestScale(ballItems, expected)
def resetPivot(pivot): if pivot == "move": cmds.manipMoveContext("Move", edit=True, mode=2, orientAxes=[0.0, 0.0, 0.0]) else: cmds.manipScaleContext("Scale", edit=True, mode=0, orientAxes=[0.0, 0.0, 0.0])
def set_reference(mode=''): c_ctx = cmds.currentCtx(q=True) #print c_ctx sel = cmds.ls(sl=True, l=True) #print 'set reference :', mode, sel current_ctx = cmds.currentCtx() if mode == 'object': #print 'set reference object mode :' cmds.selectMode(o=True) rot = cmds.xform(sel, q=True, ro=True, ws=True) pos = cmds.xform(sel, q=True, t=True, ws=True) rx = rot[0] / 180 * math.pi ry = rot[1] / 180 * math.pi rz = rot[2] / 180 * math.pi cmds.manipScaleContext('Scale', e=True, orientAxes=(rx, ry, rz)) cmds.manipRotateContext('Rotate', e=True, orientAxes=(rx, ry, rz)) cmds.manipMoveContext('Move', e=True, orientAxes=(rx, ry, rz)) cmds.setToolTo('scaleSuperContext') #マニプ表示がおかしくなるのでいったんコンテキスト設定してから戻す cmds.setToolTo('RotateSuperContext') cmds.setToolTo('moveSuperContext') cmds.setToolTo(current_ctx) else: if mode == 'vertex': manip_type = 'PointHandleTowards' comp = cmds.polyListComponentConversion(sel, tv=True) comp = cmds.filterExpand(comp, sm=31) sel_node = '" , "'.join(pre_sel) #print 'vertex ref :', sel_node, comp[0] if mode == 'edge': manip_type = 'AlignHandleWith' comp = cmds.polyListComponentConversion(sel, te=True) comp = cmds.filterExpand(comp, sm=32) sel_node = comp[0] if mode == 'face': manip_type = 'AlignHandleWith' comp = cmds.polyListComponentConversion(sel, tf=True) comp = cmds.filterExpand(comp, sm=34) sel_node = comp[0] if comp: mel.eval('manipScaleOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipScale' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') mel.eval('manipRotateOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipRotate' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') mel.eval('manipMoveOrient 5;') mel.eval('{ string $Selection1[]; $Selection1[0] = "' + comp[0] + '"; manipMove' + manip_type + '($Selection1[0], {"' + sel_node + '"}, {}, "", 0);; };') cmds.selectMode(co=True) if pre_ref_mode == 'vertex': cmds.selectType(pv=1, smu=0, smp=1, pf=0, pe=0, smf=0, sme=0, puv=0) if pre_ref_mode == 'edge': cmds.selectType(pv=0, smu=0, smp=0, pf=0, pe=1, smf=0, sme=1, puv=0) if pre_ref_mode == 'face': cmds.selectType(pv=0, smu=0, smp=0, pf=1, pe=0, smf=0, sme=1, puv=0) trans = cmds.xform(sel, q=True, t=True, ws=True) num = len(trans) / 3 x = y = z = 0 for i in range(0, len(trans), 3): x += trans[i] y += trans[i + 1] z += trans[i + 2] pos = [x / num, y / num, z / num] #sel_obj = [] #obj_list = list(set([vtx.split('.')[0] for vtx in pre_sel])) #if obj_list: #sel_obj = [cmds.listRelatives(s, p=True)[0] if cmds.nodeType(s)=='mesh' else s for s in obj_list] #print obj_list, pre_sel #cmds.hilite(obj_list, r=True) #cmds.hilite(pre_sel, r=True) #print 'set to pre mode :', pre_ref_mode #print 'set to mode pre :', pre_ref_mode if pre_ref_mode == 'object': cmds.selectMode(o=True) else: cmds.selectMode(co=True) if pre_obj_list: cmds.hilite(pre_obj_list, r=True) if pre_sel: cmds.select(pre_sel, r=True) else: cmds.select(cl=True) sb.after_pick_context(ctx=c_ctx) #移動マニプを選択の中心に移動する cmds.manipPivot(p=pos)
def lcl(): cmds.manipMoveContext("Move", e=True, m=0) cmds.manipScaleContext("Scale", e=True, m=0) cmds.manipRotateContext("Rotate", e=True, m=0)