def pointInMesh(obj, point=(0.0, 0.0, 0.0), direction=(0.0, 0.0, 1.0)): obj_dag_path = OpenMaya.MDagPath.getAPathTo( pymel.core.PyNode(obj).__apimobject__()) obj_mfn_node = OpenMaya.MFnMesh(obj_dag_path) api_point = OpenMaya.MFloatPoint(*point) api_direction = OpenMaya.MFloatVector(*direction) farray = OpenMaya.MFloatPointArray() obj_mfn_node.allIntersections( api_point, api_direction, None, None, False, OpenMaya.MSpace.kWorld, 10000, False, None, # replace none with a mesh look up accelerator if needed False, farray, None, None, None, None, None) return farray.length() % 2 == 1
def buildRestABC(self, abcMesh, js): meshSchema = abcMesh.getSchema() rawFaces = meshSchema.getFaceIndicesProperty().samples[0] rawCounts = meshSchema.getFaceCountsProperty().samples[0] rawPos = meshSchema.getPositionsProperty().samples[0] name = js["systemName"] numVerts = len(rawPos) numFaces = len(rawCounts) counts = om.MIntArray() faces = om.MIntArray() ptr = 0 for i in rawCounts: counts.append(i) for j in reversed(rawFaces[ptr:ptr + i]): faces.append(j) ptr += i vertexArray = om.MFloatPointArray() for j in xrange(numVerts): fp = om.MFloatPoint(rawPos[j][0], rawPos[j][1], rawPos[j][2]) vertexArray.append(fp) meshFn = om.MFnMesh() meshMObj = meshFn.create(numVerts, numFaces, vertexArray, counts, faces) cName = "{0}_SIMPLEX".format(name) om.MFnDependencyNode(meshMObj).setName(cName) cmds.sets(cName, e=True, forceElement="initialShadingGroup") return cName
def getIntersection(self, point_in_3d, vector_in_3d, fnMesh): """ Return a point Position of intersection.. Args: point_in_3d (OpenMaya.MPoint) vector_in_3d (OpenMaya.MVector) Returns: OpenMaya.MFloatPoint : hitPoint """ hitPoint = OpenMaya.MFloatPoint() hitFacePtr = self.UTIL.asIntPtr() idSorted = False testBothDirections = True faceIDs = None triIDs = None accelParam = None hitRayParam = None hitTriangle = None hitBary1 = None hitBary2 = None maxParamPtr = 99999 result = fnMesh.closestIntersection( OpenMaya.MFloatPoint( point_in_3d.x, point_in_3d.y, point_in_3d.z), OpenMaya.MFloatVector(vector_in_3d), faceIDs, triIDs, idSorted, OpenMaya.MSpace.kWorld, maxParamPtr, testBothDirections, accelParam, hitPoint, hitRayParam, hitFacePtr, hitTriangle, hitBary1, hitBary2) if result is True: return hitPoint else: return None
def transfer_along_normal(matrix_values, space): replaced = pm.PyNode(pm.ls(sl=1)[0]).__apimdagpath__() to_replace = pm.PyNode(pm.ls(sl=1)[1]).__apimdagpath__() replaced_mesh = om.MFnMesh(replaced) to_replace_mesh = om.MFnMesh(to_replace) to_iter_polygon = om.MItMeshPolygon(to_replace) count = 0 ptr = om.MScriptUtil() normal = om.MVector() normal_list = om.MVectorArray() face_list = om.MIntArray() face_list.setLength(to_replace_mesh.numFaceVertices()) vertex_list = om.MIntArray() vertex_list.setLength(to_replace_mesh.numFaceVertices()) matrix = om.MMatrix() om.MScriptUtil().createMatrixFromList(matrix_values, matrix) hit_face = ptr.asIntPtr() while not to_iter_polygon.isDone(): to_center_point = to_iter_polygon.center(space) to_iter_polygon.getNormal(normal, space) hit = replaced_mesh.closestIntersection(om.MFloatPoint(to_center_point), om.MFloatVector(normal), None, None, None, space, 999, True, None, om.MFloatPoint(), None, hit_face, None, None, None) if hit: replaced_mesh.getPolygonNormal(ptr.getInt(hit_face), normal, space) normal = normal * matrix vertices = om.MIntArray() to_iter_polygon.getVertices(vertices) for vertex_id in range(to_iter_polygon.polygonVertexCount()): face_list[count] = to_iter_polygon.index() vertex_list[count] = vertices[vertex_id] normal_list.append(normal) count += 1 to_iter_polygon.next() face_list.setLength(count) vertex_list.setLength(count) normal_list.setLength(count) to_replace_mesh.setFaceVertexNormals(normal_list, face_list, vertex_list, space)
def createShape_mesh(numVertices, numFaces, faceCounts, faceConnects, points, hardEdges, name=None, parent=None): """ Creates a mesh from the given parameters. These inputs are usually generated from the print_createShape_mesh function. """ if not parent: parentMObject = OpenMaya.MObject() else: if not ka_pymel.isPyTransform(parent): parent = pymel.PyNode(parent) parentMObject = parent.__apimobject__() if not name and parent: name = parent.nodeName() + 'Shape' faceCounts_MintArray = OpenMaya.MIntArray() for i in faceCounts: faceCounts_MintArray.append(i) faceConnects_MIntArray = OpenMaya.MIntArray() for i in faceConnects: faceConnects_MIntArray.append(i) points_MFloatPointArray = OpenMaya.MFloatPointArray() for point in points: points_MFloatPointArray.append(OpenMaya.MFloatPoint(*point)) meshFS = OpenMaya.MFnMesh() newMesh = meshFS.create(numVertices, numFaces, points_MFloatPointArray, faceCounts_MintArray, faceConnects_MIntArray, parentMObject) #for edge in hardEdges: #meshFS.setEdgeSmoothing(edge, False) meshFS.updateSurface() if name: mesh = cmds.rename(meshFS.name(), name) else: mesh = meshFS.name() hardEdgesStrings = [] for edge in hardEdges: hardEdgesStrings.append('%s.e[%s]' % (mesh, str(edge))) cmds.sets(mesh, e=True, fe='initialShadingGroup') cmds.polySoftEdge(*hardEdgesStrings, ch=0, a=0) return pymel.PyNode(mesh)
def getIntersect(vpX, vpY): pos = om.MPoint() intersect = om.MVector() omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, intersect) # 射线 stPos = om.MFloatPoint(pos) intersect = om.MFloatVector(intersect) return stPos, intersect
def createHalfRope( pointsCount = 5, radius = 1 ): """create 180 degrees circle, and multiple points by radius""" points = om.MFloatPointArray() baseVector = om.MPoint( 1,0,0 ) * radius points.append( om.MFloatPoint( baseVector.x, baseVector.y, baseVector.z, 1.0 ) ) for d in range( 1, pointsCount ): if d == 1: #add an extra point to make the rope more marked baseAngle = om.MAngle(( 180.0 / ( pointsCount ) * 0.25 ), om.MAngle.kDegrees) vVector = om.MVector( baseVector ).rotateBy( om.MVector.kYaxis, baseAngle.asRadians() ) points.append( om.MFloatPoint( vVector.x, vVector.y, vVector.z, 1.0 ) ) baseAngle = om.MAngle(( 180.0 / ( pointsCount ) * d ), om.MAngle.kDegrees) vVector = om.MVector( baseVector ).rotateBy( om.MVector.kYaxis, baseAngle.asRadians() ) points.append( om.MFloatPoint( vVector.x, vVector.y, vVector.z, 1.0 ) ) if d == pointsCount - 1: baseAngle = om.MAngle(( 180.0 / ( pointsCount ) * (d + 0.75) ), om.MAngle.kDegrees) vVector = om.MVector( baseVector ).rotateBy( om.MVector.kYaxis, baseAngle.asRadians() ) points.append( om.MFloatPoint( vVector.x, vVector.y, vVector.z, 1.0 ) ) return points
def onPress(self, *args): self.Context = 'Context' vpX, vpY, _ = cmds.draggerContext(self.Context, query=True, anchorPoint=True) pos = om.MPoint() dir = om.MVector() hitpoint = om.MFloatPoint() omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir) pos2 = om.MFloatPoint(pos.x, pos.y, pos.z) for mesh in cmds.ls(type='mesh'): selectionList = om.MSelectionList() selectionList.add(mesh) dagPath = om.MDagPath() selectionList.getDagPath(0, dagPath) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection(om.MFloatPoint(pos2), om.MFloatVector(dir), None, None, False, om.MSpace.kWorld, 99999, False, None, hitpoint, None, None, None, None, None) if intersection: picked = (fnMesh.name()) print picked connections = cmds.listConnections(picked, s=False, d=True, t="shadingEngine") result = list() for connection in connections: shaders = cmds.listConnections(connection + ".surfaceShader", s=True, d=False) for shader in shaders: result.append(shader) cmds.select(result) cmds.HypershadeWindow() mel.eval( 'hyperShadePanelGraphCommand("hyperShadePanel1", "showUpAndDownstream");' )
def __init__(self): self.meshIntersector = OpenMaya.MMeshIntersector() self.faceIterator = None self.meshPoint = OpenMaya.MPointOnMesh() self.closestPnt = OpenMaya.MFloatPoint() self.weightUtils = BarycentricCoordinates()
def get_raycast_translation_from_mouse_click(mesh, mpx, mpy): """get the raycasted translation of the mouse position Args: mesh (str): mesh name mpx (int): mouse position x mpy (int): mouse position x Returns: list: XYZ position """ pos = om.MPoint() dir = om.MVector() hitpoint = om.MFloatPoint() omui.M3dView().active3dView().viewToWorld(int(mpx), int(mpy), pos, dir) pos2 = om.MFloatPoint(pos.x, pos.y, pos.z) selectionList = om.MSelectionList() selectionList.add(mesh) dagPath = om.MDagPath() selectionList.getDagPath(0, dagPath) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection( om.MFloatPoint(pos2), om.MFloatVector(dir), None, None, False, om.MSpace.kWorld, 99999, False, None, hitpoint, None, None, None, None, None) if intersection: x = hitpoint.x y = hitpoint.y z = hitpoint.z return [x, y, z]
def __init__(self, *args): if len(args) == 1: self.position = args[0] else: self.position = [args[0], args[1], args[2]] self.x = self.position[0] self.y = self.position[1] self.z = self.position[2] self.MPoint = om.MPoint(self.x, self.y, self.z) self.MFloatPoint = om.MFloatPoint(self.x, self.y, self.z)
def searchArea(startPoint, endPoint, step, rayDirection, voxelCenterPositions): for point_Zcoord in floatRange(startPoint.z, endPoint.z, step): for point_Xcoord in floatRange(startPoint.x, endPoint.x, step): for point_Ycoord in floatRange(startPoint.y, endPoint.y, step): #create ray source and direction raySource = OpenMaya.MFloatPoint( point_Xcoord, point_Ycoord, point_Zcoord) #rayDirection = OpenMaya.MFloatVector(0,0,-1) hitPointArray = OpenMaya.MFloatPointArray() hitRayParams = OpenMaya.MFloatArray() tolerance = 1e-6 mMeshObj.allIntersections( raySource, #raySource rayDirection, #rayDirection None, #faceIds do not need to filter the face None, #triDis do not need to filter the tris False, # do not need to sort the IDs OpenMaya.MSpace. kTransform, #ray source and direction are specified in the mesh local coordinates float(9999), #the range of the ray False, #do not need to test both directions None, #do not need accelParams False, #do not need to sort hits hitPointArray, #return the hit point array hitRayParams, #return hit point distance params None, #do not need hit faces ids None, #do not need hit tris ids None, #do not need barycentric coordinates of faces None, #do not need barycentric coordinates of tris tolerance #hit tolerance ) #add the inside raysouce into list for voxel placement if (hitPointArray.length() % 2 == 1): voxelCenterPositions.append(raySource) #also need to query the intersection geometry color #find nearest intersection point #http://www.chadvernon.com/blog/resources/maya-api-programming/mscriptutil/ #Since the Maya API is designed as a C++ library, it has many pointers and references #that are passed into and returned from various functions. uvPoint = util.asFloat2Ptr() mPoint = OpenMaya.MPoint(raySource) mMeshObj.getUVAtPoint(mPoint, uvPoint) if self.skinCluster: pointWeight = self.getClosetPointWeight(mPoint) pointBlendWeight = self.getClosetPointBlendWeight( mPoint) voxelWeights.append(pointWeight) voxelBlendWeights.append(pointBlendWeight) u = util.getFloat2ArrayItem(uvPoint, 0, 0) v = util.getFloat2ArrayItem(uvPoint, 0, 1) uv = [u, v] uvArray.append(uv)
def getHitPoint(self): vpX, vpY, _ = cmds.draggerContext(self.name, query=True, anchorPoint=True) pos = om.MPoint() dir = om.MVector() hitPoint = om.MFloatPoint() hitFace = om.MScriptUtil().asIntPtr() omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir) pos2 = om.MFloatPoint(pos.x, pos.y, pos.z) selectionList = om.MSelectionList() selectionList.add(self.mesh) dagPath = om.MDagPath() selectionList.getDagPath(0, dagPath) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection( om.MFloatPoint(pos2), # raySource om.MFloatVector(dir), # rayDirection None, # faceIds None, # triIds False, # idsSorted om.MSpace.kWorld, # space 99999, # maxParam False, # testBothDirections None, # accelParams hitPoint, # hitPoint None, # hitRayParam hitFace, # hitFace None, # hitTriangle None, # hitBary1 None) # hitBary2 if intersection: return ( hitPoint, om.MScriptUtil(hitFace).asInt() # get face number from pointer ) else: return ()
def intersect(self, dag, pos, dir, farclip): # mesh object targetDAGPath = self.getDAGObject(dag) meshObj = om.MFnMesh(targetDAGPath) # position FP posFP = om.MFloatPoint(pos[0],pos[1],pos[2]) # dir FP dirFP = om.MFloatVector(dir[0],dir[1],dir[2]) # empty objects hitFPoint = om.MFloatPoint() # intersection hitFace = om.MScriptUtil() hitTri = om.MScriptUtil() hitFace.createFromInt(0) hitTri.createFromInt(0) hFacePtr = hitFace.asIntPtr() hTriPtr = hitTri.asIntPtr() hit = meshObj.closestIntersection( posFP, dirFP, None, None, True, om.MSpace.kWorld, farclip, True, None, hitFPoint, None, hFacePtr, hTriPtr, None, None) return hit, hitFPoint, meshObj, hitFace.getInt(hFacePtr), hitTri.getInt(hTriPtr)
def intersectFace(mesh, source, direction, testBothDirections=False, maxDist=9999): ''' Return the intersected face ID on a specified mesh given a source point and direction @param mesh: Polygon mesh to perform intersection on @type mesh: str @param source: Source point for the intersection ray @type source: list or tuple or str @param direction: Direction of the intersection ray intersection @type direction: list or tuple @param testBothDirections: Test both directions for intersection @type testBothDirections: bool ''' # Get meshFn meshFn = getMeshFn(mesh) # Get source point sourcePt = OpenMaya.MFloatPoint(source[0], source[1], source[2]) # Get direction vector directionVec = OpenMaya.MFloatVector(direction[0], direction[1], direction[2]) # Create hit face utils hitFaceUtil = OpenMaya.MScriptUtil() hitFaceUtil.createFromInt(0) hitFacePtr = hitDistUtil.asIntPtr() # Calculate intersection hitPt = OpenMaya.MFloatPoint() meshFn.closestIntersection(sourcePt, directionVec, None, None, False, OpenMaya.MSpace.kWorld, maxDist, testBothDirections, None, None, None, hitFacePtr, None, None, None, 0.0001) # Return intersection hit point return OpenMaya.MScriptUtil(hitFacePtr).asInt()
def do_plant(self, pressPosition): view = omUI.M3dView.active3dView() worldPt = om.MPoint() worldVector = om.MVector() view.viewToWorld(int(pressPosition[0]), int(pressPosition[1]), worldPt, worldVector) mSel = om.MSelectionList() mSel.add(self.lineEdit_2.text()) mDagPath = om.MDagPath() mSel.getDagPath(0, mDagPath) fnMesh = om.MFnMesh(mDagPath) farclip = 1.0 clickPos = om.MFloatPoint(worldPt.x, worldPt.y, worldPt.z) mCamPath = om.MDagPath() view.getCamera(mCamPath) cam_name = mCamPath.fullPathName() ratio_scale = mc.getAttr(cam_name + '.farClipPlane') clickDir = om.MFloatVector(worldVector.x * ratio_scale, worldVector.y * ratio_scale, worldVector.z * ratio_scale) currentHitFP = om.MFloatPoint() hit = fnMesh.closestIntersection(clickPos, clickDir, None, None, True, om.MSpace.kWorld, farclip, True, None, currentHitFP, None, None, None, None, None) if hit: tree_name = self.treeListWidget.currentItem().text() current_namespace = tree_name.split(':')[1].split('_')[1] dup_tree = mc.duplicate(tree_name) mc.move(currentHitFP.x, currentHitFP.y, currentHitFP.z, tree_name) new_namespace = self.get_namespace(current_namespace) mc.namespace(add=new_namespace) for i in dup_tree: mc.rename(i, "%s:%s" % (new_namespace, i))
def createRopesRings( ropesCount, bMatrix, points, pointsCount = 5, ropeStrength = 1 ): """creates ropes base, create half rope and move them to the final position""" angle = om.MAngle(( 180.0 / ropesCount ), om.MAngle.kDegrees) distanceToMoveRope = math.cos(om.MAngle(( 180.0 / ropesCount ), om.MAngle.kDegrees).asRadians() ) singleRopeRadius = math.sin( angle.asRadians() ) for d in range( 1, ropesCount + 1 ): ropePoints = createHalfRope( pointsCount, singleRopeRadius ) for ropP in range( ropePoints.length() ): ropP = ropePoints[ ropP ] ropP = om.MVector( ropP.x, ropP.y, ropP.z * ropeStrength ) + om.MVector( 0,0,-1 ) * distanceToMoveRope ropV = om.MVector( ropP ).rotateBy( om.MVector.kYaxis, om.MAngle(( 360.0 / ropesCount * d ), om.MAngle.kDegrees).asRadians() ) ropV = om.MPoint( ropV ) * bMatrix # move vector to final position points.append( om.MFloatPoint( ropV.x, ropV.y, ropV.z, 1.0 ) ) return points
def returnClosestUVToPos(mesh, pos): """ Return the closest point on a mesh to a point in space Arguments mesh(string) -- currently poly surface only pos(double3) -- point in world space returns(double2) -- uv coordinate on mesh """ buffer = [] for p in pos: buffer.append(returnWorldSpaceFromMayaSpace(p)) pos = buffer #Create an empty selection list. selectionList = om.MSelectionList() #Put the mesh's name on the selection list. selectionList.add(mesh) #Create an empty MDagPath object. meshPath = om.MDagPath() #Get the first item on the selection list (which will be our mesh) #as an MDagPath. selectionList.getDagPath(0, meshPath) #Create an MFnMesh functionset to operate on the node pointed to by #the dag path. meshFn = om.MFnMesh(meshPath) #Thank you Mattias Bergbom, http://bergbom.blogspot.com/2009/01/float2-and-float3-in-maya-python-api.html floatPoint = om.MFloatPoint(pos[0], pos[1], pos[2]) refPoint = om.MPoint(floatPoint) # Thank you Capper on Tech-artists.org pArray = [0.0,0.0] x1 = om.MScriptUtil() x1.createFromList( pArray, 2 ) uvPoint = x1.asFloat2Ptr() uvSet = None closestPolygon=None uvReturn = meshFn.getUVAtPoint(refPoint,uvPoint,om.MSpace.kWorld) uValue = om.MScriptUtil.getFloat2ArrayItem(uvPoint, 0, 0) or False vValue = om.MScriptUtil.getFloat2ArrayItem(uvPoint, 0, 1) or False if uValue and vValue: return [uValue,vValue] return False
def applyTopologyAdd(inPoints, fixeIndexes, envelope, attractForce, repulseForce, globalIter, topologyNeighbourIndexes, topologyNeighbourBaseLenghts): tnIs = topologyNeighbourIndexes tnLs = topologyNeighbourBaseLenghts if (envelope == 0): return inPoints outPoints = inPoints[:] for e in range(0, globalIter): tmpPoints = outPoints[:] for i in range(0, len(outPoints)): if (i in fixeIndexes): continue for tnI, tnL in zip(tnIs[i], tnLs[i]): #COMPUTE FORCES vAttract = getAttractForce(outPoints[i], outPoints[tnI], triggerDist=tnL, power=attractForce, globalIter=globalIter, repulsion=0) vRepulse = getAttractForce(outPoints[i], outPoints[tnI], triggerDist=tnL, power=repulseForce, globalIter=globalIter, repulsion=1) #APPLY FORCES print( vAttract.x, vAttract.y, vAttract.z, ) tmpPoints[i] = tmpPoints[i] + vAttract + vRepulse outPoints = tmpPoints[:] for i in range(0, len(outPoints)): xTmp = outPoints[i].x * envelope + inPoints[i].x * (1 - envelope) yTmp = outPoints[i].y * envelope + inPoints[i].y * (1 - envelope) zTmp = outPoints[i].z * envelope + inPoints[i].z * (1 - envelope) outPoints[i] = om.MFloatPoint(xTmp, yTmp, zTmp) return outPoints
def findClosest(source, targetList): """ Returns the target in targetList which is closest to the source (looks at the rotate pivot pos) :param source str: source transform :param targetList list: list of targets to test :return: target closest to source :rtype: str """ closestDistance = 10e10 closestTarget = None p = cmds.xform(source, q=True, rp=True, ws=True, a=True) source_mPoint = om.MPoint(p[0], p[1], p[2]) source_mFloatPoint = om.MFloatPoint(source_mPoint.x, source_mPoint.y, source_mPoint.z) for target in targetList: p = cmds.xform(target, q=True, rp=True, ws=True, a=True) target_mPoint = om.MPoint(p[0], p[1], p[2]) target_mFloatPoint = om.MFloatPoint(target_mPoint.x, target_mPoint.y, target_mPoint.z) d = target_mFloatPoint.distanceTo(source_mFloatPoint) if d < closestDistance: closestDistance = d closestTarget = target return closestTarget
def getPoints(inMesh, sourcePoint, direction, maxParam=99999): hitPoint = om.MFloatPoint() selectionList = om.MSelectionList() selectionList.add(inMesh) dagPath = om.MDagPath() selectionList.getDagPath(0, dagPath) fnMesh = om.MFnMesh(dagPath) intersection = fnMesh.closestIntersection(sourcePoint, direction, None, None, False, om.MSpace.kWorld, maxParam, False, None, hitPoint, None, None, None, None, None) if intersection: return hitPoint else: return None
def create(verts, faces, merge=True): ''' Given a list of vertices (iterables of floats) and a list of faces (iterable of integer vert indices), creates and returns a maya Mesh ''' cmds.select(cl=True) outputMesh = OpenMaya.MObject() numFaces = len(faces) numVertices = len(verts) # point array of plane vertex local positions points = OpenMaya.MFloatPointArray() for eachVt in verts: p = OpenMaya.MFloatPoint(eachVt[0], eachVt[1], eachVt[2]) points.append(p) # vertex connections per poly face in one array of indexs into point array given above faceConnects = OpenMaya.MIntArray() for eachFace in faces: for eachCorner in eachFace: faceConnects.append(int(eachCorner)) # an array to hold the total number of vertices that each face has faceCounts = OpenMaya.MIntArray() for c in range(0, numFaces, 1): faceCounts.append(int(4)) # create mesh object using arrays above and get name of new mesh meshFN = OpenMaya.MFnMesh() """ print numVertices,numFaces print points print faceCounts print faceConnects """ newMesh = meshFN.create(numVertices, numFaces, points, faceCounts, faceConnects, outputMesh) nodeName = meshFN.name() cmds.sets(nodeName, add='initialShadingGroup') cmds.select(nodeName) meshFN.updateSurface() # this is useful because it deletes stray vertices (ie, those not used in any faces) if merge: cmds.polyMergeVertex(nodeName, ch=0) meshFN.updateSurface() return nodeName
def find_intersect_vertex(obj_A, obj_b): ''' ''' src_pml_node = pymel.core.PyNode(obj_A) dst_pml_node = pymel.core.PyNode(obj_b) src_dag_path = src_pml_node.__apiobject__() dst_dag_path = dst_pml_node.__apiobject__() src_mfn_node = OpenMaya.MFnMesh(src_dag_path) iterator = OpenMaya.MItGeometry(dst_dag_path) comp_list = list() closest_point = OpenMaya.MPoint() farray = OpenMaya.MFloatPointArray() point = OpenMaya.MFloatPoint() for i in xrange(iterator.count()): current_point = iterator.position(OpenMaya.MSpace.kWorld) src_mfn_node.getClosestPoint(current_point, closest_point, OpenMaya.MSpace.kWorld) point.setCast(current_point) vector = OpenMaya.MFloatVector(closest_point) farray.clear() src_mfn_node.allIntersections(point, vector, None, None, False, OpenMaya.MSpace.kWorld, 10000, False, None, False, farray, None, None, None, None, None) if farray.length() % 2 == 1: comp_list.append(iterator.index()) iterator.next() api_util = OpenMaya.MScriptUtil() api_util.createFromList(comp_list, len(comp_list)) int_ptr = api_util.asIntPtr() id_array = OpenMaya.MIntArray(int_ptr, len(comp_list)) single_components = OpenMaya.MFnSingleIndexedComponent() vertex_components = single_components.create( OpenMaya.MFn.kMeshVertComponent) single_components.addElements(id_array) mSelectionList = OpenMaya.MSelectionList() mSelectionList.add(dst_dag_path, vertex_components) OpenMaya.MGlobal.setActiveSelectionList(mSelectionList)
def returnCollisionPoints(point, dir, fnMesh): ''' Get collision information from a raycast onto a mesh - point: origin point in space of the ray - dir: direction of the ray - fnMesh: mesh used for the collision testing ''' point = om.MFloatPoint(*point) hitPoints = om.MFloatPointArray() hitFaces = om.MIntArray() fnMesh.allIntersections(point, dir, None, None, False, om.MSpace.kWorld, 10000, False, fnMesh.autoUniformGridParams(), False, hitPoints, None, hitFaces, None, None, None) return hitPoints, hitFaces
def rayIntersect(mesh, point, direction): hitPoints = None try: cmds.select(cl=True) om.MGlobal.selectByName(mesh) sList = om.MSelectionList() om.MGlobal.getActiveSelectionList(sList) item = om.MDagPath() sList.getDagPath(0, item) item.extendToShape() fnMesh = om.MFnMesh(item) raySource = om.MFloatPoint(point[0], point[1], point[2], 1.0) rayDir = om.MFloatVector(direction[0], direction[1], direction[2]) faceIds = None triIds = None idsSorted = False testBothDirections = False worldSpace = om.MSpace.kWorld maxParam = 999999 accelParams = None sortHits = True hitPoints = om.MFloatPointArray() hitRayParams = om.MFloatArray() hitFaces = om.MIntArray() hitTris = None hitBarys1 = None hitBarys2 = None tolerance = 0.0001 hit = fnMesh.allIntersections(raySource, rayDir, faceIds, triIds, idsSorted, worldSpace, maxParam, testBothDirections, accelParams, sortHits, hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2, tolerance) om.MGlobal.clearSelectionList() except: cmds.warning('Ray Intersection exception: ' + mesh) return hitPoints
def rayIntersect(mesh, point, direction): #posted on cgtalk.com om.MGlobal.clearSelectionList() om.MGlobal.selectByName(mesh) sList = om.MSelectionList() #Assign current selection to the selection list object om.MGlobal.getActiveSelectionList(sList) item = om.MDagPath() sList.getDagPath(0, item) item.extendToShape() fnMesh = om.MFnMesh(item) raySource = om.MFloatPoint(point[0], point[1], point[2], 1.0) rayDir = om.MFloatVector(direction[0], direction[1], direction[2]) faceIds = None triIds = None idsSorted = False testBothDirections = False worldSpace = om.MSpace.kWorld maxParam = 999999 accelParams = None sortHits = True hitPoints = om.MFloatPointArray() #hitRayParams = om.MScriptUtil().asFloatPtr() hitRayParams = om.MFloatArray() hitFaces = om.MIntArray() hitTris = None hitBarys1 = None hitBarys2 = None tolerance = 0.0001 hit = fnMesh.allIntersections(raySource, rayDir, faceIds, triIds, idsSorted, worldSpace, maxParam, testBothDirections, accelParams, sortHits, hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2, tolerance) result = int(fmod(len(hitFaces), 2)) #clear selection as may cause problem if the function is called multiple times in succession om.MGlobal.clearSelectionList() return result
def RayIntersect(point, direction): sList = OpenMaya.MSelectionList() nodes = cmds.ls(tr=True) meshes = [] for node in nodes: shapes = cmds.listRelatives(node, shapes=True, typ="mesh") if shapes: meshes.append(node) sList.add(node) selIt = OpenMaya.MItSelectionList(sList) result = [] while not selIt.isDone(): item = OpenMaya.MDagPath() selIt.getDagPath(item) item.extendToShape() fnMesh = OpenMaya.MFnMesh(item) raySource = OpenMaya.MFloatPoint(point[0], point[1], point[2], 1.0) rayDir = OpenMaya.MFloatVector(direction[0], direction[1], direction[2]) faceIds = None triIds = None idsSorted = False testBothDirections = True worldSpace = OpenMaya.MSpace.kWorld maxParam = 999 accelParams = None sortHits = True hitPoints = OpenMaya.MFloatPointArray() hitRayParams = OpenMaya.MFloatArray() hitFaces = OpenMaya.MIntArray() hitTris = None hitBarys1 = None hitBarys2 = None tolerance = 0.0001 fnMesh.allIntersections(raySource, rayDir, faceIds, triIds, idsSorted, worldSpace, maxParam, testBothDirections, accelParams, sortHits, hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2, tolerance) try: result.append([hitPoints[0].x, hitPoints[0].y, hitPoints[0].z]) except: print('None') selIt.next() return result
def intersectTargetSurface(targetdag, clickPos, clickDir, farclip=1.0): ''' intersect a single object from the click world pos and direction. optional farclip distance return an intersectionPoint object if there was any intersection return None otherwise ''' currentHitFP = om.MFloatPoint() #current intersection hitFace = om.MScriptUtil() hitTri = om.MScriptUtil() hitFace.createFromInt(0) hitTri.createFromInt(0) hitFaceptr = hitFace.asIntPtr() hitTriptr = hitTri.asIntPtr() targetDAGPath = getDAGObject(targetdag) if (targetDAGPath): #returned targetDAGPath is sort of valid fnMesh = om.MFnMesh( targetDAGPath ) hit = fnMesh.closestIntersection( clickPos.asMFPoint(), clickDir.asMFVector(), None, None, True, om.MSpace.kWorld, farclip, True, None, currentHitFP, None, hitFaceptr, hitTriptr, None, None) if (hit): #there was a positive intersection if (sp3d_MFn): print ("Face Hit: %i || Tri Hit: %i" % (hitFace.getInt(hitFaceptr),hitTri.getInt(hitTriptr))) return intersectionPoint(point(currentHitFP.x, currentHitFP.y, currentHitFP.z), hitFace.getInt(hitFaceptr), hitTri.getInt(hitTriptr), targetDAGPath); #reaches here only if no intersection or not a valid targetDAGPath return None
def rayIntersect(mesh, point, direction): # Calculate ray direction vector raySource = om.MFloatPoint(point[0], point[1], point[2], 1.0) rayDir = om.MFloatVector(direction[0], direction[1], direction[2]) rayDir = rayDir - om.MFloatVector(raySource) # Determine surface type since each intersection is dependant on type. surfaceType = cmd.ls(mesh, st=1)[-1] # Why are there different nurbs and polygon intersect functions? # One uses MPoint the other MFloatPoint. There is a REASON that # python is a DUCK TYPED language autodesk. surfaceData = None if surfaceType == 'nurbsSurface': surfaceData = getNurbsSurfaceData(mesh, raySource, rayDir, surfaceType) elif surfaceType == 'mesh': surfaceData = getPolygonSurfaceData(mesh, raySource, rayDir, surfaceType) return surfaceData
def rayIntersect(mesh, point, direction=(0.0, 0.0, -1.0)): # get dag path of mesh - so obnoxious om.MGlobal.clearSelectionList() om.MGlobal.selectByName(mesh) sList = om.MSelectionList() om.MGlobal.getActiveSelectionList(sList) item = om.MDagPath() sList.getDagPath(0, item) item.extendToShape() fnMesh = om.MFnMesh(item) raySource = om.MFloatPoint(point[0], point[1], point[2], 1.0) rayDir = om.MFloatVector(direction[0], direction[1], direction[2]) faceIds = None triIds = None idsSorted = False worldSpace = om.MSpace.kWorld maxParam = 99999999 testBothDirections = False accelParams = None sortHits = True hitPoints = om.MFloatPointArray() hitRayParams = om.MFloatArray() hitFaces = om.MIntArray() hitTris = None hitBarys1 = None hitBarys2 = None tolerance = 0.0001 hit = fnMesh.allIntersections(raySource, rayDir, faceIds, triIds, idsSorted, worldSpace, maxParam, testBothDirections, accelParams, sortHits, hitPoints, hitRayParams, hitFaces, hitTris, hitBarys1, hitBarys2, tolerance) # clear selection as may cause problems if called repeatedly om.MGlobal.clearSelectionList() result = [] faces = [] for x in range(hitPoints.length()): result.append((hitPoints[x][0], hitPoints[x][1], hitPoints[x][2])) for x in range(hitFaces.length()): faces.append(hitFaces[x]) result = [result, faces] return result