def cut_one_with_one(cutter, target): print 'Cutting 1:1 %s with %s' % (target, cutter) # Duplicate targets targetA = cmds.duplicate(target, returnRootsOnly=True)[0] targetB = cmds.duplicate(target, returnRootsOnly=True)[0] prep(targetA) prep(targetB) cmds.delete(target) # Set up cutters cutterA = cmds.duplicate(cutter, returnRootsOnly=True)[0] cutterB = cmds.duplicate(cutter, returnRootsOnly=True)[0] prep(cutterA) prep(cutterB) # Flip second cutter's normals cmds.polyNormal(cutterB, normalMode=0, userNormalMode=0, constructionHistory=0) # Perform intersections newTargetA = cmds.polyBoolOp(cutterA, targetA, op=3, constructionHistory=False)[0] newTargetB = cmds.polyBoolOp(cutterB, targetB, op=3, constructionHistory=False)[0] return [newTargetA, newTargetB]
def fixReverseDo(sel_child): selShape = sel_child if len(selShape) == 0: print("Nothing Selected!") else: node_CPOM = cmds.createNode('closestPointOnMesh') selShape_worldMesh = selShape + '.worldMesh[0]' selShape_worldMatrix = selShape + '.worldMatrix[0]' node_CPOM_inMesh = node_CPOM + '.inMesh' node_CPOM_inPosition = node_CPOM + '.inPosition' node_CPOM_inputMatrix = node_CPOM + ".inputMatrix" node_CPOM_result_normal = node_CPOM + ".result.normal" node_CPOM_outPosition = node_CPOM + ".position" persp_translate = "persp.translate" cmds.connectAttr(selShape_worldMesh, node_CPOM_inMesh, force=1) cmds.connectAttr(persp_translate, node_CPOM_inPosition, force=1) cmds.connectAttr(selShape_worldMatrix, node_CPOM_inputMatrix, force=1) vec_persp_pos = cmds.getAttr(persp_translate) vec_closestPoint_pos = cmds.getAttr(node_CPOM_outPosition) vec_closestPoint_normal = cmds.getAttr(node_CPOM_result_normal) vec_persp_closestPoint = [ vec_persp_pos[0][0] - vec_closestPoint_pos[0][0], vec_persp_pos[0][1] - vec_closestPoint_pos[0][1], vec_persp_pos[0][2] - vec_closestPoint_pos[0][2] ] dotProductResult = dotProduct(vec_persp_closestPoint, vec_closestPoint_normal[0]) if dotProductResult < 0: cmds.polyNormal(selShape, normalMode=0, userNormalMode=1, ch=1) cmds.delete(node_CPOM)
def kmReverseNormal(self): selectionList = mc.ls(selection=True, type='transform') if selectionList: for obj in selectionList: mc.polyNormal(obj, normalMode=0) sel = mc.select(selectionList) else: print ">> No selection"
def cycloGeoCreation(namespace, name): pp1 = [-12, -2.6394186146319176e-15, 11] pp2 = [-12, 15.735990524291992, -7.29987907409668] pp3 = [-12, -2.6394186146319176e-15, -4.922739028930664] pp4 = [-12, 0.18094894289970398, -5.832431793212891] pp5 = [-12, 0.696247935295105, -6.603630065917969] pp6 = [-12, 1.4674474000930786, -7.118930816650391] pp7 = [-12, 2.37713885307312, -7.29987907409668] pp8 = [-12, 12.396276473999023, -7.29987907409668] pp9 = [-12, 9.056564331054688, -7.29987907409668] pp10 = [-12, 5.716851234436035, -7.29987907409668] pp11 = [-12, -2.6394186146319176e-15, -0.9603691101074219] pp12 = [-12, -2.6394186146319176e-15, 3.002007007598877] pp13 = [-12, -2.6394186146319176e-15, 7] cmds.curve(n=namespace + ':tempCurve', d=1, p=[ pp1, pp13, pp12, pp11, pp3, pp4, pp5, pp6, pp7, pp10, pp9, pp8, pp2 ]) cmds.extrude(namespace + ':tempCurve', ch=True, rn=False, po=1, et=0, upn=0, d=[1, 0, 0], length=24, scale=1, dl=1, n=namespace + ':' + name) tesselateNode = cmds.listHistory(namespace + ':' + name, pdo=True)[0] cmds.setAttr(tesselateNode + '.polygonType', 1) cmds.setAttr(tesselateNode + '.format', 2) cmds.setAttr(tesselateNode + '.uNumber', 1) cmds.setAttr(tesselateNode + '.vNumber', 6) cmds.polyNormal(namespace + ':' + name, ch=False) cmds.delete(namespace + ':' + name, ch=True) cmds.delete(namespace + ':tempCurve') cmds.select(cl=True) cycloShader = cmds.shadingNode('lambert', name=namespace + ':' + 'cyclo_MAT', asShader=True) cycloShaderSG = cmds.sets(name=namespace + ':' + 'cyclo_MAT_SG', empty=True, renderable=True, noSurfaceShader=True) cmds.connectAttr(cycloShader + '.outColor', cycloShaderSG + '.surfaceShader') cmds.setAttr(cycloShader + '.color', 0.9, 0.9, 0.9, type='double3') cmds.sets(namespace + ':' + name, e=True, forceElement=cycloShaderSG) activateSmoothPreview(namespace + ':' + name)
def readyToExtrude(subdX, twistT, divisionsD, number): cmds.setAttr('combined.rotate', 0, 0, 90) cmds.select('curve1') checkFaces2(subdX, number) cmds.setAttr('polyExtrudeFace1.divisions', divisionsD) cmds.setAttr('polyExtrudeFace1.twist', twistT) cmds.select('combined') cmds.polyNormal(normalMode=0, userNormalMode=0) cmds.polySeparate('combined')
def reverseNormalMesh( *args ): cam = getCurrentCam() camMtx = getDagPath( cam ).inclusiveMatrix() camPos = om.MPoint( camMtx(3,0), camMtx(3,1), camMtx(3,2) ) sels = cmds.ls( sl=1 ) for sel in sels: if not cmds.nodeType( sel ) in ['transform', 'mesh']: continue if cmds.nodeType( sel ) == 'transform': shapes = cmds.listRelatives( sel, s=1 ) if not shapes: continue if cmds.nodeType( shapes[0] ) != 'mesh': continue sel = shapes[0] pathMesh = getDagPath( sel ) fnMesh = om.MFnMesh( pathMesh ) pointsMesh = om.MPointArray() fnMesh.getPoints( pointsMesh ) meshMtx = pathMesh.inclusiveMatrix() meshMtxInv = pathMesh.inclusiveMatrixInverse() posLocalCam = camPos* meshMtxInv #cmds.spaceLocator( p=[posLocalCam.x, posLocalCam.y, posLocalCam.z]) numPolygon = fnMesh.numPolygons() revFaces = [] for i in range( numPolygon ): normal = om.MVector() vertices = om.MIntArray() fnMesh.getPolygonNormal( i, normal ) fnMesh.getPolygonVertices( i, vertices ) avPoint = om.MVector( 0,0,0 ) for j in range( vertices.length() ): avPoint += om.MVector( pointsMesh[ vertices[j] ] ) avPoint /= vertices.length() vectorCamPos = om.MVector( posLocalCam - avPoint ) if vectorCamPos*normal > 0: continue points = om.MPointArray() rayExists = fnMesh.intersect( om.MPoint( avPoint ), om.MVector( vectorCamPos ), points ) if rayExists: dist = points[0].distanceTo( om.MPoint( avPoint ) ) if dist > 0.0001 and dist < 0.0002: continue revFaces.append( sel+'.f[%d]' % i ) if not revFaces: continue cmds.polyNormal( revFaces, normalMode=0, userNormalMode=0, ch=0 )
def reverseNormalMesh(*args): cam = getCurrentCam() camMtx = getDagPath(cam).inclusiveMatrix() camPos = om.MPoint(camMtx(3, 0), camMtx(3, 1), camMtx(3, 2)) sels = cmds.ls(sl=1) for sel in sels: if not cmds.nodeType(sel) in ['transform', 'mesh']: continue if cmds.nodeType(sel) == 'transform': shapes = cmds.listRelatives(sel, s=1) if not shapes: continue if cmds.nodeType(shapes[0]) != 'mesh': continue sel = shapes[0] pathMesh = getDagPath(sel) fnMesh = om.MFnMesh(pathMesh) pointsMesh = om.MPointArray() fnMesh.getPoints(pointsMesh) meshMtx = pathMesh.inclusiveMatrix() meshMtxInv = pathMesh.inclusiveMatrixInverse() posLocalCam = camPos * meshMtxInv #cmds.spaceLocator( p=[posLocalCam.x, posLocalCam.y, posLocalCam.z]) numPolygon = fnMesh.numPolygons() revFaces = [] for i in range(numPolygon): normal = om.MVector() vertices = om.MIntArray() fnMesh.getPolygonNormal(i, normal) fnMesh.getPolygonVertices(i, vertices) avPoint = om.MVector(0, 0, 0) for j in range(vertices.length()): avPoint += om.MVector(pointsMesh[vertices[j]]) avPoint /= vertices.length() vectorCamPos = om.MVector(posLocalCam - avPoint) if vectorCamPos * normal > 0: continue points = om.MPointArray() rayExists = fnMesh.intersect(om.MPoint(avPoint), om.MVector(vectorCamPos), points) if rayExists: dist = points[0].distanceTo(om.MPoint(avPoint)) if dist > 0.0001 and dist < 0.0002: continue revFaces.append(sel + '.f[%d]' % i) if not revFaces: continue cmds.polyNormal(revFaces, normalMode=0, userNormalMode=0, ch=0)
def mirrorPieces(arg): L = mc.radioButton(buttomL, q=1, select=True) R = mc.radioButton(buttomR, q=1, select=True) C = mc.radioButton(buttomC, q=1, select=True) if L: side = 'L' elif R: side = 'R' elif C: side = 'C' sel = mc.ls(sl=True) for o in sel: # Mirror the piece if mc.nodeType(mc.listRelatives(o)[0]) == 'mesh': if mc.objExists(o + '_mirror') == False: mirroredGeo = '' attrs = mc.listAttr(o, keyable=1) for attr in attrs: mc.setAttr(o + "." + attr, lock=0) mc.xform(o, ws=True, piv=(0, 0, 0)) mc.makeIdentity(o, translate=1, rotate=1, scale=True, apply=True) mirroredGeo = mc.duplicate(o, n=o + '_mirror')[0] mc.setAttr(mirroredGeo + '.scaleX', -1) mc.makeIdentity(mirroredGeo, translate=1, rotate=1, scale=True, apply=True) mc.polyNormal(mirroredGeo, normalMode=0, userNormalMode=0) if 'L_' in mirroredGeo: mc.rename(mirroredGeo, o.replace('L_', 'R_')) elif 'R_' in mirroredGeo: mc.rename(mirroredGeo, o.replace('R_', 'L_')) elif 'Left' in mirroredGeo: mc.rename(mirroredGeo, o.replace('Left', 'Right')) elif 'Right' in mirroredGeo: mc.rename(mirroredGeo, o.replace('Right', 'Left')) elif 'Mid' or 'C_' or 'mid' in mirroredGeo or None == mirroredGeo: mc.polyUnite(o, mirroredGeo, name=str(o), constructionHistory=1, mergeUVSets=1, caching=True) mc.delete(mirroredGeo, ch=True) mc.rename(mirroredGeo, str(o)) mc.polyMergeVertex(mirroredGeo, d=0.379) else: print 'Ya existe el mirror.' else: print 'No es una geometria'
def ncsc_normal_dir_fix(): """Reverse the selected polygons """ sel = mc.ls(sl=True) if sel: for obj in sel: mc.polyNormal(obj, normalMode=0, userNormalMode=0, ch=1) mc.select(clear=True) else: mc.warning("No faces have been selected! Run \"Normal Direction - Show\" first.")
def revNormals(): labelRevOn = 'Toggle Reverse Front' labelRevOff = 'Toggle Reverse Back' revNrmls = mc.ls(sl=True, dag=True, lf=True) revState = mc.button('btn2', q=True, l=True) if revState != labelRevOn: mc.button('btn2', e=True, l=labelRevOn) for revNrm in revNrmls: mc.polyNormal(revNrm, nm=0, unm=0, ch=True) else: mc.button('btn2', e=True, l=labelRevOff) for revNrm in revNrmls: mc.polyNormal(revNrm, nm=0, unm=0, ch=True)
def generate(self): boxe = cmd.ls(sl=True) if not len(boxe): raise Exception("non hai selezionato la stanza") boxe = boxe[0] self.bb = BoundingBox(extract=boxe) convex = [0.25, 0.25, 0.25, 0.25] self.createRooms(convex) for r in self.rooms: r.draw() cmd.select(r.mayaBB, r=True) mel.eval('CenterPivot') cmd.makeIdentity(apply=True, t=1, r=1, s=1, n=2) cmd.scale(0.97, 0.97, 0.97) r.updateFromMayaBB() cmd.polyNormal(r.mayaBB, normalMode=0, userNormalMode=1, ch=0)
def make_snapshots_array(model_snap): # 229 - create morph targets frame_array = [] frame_skip = cm.intField(self.frame_skip, q=1, v=1) # >>>> deleted by Hiura # for frame in range(get_frame_end()+1): # if frame % (frame_skip + 1) == 0: # frame skipping logic # new_time = get_frame_start() + frame # <<<< deleted by Hiura for frame in range(get_frame_start(), get_frame_end() + 1, (frame_skip + 1)): # modified by Hiura new_time = frame snap = snapshot(model_snap, new_time) # snap = cm.parent(snap, w=1) cm.polyNormal(snap, nm=2, ch=0) frame_array.append(snap) return frame_array
def make_snapshots_array(model_snap): # 229 - create morph targets frame_array = [] frame_skip = cm.intField(self.frame_skip, q=1, v=1) # for frame in range(get_frame_start(), get_frame_end()+1, (frame_skip + 1)): # modified by Hiura frameAry = range(get_frame_start(), get_frame_end() + 1, (frame_skip + 1)) # for [base frame] by Hiura if cm.checkBox(self.cbBaseFrame, q=1, v=1): base_frame = cm.intField(self.frame_base, q=1, v=1) frameAry = [base_frame] + frameAry for frame in frameAry: new_time = frame snap = snapshot(model_snap, new_time) # snap = cm.parent(snap, w=1) cm.polyNormal(snap, nm=2, ch=0) frame_array.append(snap) return frame_array
def createPatchMesh(vertices, normals): width = len(vertices) height = len(vertices[0]) cmds.polyPlane(n="tp", sx=width-1, sy=height-1, ax=[0, 0, 1]) for j in range(height): for i in range(width): cmds.select("tp.vtx[%s]" % (j*width+i), r=True) cmds.move(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2], a=True) cmds.polyNormalPerVertex(xyz=normals[i][j].tolist()) normalZ = cmds.polyInfo("tp.f[0]", fn=True)[0].split()[-1] if normalZ[0]=="-": cmds.polyNormal("tp", normalMode=0, userNormalMode=0, ch=1); cmds.rename("tp", "patch1") cmds.select(cl=True)
def convexHull(pointList): """ from maya import cmds import sys sys.path.insert(0, '/Users/jarlske/Documents/scripts/python/jm_maya/mesh/') import delaunay reload(delaunay) sel = cmds.ls(sl=1) pointList = [] for each in sel: vtxLen = cmds.polyEvaluate(each, vertex=1) for i in range(0, vtxLen): pointList.append(cmds.xform('{0}.vtx[{1}]'.format(each, str(i)), q=1, t=1 ,ws=1)) geo = delaunay.convexHull(pointList) """ points = numpy.array(pointList) hull = ConvexHull(points) facetList = [] for each in hull.simplices: indexList = each.tolist() xpoint = [ pointList[indexList[0]][0], pointList[indexList[0]][1], pointList[indexList[0]][2] ] ypoint = [ pointList[indexList[1]][0], pointList[indexList[1]][1], pointList[indexList[1]][2] ] zpoint = [ pointList[indexList[2]][0], pointList[indexList[2]][1], pointList[indexList[2]][2] ] facetList.append( cmds.polyCreateFacet(ch=False, p=[xpoint, ypoint, zpoint])[0]) poly = cmds.polyUnite(facetList, ch=False, mergeUVSets=True) cmds.polyMergeVertex(poly, ch=False) cmds.polyNormal(poly, normalMode=2, userNormalMode=0, ch=False) cmds.select(cl=True) return poly
def sangkhuen(chue_tem_file, khanat, yaek_poly=0, ao_bs=1, ao_kraduk=1, ao_ik=0, watsadu=1, ao_alpha_map=1, yaek_alpha=0): t_roem = time.time() # เริ่มจับเวลา mmddata = an_model(chue_tem_file) # อ่านข้อมูลโมเดล # สร้างโพลิกอน chue_nod_poly, list_mat_mi_alpha = sang_poly(chue_tem_file, mmddata, khanat, ao_alpha_map, yaek_poly, watsadu, yaek_alpha) if (not yaek_poly): # สร้างเบลนด์เชป (ถ้าติ๊กว่าให้สร้าง) if (ao_bs): sang_bs(mmddata, chue_nod_poly, khanat) # สร้างกระดูก (ถ้าติ๊กว่าให้สร้าง) if (ao_kraduk): list_chue_nod_nok = sang_kraduk(mmddata, chue_nod_poly, khanat, ao_ik) mc.select(chue_nod_poly) if (not yaek_poly): mc.polyNormal() mc.polyNormal() if (ao_kraduk): mc.select(list_chue_nod_nok) print(u'作成完了。%.2fかかりました' % (time.time() - t_roem)) return chue_nod_poly, list_mat_mi_alpha
def opFlagEraser(): selection = m.ls(sl=True, l=True) if selection: targets = m.ls(sl=True, l=True, dag=True, ap=True, typ="mesh") else: targets = m.ls(l=True, typ="mesh") if not targets: return counter = 0 for t in targets: opAttr = t + ".opposite" op = m.getAttr(opAttr) if op: counter += 1 m.polyNormal(t, nm=0, ch=False) m.setAttr(opAttr, False) print "{} opposite flag(s) erased.".format(counter), m.select(selection, r=True)
def opFlagEraser(): selection = m.ls(sl=True, l=True) if selection: targets = m.ls(sl=True, l=True, dag=True, ap=True, typ='mesh') else: targets = m.ls(l=True, typ='mesh') if not targets: return counter = 0 for t in targets: opAttr = t + '.opposite' op = m.getAttr(opAttr) if op: counter += 1 m.polyNormal(t, nm=0, ch=False) m.setAttr(opAttr, False) print '{} opposite flag(s) erased.'.format(counter), m.select(selection, r=True)
def ncsc_normal_dir(): """Select the normals that are turning the "wrong" way """ a = [] sel = api.ncsc_get_obj_from_pref() if sel: for index, obj in enumerate(sel): obj_face_normal = [] dup_obj_face_normal = [] if mc.objExists(obj): # Duplicate the original object and run "conform", to get the correct normal vector mc.select(obj) dup_obj = mc.duplicate(name="dup_" + obj, rr=False)[0] mc.polyNormal(normalMode=2, userNormalMode=1, ch=1) mc.select(clear=True) face_count = mc.polyEvaluate(dup_obj, f=True) if isinstance(face_count, int): # Iterate through the duplicate and original object's faces and get the normal vector using api.face_normal for i in range(face_count): obj_face_normal.append(api.face_normal('{}.f[{}]'.format(obj, i))) dup_obj_face_normal.append(api.face_normal('{}.f[{}]'.format(dup_obj, i))) mc.select(clear=True) # Compare face normals, and select the ones that are different on the original object for index in range(len(obj_face_normal)): if obj_face_normal[index] != dup_obj_face_normal[index]: mc.select(obj + '.f[{}]'.format(index), add=True) a.extend(mc.ls(sl=True)) mc.delete(dup_obj) mc.select(clear=True) else: mc.warning("No objects selected!") mc.select(a, add=True)
def build(self, file): print "start to build" osm = pooper.data() osm.castData(file) osm.freezePoints(100000) ct = 0 pro = self.progressBar(len(osm.buildings), 100) for key, val in osm.buildings.items(): if ct in pro: self.valueUpdated.emit(pro[ct]) ct += 1 if val.type and val.type.startswith("build"): tPoint = self.ps2tuple(osm.points, val.pID) if len(tPoint) <= 2: continue bid = "b" + str(key) cmds.polyCreateFacet(p=tPoint, n=bid) if cmds.polyInfo(fn=True)[0].split(' ')[-2][0] == "-": cmds.polyNormal(nm=0) if val.height: cmds.select(bid) cmds.xform(cp=True) cmds.polyExtrudeFacet(kft=False, ltz=val.height) elif len(val.pID) >= 3 and val.pID[0] == val.pID[-1]: tPoint = self.ps2tuple(osm.points, val.pID) if len(tPoint) <= 2: continue bid = "b" + str(key) cmds.polyCreateFacet(p=tPoint, n=bid) if cmds.polyInfo(fn=True)[0].split(' ')[-2][0] == "-": cmds.polyNormal(nm=0) if val.height: cmds.select(bid) cmds.xform(cp=True) cmds.polyExtrudeFacet(kft=False, ltz=val.height) elif "boundary" in val.tags: tPoint = self.ps2tuple(osm.points, val.pID) if len(tPoint) <= 2: continue cmds.curve(p=tPoint, d=1)
def check_normal_uv(self): self.check_normal_flag = True pre_sel = cmds.ls(sl=True) cmds.selectMode(o=True) nmv = common.conv_comp(cmds.polyInfo(nmv=True), mode='vtx') last_face = common.conv_comp(self.mesh, mode='face')[-1] last_vtx = common.conv_comp(last_face, mode='vtx')[-3:] #print 'nmv :',nmv if nmv: #print 'last vtx :', last_vtx #フェースの頂点がすべて非多様頂点だった場合は反転する if len(list(set(nmv) & set(last_vtx))) == 3: #print 'get rev face :', last_face if maya_ver <= 2015: #2016以降、コマンドのふるまいが変わっていたので使い分け cmds.polyNormal(last_face, ch=1, normalMode=4) else: cmds.polyNormal(last_face, ch=1, normalMode=0) self.move_uv(last_face) #UV座標の移動 cmds.selectMode(co=True) cmds.select(pre_sel) self.check_normal_flag = False cmds.polySoftEdge(last_face, a=self.soft_angle.value())
def cleanupNonManifoldGeometry(self, normals = True): ## Get all the mesh that has mentalraySubdivApprox connected and has non-manifold problem # subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.listConnections(mesh, type = 'mentalraySubdivApprox') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = list( set( subdiv_mesh ) ) if subdiv_mesh: for each in subdiv_mesh: ## Make sure we do indeed have nonmanifold geometry ## nonManifold = cmds.polyInfo(each, nmv = True, nme = True) if nonManifold: proceed = cmds.confirmDialog(title = 'Non-Manifold Geometry!', message = 'Geo Name:\n%s' % each, button = ['Cleanup!', 'Skip...'], defaultButton = 'Skip...', cancelButton = 'Skip...', dismissString = 'Skip...') if proceed == 'Cleanup!': ## Conform the geo and see if that gets rid of all the nonmanifold bits ## if normals: cmds.polyNormal('%s.f[*]' % each, normalMode = 2, constructionHistory = True) edges = cmds.polyInfo(each, nme = True) if cmds.polyInfo(each, nme = True) else [] vertices = [] if edges else cmds.polyInfo(each, nmv = True) lastEdges = [] lastVertices = [] while ( not self.arraysMatch(lastEdges, edges) or not self.arraysMatch(lastVertices, vertices) ) and ( edges or vertices ): ## Remember what was nonmanifold last time ## lastEdges = edges lastVertices = vertices ## Split any nonmanifold edges ## if edges: cmds.polySplitEdge(edges, constructionHistory = True) vertices = cmds.polyInfo(each, nmv = True) edges = [] ## Split any remaining nonmanifold vertices ## if vertices: cmds.polySplitVertex(vertices, constructionHistory = True) vertices = [] ## Now check to see if the object is still nonmanifold ## nonManifold = cmds.polyInfo(each, nmv = True, nme = True) if nonManifold: ## Chip off the faces ## nonManifoldFaces = cmds.polyListComponentConversion(nonManifold, toFace = True) cmds.polyChipOff(nonManifoldFaces, kft = 0, dup = 0, constructionHistory = True) ## And then check for nonmanifold bits again ## edges = cmds.polyInfo(each, nme = True) if not edges: vertices = cmds.polyInfo(each, nmv = True) ## Check to see if we failed to cleanup if edges or vertices: cmds.warning('Failed to cleanup non-manifold geometry of %s...' % each)
def conformNormals(*args): cmds.polyNormal(nm=2) print'Conforming Normals'
#change perspective clip plane mc.viewClipPlane("perspShape", farClipPlane = 100000) #set up naming loop matteNames = ("g_foreground", "g_midground", "g_background") inc = 0 #create rings for ring in range(3): newRing = mc.polyCylinder(n = matteNames[inc], sx=24, sy=3, sz=0, radius=3000, h=2000) mc.move(340, y=True) mc.polyNormal(nm=0) inc = inc + 1 #adjust the scale mc.setAttr("polyCylinder2.radius", 3440) mc.setAttr("polyCylinder3.radius", 3880) #delete caps on all cylinders mc.delete("g_foreground.f[72:73]", "g_midground.f[72:73]", "g_background.f[72:73]") #set up ctrl naming loop ctrlNames = ("c_ForegroundMatte", "c_MidgroundMatte", "c_BackgroundMatte") #create controls
def extrude(*args): sel = cmds.ls(sl=True, exactType="transform") #keep = cmds.checkBoxGrp(widgets["keepCBG"], q=True, v1=True) if len(sel) < 3: cmds.warning( "You need to select the profile, then cap, then path curve in order!" ) return profileOrig = sel[0] cap = sel[1] curves = sel[2:] if not cmds.objExists("pastaRigSetupComponents_Grp"): cmds.group(empty=True, name="pastaRigSetupComponents_Grp") if not curveCheck(profileOrig): cmds.warning("Your first selection (profile) is not a curve!") return if not cmds.objExists("curveRebuild_originals_grp"): cmds.group(empty=True, name="curveRebuild_originals_grp") cmds.parent("curveRebuild_originals_grp", "pastaRigSetupComponents_Grp") cmds.parent(profileOrig, cap, "pastaRigSetupComponents_Grp") for curve in curves: if not curveCheck(curve): cmds.warning("{} is not a curve, skipping!".format(curve)) else: profile = cmds.duplicate(profileOrig, name="{}_profileCrv".format(curve))[0] newCap = cmds.duplicate(cap, returnRootsOnly=True, rebuildType=0, renameChildren=True, name="{}_capRig".format(curve))[0] # rigGrp = cmds.group(empty=True, name = "{}_rig_grp".format(curve)) curveResults = rebuildCurve(curve) newCrv = curveResults[0] rebuild = curveResults[1] cmds.parent(curve, "curveRebuild_originals_grp") capAxis = "y" capUp = "z" ctrl = rig.createControl(type="sphere", name="{}_CTRL".format(curve), color="blue") ctrlScale(ctrl) capGrp = cmds.group(empty=True, name="{}_cap_grp".format(curve)) deadGrp = cmds.group(empty=True, name="{}_noInherit_grp".format(curve)) cmds.parent(deadGrp, ctrl) #cmds.parent(ctrl, rigGrp) cmds.parent(newCap, capGrp) # add attrs to control cmds.addAttr(ctrl, ln="__xtraAttrs__", nn="__xtraAttrs__", at="bool", k=True) cmds.setAttr("{}.__xtraAttrs__".format(ctrl), l=True) cmds.addAttr(ctrl, ln="alongPath", at="float", min=0, max=100, k=True, dv=100.0) cmds.setAttr("{}.alongPath".format(ctrl), 100) cmds.addAttr(ctrl, ln="geoVis", at="long", min=0, max=1, k=True, dv=1) cmds.addAttr(ctrl, ln="pathCurveVis", at="long", min=0, max=1, k=True, dv=1) cmds.addAttr(ctrl, ln="__curveStuff__", nn="__curveStuff__", at="bool", k=True) cmds.setAttr("{}.__curveStuff__".format(ctrl), l=True) cmds.addAttr(ctrl, ln="density", at="float", min=0.02, max=8, k=True, dv=0.05) cmds.addAttr(ctrl, ln="radiusDivisions", at="float", k=True, min=1, max=3, dv=1.0) cmds.addAttr(ctrl, ln="reverseNormals", at="long", min=0, max=1, k=True) cmds.addAttr(ctrl, ln="capVisibility", at="long", min=0, max=1, k=True) cmds.setAttr("{}.capVisibility".format(ctrl), 1) cmds.addAttr(ctrl, ln="profileWidth", at="float", k=True, min=.001, max=3, dv=1.0) cmds.addAttr(ctrl, ln="capWidth", at="float", k=True, min=.01, max=2.0, dv=1.0) cmds.addAttr(ctrl, ln="capHeight", at="float", k=True, min=.01, max=2.0, dv=1.0) cmds.addAttr(ctrl, ln="rotateExtrusion", at="float", k=True, min=0, max=360) cmds.addAttr(ctrl, ln="rotateCap", at="float", k=True) cmds.addAttr(ctrl, ln="__textureAndRef__", nn="__textureAndRef__", at="bool", k=True) cmds.setAttr("{}.__textureAndRef__".format(ctrl), l=True) cmds.addAttr(ctrl, ln="textureRepeatMult", at="float", min=0.01, dv=1.0, k=True) cmds.addAttr(ctrl, ln="length", at="float", k=True) initLen = cmds.arclen(newCrv, ch=False) cmds.setAttr("{}.length".format(ctrl), initLen) cmds.setAttr("{}.length".format(ctrl), l=True) cmds.addAttr(ctrl, ln="geo", at="message") cmds.addAttr(ctrl, ln="fileTexture", at="message") cmds.addAttr(ctrl, ln="capRig", at="message") cmds.connectAttr("{}.message".format(newCap), "{}.capRig".format(ctrl)) # reference/driver attrs cmds.addAttr(ctrl, ln="prmHolder", at="float", k=True) cmds.addAttr(ctrl, ln="rptHolder", at="float", k=True) #cmds.setAttr("{}.radiusDivisions".format(ctrl), l=True) # connect mult to path mult = cmds.shadingNode("multiplyDivide", asUtility=True, name="{}_paraMult".format(curve)) cmds.connectAttr("{}.alongPath".format(ctrl), "{}.input1X".format(mult)) cmds.setAttr("{}.input2X".format(mult), 0.01) cmds.connectAttr("{}.profileWidth".format(ctrl), "{}.scaleX".format(profile)) cmds.connectAttr("{}.profileWidth".format(ctrl), "{}.scaleZ".format(profile)) # reverse for normals reverse = cmds.shadingNode("reverse", asUtility=True, name="{}_reverse".format(curve)) cmds.connectAttr("{}.reverseNormals".format(ctrl), "{}.inputX".format(reverse)) # cap, path and texture attrs and nodes cmds.connectAttr("{}.capVisibility".format(ctrl), "{}.v".format(capGrp)) repeatMult = cmds.shadingNode("multiplyDivide", asUtility=True, name="{}_RptMult".format(curve)) cmds.connectAttr("{}.outputX".format(mult), "{}.input1X".format(repeatMult)) cmds.connectAttr("{}.textureRepeatMult".format(ctrl), "{}.input2X".format(repeatMult)) cmds.connectAttr("{}.pathCurveVis".format(ctrl), "{}.visibility".format(newCrv)) #connect the rebuild density densityMult = cmds.shadingNode("multiplyDivide", asUtility=True, name="{}_DensityMult".format(curve)) cmds.connectAttr("{}.density".format(ctrl), "{}.input1X".format(densityMult)) cmds.connectAttr("{}.length".format(ctrl), "{}.input2X".format(densityMult)) cmds.connectAttr("{}.outputX".format(densityMult), "{}.spans".format(rebuild)) cmds.connectAttr("{}.outputX".format(repeatMult), "{}.rptHolder".format(ctrl)) cmds.connectAttr("{}.outputX".format(mult), "{}.prmHolder".format(ctrl)) cmds.setAttr("{}.prmHolder".format(ctrl), l=True) cmds.setAttr("{}.rptHolder".format(ctrl), l=True) cmds.connectAttr("{}.capWidth".format(ctrl), "{}.scaleX".format(capGrp)) cmds.connectAttr("{}.capWidth".format(ctrl), "{}.scaleZ".format(capGrp)) cmds.connectAttr("{}.capHeight".format(ctrl), "{}.scaleY".format(capGrp)) cmds.connectAttr("{}.rotateCap".format(ctrl), "{}.rotateY".format(newCap)) # position control at start of curve startPos = cmds.pointOnCurve(curve, parameter=0, position=True) cmds.xform(ctrl, ws=True, t=startPos) moPath = cmds.pathAnimation(capGrp, newCrv, fractionMode=True, follow=True, followAxis=capAxis, upAxis=capUp, worldUpType="scene", startTimeU=0.0, endTimeU=100.0) moPathAnimAttr = cmds.listConnections("{}.uValue".format(moPath), d=False, p=True)[0] start, end = getSliderRange() current = cmds.currentTime(q=True) cmds.currentTime(0) pPos = cmds.xform(capGrp, q=True, ws=True, rp=True) pRot = cmds.xform(capGrp, q=True, ws=True, ro=True) cmds.xform(profile, ws=True, t=pPos) cmds.xform(profile, ws=True, ro=pRot) cmds.currentTime(current) # extrude the curve extr = cmds.extrude(profile, newCrv, ch=True, range=True, polygon=True, extrudeType=2, useComponentPivot=True, fixedPath=True, useProfileNormal=True, reverseSurfaceIfPathReversed=True) extrGeo, extrNode = extr[0], extr[1] normal = cmds.polyNormal(extrGeo, normalMode=4, userNormalMode=0, ch=1)[0] cmds.connectAttr("{}.outputX".format(reverse), "{}.normalMode".format(normal)) cmds.connectAttr("{}.message".format(extrGeo), "{}.geo".format(ctrl)) cmds.connectAttr("{}.geoVis".format(ctrl), "{}.visibility".format(extrGeo)) cmds.connectAttr("{}.rotateExtrusion".format(ctrl), "{}.rotation".format(extrNode)) # get extrude connections connects = cmds.listConnections(extrNode) profNode, pathNode, tessNode = connects[0], connects[1], connects[ 2] # connect up stuff to extrusion cmds.connectAttr("{}.outputX".format(mult), "{}.maxValue".format(pathNode)) cmds.connectAttr("{}.radiusDivisions".format(ctrl), "{}.uNumber".format(tessNode)) cmds.parent(newCrv, ctrl) cmds.setAttr("{}.inheritsTransform".format(deadGrp), 0) cmds.parent(extrGeo, deadGrp) cmds.parent(profile, deadGrp) cmds.setAttr("{}.v".format(profile), 0) cmds.parent(capGrp, deadGrp) # motion path stuff cmds.delete(moPathAnimAttr.partition(".")[0]) cmds.connectAttr("{}.outputX".format(mult), "{}.uValue".format(moPath)) cmds.setAttr("{}.visibility".format(cap)) cmds.setAttr("{}.visibility".format(profileOrig))
def setUpSky(self): c.polyPlane( h=120,w=120,n='emitPlane'); c.polyNormal('emitPlane', nm=3 , n='polynormalReversed'); c.move(0,100,0,'emitPlane'); c.select(cl=True);
def reverseNormal(*args): a = cmds.ls(sl=True) if (len(a) > 0): cmds.polyNormal(nm=0)
def mirrorGeo(self, axis): selection = cmds.ls(sl=True) selectionPointList = cmds.polyListComponentConversion(selection, tv=True) points = cmds.ls(selectionPointList, fl=True) xformP = cmds.xform(points[0], q=True, ws=True, t=True) minX = xformP[0] midX = xformP[0] maxX = xformP[0] minY = xformP[1] midY = xformP[1] maxY = xformP[1] minZ = xformP[2] midZ = xformP[2] maxZ = xformP[2] for p in points: pPos = cmds.xform(p, q=True, ws=True, t=True) if pPos[0] > maxX : maxX = pPos[0] if pPos[1] > maxY : maxY = pPos[1] if pPos[2] > maxZ : maxZ = pPos[2] if pPos[0] < minX : maxX = pPos[0] if pPos[1] < minY : minY = pPos[1] if pPos[2] < minZ : minZ = pPos[2] midX = ((midX+pPos[0])/2) midY = ((midY+pPos[1])/2) midZ = ((midZ+pPos[2])/2) if axis == '+X': flipPivots = maxX, midY, midZ scaleAxis = 'X' if axis == '+Y': flipPivots = midX, maxY, midZ scaleAxis = 'Y' if axis == '+Z': flipPivots = midX, midY, maxZ scaleAxis = 'Z' if axis == '-X': flipPivots = minX, midY, midZ scaleAxis = 'X' if axis == '-Y': flipPivots = midX, minY, midZ scaleAxis = 'Y' if axis == '-Z': flipPivots = midX, midY, minZ scaleAxis = 'Z' newSelection = [] for item in selection: cmds.select(item) pivot = cmds.xform(item, q=True, ws=True, sp=True) print item, axis, scaleAxis, pivot, flipPivots # duplicate mesh dupItem = cmds.duplicate(rr=True, rc=True)[0] dupItemShape = cmds.listRelatives(dupItem)[0] cmds.makeIdentity(dupItem, apply=True, t=True, r=True, s=True, n=False) # set pivots cmds.xform(dupItem, ws=True, sp=flipPivots) # mirror cmds.setAttr(dupItem+'.scale'+scaleAxis, -1) cmds.polyNormal(dupItem, normalMode=0, ch=True) # set opposite cmds.setAttr(dupItemShape+'.opposite', not cmds.getAttr(dupItemShape+'.opposite')) # reapply pivots cmds.xform(item, ws=True, sp=pivot) cmds.xform(dupItem, ws=True, sp=pivot) # delete history center pivot cmds.makeIdentity(dupItem, apply=True, t=True, r=True, s=True, n=False) cmds.delete(dupItem, ch=True) cmds.select(dupItem) newSelection.append(dupItem) cmds.select(newSelection)
def extrude(name = "defaultName", *args): print "starting extrude" sel = cmds.ls(sl=True) guideCrv = sel[0] if len(sel)>1: profileCrv = cmds.duplicate(sel[1], name="{}_profile_CRV".format(name))[0] else: profileCrv = cmds.circle(r=1, normal = (0, 1, 0), name="{}_profile_CRV".format(name), ch=False)[0] if len(sel) == 3: capRig = sel[2] else: capRig = "" if len(sel) > 3: return capAxis = "y" capUp = "z" # upLoc = cmds.spaceLocator(name = "{}_upLoc".format(name))[0] ctrl = rig.createControl(type="sphere", name="{}_CTRL".format(name), color="blue") ctrlGrp = cmds.group(empty=True, name="{}_path_GRP".format(name)) capGrp = cmds.group(empty=True, name="{}_cap_GRP".format(name)) deadGrp = cmds.group(empty=True, name="{}_noInherit_GRP".format(name)) if capRig: cmds.parent(capRig, capGrp) cmds.parent(deadGrp, ctrlGrp) cmds.parent(ctrl, ctrlGrp) # add attrs to control cmds.addAttr(ctrl, ln="__xtraAttrs__", nn="__xtraAttrs__", at="bool", k=True) cmds.setAttr("{}.__xtraAttrs__".format(ctrl), l=True) cmds.addAttr(ctrl, ln="alongPath", at="float", min=0, max=100, k=True, dv=100.0) cmds.setAttr("{}.alongPath".format(ctrl), 100) cmds.addAttr(ctrl, ln="reverseNormals", at="long", min=0, max=1, k=True) cmds.addAttr(ctrl, ln="capVisibility", at="long", min=0, max=1, k=True) cmds.setAttr("{}.capVisibility".format(ctrl), 1) cmds.addAttr(ctrl, ln="capWidth", at="float", k=True, min=.01, max=2.0, dv=1.0) cmds.addAttr(ctrl, ln="capHeight", at="float", k=True, min=.01, max=2.0, dv=1.0) cmds.addAttr(ctrl, ln="profileWidth", at="float", k=True, min=.001, max=3, dv=1.0) # driver attrs cmds.addAttr(ctrl, ln="textureRepeatMult", at="float", min = 0.01, dv= 1.0, k=True) cmds.addAttr(ctrl, ln="prmHolder", at="float", k=True) cmds.addAttr(ctrl, ln="rptHolder", at="float", k=True) # cmds.addAttr(ctrl, ln="repeatMult", at="message", k=True) # cmds.addAttr(ctrl, ln="parameterMult", at ="message", k=True) # connect mult to path mult = cmds.shadingNode("multiplyDivide", asUtility=True, name="{}_paraMult".format(name)) cmds.connectAttr("{}.alongPath".format(ctrl), "{}.input1X".format(mult)) cmds.setAttr("{}.input2X".format(mult), 0.01) cmds.connectAttr("{}.profileWidth".format(ctrl), "{}.scaleX".format(profileCrv)) cmds.connectAttr("{}.profileWidth".format(ctrl), "{}.scaleZ".format(profileCrv)) # reverse for normals reverse = cmds.shadingNode("reverse", asUtility=True, name="{}_reverse".format(name)) cmds.connectAttr("{}.reverseNormals".format(ctrl), "{}.inputX".format(reverse)) # cap and texture attrs and nodes cmds.connectAttr("{}.capVisibility".format(ctrl), "{}.v".format(capGrp)) repeatMult = cmds.shadingNode("multiplyDivide", asUtility=True, name="{}_RptMult".format(name)) cmds.connectAttr("{}.outputX".format(mult), "{}.input1X".format(repeatMult)) cmds.connectAttr("{}.textureRepeatMult".format(ctrl), "{}.input2X".format(repeatMult)) # cmds.connectAttr("{}.message".format(repeatMult), "{}.repeatMult".format(ctrl)) # cmds.connectAttr("{}.message".format(mult), "{}.parameterMult".format(ctrl)) cmds.connectAttr("{}.outputX".format(repeatMult), "{}.rptHolder".format(ctrl)) cmds.connectAttr("{}.outputX".format(mult), "{}.prmHolder".format(ctrl)) cmds.setAttr("{}.prmHolder".format(ctrl), l=True) cmds.setAttr("{}.rptHolder".format(ctrl), l=True) cmds.connectAttr("{}.capWidth".format(ctrl), "{}.scaleX".format(capGrp)) cmds.connectAttr("{}.capWidth".format(ctrl), "{}.scaleZ".format(capGrp)) cmds.connectAttr("{}.capHeight".format(ctrl), "{}.scaleY".format(capGrp)) # position control at start of curve startPos = cmds.pointOnCurve(guideCrv, parameter = 0, position = True) cmds.xform(ctrlGrp, ws=True, t=startPos) # cmds.xform(upLoc, ws=True, t=(startPos[0], startPos[1]+3.0, startPos[2])) moPath = cmds.pathAnimation(capGrp, guideCrv, fractionMode=True, follow=True, followAxis=capAxis, upAxis=capUp, worldUpType="scene", startTimeU=0.0, endTimeU=100.0) moPathAnimAttr = cmds.listConnections("{}.uValue".format(moPath), d=False, p=True)[0] start, end = getSliderRange() current = cmds.currentTime(q=True) cmds.currentTime(start) pPos = cmds.xform(capGrp, q=True, ws=True, rp=True) pRot = cmds.xform(capGrp, q=True, ws=True, ro=True) cmds.xform(profileCrv, ws=True, t=pPos) cmds.xform(profileCrv, ws=True, ro=pRot) cmds.currentTime(current) # extrude the curve extr = cmds.extrude(profileCrv, guideCrv, ch=True, range=True, polygon=True, extrudeType=2, useComponentPivot=True, fixedPath=True, useProfileNormal=True, reverseSurfaceIfPathReversed=True) extrGeo, extrNode = extr[0], extr[1] normal = cmds.polyNormal(extrGeo, normalMode=4, userNormalMode=0, ch=1)[0] cmds.connectAttr("{}.outputX".format(reverse), "{}.normalMode".format(normal)) # get extrude connections connects = cmds.listConnections(extrNode) profNode, pathNode, tessNode = connects[0], connects[1], connects[2] # connect up stuff to extrusion cmds.connectAttr("{}.outputX".format(mult), "{}.maxValue".format(pathNode)) cmds.parent(guideCrv, ctrl) cmds.setAttr("{}.inheritsTransform".format(deadGrp), 0) cmds.parent(extrGeo, deadGrp) cmds.parent(profileCrv, deadGrp) cmds.setAttr("{}.v".format(profileCrv), 0) cmds.parent(capGrp, deadGrp) # motion path stuff cmds.delete(moPathAnimAttr.partition(".")[0]) cmds.connectAttr("{}.outputX".format(mult), "{}.uValue".format(moPath)) # reference # extrude -ch true -rn true -po 1 -et 2 -ucp 1 -fpt 1 -upn 1 -rotation 0 -scale 1 -rsp 1 "nurbsCircle1" "curve4" ; print "ending extrude"
ct = 0 total = len(buildings) onek = 1000 for key, val in buildings.items(): ct += 1 if ct == onek: print str(ct) + "/" + str(total) onek += 1000 if val[2] and val[2].startswith("build"): tPoint = ps2tuple(points, val[0]) if len(tPoint) <= 2: continue bid = "b" + str(key) cmds.polyCreateFacet(p=tPoint, n=bid) if cmds.polyInfo(fn=True)[0].split(' ')[-2][0] == "-": cmds.polyNormal(nm=0) if val[1]: cmds.select(bid) cmds.xform(cp=True) cmds.polyExtrudeFacet(kft=False, ltz=val[1]) elif len(val[0]) >= 3 and val[0][0] == val[0][-1]: tPoint = ps2tuple(points, val[0]) if len(tPoint) <= 2: continue bid = "b" + str(key) cmds.polyCreateFacet(p=tPoint, n=bid) if cmds.polyInfo(fn=True)[0].split(' ')[-2][0] == "-": cmds.polyNormal(nm=0) if val[1]: cmds.select(bid) cmds.xform(cp=True) cmds.polyExtrudeFacet(kft=False, ltz=val[1])
def cleanupNonManifoldGeometry(self, normals=True): ## Get all the mesh that has mentalraySubdivApprox connected and has non-manifold problem # subdiv_mesh = [cmds.listRelatives(mesh, parent = True, fullPath = True)[0] for mesh in cmds.ls(type = 'mesh') if cmds.listConnections(mesh, type = 'mentalraySubdivApprox') if cmds.polyInfo(mesh, nme = True) or cmds.polyInfo(nmv = True)] subdiv_mesh = [ cmds.listRelatives(mesh, parent=True, fullPath=True)[0] for mesh in cmds.ls(type='mesh') if cmds.polyInfo(mesh, nme=True) or cmds.polyInfo(nmv=True) ] subdiv_mesh = list(set(subdiv_mesh)) if subdiv_mesh: for each in subdiv_mesh: ## Make sure we do indeed have nonmanifold geometry ## nonManifold = cmds.polyInfo(each, nmv=True, nme=True) if nonManifold: proceed = cmds.confirmDialog( title='Non-Manifold Geometry!', message='Geo Name:\n%s' % each, button=['Cleanup!', 'Skip...'], defaultButton='Skip...', cancelButton='Skip...', dismissString='Skip...') if proceed == 'Cleanup!': ## Conform the geo and see if that gets rid of all the nonmanifold bits ## if normals: cmds.polyNormal('%s.f[*]' % each, normalMode=2, constructionHistory=True) edges = cmds.polyInfo(each, nme=True) if cmds.polyInfo( each, nme=True) else [] vertices = [] if edges else cmds.polyInfo(each, nmv=True) lastEdges = [] lastVertices = [] while (not self.arraysMatch(lastEdges, edges) or not self.arraysMatch(lastVertices, vertices) ) and (edges or vertices): ## Remember what was nonmanifold last time ## lastEdges = edges lastVertices = vertices ## Split any nonmanifold edges ## if edges: cmds.polySplitEdge(edges, constructionHistory=True) vertices = cmds.polyInfo(each, nmv=True) edges = [] ## Split any remaining nonmanifold vertices ## if vertices: cmds.polySplitVertex(vertices, constructionHistory=True) vertices = [] ## Now check to see if the object is still nonmanifold ## nonManifold = cmds.polyInfo(each, nmv=True, nme=True) if nonManifold: ## Chip off the faces ## nonManifoldFaces = cmds.polyListComponentConversion( nonManifold, toFace=True) cmds.polyChipOff(nonManifoldFaces, kft=0, dup=0, constructionHistory=True) ## And then check for nonmanifold bits again ## edges = cmds.polyInfo(each, nme=True) if not edges: vertices = cmds.polyInfo(each, nmv=True) ## Check to see if we failed to cleanup if edges or vertices: cmds.warning( 'Failed to cleanup non-manifold geometry of %s...' % each)
def mirrorProxy(proxy,axis='x'): ''' Mirror specified proxy geometry across a given axis @param proxy: The proxy bounds mesh to mirror @type proxy: str @param axis: The world axis to mirror across @type axis: str ''' # ========== # - Checks - # ========== if not mc.objExists(proxy): raise Exception('Proxy object "'+proxy+'" does not exist!') if not isProxyBound(proxy): raise Exception('Object "'+proxy+'" is not a vlid proxy bounds object!') # Check Side Prefix if not proxy.startswith('lf') and not proxy.startswith('rt'): raise Exception('Proxy object "'+proxy+'" does not have a valid side prefix! ("lf_" or "rt_")') # Check Axis axis = axis.lower()[0] if not ['x','y','z'].count(axis): raise Exception('Invalid mirror axis! ("'+axis+'")') # =================== # - Duplicate Proxy - # =================== search = '' replace = '' if proxy.startswith('lf'): search = 'lf' replace = 'rt' elif proxy.startswith('rt'): search = 'rt' replace = 'lf' else: raise Exception('Proxy object "'+proxy+'" does not have a valid side prefix! ("lf_" or "rt_")') # Duplicate Proxy mProxy = mc.duplicate(proxy)[0] # Duplicate Proxy Group proxyGrp = mc.listRelatives(proxy,p=True)[0] mProxyGrp = mc.duplicate(proxyGrp,po=True)[0] # Rename mProxyNew = proxy.replace(search,replace) if mc.objExists(mProxyNew): mc.delete(mProxyNew) mProxy = mc.rename(mProxy,mProxyNew) mProxyGrpNew = proxyGrp.replace(search,replace) if mc.objExists(mProxyGrpNew): mc.delete(mProxyGrpNew) mProxyGrp = mc.rename(mProxyGrp,mProxyGrpNew) # Retarget Joint joint = mc.getAttr(proxy+'.jointProxy') joint = joint.replace(search,replace) mc.setAttr(mProxy+'.jointProxy',joint,type='string') # Retarget Cut and Add Geo cutGeo = mc.getAttr(proxy+'.cutGeometry') addGeo = '[]' if mc.attributeQuery('addGeometry',n=proxy,ex=True): addGeo = mc.getAttr(proxy+'.addGeometry') try: cutGeo = ast.literal_eval(cutGeo) addGeo = ast.literal_eval(addGeo) except: pass else: cutGeo = [geo.replace(search,replace) for geo in cutGeo] addGeo = [geo.replace(search,replace) for geo in addGeo] if cutGeo: mc.setAttr(mProxy+'.cutGeometry',str(cutGeo),type='string') if addGeo: mc.setAttr(mProxy+'.addGeometry',str(addGeo),type='string') # ================ # - Mirror Proxy - # ================ # Position Proxy Grp to Joint if mc.objExists(joint): mirrorCon = mc.parentConstraint(joint,mProxyGrp) mc.delete(mirrorCon) # Mirror Proxy mProxy = mc.parent(mProxy,w=True)[0] mc.reorder(mProxy,f=True) mc.makeIdentity(mProxy,apply=True,t=True,r=True,s=True)#,n=True) mc.xform(mProxy,ws=True,piv=[0,0,0]) mc.setAttr(mProxy+'.s'+axis,-1.0) mProxy = mc.parent(mProxy,mProxyGrp)[0] mc.makeIdentity(mProxy,apply=True,t=True,r=True,s=True)#,n=True) mc.setAttr(mProxy+'.opposite',0) piv = mc.xform(mProxyGrp,q=True,ws=True,sp=True) mc.xform(mProxy,ws=True,piv=piv) # Reverse Normal mc.polyNormal(mProxy,ch=0,normalMode=0) mc.polyNormalPerVertex(mProxy,unFreezeNormal=True) # Set Colour glTools.utils.colorize.setColour(mProxy) # Reconnect Shading Toggle mc.connectAttr(mProxy+'.shading',mProxy+'.overrideShading') # ================= # - Return Result - # ================= return mProxy
def mayaExporterReady(): print('\nLancement du script\n') cmds.undoInfo(cn="mayaExporterReady", ock=True) # Aware the user of what it will happen if storage.values.displayInfo: ui.info( "Info", "The script will now proceed through several operations, as you parametered it in the preceding window" ) # Getting all transformNodes needed if storage.values.displayInfo: ui.info( "Info", "The script gather all the transformNodes of the scene to prepare them to the export" ) # Store meshes following the options if not storage.values.selectionOnly: cmds.select(all=True, hierarchy=True) selectedMeshes = cmds.ls(sl=True, type="transform") # """"""""""""" # CHECK FILES # """"""""""""" storage.scene = storage.scene = cmds.file(q=True, sn=True) # check the localization of the file storage.scene = cmds.file(q=True, sn=True) if not checkSave(): return storage.sceneName, storage.sceneExt = os.path.splitext( os.path.basename(storage.scene)) # check if the file is not an export file if not checkExportFile(storage.sceneName): return # Check if there is no duplicated project sceneCopy = os.path.join(os.path.dirname(storage.scene), storage.sceneName + "_export" + storage.sceneExt) if storage.values.displayInfo: ui.info( "Info", "The script is now checking for an existing export file generated earlier" ) if not checkDuplication(sceneCopy): return # Duplicate the project if storage.values.displayInfo: ui.info("Info", "The script duplicate your scene as an 'export' file") cmds.sysFile(storage.scene, copy=sceneCopy) # Opening of the new project into Maya if storage.values.displayInfo: ui.info("Info", "The script is opening the duplicated scene in Maya") # We need to save the scene to save the metadata modified cmds.file(save=True) cmds.file(sceneCopy, open=True) # """"""""""""""""""""" # PREPARE THE PROCESS # """"""""""""""""""""" # First delete history of the transforms for node in selectedMeshes: cmds.delete(node, constructionHistory=True) # Splitting into meshes and otherElement splitTransform(selectedMeshes) # Make sure that at least one mesh or group is selected if len(storage.transformNodes) == 0: ui.info("Error", "No mesh or group detected in your scene") cmds.file(storage.scene, force=True, open=True) print('\nFin du script\n') return if storage.values.displayInfo: ui.info("Info", "The script is ready to prepare your transformNodes") # """"""""" # PROCESS # """"""""" # conform normals if storage.values.conformNormals: if storage.values.displayInfo: ui.info( "Info", "The script conform the normals of your transformNodes as you asked for" ) for mesh in storage.meshes: cmds.polyNormal(mesh, nm=2) # Rebuild normals if storage.values.rebuildNormals: if storage.values.displayInfo: ui.info( "Info", "The script rebuild the normals of your transformNodes as you asked for, with parameter " + str(storage.values.rebuildNormalOption)) rebuildNormals() # set pivot of the mesh setPivot() # clean up if storage.values.cleanUpMesh: if storage.values.displayInfo: ui.info("Info", "The script is cleaning your mesh") for mesh in storage.meshes: cmds.polyClean(mesh) # _freezeTransform transformations if storage.values.freezeTransform: if storage.values.displayInfo: ui.info( "Info", "The script is freezing the transformations of your meshes") for node in storage.transformNodes: cmds.makeIdentity(node, apply=True, t=1, r=1, s=1, n=0) # delete history if storage.values.deleteHistory: if storage.values.displayInfo: ui.info( "Info", "The script is deleting the history of your transformNodes") for node in storage.transformNodes: cmds.delete(node, constructionHistory=True) # export meshes if storage.values.exportResult: # Check or create a destination directory prepareExport(storage.sceneName, storage.values.exportName) # check non manyfold mesh probMesh = [] cmds.select(clear=True) if storage.values.checkNonManyfold: if storage.values.displayInfo: ui.info("Info", "The script is looking for non-manyfold transformNodes") probMesh = checkNonManyfold() # set back the user to the original scene if storage.values.stayInScene: if storage.values.displayInfo: ui.info("Info", "You choose to stay in your active scene") cmds.file(save=True) cmds.file(storage.scene, open=True) if len(probMesh) > 0: for prob in probMesh: cmds.select(prob, add=True) ui.info("Non-manyfold transformNodes", "Problematic transformNodes have been seleted") cmds.undoInfo(cn="mayaExporterReady", cck=True) if storage.values.displayInfo: ui.info("Info", "The script has now finished !") print('\nFin du script\n')
def normRev(*args): cmds.polyNormal(normalMode=0)
def SAVEPOSE(listPoseWidget, home): poseSettings = "" pathContainer = "" customFile = py.file(home + "CUSTOM.json", q=1, ex=1) if (customFile == 1): with open(home + 'CUSTOM.json', 'r') as f: line = json.load(f) primaryColor = [] secondaryColor = [] secondaryFont = "smallFixedWidthFont" i = 0 while (i < 3): primaryColor.append(float(line['PRIMARY UI COLOR'].split(",")[i])) secondaryColor.append(float(line['SECONDARY UI COLOR'].split(",")[i])) i += 1 ############################################################################### # DETERMINES THE VALIDITY OF THE PREVIOUSLY SELECTED # ############################################################################### rigControllers = [] selections = py.ls(sl=1) i = 0 while (i < len(selections)): RiGGiE = py.listAttr(selections[i], st=["RiGGiE"], r=1) WiGGiE = py.listAttr(selections[i], st=["WiGGiE"], r=1) if (isinstance(RiGGiE, list) == 1 or isinstance(WiGGiE, list) == 1): rigControllers.append(selections[i]) i += 1 if (rigControllers != []): nameSpace = "" if (":" in rigControllers[0]): name = rigControllers[0].split(":")[-1] nameSpace = rigControllers[0][0:(len(rigControllers[0]) - len(name))] else: name = rigControllers[0] ############################################################################### # FIND ALL CONTROLLERS IN FIRST SELECTION # ############################################################################### outputControllers = [] masterCenter = name.replace("_L_", "_M_").replace("_R_", "_M_") masterName = masterCenter.replace( masterCenter.split("_")[2], "master") masterController = nameSpace + masterName.replace( masterName.split("_")[-1], "CTRL") outputItems = py.listRelatives(masterController, ad=1, pa=1) outputControllerShapes = [s for s in outputItems if "CTRL" in s] outputShapes = [s for s in outputItems if "Shape" in s] outputItems = list(set(outputControllerShapes) - set(outputShapes)) i = 0 while (i < len(outputItems)): RiGGiE = py.listAttr(outputItems[i], st=["RiGGiE"], r=1) WiGGiE = py.listAttr(outputItems[i], st=["WiGGiE"], r=1) if (isinstance(RiGGiE, list) == 1 or isinstance(WiGGiE, list) == 1): outputControllers.append(outputItems[i]) i += 1 outputControllers.insert(0, masterController) ############################################################################### # GATHER CONTROLLERS AND THEIR ATTRIBUTES AND VALUES THEN STORE IN STRING # ############################################################################### dialog = py.promptDialog(t="Pose Name", m="What kind of pose is this?", b=["OK", "CANCEL"], db="OK", cb="CANCEL", ds="OK") poseName = py.promptDialog(text=1, q=1) try: poseName.decode('ascii') except: poseName = "?" if (dialog != "CANCEL" and len(poseName) > 0 and "?" not in poseName and "/" not in poseName): poseName = poseName.replace("_POSE", "") i = 0 while (i < len(outputControllers)): controller = outputControllers[i][len(nameSpace):] poseSettings = poseSettings + controller + "--" attribute = py.listAttr(outputControllers[i], k=1) rotationOrder = py.listAttr(outputControllers[i], st=["ROTATE_ORDER"], r=1) if (isinstance(rotationOrder, list) == 1 and isinstance(attribute, list) == 1): attribute.append("ROTATE_ORDER") if (isinstance(attribute, list) == 1): ii = 0 while (ii < len(attribute)): poseSettings = poseSettings + attribute[ii] + "=" value = py.getAttr(outputControllers[i] + "." + attribute[ii]) poseSettings = poseSettings + str(value) + "," ii += 1 poseSettings = poseSettings + "\r\n" i += 1 #DETERMINE LOCAL OR GLOBAL PATH FOR POSE TO BE SAVED TO globalPosePath = "R:/Jx4/tools/dcc/maya/scripts/poseLibrary/" localPosePath = line['POSE (PATH)'] if (os.path.isdir(globalPosePath) == 1 and line['LOCAL POSE'] == 0 and line['GLOBAL POSE'] == 1): dialogPassword = py.promptDialog(t="Save Global Pose", m="What is the password?", b=["OK", "CANCEL"], db="OK", cb="CANCEL", ds="OK") passwordAttempt = py.promptDialog(text=1, q=1) try: passwordAttempt.decode('ascii') except: passwordAttempt = "?" if (dialogPassword != "CANCEL" and passwordAttempt.lower() == "kendrick"): posePath = globalPosePath else: posePath = localPosePath else: posePath = localPosePath if (line['LOCAL POSE'] == 1 or (line['GLOBAL POSE'] == 1 and posePath == globalPosePath)): if (localPosePath != globalPosePath): input = open(posePath + "p_" + poseName + "_POSE.txt", "w+") outline = input.writelines(poseSettings) input.close() else: posePath = "none" print '"Please check the LOCAL PATH (or GLOBAL PATH) on." - HiGGiE' py.headsUpMessage( '"Please check the LOCAL PATH (or GLOBAL PATH) on." - HiGGiE', t=2) if (localPosePath == globalPosePath): posePath = "none" print '"LOCAL PATH cannot be the same as the GLOBAL PATH!" - HiGGiE' py.headsUpMessage( '"LOCAL PATH cannot be the same as the GLOBAL PATH!" - HiGGiE', t=2) ############################################################################### # UPDATE UI WITH NEW LIST # ############################################################################### if (posePath != "none"): globalTextFiles = [] localTextFiles = [] if (os.path.isdir(globalPosePath) == 1 and line['GLOBAL POSE'] == 1): globalTextFiles = glob.glob(globalPosePath + "*_POSE.txt") if (os.path.isdir(localPosePath) == 1 and line['LOCAL POSE'] == 1): localTextFiles = glob.glob(localPosePath + "*_POSE.txt") textFiles = globalTextFiles + localTextFiles i = 0 while (i < len(textFiles)): pathContainer = pathContainer + textFiles[i].replace( "\\", "/") pathContainer = pathContainer + "," i += 1 os.remove(home + "CUSTOM.json") line['POSE FILES (FULL NAME)'] = pathContainer presets = line with open(home + 'CUSTOM.json', 'w+') as f: json.dump(presets, f, sort_keys=False, indent=4) #TAKE SCREEN CAP ToggleViewAxis() mel.eval("setCameraNamesVisibility(0);") gridStatus = 0 if (py.grid(tgl=1, q=1) == 1) else 1 py.grid(tgl=gridStatus) currentCamera = py.lookThru(q=1) translations = list(py.getAttr(currentCamera + ".t")[0]) centerOfInterest = py.getAttr(currentCamera + ".centerOfInterest") py.setAttr(currentCamera + "Shape.cameraScale", 1) FrameSelected() py.setAttr(currentCamera + "Shape.cameraScale", 0.25) thumbnailFormat = py.getAttr( "defaultRenderGlobals.imageFormat") py.setAttr("defaultRenderGlobals.imageFormat", 32) currentFrame = py.currentTime(q=1) #START: APPLY BACKGROUND COLOR scaleValue = 10000 shader = py.shadingNode("blinn", asShader=1) shaderGRP = py.sets(renderable=1, noSurfaceShader=1, empty=1) py.connectAttr('%s.outColor' % shader, '%s.surfaceShader' % shaderGRP) background = py.polyCube()[0] py.hyperShade(assign=shader) py.polyNormal(background, normalMode=0, userNormalMode=0, ch=1) py.parentConstraint(selections, background, mo=0, w=1) py.setAttr(background + ".s", scaleValue, scaleValue, scaleValue) if (posePath == localPosePath): py.setAttr(shader + ".incandescence", 0.0771, 0.2296, 0.2901, type="double3") else: py.setAttr(shader + ".incandescence", 0.4318, 0.2022, 0.2022, type="double3") py.setAttr(shader + ".color", 0, 0, 0, type="double3") py.setAttr(shader + ".eccentricity", 0) py.select(selections, r=1) #END: APPLY BACKGROUND COLOR py.playblast(frame=currentFrame, format="image", cf=posePath + "p_" + poseName + "_POSE.png", wh=[100, 200], p=100, v=0) py.delete(background, shader) py.setAttr("defaultRenderGlobals.imageFormat", thumbnailFormat) py.setAttr(currentCamera + "Shape.cameraScale", 1) py.setAttr(currentCamera + "Shape.centerOfInterest", centerOfInterest) py.setAttr(currentCamera + ".t", translations[0], translations[1], translations[2]) gridStatus = 0 if (py.grid(tgl=1, q=1) == 1) else 1 py.grid(tgl=gridStatus) ToggleViewAxis() #ADD ITEMS TO GRID thumbnailSize = [100, 180] poseList = line['POSE FILES (FULL NAME)'].split(",") listPoseWidget.clear() i = 0 while (i < len(poseList)): if (len(poseList[i]) > 0 and py.file(poseList[i], q=1, ex=1) == 1): if (py.file(poseList[i].replace(".txt", ".png"), q=1, ex=1) == 1): name = poseList[i].split("/")[-1].split( ".")[0].split("_POSE")[0].replace("p_", "", 1) thumbnailItem = qt.QListWidgetItem(name) thumbnailImage = qt.QIcon() thumbnailImage.addPixmap( qt.QPixmap( _fromUtf8(poseList[i].replace( ".txt", ".png"))), qt.QIcon.Normal, qt.QIcon.Off) thumbnailItem.setIcon(thumbnailImage) listPoseWidget.addItem(thumbnailItem) i += 1 py.headsUpMessage('"Successfully saved your ' + poseName + ' pose to: ' + posePath + '" - HiGGiE', t=3) elif (dialog != "CANCEL" and len(poseName) > 0 and ("?" in poseName or "/" in poseName)): print '"You must type a valid name (English only and no "_")." - HiGGiE' py.headsUpMessage( '"You must type a valid name (English only and no "_")." - HiGGiE', t=10) else: print '"You must select a valid rig controller." - HiGGiE' py.headsUpMessage('"You must select a valid rig controller." - HiGGiE', t=2)
def ImportToMaya(vertexArray, polygonConnects, uvArray, texturePath, texture): global g_Mesh_Index printMessage("Creating mesh...") polygonCounts = OpenMaya.MIntArray(polygonConnects.length() / 3, 3) mesh = OpenMaya.MFnMesh() transform = mesh.create(vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects) printDebug("connects cnt {}".format(polygonConnects.length())) printDebug("cnt {}".format(polygonCounts.length())) printDebug("u cnt {}".format(uvArray[0].length())) printDebug("v cnt {}".format(uvArray[1].length())) # UV map. printMessage("Mapping UVs...") mesh.setUVs(uvArray[0], uvArray[1]) try: mesh.assignUVs(polygonCounts, polygonConnects) except RuntimeError: printDebug("mesh.assignUVs() failed. Assign manually...") for i in range(0, polygonConnects.length()): try: mesh.assignUV(i / 3, i % 3, polygonConnects[i]) except RuntimeError: printMessage("AssignUV failed: " + "[{}] = {}".format(i, polygonConnects[i])) # Rename mesh. printMessage("Renaming mesh...") transformDagPath = OpenMaya.MDagPath() OpenMaya.MDagPath.getAPathTo(transform, transformDagPath) meshName = cmds.rename(transformDagPath.fullPathName(), "NinjaMesh_{}".format(g_Mesh_Index)) g_Mesh_Index = g_Mesh_Index + 1 # Apply textures. printMessage("Applying textures...") shader = cmds.shadingNode("lambert", name="NinjaTexture_{}".format(g_Mesh_Index), asShader=True) cmds.select(meshName) cmds.hyperShade(assign=shader) colorMap = cmds.shadingNode("file", name="{}_colorMap".format(texture), asTexture=True) cmds.connectAttr("{}.outColor".format(colorMap), "{}.color".format(shader)) cmds.setAttr("{}.fileTextureName".format(colorMap), "{}/{}".format(texturePath, texture), type='string') # Set vertex color to White. printMessage("Forcing vertex color to white...") cmds.select(meshName) cmds.polyColorPerVertex(cdo=True, rgb=[1, 1, 1]) # Apply transformations. printMessage("Applying transformations...") cmds.setAttr("{}.rotateX".format(meshName), g_ninjarotX) cmds.setAttr("{}.rotateY".format(meshName), g_ninjarotY) cmds.setAttr("{}.rotateZ".format(meshName), g_ninjarotZ) cmds.setAttr("{}.scaleX".format(meshName), mdlscaler) cmds.setAttr("{}.scaleY".format(meshName), mdlscaler) cmds.setAttr("{}.scaleZ".format(meshName), mdlscaler) # Freeze transformations. printMessage("Zeroing new transform values...") cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1) # Scale UVs. printMessage("Scaling UVs...") uvs = cmds.polyListComponentConversion(meshName, tuv=True) cmds.select(uvs) cmds.polyEditUV(su=uvscaler, sv=uvscaler * g_flipUV) # Normalize UV. if g_normalizeUV: printMessage("Normalizing UVs...") cmds.polyNormalizeUV(nt=1, pa=True, centerOnTile=True) # Merge duplicates. printMessage("Removing duplicate vertex...") cmds.select(cl=True) cmds.select(meshName) cmds.polyMergeVertex(d=0.01, am=True, ch=1) cmds.polyMergeUV(d=0.01, ch=True) # Reverse normals (First met in MWR) if g_reverseNormals: printMessage("Reversing normals...") cmds.select(cl=True) cmds.select(meshName) cmds.polyNormal(meshName, ch=1) cmds.select(cl=True) print("Import done for mesh '{}'".format(meshName))
def create_limb(limb_pos, limb_name, aim_axis, up_axis): if up_axis == aim_axis: sys.exit('Aim and Up axis are the same ones !!') axis = [aim_axis, up_axis] for idx, vector in enumerate(axis): if vector == 'x': vector = (1, 0, 0) elif vector == 'y': vector = (0, 1, 0) elif vector == 'z': vector = (0, 0, 1) else: sys.exit('Axe non valide !') axis[idx] = vector print(axis) aim_axis = axis[0] up_axis = axis[1] print(up_axis) print('aim_axis == ' + str(aim_axis)) print('up_axis == ' + str(up_axis)) loc_sel = mc.ls(sl=True) if not len(loc_sel) == 3: sys.exit('You must select 3 locators for creating a limb.') if not mc.objExists('TEMP__grp'): temp_grp = mc.group(em=True, n='TEMP__grp') #mc.select('locator1','locator2','locator3', r=True) if limb_pos == 'l': limb_opp = 'r' elif limb_pos == 'r': limb_opp = 'l' else: sys.exit('No left of right. Wrong argument.') name_base = limb_pos + '_' + limb_name + '_' jnt_sel = [] for each in loc_sel: print(each) jnt = mc.createNode('joint') mc.parent(jnt, each) mc.xform(jnt, t=(0, 0, 0)) mc.parent(jnt, w=True) jnt_sel.append(jnt) print(jnt_sel) mc.rename(jnt_sel[0], name_base + 'fk_0__anim') mc.rename(jnt_sel[1], name_base + 'fk_1__anim') mc.rename(jnt_sel[2], name_base + 'fk_x__anim') jnt_sel = [] jnt_sel.append(name_base + 'fk_0__anim') jnt_sel.append(name_base + 'fk_1__anim') jnt_sel.append(name_base + 'fk_x__anim') # GET TRIPLANAR NORMAL coords = [] for each in loc_sel: pos = mc.xform(each, q=True, t=True) coords.append(pos) poly = mc.polyCreateFacet(p=coords) normals = mc.polyInfo(poly[0], faceNormals=True) mc.polyNormal(nm=0) print(normals) rivet.ch4_rivet(name_base + '__normal') limb_normal = name_base + '__normal' print(limb_normal) # ZeroOut sur le premier Joint n_Rot = mc.xform(limb_normal, q=True, ro=True) for each in jnt_sel: mc.xform(each, ro=n_Rot) sys.exit('dfgdfg') if up_axis == (0, 1, 0): mc.xform(jnt_sel[1], ro=(0, 0, 0), roo='yxz') elif up_axis == (0, 0, 1): mc.xform(jnt_sel[1], ro=(0, 0, 0), roo='zxy') elif up_axis == (1, 0, 0): mc.xform(jnt_sel[1], ro=(0, 0, 0), roo='zyx') temp_x = mc.getAttr(jnt_sel[2] + '.rotateX') temp_y = mc.getAttr(jnt_sel[2] + '.rotateY') temp_z = mc.getAttr(jnt_sel[2] + '.rotateZ') mc.setAttr(jnt_sel[2] + '.jointOrientX', 0) mc.setAttr(jnt_sel[2] + '.jointOrientY', 0) mc.setAttr(jnt_sel[2] + '.jointOrientZ', 0) mc.xform(jnt_sel[2], r=True, ro=(0, 0, 0)) mc.parent(jnt_sel[2], w=True) # Parenter les joints entre eux mc.parent(jnt_sel[2], jnt_sel[1]) mc.parent(jnt_sel[1], jnt_sel[0]) flip_bone = mc.getAttr(jnt_sel[1] + '.jointOrientX') if abs(flip_bone) == 180: mc.setAttr(jnt_sel[1] + '.jointOrientX', 0) # Miroir jnt_sel_mir = mirror_joints(joint_zero) # CHANGER DE FONCTION ICI # Creer IK create_ik(jnt_sel) create_ik(jnt_sel_mir) mc.confirmDialog( t='Warning !!!', m='Ne pas oublier de regler les axes de rotation TOUT DE SUITE')
elif "R_" in org_obj and "left" not in org_obj and "right" in org_obj: mirrored_obj="L_{0}left{1}".format(org_obj.split('R_')[1].split('right')[0],org_obj.split('R_')[1].split('right')[1]) return mirrored_obj elif "M_" in org_obj and "left" not in org_obj and "right" in org_obj: mirrored_obj="{0}left{1}".format(org_obj.split('right')[0],org_obj.split('right')[1]) return mirrored_obj elif "M_" in org_obj and "left" in org_obj and "right" not in org_obj: mirrored_obj="{0}right{1}".format(org_obj.split('left')[0],org_obj.split('left')[1]) return mirrored_obj else: mirrored_obj="Mirrored_{0}".format(org_obj) return mirrored_obj def doMirror(self,*args): # mirror objs objs = cmds.ls(sl=True,fl=True,tr=True); for obj in objs: cur_center = cmds.objectCenter(obj) bbox = cmds.xform(obj,q=True,bb=True) cur_piv = cmds.xform(obj,q=True,ws=True,piv=True)[:3] origin = [0,0,0] dup_node = cmds.duplicate(obj,n=self.renameDup(obj)) cmds.scale(-1,1,1,dup_node,p=origin,ws=True,r=True) cmds.xform(dup_node,ws=True,piv=origin) cmds.polyNormal(dup_node,nm=0,ch=0) cmds.select(d=True)
def polyNormal(*args, **kwargs): res = cmds.polyNormal(*args, **kwargs) if not kwargs.get('query', kwargs.get('q', False)): res = _factories.maybeConvert(res, _general.PyNode) return res
def run(*args, **kwargs): """Detect flipped (reversed) normals. Find polygon objects with normals that point away from the camera as long as that camera is outside the object. Any objects found should be subject to a visual inspection. The test is unable to determine the proper normal direction for flat objects. This test may give seemingly false positives if a node's parent transforms are scaled by a negative value. --- To fix a scene, run [Polygons] Normals->Reverse return result, len(nonconformingfaces), len(reversedmeshes) nonconformingfaces, reversedmeshes, err has_flippednormals([verbose=boolean]) -> boolean, int, int, list, list list """ t0 = float(time.time()) valid_kwargs = ["verbose", "diag"] for k, v in kwargs.iteritems(): if k not in valid_kwargs: raise TypeError("Invalid keyword argument %s" % k) result = False err = list() verbose = False batch = cmds.about(batch=True) # verbose defaults to False if verbose option not set in menu # or specified in cmdline try: verbose = kwargs["verbose"] print "verbose is:", verbose except KeyError: verbose = False if cmds.optionVar(exists="checkmateVerbosity"): verbose = cmds.optionVar(query="checkmateVerbosity") try: diag = kwargs["diag"] except KeyError: diag = False # require OpenMaya for vector math import maya.OpenMaya as om result = False # meshes = cmds.ls(type='mesh') meshes = [x for x in cmds.ls(typ="mesh", noIntermediate=True) if not cm.tests.shapes.mesh.isEmpty(x)] cmds.select(clear=True) # make sure undo is on cmds.undoInfo(state=True, infinity=True) # set up necessary plug-ins if not cmds.pluginInfo("nearestPointOnMesh", query=True, loaded=True): try: cmds.loadPlugin("nearestPointOnMesh") except NameError: pass err = list() nonconformingfaces = list() reversedmeshes = list() if not batch: # put a progress bar in try: gMainProgressBar = mel.eval("$tmp = $gMainProgressBar") except RuntimeError: pass if len(meshes) < 1: err.append(["#Warning: No meshes in scene"]) return result, 0, 0, [], [], err if not batch: try: cmds.progressBar( gMainProgressBar, edit=True, beginProgress=True, isInterruptable=True, status="checking for reversed normals...", maxValue=len(meshes), ) except UnboundLocalError: pass for mesh in meshes: if not batch: if cmds.progressBar(gMainProgressBar, query=True, isCancelled=True): break cmds.progressBar(gMainProgressBar, edit=True, step=1) if verbose: print mesh # unlock normals, not spec'd but should be in here cmds.polyNormalPerVertex(mesh, ufn=True) # first check that all normals are conformed # this requires undo # if conform gives a selection, we know that not all normals conform cmds.select(mesh, replace=True) faces = cmds.polyListComponentConversion(toFace=True) # polyNormal will select and reverse the nonconforming faces or do # nothing # deselect the mesh, keep only faces, if any try: cmds.polyNormal(faces, normalMode=2, userNormalMode=0, ch=0) except TypeError: pass cmds.select(mesh, deselect=True) try: selection = cmds.ls(selection=True, flatten=True) except TypeError: pass ######################################################################## # if we have selected faces, we can stop at this point, because it is # not clear what the right # orientation of the normals is, assume the selection is correct # and is only faces (needs additional check) if len(cmds.ls(selection=True, flatten=True)): result = True nonconformingfaces.extend(selection) # should probably reverse the faces again cmds.polyNormal(selection, normalMode=0, userNormalMode=0, ch=0) # continue with the next loop continue # only continue if there are no nonconforming normals, # we now only have an objects that is completely reversed else: # find a point that is guaranteed to be outside the object if verbose: print "checking mes:h %s" % mesh p = cmds.exactWorldBoundingBox(mesh) point = tuple([(p[3] + 0.1), (p[4] + 1.0), (p[5] + 0.1)]) if verbose: print point if diag: cmds.spaceLocator(p=point) # the result of nearestPointOnMesh is a nearestPointOnMesh node nearestnode = cmds.nearestPointOnMesh(mesh, inPosition=point) if verbose: print nearestnode # get the normal, face index and position at the nearest point # getattr resuturns a list of tuples, take the first index nearestnormal = cmds.getAttr("%s.normal" % nearestnode)[0] if verbose: print "nearest normal: ", nearestnormal nearestposition = cmds.getAttr("%s.position" % nearestnode)[0] if verbose: print "nearest position: ", nearestposition if diag: cmds.spaceLocator(p=nearestposition) nearestfaceindex = cmds.getAttr("%s.nearestFaceIndex" % nearestnode) face = "%s.f[%d]" % (mesh, nearestfaceindex) cmds.select(face) if verbose: print "face: %s" % face cmds.delete(nearestnode) # select the nearest face (is this really necessary?) # cmds.select('%s.f[%s]' % (mesh,nearestfaceindex)) # figure out the direction which the facenormal should be looking # (should be toward point) # the differnce between point and nearestposition is a vector delta = ((point[0] - nearestposition[0]), (point[1] - nearestposition[1]), (point[2] - nearestposition[2])) # to avoid selecting a point at which the normal is difficult to determine # find the centroid of the face and use that to find the direction and use the normal of the face, # not the normal at the nearest point (label, num, nearestnormalX, nearestnormalY, nearestnormalZ) = cmds.polyInfo(face, fn=True)[0].split() # there's no need to normalize it facenormal = om.MVector(float(nearestnormalX), float(nearestnormalY), float(nearestnormalZ)) direction = om.MVector(delta[0], delta[1], delta[2]) if verbose: print "facenormal :", facenormal print "direction :", direction # Calculate dot product as an indication of how similar the two # vectors are. acosd(dot) gives the angle between the two, 0 means # identitcal, -1 means they're at a 180 degree angle # positive values mean the face normal is looking out, # negative means the normal is reversed dot = facenormal * direction if verbose: print "dot: %f5.2" % dot if dot > 0: pass else: reversedmeshes.append(mesh) result = True err.append("# FAIL : %s has reversed normals #" % mesh) # kill the progressBar if not batch: cmds.progressBar(gMainProgressBar, edit=True, endProgress=True) # turn off selection constraints cmds.polySelectConstraint(disable=True) # to make it easy to fix the scene select everything that is reversed cmds.select(clear=True) try: cmds.select(nonconformingfaces, add=True) except TypeError: pass try: cmds.select(reversedmeshes, add=True) except TypeError: pass # print execution time print "%-24s : %.6f seconds" % ("f.normals.run()", (float(time.time()) - t0)) return result, len(nonconformingfaces), len(reversedmeshes), nonconformingfaces, reversedmeshes, err
def makePolyNormal(): cmds.polyNormal(normalMode=4)
def ImportToMaya(vertexArray, polygonConnects, uvArray, texturePath, texture): global g_Mesh_Index printMessage("Creating mesh...") polygonCounts = OpenMaya.MIntArray(polygonConnects.length() / 3, 3) mesh = OpenMaya.MFnMesh() transform = mesh.create( vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects ) printDebug("connects cnt {}".format(polygonConnects.length())) printDebug("cnt {}".format(polygonCounts.length())) printDebug("u cnt {}".format(uvArray[0].length())) printDebug("v cnt {}".format(uvArray[1].length())) # UV map. printMessage("Mapping UVs...") mesh.setUVs(uvArray[0], uvArray[1]) try: mesh.assignUVs(polygonCounts, polygonConnects) except RuntimeError: printDebug("mesh.assignUVs() failed. Assign manually...") for i in range(0, polygonConnects.length()): try: mesh.assignUV(i / 3, i % 3, polygonConnects[i]) except RuntimeError: printMessage("AssignUV failed: " + "[{}] = {}".format(i, polygonConnects[i])) # Rename mesh. printMessage("Renaming mesh...") transformDagPath = OpenMaya.MDagPath() OpenMaya.MDagPath.getAPathTo(transform, transformDagPath) meshName = cmds.rename( transformDagPath.fullPathName(), "NinjaMesh_{}".format(g_Mesh_Index) ) g_Mesh_Index = g_Mesh_Index + 1 # Apply textures. printMessage("Applying textures...") shader = cmds.shadingNode( "lambert", name="NinjaTexture_{}".format(g_Mesh_Index), asShader=True ) cmds.select(meshName) cmds.hyperShade(assign=shader) colorMap = cmds.shadingNode( "file", name="{}_colorMap".format(texture), asTexture=True ) cmds.connectAttr( "{}.outColor".format(colorMap), "{}.color".format(shader) ) cmds.setAttr( "{}.fileTextureName".format(colorMap), "{}/{}".format(texturePath, texture), type='string' ) # Set vertex color to White. printMessage("Forcing vertex color to white...") cmds.select(meshName) cmds.polyColorPerVertex(cdo=True, rgb=[1, 1, 1]) # Apply transformations. printMessage("Applying transformations...") cmds.setAttr("{}.rotateX".format(meshName), g_ninjarotX) cmds.setAttr("{}.rotateY".format(meshName), g_ninjarotY) cmds.setAttr("{}.rotateZ".format(meshName), g_ninjarotZ) cmds.setAttr("{}.scaleX".format(meshName), mdlscaler) cmds.setAttr("{}.scaleY".format(meshName), mdlscaler) cmds.setAttr("{}.scaleZ".format(meshName), mdlscaler) # Freeze transformations. printMessage("Zeroing new transform values...") cmds.makeIdentity(apply=True, t=1, r=1, s=1, n=0, pn=1) # Scale UVs. printMessage("Scaling UVs...") uvs = cmds.polyListComponentConversion(meshName, tuv=True) cmds.select(uvs) cmds.polyEditUV(su=uvscaler, sv=uvscaler*g_flipUV) # Normalize UV. if g_normalizeUV: printMessage("Normalizing UVs...") cmds.polyNormalizeUV(nt=1, pa=True, centerOnTile=True) # Merge duplicates. printMessage("Removing duplicate vertex...") cmds.select(cl=True) cmds.select(meshName) cmds.polyMergeVertex(d=0.01, am=True, ch=1) cmds.polyMergeUV(d=0.01, ch=True) # Reverse normals (First met in MWR) if g_reverseNormals: printMessage("Reversing normals...") cmds.select(cl=True) cmds.select(meshName) cmds.polyNormal(meshName, ch=1) cmds.select(cl=True) print("Import done for mesh '{}'".format(meshName))
def reverseNormals(*args): cmds.polyNormal(nm=3) print'Reversing Normal(s)'