def compute(self, plug, dataBlock): if plug != MeshIntersectionNode.Loc_3_Pos: return om.kUnknownParameter locator1Vector = om.MVector(dataBlock.inputValue(MeshIntersectionNode.Loc_1_Pos).asFloatVector()) locator2Vector = om.MVector(dataBlock.inputValue(MeshIntersectionNode.Loc_2_Pos).asFloatVector()) inputMeshObj = dataBlock.inputValue(MeshIntersectionNode.inMesh).asMesh() direction = om.MFloatVector(locator2Vector - locator1Vector) sourcePoint = om.MFloatPoint(dataBlock.inputValue(MeshIntersectionNode.Loc_1_Pos).asFloatVector()) inputMeshMFn = om.MFnMesh(inputMeshObj) hitPoints = om.MFloatPoint() tolerance = float(0.0) inputMeshMFn.closestIntersection(sourcePoint, direction, None, None, False, om.MSpace.kWorld, 10000.0, False, None, hitPoints, None, None, None, None, None, tolerance) outputPoint = dataBlock.outputValue(MeshIntersectionNode.Loc_3_Pos) if hitPoints[0]: outputVector = om.MFloatVector(hitPoints.x, hitPoints.y, hitPoints.z) else: outputVector = om.MFloatVector(0.0, 0.0, 0.0) outputPoint.setMFloatVector(outputVector) dataBlock.setClean(plug)
def priv_doCut( _way, _loc1, _loc2, _object, _crack): # make sure it`s a positive value, a negative value will make pieces grow and overlap if _crack < 0: _crack = 0 _start = [] _end = [] if _way == 0: _start = mc.xform( _loc1, q=True, ws=True, t=True) _end = mc.xform( _loc2, q=True, ws=True, t=True ) else: _start = mc.xform( _loc2, q=True, ws=True, t=True ) _end = mc.xform( _loc1, q=True, ws=True, t=True ) _distFactor = 0.5 + _crack _dir = om.MFloatVector( (_end[0] - _start[0]), (_end[1] - _start[1]), (_end[2] - _start[2]) ) _planePos = om.MFloatVector( _start[0] + (_dir[0] * _distFactor), _start[1] + (_dir[1] * _distFactor), _start[2] + (_dir[2] * _distFactor) ) _dir = _dir.normal() _xrot = - mt.degrees(mt.asin( _dir.y )) _yrot = mt.degrees(mt.atan2( _dir.x, _dir.z )) mc.select( _object, r=True ) #mc.polyCut( constructionHistory=False, deleteFaces=True, cutPlaneCenter=( _planePos.x, _planePos.y, _planePos.z), cutPlaneRotate=( _xrot, _yrot, 0), cch=True ) mc.polyCut( constructionHistory=False, deleteFaces=True, cutPlaneCenter=( _planePos.x, _planePos.y, _planePos.z), cutPlaneRotate=( _xrot, _yrot, 0) ) mc.polyCloseBorder( constructionHistory=False )
def compute(self, plug, block): if plug == thindielectric.mOutColor: resultColor = OpenMaya.MFloatVector(0.0,0.0,0.0) outColorHandle = block.outputValue( thindielectric.mOutColor ) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() elif plug == thindielectric.mOutTransparency: outTransHandle = block.outputValue( thindielectric.mOutTransparency ) outTransHandle.setMFloatVector(OpenMaya.MFloatVector(0.75,0.75,0.75)) outTransHandle.setClean() else: return OpenMaya.kUnknownParameter
def compute(self, plug, dataBlock): print('compute') self.coords = utils.nodeAttrToMVectors(dataBlock, self.attrInCoords) self.thickness = utils.nodeAttrToFloat(dataBlock, self.attrInThickness) self.color = utils.nodeAttrToMVector(dataBlock, self.attrInColor) camMatrix = utils.nodeAttrToMatrixFloatList(dataBlock, self.attrInCamMatrix) #GET UNIT VECTOR self.camPos = om.MFloatVector(camMatrix[12], camMatrix[13], camMatrix[14]) self.v2X = om.MFloatVector(camMatrix[0], camMatrix[1], camMatrix[2]) self.v2Y = om.MFloatVector(camMatrix[4], camMatrix[5], camMatrix[6]) utils.floatToNodeAttr(dataBlock, self.attrOutTrig, 0.0)
def __cacheMeshTweaks(self): self._fTweakIndexArray.clear() self._fTweakVectorArray.clear() if self._fHasTweaks: meshNode = self._fDagPath.node() depNodeFn = om.MFnDependencyNode(meshNode) meshTweakPlug = depNodeFn.findPlug("pnts") tweakVector = om.MFloatVector() if not meshTweakPlug.isArray(): raise Exception( u"meshTweakPlug.isArray() -- meshTweakPlug is not an array plug" ) numElements = meshTweakPlug.numElements() for i in range(numElements): tweak = meshTweakPlug.elementByPhysicalIndex(i) if not tweak.isNull(): logicalIndex = tweak.logicalIndex() self._fTweakIndexArray.append(logicalIndex) getFloat3PlugValue(tweak, tweakVector) self._fTweakVectorArray.append(tweakVector)
def fixFaceShaderObject(items): for shapename in items(): templist = om.MSelectionList() om.MGlobal.getSelectionListByName(shapename, templist) shapedagpath = om.MDagPath() templist.getDagPath(0, shapedagpath) fnmesh = om.MFnMesh(shapedagpath) sgs = om.MObjectArray() faceinsg = om.MObjectArray() fnmesh.getConnectedSetsAndMembers(0, sgs, faceinsg, True) fn_firstsg = om.MFnDependencyNode(sgs[0]) firstsgname = fn_firstsg.name() fn_compent = om.MFnSingleIndexedComponent(faceinsg[0]) m_faceid = om.MIntArray() fn_compent.getElements(m_faceid) tempTrans = om.MFloatVector() fnmesh.extractFaces(m_faceid, tempTrans) fnmesh.updateSurface() try: shapes = mc.polySeparate(fnmesh.fullPathName(), ch=False) except RuntimeError: shapes = [] if filter(pmcfs.checkShaderMulti, shapes): for objname in filter(pmcfs.checkShaderMulti, shapes): fixFaceShaderObject(objname)
def find_intersection_other(self, mesh1, mesh2): mesh1_dagPath = mesh1.__apimdagpath__() # mesh的节点路径 mesh2_dagPath = mesh2.__apimdagpath__() mesh1_itr = OpenMaya.MItMeshEdge(mesh1_dagPath) # MItMeshEdge 多边形边迭代器 mesh2_mesh = OpenMaya.MFnMesh(mesh2_dagPath) util = OpenMaya.MScriptUtil() # MScriptUtil 实用程序类,用于在Python中使用指针和引用 edge_len_ptr = util.asDoublePtr() # asDoublePtr() 返回指向此类数据的双指针。 edge_list = set() while not mesh1_itr.isDone(): mesh1_itr.getLength(edge_len_ptr) # getLength()返回当前边的长度。 edge_len = util.getDouble(edge_len_ptr) # getDouble() 获取Double型参数的值 start_pt = mesh1_itr.point(0, OpenMaya.MSpace.kWorld) # point()返回当前边的指定顶点的位置。 end_pt = mesh1_itr.point(1, OpenMaya.MSpace.kWorld) # MSpace 空间转换标识符 # kWorld 对象世界坐标系的数据 raySource = OpenMaya.MFloatPoint(start_pt) # MFloatPoint 以浮点类型来实现处理点 rayDirection = OpenMaya.MFloatVector(end_pt - start_pt) # MFloatVector 浮点数向量的向量类 faceIds = None triIds = None idsSorted = False # 不排序 space = OpenMaya.MSpace.kWorld maxParam = edge_len # 边长度、搜索半径 testBothDirections = False # accelParams = mesh2_mesh.autoUniformGridParams() # autoUniformGridParams创建一个MMeshIsectAccelParams配置对象 sortHits = False hitPoints = OpenMaya.MFloatPointArray() # MFloatPoint数据类型的矩阵 hitRayParams = None hitFaces = OpenMaya.MIntArray() # int数据类型矩阵 hitTriangles = None hitBary1s = None hitBary2s = None rayDirection.normalize() # 单位化 gotHit = mesh2_mesh.allIntersections( raySource, rayDirection, faceIds, triIds, idsSorted, space, maxParam, testBothDirections, accelParams, sortHits, hitPoints, hitRayParams, hitFaces, hitTriangles, hitBary1s, hitBary2s) # allIntersections 查找从raySource开始并与mesh在rayDirection中传播的射线的所有交点。 # 如果faceIds和triIds均为NULL,则将考虑网格中的所有三角形面片。 # 返回值True、False if gotHit: edge_list.add(mesh1_itr.index()) # 把边的序号存入edge_list mesh1_itr.next() # 获取碰撞的边再通过边转面 edge_list = ["%s.e[%s]" % (mesh1_dagPath.fullPathName(), edge_id) for edge_id in edge_list] facelist = pm.polyListComponentConversion(edge_list, fe=True, tf=True) # polyListComponentConversion 将多边形组件从一种或多种类型转换为另一种或多种类型 # fromEdge(fe)toFace(tf) # 展平序号 return pm.ls(facelist, flatten=True)
def check_normal(objects): LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" logger = logging.getLogger("mylog") logger.setLevel(logging.ERROR) handle = logging.FileHandler('D:/mayaCheckNormal.log') formatter = logging.Formatter(LOG_FORMAT) handle.setFormatter(formatter) logger.addHandler(handle) if not objects: logger.error("{}:The scene lacks objects".format(mc.file(exn=1))) return for obj in objects: dag = pm.PyNode(obj).__apimdagpath__() it = OpenMaya.MItMeshPolygon(dag) temp = OpenMaya.MFnMesh(dag) ray_source = OpenMaya.MFloatPoint() hit_points = OpenMaya.MFloatPointArray() while not it.isDone(): center_point = it.center(OpenMaya.MSpace.kWorld) face_normal = OpenMaya.MVector() it.getNormal(face_normal, OpenMaya.MSpace.kWorld) d_normal = face_normal * 0.1 temp_point = center_point + d_normal ray_source.setCast(temp_point) b_intersection = temp.allIntersections( ray_source, OpenMaya.MFloatVector(face_normal), None, None, False, OpenMaya.MSpace.kWorld, 999, False, None, False, hit_points, None, None, None, None, None) if b_intersection and hit_points.length() % 2 != 0: logger.warning("%s.f[%d]" % (obj, it.index())) it.next()
def extract_point_on_surface_infos(self, inputStruct): cubePointVal = inputStruct[0] polyMfnMesh = inputStruct[1] #samplePos = [round( cubePointVal[0],5),round( cubePointVal[1],5),round( cubePointVal[2],5)] VectorFloat = OpenMaya.MFloatVector(cubePointVal[0], cubePointVal[1], cubePointVal[2]) #pointer for hitFace hitFaceParam = OpenMaya.MScriptUtil() hitFaceParam.createFromInt(0) hitFacePtr = hitFaceParam.asIntPtr() InFloatPoint = OpenMaya.MFloatPoint(0, 0, 0) hitPoint = OpenMaya.MFloatPoint() #Intersection parameter setup mmAccelParams = OpenMaya.MMeshIsectAccelParams() mmAccelParams = polyMfnMesh.autoUniformGridParams() testHit = polyMfnMesh.closestIntersection(InFloatPoint, VectorFloat, None, None, False, OpenMaya.MSpace.kObject, 4.0, False, mmAccelParams, hitPoint, None, hitFacePtr, None, None, None, 0.001) #Data packing and return if testHit == False: return None else: fceNm = OpenMaya.MScriptUtil(hitFacePtr).asInt() return [OpenMaya.MPoint(hitPoint), fceNm]
def __init__(self): #print('__init__') ommpx.MPxLocatorNode.__init__(self) self.vectors = [] self.vectorsSize = [] self.vectorsColor = [] self.vectorsName = [] self.triangles = [] self.trianglesSize = [] self.trianglesColor = [] self.squares = [] self.squaresSize = [] self.squaresColor = [] self.circles = [] self.circlesSize = [] self.circlesColor = [] self.camPos = [] self.v2X = [] self.v2Y = [] self.distProjInt = 1 self.distIncr = 0.01 self.motionTrailMaxMemory = 40 self.pointO = om.MFloatVector(0.0, 0.0, 0.0) self.StorePoints = DynamicStore( arrayFill=[self.pointO, self.pointO, self.pointO, self.pointO], maxIndex=self.motionTrailMaxMemory) self.motionTrailSizeLast = 0
def convertToPointOnProjPlane(pointO, point, v2X, v2Y, distance): vectorTmp = om.MFloatVector(point.x - pointO.x, point.y - pointO.y, point.z - pointO.z) vectorTmp.normalize() pointTmp = pointO + vectorTmp * distance planeCoords = [ pointTmp.x, pointTmp.y, pointTmp.z, pointTmp.x + v2X.x, pointTmp.y + v2X.y, pointTmp.z + v2X.z, pointTmp.x + v2Y.x, pointTmp.y + v2Y.y, pointTmp.z + v2Y.z ] lineCoords = [pointO.x, pointO.y, pointO.z, point.x, point.y, point.z] iPoint = utils_getLinePlaneIntersectionPoint(lineCoords, planeCoords) return om.MFloatVector(iPoint[0], iPoint[1], iPoint[2])
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 compute(self, plug, block): if plug == roughdielectric.mOutColor: print "out color" resultColor = OpenMaya.MFloatVector(0.0,0.0,0.0) color = block.inputValue( roughdielectric.mReflectance ).asFloatVector() outColorHandle = block.outputValue( roughdielectric.mOutColor ) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() elif plug == roughdielectric.mOutTransparency: outTransHandle = block.outputValue( roughdielectric.mOutTransparency ) outTransHandle.setMFloatVector(OpenMaya.MFloatVector(0.75,0.75,0.75)) outTransHandle.setClean() else: return OpenMaya.kUnknownParameter
def test_if_inside_mesh(point, obj): dir=(0.0, 0.0, 1.0) sel = om.MSelectionList() dag = om.MDagPath() #replace torus with arbitrary shape name sel.add(obj) sel.getDagPath(0,dag) mesh = om.MFnMesh(dag) point = om.MFloatPoint(*point) dir = om.MFloatVector(*dir) farray = om.MFloatPointArray() mesh.allIntersections( point, dir, None, None, False, om.MSpace.kWorld, 10000, False, None, False, farray, None, None, None, None, None ) return farray.length()%2 == 1
def meshHeight(name, x, z): # mesh object selectionList = om.MSelectionList() selectionList.add(name) nodeDagPath = om.MDagPath() selectionList.getDagPath(0, nodeDagPath) meshObj = om.MFnMesh(nodeDagPath) # position FP posFP = om.MFloatPoint(x, 1000, z) # dir FP dirFP = om.MFloatVector(0, -1, 0) # empty objects hitFPoint = om.MFloatPoint() # intersection hitFace = om.MScriptUtil() hitTri = om.MScriptUtil() hitFace.createFromInt(0) hitTri.createFromInt(0) hFacePtr = hitFace.asIntPtr() hTriPtr = hitTri.asIntPtr() farclip = 10000.0 hit = meshObj.closestIntersection(posFP, dirFP, None, None, True, om.MSpace.kWorld, farclip, True, None, hitFPoint, None, hFacePtr, hTriPtr, None, None) return hitFPoint[ 1] # ===========================================================================
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 = UTIL.asIntPtr() idSorted = False testBothDirections = False faceIDs = None triIDs = None accelParam = None hitRayParam = None hitTriangle = None hitBary1 = None hitBary2 = None maxParamPtr = 99999 # intersectPoint = OpenMaya.MFloatPoint( 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, self.SPACE, maxParamPtr, testBothDirections, accelParam, hitPoint, hitRayParam, hitFacePtr, hitTriangle, hitBary1, hitBary2) faceID = UTIL.getInt(hitFacePtr) if result is True: return hitPoint, faceID else: return None, None
def intersectAllFaces(mesh, source, direction, testBothDirections=False, maxDist=9999): ''' Return all intersected faces 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]) # Calculate intersection hitFaceArray = OpenMaya.MIntArray() meshFn.allIntersections(sourcePt, directionVec, None, None, False, OpenMaya.MSpace.kWorld, maxDist, testBothDirections, None, True, None, None, hitFaceArray, None, None, None, 0.0001) # Return intersection hit point return list(hitFaceArray)
def getIntersection(self): # Create mpoint variables pos = om.MPoint() # 3D point with double-precision coordinates dir = om.MVector() # 3D vector with double-precision coordinates vpX, vpY, _ = cmds.draggerContext(self.ctx, query=True, dragPoint=True) # This takes vpX and vpY as input and outputs position and direction # values for the active view. # - M3dView: provides methods for working with 3D model views # - active3dView(): Returns the active view in the form of a class # - viewToWorld: Takes a point in port coordinates and # returns a corresponding ray in world coordinates omui.M3dView().active3dView().viewToWorld(int(vpX), int(vpY), pos, dir) #pos2 = om.MFloatPoint(pos.x, pos.y, pos.z) # Creating a 3 vector float point to use #raySource = om.MFloatPoint(pos2) raySource = om.MFloatPoint(pos) rayDirection = om.MFloatVector(dir) faceIds = None triIds = None idsSorted = False maxParamPtr = 99999999 testBothDirections = False accelParams = None hitpoint = om.MFloatPoint() hitRayParam = None hitFacePtr = om.MScriptUtil().asIntPtr() hitTriangle = None hitBary1 = None hitBary2 = None intersection = self.fnMesh.closestIntersection( raySource, rayDirection, faceIds, triIds, idsSorted, om.MSpace.kWorld, maxParamPtr, testBothDirections, accelParams, hitpoint, hitRayParam, hitFacePtr, hitTriangle, hitBary1, hitBary2) return intersection, hitFacePtr
def deform(self, data_block, geo_iter, world_matrix, multi_index): envelope = data_block.inputValue(self.envelope).asFloat() if envelope == 0: return max_distance = data_block.inputValue( AttractorDeformerNode.max_distance).asFloat() if max_distance == 0: return target_position = data_block.inputValue( AttractorDeformerNode.target_position).asFloatVector() target_position = om.MPoint(target_position) * world_matrix.inverse() target_position = om.MFloatVector(target_position) input_handle = data_block.outputArrayValue(self.input) input_handle.jumpToElement(multi_index) input_element_handle = input_handle.outputValue() input_geom = input_element_handle.child(self.inputGeom).asMesh() mesh_fn = om.MFnMesh(input_geom) normals = om.MFloatVectorArray() mesh_fn.getVertexNormals(False, normals) geo_iter.reset() while not geo_iter.isDone(): pt_local = geo_iter.position() target_vector = target_position - om.MFloatVector(pt_local) distance = target_vector.length() if distance <= max_distance: normal = normals[geo_iter.index()] angle = normal.angle(target_vector) if angle <= AttractorDeformerNode.MAX_ANGLE: offset = target_vector * ( (max_distance - distance) / max_distance) geo_iter.setPosition(pt_local + om.MVector(offset)) geo_iter.next()
def getIntersection(self, point, normal, mesh): """Get the "best" intersection to move point to on given mesh. Args: point (MFloatPoint): point to check if inside mesh. normal (MFloatVector): inverted normal of given point. mesh (MFnMesh): mesh to check if point inside. Returns: MPoint """ intersection_normal = OpenMaya.MVector() closest_point = OpenMaya.MPoint() # Get closest point/normal to given point in normal direction on mesh. mesh.getClosestPointAndNormal( OpenMaya.MPoint(point), closest_point, intersection_normal, OpenMaya.MSpace.kWorld, ) # if the the found normal on the mesh is in a direction opposite to the # given normal, fall back to given normal, else use the average normal. # This is to get a more even vertex distribution on the new mesh. angle = normal.angle(OpenMaya.MFloatVector(intersection_normal)) if angle >= math.pi or angle <= -math.pi: average_normal = normal else: average_normal = OpenMaya.MVector(normal) + intersection_normal # Find intersection in direction determined above. intersections = OpenMaya.MFloatPointArray() mesh.allIntersections(point, OpenMaya.MFloatVector(average_normal), None, None, False, OpenMaya.MSpace.kWorld, 1000, False, None, True, intersections, None, None, None, None, None) # If number of intersections is even then the given point is not inside # the mesh. The intersections are ordered so return the first one found # as that is the closest one. intersecting_point = None if intersections.length() % 2 == 1: intersecting_point = intersections[0] return intersecting_point
def getClickedParams(self): pressPosition = cmds.draggerContext(self.ctxName, query=True, anchorPoint=True) m3dView = OpenMayaUI.M3dView() active = m3dView.active3dView() cameraPath = OpenMaya.MDagPath() active.getCamera(cameraPath) clip = OpenMaya.MFnCamera(cameraPath).farClippingPlane() pos = OpenMaya.MPoint() dirV = OpenMaya.MVector() active.viewToWorld(int(pressPosition[0]), int(pressPosition[1]), pos, dirV) itrDag = OpenMaya.MItDag(OpenMaya.MItDag.kDepthFirst, OpenMaya.MFn.kMesh) nearDist = None nearPos = None nearDagPath = None while (not itrDag.isDone()): dagPath = OpenMaya.MDagPath() itrDag.getPath(dagPath) if (dagPath.isVisible()): fnMesh = OpenMaya.MFnMesh(dagPath) p = OpenMaya.MFloatPoint() f = OpenMaya.MScriptUtil() f.createFromInt(0) t = OpenMaya.MScriptUtil() t.createFromInt(0) fp = f.asIntPtr() tp = t.asIntPtr() if (fnMesh.closestIntersection(OpenMaya.MFloatPoint(pos), OpenMaya.MFloatVector(dirV), None, None, True, OpenMaya.MSpace.kWorld, clip, True, None, p, None, fp, tp, None, None)): d = (OpenMaya.MFloatPoint(pos) - p).length() if (not nearDist): nearDist = d nearPos = p nearDagPath = dagPath elif (nearDist > d): nearDist = d nearPos = p nearDagPath = dagPath itrDag.next() if (nearPos): n = OpenMaya.MVector() OpenMaya.MFnMesh(nearDagPath).getClosestNormal( OpenMaya.MPoint(nearPos), n, OpenMaya.MSpace.kWorld) return ClickedPos(nearPos, n, nearDagPath) else: return None
def compute(self, plug, data): if plug != JigglePoint.aOutput: return OpenMaya.kUnknownParameter # Get the inputs damping = data.inputValue(self.aDamping).asFloat() stiffness = data.inputValue(self.aStiffness).asFloat() goal = OpenMaya.MPoint(data.inputValue(self.aGoal).asFloatVector()) parentInverse = data.inputValue(self.aParentInverse).asMatrix() currentTime = data.inputValue(self.aTime).asTime() jiggleAmount = data.inputValue(self.aJiggleAmount).asFloat() # Initialize the data if not self._initialized: self._previousTime = currentTime self._currentPosition = goal self._previousPosition = goal self._initialized = True # Check if the timestep is just 1 frame since we want a stable simulation timeDifference = currentTime.value() - self._previousTime.value() if timeDifference > 1.0 or timeDifference < 0.0: self._initialized = False self._previousTime = currentTime return # Calculate the output position #stiffness *= 1.0 - jiggleAmount #damping *= jiggleAmount #if damping > 1.0: # damping = 1.0 #if stiffness > 1.0: # stiffness = 1.0 #if stiffness <= 0.0: # stiffness = 0.001 velocity = (self._currentPosition - self._previousPosition) * (1.0 - damping) newPosition = self._currentPosition + velocity goalForce = (goal - newPosition) * stiffness newPosition += goalForce # Store the states for the next computation self._previousPosition = OpenMaya.MPoint(self._currentPosition) self._currentPosition = OpenMaya.MPoint(newPosition) self._previousTime = OpenMaya.MTime(currentTime) newPosition = goal + ((newPosition - goal) * jiggleAmount) # Put in the output local space newPosition *= parentInverse hOutput = data.outputValue(JigglePoint.aOutput) outVector = OpenMaya.MFloatVector(newPosition.x, newPosition.y, newPosition.z) hOutput.setMFloatVector(outVector) hOutput.setClean() data.setClean(plug)
def compute(self, plug, data): if plug != JigglePoint.aOutput: return OpenMaya.kUnknownParameter # Get thi inputs damping = data.inputValue(self.aDamping).asFloat() stiffness = data.inputValue(self.aStiffness).asFloat() goal = OpenMaya.MPoint(data.inputValue(self.aGoal).asFloatVector()) current_time = data.inputValue(self.aTime).asTime() parent_inverse = data.inputValue(self.aParentInverse).asMatrix() jiggle_amount = data.inputValue(self.aJiggleAmount).asFloat() # check for the inilize state of the comuting/node if not self._initialize: self._previous_time = current_time self._current_position = goal self._previous_position = goal self._initialize = True # calculating the time difference --- if the timestep is just 1 frame we want a stable simulation time_difference = current_time.value() - self._previous_time.value() if time_difference > 1.0 or time_difference < 0.0: self._initialize = False self._previous_time = current_time data.setClean(plug) return # calculating the velocity vector velocity = (self._current_position - self._previous_position) * (1.0 - damping) # calculating the new positio point new_position = self._current_position + velocity # updating the final result with the stuffness factor goal_force = (goal - new_position) * stiffness new_position += goal_force # store the state of the next computation self._previous_position = OpenMaya.MPoint(self._current_position) self._current_position = OpenMaya.MPoint(new_position) self._previous_time = OpenMaya.MTime(current_time) # involving the jiggle amount factor new_position = goal + ((new_position - goal) * jiggle_amount) if DEBUG_MODE: print new_position.x print new_position.y print new_position.z # caculatin the new position in the local space of the object which is affected new_position *= parent_inverse # give the final result to aOutput attribute that has been created before (output of our node) hOutput = data.outputValue(JigglePoint.aOutput) out_vector = OpenMaya.MFloatVector(new_position.x, new_position.y, new_position.z) hOutput.setMFloatVector(out_vector) hOutput.setClean() data.setClean(plug)
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 compute(self, plug, block): if plug == hair.mOutColor: resultColor = OpenMaya.MFloatVector(0.0,0.0,0.0) outColorHandle = block.outputValue( hair.mOutColor ) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() else: return OpenMaya.kUnknownParameter
def compute(self, plug, block): if plug == roughcoating.mOutColor or plug.parent( ) == roughcoating.mOutColor: resultColor = OpenMaya.MFloatVector(0.0, 0.0, 0.0) outColorHandle = block.outputValue(roughcoating.mOutColor) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() else: return OpenMaya.kUnknownParameter
def compute(self, plug, dataBlock): if plug != JigglePointNode.outputPoint: return om.kUnknownParameter # get input values damping = dataBlock.inputValue(JigglePointNode.dampingVal).asFloat() stiff = dataBlock.inputValue(JigglePointNode.stiffVal).asFloat() goal = om.MPoint( dataBlock.inputValue(JigglePointNode.goalPos).asFloatVector()) currentTime = dataBlock.inputValue(JigglePointNode.timeVal).asTime() parentInvMat = dataBlock.inputValue( JigglePointNode.parentInverseMatrix).asMatrix() jiggleAmount = dataBlock.inputValue( JigglePointNode.jiggleAmount).asFloat() # test initialize flag if not self.initializeFlag: self.currentPos = goal self.previousPos = goal self.previousTime = currentTime self.initializeFlag = True # Check if the time step is just 1 frame since we want a stable simulation timeDiff = currentTime.value() - self.previousTime.value() if timeDiff > 1.0 or timeDiff < 0.0: self.initializeFlag = False self.previousTime = currentTime dataBlock.setClean(plug) return # Algorithm velocity = (self.currentPos - self.previousPos) * (1.0 - damping) # get P_n newPos = self.currentPos + velocity # get goal vector goalVector = (goal - newPos) * stiff newPos = newPos + goalVector # store value for next computing self.previousPos = om.MPoint(self.currentPos) self.currentPos = om.MPoint(newPos) self.previousTime = om.MTime(currentTime) newPos = goal + ((newPos - goal) * jiggleAmount) # put in the output local space newPos = newPos * parentInvMat outputPoint = dataBlock.outputValue(JigglePointNode.outputPoint) outputVector = om.MFloatVector(newPos.x, newPos.y, newPos.z) outputPoint.setMFloatVector(outputVector) outputPoint.setClean() dataBlock.setClean(plug)
def getBlackbodyColorAndCoord(index, nSamples, minTemp, maxTemp, energyExp, energyOffset, energyMult): coordStep = 1.0 / (nSamples - 1) sampleStep = (maxTemp - minTemp) / (nSamples - 1.0) iMaxEnergy = 1.0 / pow(maxTemp, energyExp) iEnergyOffset = 1.0 - energyOffset t = int(minTemp + sampleStep * index) e = (pow(t, energyExp) * iMaxEnergy * iEnergyOffset + energyOffset) * energyMult c = blackbody.blackbodyToRGB(t) return OpenMaya.MFloatVector(c[0] * e, c[1] * e, c[2] * e), coordStep
def compute(self, plug, data): if plug == speechMaterial.outputColor or plug.parent( ) == speechMaterial.outputColor: resultColor = om.MFloatVector(0.0, 0.0, 0.0) try: speechWeightHandle = data.inputValue( speechMaterial.inputWeight) except: sys.stderr.write("Failed to get speech weight") raise speechWeightValue = speechWeightHandle.asInt() try: neutralColorHandle = data.inputValue(speechMaterial.aNeutral) except: sys.stderr.write("Failed to get neutral color") raise neutralColor = neutralColorHandle.asFloatVector() jawDownColor = data.inputValue( speechMaterial.aJawDown).asFloatVector() jawUpColor = data.inputValue(speechMaterial.aJawUp).asFloatVector() wideColor = data.inputValue(speechMaterial.aWide).asFloatVector() narrowColor = data.inputValue( speechMaterial.aNarrow).asFloatVector() lipsOpenColor = data.inputValue( speechMaterial.aLipsOpen).asFloatVector() lipsClosedColor = data.inputValue( speechMaterial.aLipsClosed).asFloatVector() if speechWeightValue == 6: resultColor = neutralColor elif speechWeightValue == 5: resultColor = jawUpColor elif speechWeightValue == 4: resultColor = jawDownColor elif speechWeightValue == 3: resultColor = lipsOpenColor elif speechWeightValue == 2: resultColor = lipsClosedColor elif speechWeightValue == 1: resultColor = narrowColor elif speechWeightValue == 0: resultColor = wideColor outColorHandle = data.outputValue(speechMaterial.outputColor) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() else: sys.stderr.write("fail compute") return om.kUnknownParameter
def compute(self, plug, block): if plug == self.outColor or plug.parent() == self.outColor: resultColor = OpenMaya.MFloatVector(0.0, 0.0, 1.0) # set the output as a flat color outColorHandle = block.outputValue(self.outColor) outColorHandle.setMFloatVector(resultColor) outColorHandle.setClean() else: return OpenMaya.kUnknownParameter