private static string GetParentName(MFnIkJoint Joint) { // Attempt to result var FullPath = Joint.fullPathName; var SplitPath = FullPath.Substring(1).Split('|'); if (SplitPath.Length > 2) { // We have parents, fetch second to last return(CleanNodeName(SplitPath[SplitPath.Length - 2])); } else if (SplitPath.Length == 2) { // We have parents, ensure this is a joint parent var SelectList = new MSelectionList(); SelectList.add(FullPath.Substring(0, FullPath.IndexOf("|", 1))); // Grab it var Result = new MDagPath(); SelectList.getDagPath(0, Result); // Check if (Result.hasFn(MFn.Type.kJoint)) { return(CleanNodeName(SplitPath[SplitPath.Length - 2])); } } // Root bone return(string.Empty); }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { fMesh = new MFnMesh(obj); fObj = obj; fObjTransform = dagPath.node; } } if (fMesh == null || fObj == null || fObjTransform == null) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
public override void doIt(MArgList args) // // Takes the nodes that are on the active selection list and adds an // attribute changed callback to each one. // { MObject node = new MObject(); MSelectionList list = new MSelectionList(); // Register node callbacks for all nodes on the active list. // MGlobal.getActiveSelectionList(list); for (uint i = 0; i < list.length; i++) { list.getDependNode(i, node); try { node.AttributeChanged += userCB; } catch (Exception) { MGlobal.displayInfo("MNodeMessage.addCallback failed\n"); continue; } // C# SDK will cleanup events, when this plugin is unloaded // callbacks.append(node); } return; }
// This method creates the ik2Bsolver after a File->New. // private static void createIK2BsolverAfterNew(object sender, MBasicFunctionArgs arg) { MSelectionList selList = new MSelectionList(); MGlobal.getActiveSelectionList( selList ); MGlobal.executeCommand("createNode -n ik2BsolverCSharp ik2BsolverCSharp"); MGlobal.setActiveSelectionList( selList ); }
public MSelectionList RestoreSelectionOnList(MSelectionList targetList = null, bool selectResult = false) { if (targetList == null || targetList.length == 0) { targetList = BasicFunc.GetSelectedList(); } MSelectionList resultSelection = new MSelectionList(); for (int i = 0; i < targetList.length; i++) { if (i >= selectedIndicesList.Count) { break; } MDagPath dag = new MDagPath(); targetList.getDagPath((uint)i, dag); MFnSingleIndexedComponent sic = new MFnSingleIndexedComponent(); MObject components = sic.create(MFn.Type.kMeshPolygonComponent); sic.addElements(new MIntArray(selectedIndicesList[i])); resultSelection.add(dag, components); //resultSelection.add(dag); } if (selectResult) { BasicFunc.Select(resultSelection); } return(resultSelection); }
public void ResetCamera() { //<PerspectiveCamera UpDirection="0,1,0" Position="1,1,1" LookDirection="-1,-1,-1" FieldOfView="45" /> MDagPath cameraPath; try { // Try with a Maya host first cameraPath = M3dView.active3dView.Camera; } catch { // We are in standalone mode (WPF application) MSelectionList list = new MSelectionList(); list.add("persp"); cameraPath = new MDagPath(); list.getDagPath(0, cameraPath); } MFnCamera fnCamera = new MFnCamera(cameraPath); MPoint eyePoint = fnCamera.eyePoint(MSpace.Space.kWorld); MPoint centerOfInterestPoint = fnCamera.centerOfInterestPoint(MSpace.Space.kWorld); MVector direction = centerOfInterestPoint.minus(eyePoint); MVector upDirection = fnCamera.upDirection(MSpace.Space.kWorld); camera.Position = new Point3D(eyePoint.x, eyePoint.y, eyePoint.z); camera.LookDirection = new Vector3D(direction.x, direction.y, direction.z); MAngle fieldOfView = new MAngle(fnCamera.verticalFieldOfView); //verticalFieldOfView / horizontalFieldOfView camera.FieldOfView = fieldOfView.asDegrees; camera.UpDirection = new Vector3D(upDirection.x, upDirection.y, upDirection.z); camera.NearPlaneDistance = fnCamera.nearClippingPlane; camera.FarPlaneDistance = fnCamera.farClippingPlane; camera.Transform = new Transform3DGroup(); (camera.Transform as Transform3DGroup).Children.Add(new TranslateTransform3D(new Vector3D())); }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { fMesh = new MFnMesh(obj); fObj = obj; fObjTransform = dagPath.node; } } if( fMesh == null || fObj == null || fObjTransform == null ) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
public static bool CheckSelectionList(MSelectionList list, int minCount = 0, int maxCount = 0, bool debugLog = true) { if (list == null) { if (debugLog) { Debug.Log("list null"); } return(false); } if (minCount > 0) { if (list.length < minCount) { Debug.Log("current count:" + list.length + " less than " + minCount); return(false); } } if (maxCount > 0) { if (list.length > maxCount) { Debug.Log("current count:" + list.length + " more than " + maxCount); return(false); } } return(true); }
public static MDagPath[] BindIKControl(MSelectionList jointList = null, JointProcess.IKSolverType iKSolverType = JointProcess.IKSolverType.RotatePlane) { if (jointList == null || jointList.isEmpty) { jointList = new MSelectionList(); MGlobal.getActiveSelectionList(jointList); } if (jointList.length == 3) { MDagPath rootObject = new MDagPath(), endObject = new MDagPath(), ctlDagPath = new MDagPath(); jointList.getDagPath(0, rootObject); jointList.getDagPath(1, endObject); jointList.getDagPath(2, ctlDagPath); return(BindIKControl(rootObject, endObject, iKSolverType, ctlDagPath)); } else if (jointList.length == 2) { MDagPath rootObject = new MDagPath(), endObject = new MDagPath(); jointList.getDagPath(0, rootObject); jointList.getDagPath(1, endObject); return(BindIKControl(rootObject, endObject, iKSolverType)); } else { return(null); } }
public static void BindShoulder(MSelectionList jointList = null) { if (jointList == null) { jointList = BasicFunc.GetSelectedList(MFn.Type.kJoint); } if (jointList.length != 4) { Debug.Log("please select joints"); return; } MDagPath dag_shoulder = new MDagPath(), dag_armRoot = new MDagPath(), dag_elbow = new MDagPath(), dag_wrist = new MDagPath(); jointList.getDagPath((uint)0, dag_shoulder); jointList.getDagPath((uint)1, dag_armRoot); jointList.getDagPath((uint)2, dag_elbow); jointList.getDagPath((uint)3, dag_wrist); //string shoulderIkName = JointProcess.AddIKHandle(dag_shoulder, dag_armRoot, JointProcess.IKSolverType.SingleChain)[0]; MDagPath[] shoulderResult = BindIKControl(dag_shoulder, dag_armRoot, JointProcess.IKSolverType.SingleChain); MDagPath[] armResult = BindIKControl(dag_armRoot, dag_wrist, JointProcess.IKSolverType.RotatePlane); MDagPath dag_ctl_shoulder = shoulderResult[1], dag_ctl_arm = armResult[1], dag_ctl_pole = armResult[2]; BasicFunc.SetTransformParent(dag_ctl_arm.fullPathName, dag_ctl_shoulder.fullPathName); BasicFunc.SetTransformParent(dag_ctl_pole.fullPathName, dag_ctl_shoulder.fullPathName); BasicFunc.AddConstraint(dag_ctl_arm.fullPathName, dag_wrist.fullPathName, ConstantValue.ConstraintType.Orient); //MFnTransform trans_ctl_shoulder = new MFnTransform(dag_ctl_shoulder); //MFnTransform trans_ctl_arm = new MFnTransform(dag_ctl_arm); //MFnTransform trans_ctl_pole = new MFnTransform(dag_ctl_pole); //BasicFunc.SetTransformParent(trans_ctl_arm, trans_ctl_shoulder); //BasicFunc.SetTransformParent(trans_ctl_pole, trans_ctl_shoulder); }
public static void DeleteUnusedShadingNode(MSelectionList list) { if (list == null) { Debug.Log("list null"); return; } List <MFnDependencyNode> deleteList = new List <MFnDependencyNode>(); for (int i = 0; i < list.length; i++) { MObject mo = new MObject(); list.getDependNode((uint)i, mo); if (mo.hasFn(MFn.Type.kShadingEngine)) { MFnDependencyNode sgNode = new MFnDependencyNode(mo); MPlug plug_dagSetMemebers = sgNode.findPlug(ConstantValue.plugName_dagSetMembers); Debug.Log("numelements:" + plug_dagSetMemebers.numElements); if (plug_dagSetMemebers.numElements == 0) { deleteList.Add(sgNode); } } //Debug.Log(sgNode.name); } BasicFunc.DeleteObjects(deleteList); }
public static MDagPath CreateJointsCurve(MSelectionList jointDagPathList) { int count = (int)jointDagPathList.length; string curveName = "curve_"; MVector[] vectors = new MVector[count]; for (int i = 0; i < count; i++) { MDagPath dagPath = new MDagPath(); jointDagPathList.getDagPath((uint)i, dagPath); if (i == 0) { curveName += dagPath.partialPathName + "_"; } else if (i == count - 1) { curveName += dagPath.partialPathName; } MFnTransform ptTrans = new MFnTransform(dagPath); vectors[i] = ptTrans.getTranslation(MSpace.Space.kWorld); //MGlobal.displayInfo(BasicFunc::ToCMDSParamStr(vectors[i])); } MDagPath curveDagPath = BasicFunc.CreateCurve(vectors, curveName); //MGlobal.displayInfo("create Finish"); return(curveDagPath); }
public override void doIt(MArgList args) { MTypeId id = new MTypeId(0x0008106c); MObject setNode = fDGMod.createNode(id); fDGMod.doIt(); MSelectionList selList = new MSelectionList(); MGlobal.getActiveSelectionList(selList); if (selList.length > 0) { try { MFnSet setFn = new MFnSet(setNode); setFn.addMembers(selList); } catch (System.Exception) { } } MFnDependencyNode depNodeFn = new MFnDependencyNode(setNode); setResult(depNodeFn.name); return; }
public static void Select(MDagPath dagPath) { MSelectionList list = new MSelectionList(); list.add(dagPath); Select(list); }
public static void RemoveUnusedTextures(MSelectionList list) { if (list == null) { Debug.Log("list null"); return; } List <MObject> deleteList = new List <MObject>(); for (int i = 0; i < list.length; i++) { MObject mo = new MObject(); list.getDependNode((uint)i, mo); MFnDependencyNode imageNode = new MFnDependencyNode(mo); MPlug texOutputPlug = imageNode.findPlug(ConstantValue.plugName_fileTexOutputColor); MPlugArray destPlugs = new MPlugArray(); texOutputPlug.destinations(destPlugs); if (destPlugs.Count == 0) { deleteList.Add(mo); Debug.Log("remove no use:" + imageNode.absoluteName); } else { Debug.Log("still used:" + imageNode.absoluteName); for (int j = 0; j < destPlugs.length; j++) { Debug.Log(" by:" + destPlugs[0].partialName(true)); } } } BasicFunc.DeleteObjects(deleteList); }
public static MSelectionList DuplicateDags(MSelectionList list) { if (list == null) { return(null); } MSelectionList originSelect = GetSelectedList(); CmdStrConstructor cc = new CmdStrConstructor("duplicate"); cc.UpdateToggle("rr", true); List <string> targets = new List <string>(); foreach (MDagPath dag in list.DagPaths()) { targets.Add(dag.fullPathName); } cc.UpdateTargets(targets); MGlobal.executeCommand(cc.ToString()); //string resultName = MGlobal.executeCommandStringResult("duplicate -rr"); MSelectionList newList = GetSelectedList(); Select(originSelect); return(newList); }
public override bool doRelease(M3dView view) { // Scale nodes on the selection list. // Simple implementation that does not // support undo. MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MObject node = new MObject(); for (MItSelectionList iter = new MItSelectionList(list); !iter.isDone; iter.next()) { iter.getDependNode(node); MFnTransform xform; try { xform = new MFnTransform(node); } catch (System.Exception) { continue; } double[] newScale = new double[3]; newScale[0] = mousePointGlName.x + 1; newScale[1] = mousePointGlName.y + 1; newScale[2] = mousePointGlName.z + 1; xform.setScale(newScale); } return(true); }
public static MDagPath AddDynamicChainControl(ref MDagPath hairSystem, MSelectionList jointChains = null, ConstantValue.HairPointLockType pointLock = ConstantValue.HairPointLockType.Base) { //get bones if (jointChains == null) { jointChains = BasicFunc.GetSelectedList(); } if (jointChains.length == 0) { return(null); } MDagPath dagPath_startJoint = new MDagPath(), dagPath_endJoint = new MDagPath(); if (jointChains.length == 1) { BasicFunc.Select(jointChains); jointChains.getDagPath((uint)0, dagPath_startJoint); MGlobal.executeCommand("select -hierarchy " + dagPath_startJoint.fullPathName); jointChains = BasicFunc.GetSelectedList(MFn.Type.kJoint); } jointChains.getDagPath(0, dagPath_startJoint); jointChains.getDagPath(jointChains.length - 1, dagPath_endJoint); MDagPath startCurveDagPath = JointProcess.CreateJointsCurve(jointChains); MDagPath outCurveDagPath = CurveToHair(ref hairSystem, startCurveDagPath, pointLock); JointProcess.AddIKHandle(dagPath_startJoint, dagPath_endJoint, JointProcess.IKSolverType.Spline, outCurveDagPath.fullPathName); BasicFunc.SetTransformParent(BasicFunc.GetParent(startCurveDagPath), BasicFunc.GetParent(dagPath_startJoint)); return(outCurveDagPath); }
public static void ExtractFacesIntoOneObject(MSelectionList faceList) { if (faceList == null) { return; } MDagPath originDag = new MDagPath(); faceList.getDagPath(0, originDag); Selector selector = new Selector(); selector.SetFromSelection(faceList); MDagPath newDag = BasicFunc.Duplicate(originDag); MSelectionList targetPartInDuplicated = selector.RestoreSelectionOnDag(newDag, true); //new MFnTransform(newDag).setTranslation(new MVector(0, 2, 0), MSpace.Space.kWorld); //BasicFunc.Select(faceList); BasicFunc.DoDelete(faceList); MDagPath dag_targetPartInD = new MDagPath(); MSelectionList invertSelection = BasicFunc.InvertSelect(targetPartInDuplicated, newDag, ConstantValue.PolySelectType.Facet); BasicFunc.DoDelete(invertSelection); }
// // Takes the nodes that are on the active selection list and adds an // attribute changed callback to each one. // public override void doIt(MArgList args) { MObject node = new MObject(); MSelectionList list = new MSelectionList(); // Register node callbacks for all nodes on the active list. // MGlobal.getActiveSelectionList( list ); for ( uint i=0; i<list.length; i++ ) { list.getDependNode( i, node ); try { node.AttributeChanged += userCB; } catch (Exception) { MGlobal.displayInfo("MNodeMessage.addCallback failed\n"); continue; } // C# SDK will cleanup events, when this plugin is unloaded // callbacks.append(node); } return; }
public static void CreateRelativeCurve(MSelectionList selected = null, ConstantValue.SampleType st = ConstantValue.SampleType.ObjectTrans, bool reOrder = true, bool closedArc = true, string ctlName = null) { if (selected == null) { selected = BasicFunc.GetSelectedList(); } List <MVector> positions = new List <MVector>(); switch (st) { case ConstantValue.SampleType.Vert: { MItSelectionList it_selectionList = new MItSelectionList(selected); MVector totalWeight = MVector.zero; for (; !it_selectionList.isDone; it_selectionList.next()) { MObject component = new MObject(); MDagPath item = new MDagPath(); it_selectionList.getDagPath(item, component); MItMeshVertex it_verts = new MItMeshVertex(item, component); for (; !it_verts.isDone; it_verts.next()) { //Debug.Log(it_verts.index().ToString()); MPoint point = it_verts.position(MSpace.Space.kWorld); MVector pos = new MVector(point.x, point.y, point.z); //BasicFunc.CreateLocator(pos, "vert_" + it_verts.index()); positions.Add(pos); totalWeight += pos; } } break; } case ConstantValue.SampleType.Edge: { break; } case ConstantValue.SampleType.Poly: { break; } case ConstantValue.SampleType.ObjectTrans: { foreach (MDagPath dag in selected.DagPaths()) { MFnTransform trans = new MFnTransform(dag); positions.Add(trans.getTranslation(MSpace.Space.kWorld)); } break; } } if (ctlName == null) { ctlName = "samplerCurve_00"; } CreateLoopCircleByPos(positions, reOrder, closedArc, ctlName); }
internal void GetNewGeom() { // VMDataBridge.DataBridge.Instance.UnregisterCallback(GUID.ToString()); if (firstRun) { firstRun = false; } else { if (SelectedItems != null) { foreach (var itm in SelectedItems.Values) { itm.Dispose(); } } } MSelectionList selectionList = new MSelectionList(); MGlobal.getActiveSelectionList(selectionList, true); if (selectionList.isEmpty) { if (selectionList.isEmpty) { SelectedItems = null; OnNodeModified(true); return; } } var TransObjectList = selectionList.DagPaths(MFn.Type.kTransform).ToList(); var DagObjectList = selectionList.DagPaths(MFn.Type.kMesh).ToList(); SelectedItems = new Dictionary <string, DMMesh>(DagObjectList.Count); m_SelectedItemNames = new List <string>(DagObjectList.Count); foreach (var dag in TransObjectList) { if (dag.hasFn(MFn.Type.kMesh)) { var itm = new DMMesh(dag, space); itm.Renamed += Itm_Renamed; itm.Deleted += MObjOnDeleted; SelectedItems.Add(itm.dagName, itm); m_SelectedItemNames.Add(itm.dagName); // ct++; } else { MGlobal.displayWarning($"Selected item is not a kMesh, it is a {dag.apiType}"); } } m_SelectedItemNamesString = ConvertStringListToString(m_SelectedItemNames); OnNodeModified(true); }
public static MSelectionList GetObjectsByName(string name) { MSelectionList matched = new MSelectionList(); MGlobal.getSelectionListByName(name, matched); //Debug.Log("ask if [" + name + "] exist,result count:" + matched.length); return(matched); }
public override void doIt(MArgList args) { MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); iter = new MItSelectionList(list, MFn.Type.kInvalid); redoIt(); }
public static MItSelectionList GetActiveSelectionListIterator(MFn.Type type) { MSelectionList selectionList = new MSelectionList(); MGlobal.getActiveSelectionList(selectionList); return(new MItSelectionList(selectionList, type)); }
//====================================================================== // // Look through the arg database and verify that the arguments are // valid. Only checks the common flags so derived classes should call // this parent method first before checking their own flags. // public virtual void checkArgs(MArgDatabase argsDb) { String formatType = "raw"; fSerialize = AssociationsSerializer.formatByName(formatType); if (fSerialize == null) { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kMetadataFormatNotFound); String msg = String.Format(fmt, formatType); displayError(msg); throw new System.ArgumentException(msg); } //---------------------------------------- // (selection list) // // Commands need at least one mesh object on which to operate so gather up // the list of meshes specified and/or selected. // // Empty out the list of meshes on which to operate so that it can be // populated from the selection or specified lists. fMeshes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (int i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { MFnMesh mesh = new MFnMesh(obj); if (mesh != null) { fMeshes.append(obj); } } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if (fMeshes.length == 0) { String msg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); displayError(msg); throw new System.InvalidOperationException(msg); } }
public static void Select(MSelectionList list, bool selectInComponentMode = false) { MGlobal.setActiveSelectionList(list); if (selectInComponentMode) { Debug.Log("select in component mode"); List <MSelectionList> facesListToAdd = new List <MSelectionList>(); MItSelectionList it_selectionList = new MItSelectionList(list); Debug.Log("has components:" + it_selectionList.hasComponents); for (; !it_selectionList.isDone; it_selectionList.next()) { MObject component = new MObject(); MDagPath item = new MDagPath(); it_selectionList.getDagPath(item, component); //Debug.Log(item.fullPathName + " has components:" + it_selectionList.hasComponents); //List<int> selectedIndcies = new List<int>(); //MItMeshPolygon it_poly = new MItMeshPolygon(item, component); if (!it_selectionList.hasComponents) { //Debug.Log("没有组件被选择,怀疑是一整个物体:" + item.fullPathName); BasicFunc.SelectComponent(item.fullPathName, ConstantValue.PolySelectType.Facet, true); facesListToAdd.Add(BasicFunc.GetSelectedList()); } //else //{ // Debug.Log("有组件被选择:" + it_poly.count()); //} } if (facesListToAdd.Count > 0) { MGlobal.setActiveSelectionList(list); for (int i = 0; i < facesListToAdd.Count; i++) { MGlobal.setActiveSelectionList(facesListToAdd[i], MGlobal.ListAdjustment.kAddToList); } } } //bool hasDag = false; //if (hasDag) //{ // Debug.Log("has dag length:" + list.length); // foreach (MDagPath dag in list.DagPaths()) // { // Debug.Log(dag.fullPathName); // } // MGlobal.setActiveSelectionList(list); //} //else //{ // Debug.Log("no dag but length:" + list.length); // MGlobal.setActiveSelectionList(list); //} }
/// <summary> /// well, this action is truely dangerous /// </summary> /// <param name="list"></param> /// <returns></returns> public static bool CombineMaterials(MSelectionList list, bool deleteRepeated = true) { if (!BasicFunc.CheckSelectionList(list, 2)) { Debug.Log("please choose at least 2 materials"); return(false); } string firstMatName = ""; List <MObject> deleteList = new List <MObject>(); List <MSelectionList> waitForAssign = new List <MSelectionList>(); MDGModifier dGModifier = new MDGModifier(); for (uint i = 0; i < list.length; i++) { //Debug.Log(i + " mat test"); MObject matObject = new MObject(); list.getDependNode(i, matObject); MFnDependencyNode dnode = new MFnDependencyNode(matObject); if (i == 0) { firstMatName = dnode.absoluteName; continue; } else { deleteList.Add(matObject); } //Debug.Log(i + " node:" + dnode.absoluteName); if (matObject.hasFn(MFn.Type.kLambert) || matObject.hasFn(MFn.Type.kBlinn) || matObject.hasFn(MFn.Type.kPhong)) { //Debug.Log("has mat fn"); //MMaterial mat = new MMaterial(matObject); //MColor color = new MColor(); //mat.getDiffuse(color); //Debug.Log("mat:" + dnode.absoluteName + " ,color:" + BasicFunc.MToString(color)); SelectObjectsWithMat(dnode); //Debug.Log("finish select"); //waitForAssign.Add(BasicFunc.GetSelectedList()); AssignMat(firstMatName); //Debug.Log("finish assign"); BasicFunc.DeleteByCMD(dnode.absoluteName); //Debug.Log("finish delete"); } else { Debug.Log("no mat fn"); } } dGModifier.doIt(); //MGlobal.executeCommandOnIdle("hyperShade -objects " + matNode.absoluteName); return(true); }
void parseArgs(MArgList args) { string arg = ""; MSelectionList list = new MSelectionList(); bool charNameUsed = false; string charName; const string charFlag = "-c"; const string charFlagLong = "-char"; for (uint i = 0; i < args.length; i++) { arg = args.asString(i); if (arg == charFlag || arg == charFlagLong) { // get the char name // if (i == args.length - 1) { arg += ": must specify a character name"; throw new ArgumentException(arg, "args"); } i++; charName = args.asString(i); list.add(charName); charNameUsed = true; } else { arg += ": unknown argument"; throw new ArgumentException(arg, "args"); } } if (charNameUsed) { // get the character corresponding to the node name // MItSelectionList iter = new MItSelectionList(list); for (; iter.isDone; iter.next()) { MObject node = new MObject(); iter.getDependNode(node); if (node.apiType == MFn.Type.kCharacter) { fCharacter = node; break; } } if (fCharacter.isNull) { throw new ApplicationException("Unable to get the character corresponding to the node name."); } } }
public static void Select(List <MObject> list) { MSelectionList sl = new MSelectionList(); foreach (MObject mo in list) { sl.add(mo); } MGlobal.setActiveSelectionList(sl); }
public static void MakeJointsHairChain(MSelectionList jointDagPaths) { //begin convert curve to dynamic MDagPath curveDagPath = CreateJointsCurve(jointDagPaths); string cmdStr = "cmds.makeCurveDynamic(0,0,0,1,0)"; string resultStr = MGlobal.executePythonCommandStringResult(cmdStr); //string resultStr = MGlobal.executeCommandStringResult("makeCurvesDynamic 2 {\"0\",\"0\",\"0\",\"1\",\"0\"}"); MGlobal.displayInfo("message" + resultStr); }
// get the dependency node private MObject getDependNode(string node_name) { var sl = new MSelectionList(); sl.add(node_name, true); var o = new MObject(); sl.getDependNode(0, o); return(o); }
// get the DAG node public MDagPath getDagNode(string node_name) { var sl = new MSelectionList(); sl.add(node_name, true); var dp = new MDagPath(); sl.getDagPath(0, dp); return(dp); }
//====================================================================== // // Look through the arg database and verify that the arguments are // valid. Only checks the common flags so derived classes should call // this parent method first before checking their own flags. // public virtual void checkArgs(MArgDatabase argsDb) { String formatType = "raw"; fSerialize = AssociationsSerializer.formatByName( formatType ); if( fSerialize == null) { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kMetadataFormatNotFound); String msg = String.Format(fmt, formatType); displayError(msg); throw new System.ArgumentException(msg); } //---------------------------------------- // (selection list) // // Commands need at least one mesh object on which to operate so gather up // the list of meshes specified and/or selected. // // Empty out the list of meshes on which to operate so that it can be // populated from the selection or specified lists. fMeshes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (int i = 0; i<objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode( dagPath.node ); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { MFnMesh mesh = new MFnMesh(obj); if(mesh != null) fMeshes.append(obj); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if( fMeshes.length == 0 ) { String msg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); displayError(msg); throw new System.InvalidOperationException(msg); } }
// This method creates the ik2Bsolver after a File->Open // if the ik2Bsolver does not exist in the loaded file. // private static void createIK2BsolverAfterOpen(object sender, MBasicFunctionArgs arg) { MSelectionList selList = new MSelectionList(); MGlobal.getSelectionListByName("ik2BsolverCSharp", selList); if (selList.length == 0) { MGlobal.getActiveSelectionList( selList ); MGlobal.executeCommand("createNode -n ik2BsolverCSharp ik2BsolverCSharp"); MGlobal.setActiveSelectionList( selList ); } }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { //---------------------------------------- // (selection list) // // Commands need at least one node on which to operate so gather up // the list of nodes specified and/or selected. // // Empty out the list of nodes on which to operate so that it can be // populated from the selection or specified lists. fNodes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { if (obj == MObject.kNullObj) { throw new ApplicationException("Error: objects.getDependNode() "); } fNodes.append(dagPath.node); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if (fNodes.length == 0) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
public override void doIt(MArgList args) { MTypeId id = new MTypeId(0x0008106c); MObject setNode = fDGMod.createNode(id); fDGMod.doIt(); MSelectionList selList = new MSelectionList(); MGlobal.getActiveSelectionList( selList ); if( selList.length > 0 ) { try { MFnSet setFn = new MFnSet(setNode); setFn.addMembers(selList); } catch (System.Exception) { } } MFnDependencyNode depNodeFn = new MFnDependencyNode( setNode ); setResult( depNodeFn.name ); return; }
private bool exportSelected(ref StreamWriter animFile, ref string copyFlags, bool nodeNames = false, bool verboseUnits = false) { // If the selection list is empty, then there are no anim curves // to export. // MSelectionList sList = new MSelectionList(); MGlobal.getActiveSelectionList(sList); if (sList.isEmpty) { string msg = MStringResource.getString(RegisterMStringResources.kNothingSelected); MGlobal.displayError(msg); return false; } // Copy any anim curves to the API clipboard. // int result = 0; string command = copyFlags; try { MGlobal.executeCommand(command, out result, false, true); } catch (System.Exception) { string msg = MStringResource.getString(RegisterMStringResources.kAnimCurveNotFound); MGlobal.displayError(msg); return false; } if (result == 0 || MAnimCurveClipboard.theAPIClipboard.isEmpty) { string msg = MStringResource.getString(RegisterMStringResources.kAnimCurveNotFound); MGlobal.displayError(msg); return false; } fWriter.writeClipboard(ref animFile, MAnimCurveClipboard.theAPIClipboard, nodeNames, verboseUnits); return true; }
// // Select function. Gets called when the bbox for the object is selected. // This function just selects the object without doing any intersection tests. // /* override */ public override bool select(MSelectInfo selectInfo, MSelectionList selectionList, MPointArray worldSpaceSelectPts) { MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectObjectsMask); MSelectionList item = new MSelectionList(); item.add(selectInfo.selectPath); MPoint xformedPt = new MPoint(); selectInfo.addSelection(item, xformedPt, selectionList, worldSpaceSelectPts, priorityMask, false); return true; }
/*! Callback that creates the manipulator if valid geometry is selected. Also removes the manipulator if no geometry is selected. Handles connecting the manipulator to multiply selected nodes. \param[in] data Pointer to the current context class. */ void updateManipulators() { deleteManipulators(); if ( ! validGeometrySelected() ) { return; } // Clear info owner = null; firstObjectSelected = MObject.kNullObj; MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); string manipName = "lineManipContainerCSharp"; MObject manipObject = new MObject(); lineManipContainer manipulator = MPxManipContainer.newManipulator(manipName, manipObject) as lineManipContainer; if (null != manipulator) { // Save state owner = manipulator; // Add the manipulator addManipulator(manipObject); // for (; !iter.isDone; iter.next()) { MObject dependNode = new MObject(); iter.getDependNode(dependNode); MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); // Connect the manipulator to the object in the selection list. manipulator.connectToDependNode(dependNode); // if (MObject.kNullObj == firstObjectSelected) { firstObjectSelected = dependNode; } } // Allow the manipulator to set initial state setInitialState(); } }
//! Ensure that valid geometry is selected bool validGeometrySelected() { MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MItSelectionList iter = new MItSelectionList(list, MFn.Type.kInvalid); for (; !iter.isDone; iter.next()) { MObject dependNode = new MObject(); iter.getDependNode(dependNode); if (dependNode.isNull || !dependNode.hasFn(MFn.Type.kTransform)) { MGlobal.displayWarning("Object in selection list is not right type of node"); return false; } MFnDependencyNode dependNodeFn = new MFnDependencyNode(dependNode); MStringArray attributeNames = new MStringArray(); attributeNames.append("scaleX"); attributeNames.append("translateX"); int i; for ( i = 0; i < attributeNames.length; i++ ) { MPlug plug = dependNodeFn.findPlug(attributeNames[i]); if ( plug.isNull ) { MGlobal.displayWarning("Object cannot be manipulated: " + dependNodeFn.name); return false; } } } return true; }
public override bool doRelease(M3dView view) { // Scale nodes on the selection list. // Simple implementation that does not // support undo. MSelectionList list = new MSelectionList(); MGlobal.getActiveSelectionList(list); MObject node = new MObject(); for (MItSelectionList iter = new MItSelectionList(list); !iter.isDone; iter.next()) { iter.getDependNode(node); MFnTransform xform; try { xform = new MFnTransform(node); } catch (System.Exception) { continue; } double[] newScale = new double[3]; newScale[0] = mousePointGlName.x + 1; newScale[1] = mousePointGlName.y + 1; newScale[2] = mousePointGlName.z + 1; xform.setScale(newScale); } return true; }
public void ResetCamera() { //<PerspectiveCamera UpDirection="0,1,0" Position="1,1,1" LookDirection="-1,-1,-1" FieldOfView="45" /> MDagPath cameraPath ; try { // Try with a Maya host first cameraPath =M3dView.active3dView.Camera ; } catch { // We are in standalone mode (WPF application) MSelectionList list =new MSelectionList () ; list.add ("persp") ; cameraPath =new MDagPath () ; list.getDagPath (0, cameraPath) ; } MFnCamera fnCamera =new MFnCamera (cameraPath) ; MPoint eyePoint =fnCamera.eyePoint (MSpace.Space.kWorld) ; MPoint centerOfInterestPoint =fnCamera.centerOfInterestPoint (MSpace.Space.kWorld) ; MVector direction =centerOfInterestPoint.minus (eyePoint) ; MVector upDirection =fnCamera.upDirection (MSpace.Space.kWorld) ; camera.Position =new Point3D (eyePoint.x, eyePoint.y, eyePoint.z) ; camera.LookDirection =new Vector3D (direction.x, direction.y, direction.z) ; MAngle fieldOfView =new MAngle (fnCamera.verticalFieldOfView) ; //verticalFieldOfView / horizontalFieldOfView camera.FieldOfView =fieldOfView.asDegrees ; camera.UpDirection =new Vector3D (upDirection.x, upDirection.y, upDirection.z) ; camera.NearPlaneDistance =fnCamera.nearClippingPlane ; camera.FarPlaneDistance =fnCamera.farClippingPlane ; camera.Transform =new Transform3DGroup () ; (camera.Transform as Transform3DGroup).Children.Add (new TranslateTransform3D (new Vector3D ())) ; }
// Parses the given command line arguments and executes them. // public override void doIt(MArgList args) { parseArgs(args); bool nothingSet = (!createdUsed && !appendCameraUsed && !appendCameraAndSetUsed && !deleteLayerUsed && !cameraUsed && !layerUsed && !helpUsed && !setUsed && !layerTypeUsed && !numLayersUsed); if (nothingSet) { throw new ArgumentException("A flag must be used. testCameraSet -help for available flags", "args"); } if (helpUsed) { MGlobal.displayInfo("testExCameraSet -help"); MGlobal.displayInfo("\ttestExCameraSet tests the functionality of the exCameraSet node."); MGlobal.displayInfo(""); MGlobal.displayInfo("\t-h -help : This message is printed"); MGlobal.displayInfo("\t-a -active [true/false]: Set/get whether a particular layer is active"); MGlobal.displayInfo("\t-ac -appendCamera <cameraName>: Append a new camera layer to the cameraSet using the specified camera"); MGlobal.displayInfo("\t-acs -appendCameraAndSet <cameraName> <setName>: Append a new camera layer to the cameraSet using the specified camera and set"); MGlobal.displayInfo("\t-cam -camera [<cameraName>]: Set/get the camera for a particular layer"); MGlobal.displayInfo("\t-c -create : Create a new cameraSet node"); MGlobal.displayInfo("\t-d -deleteLayer <layerIndex>: Delete the layer at the given index"); MGlobal.displayInfo("\t-nl -numLayers: Returns the number of layers defined in the specified cameraSet"); MGlobal.displayInfo("\t-l -layer <layerIndex>: Specifies the layer index to be used when accessing layer information"); MGlobal.displayInfo("\t-lt -layerType [<layerTypeName>]: Set/get the layer type for a particular layer. Possible values are Mono, Left, and Right."); MGlobal.displayInfo("\t-s -set [<setName>]: Set/get the set for a particular layer"); MGlobal.displayInfo("\t-e -edit : Perform an edit operation"); MGlobal.displayInfo("\t-q -query : Perform a query operation"); MGlobal.displayInfo(""); } uint nObjs = list.length; if (nObjs == 0) { if (createdUsed) { // Create a new cameraSet node. // MFnDependencyNode dirFn = new MFnDependencyNode(); string noName = ""; try { MObject dirObj = dirFn.create(exCameraSet.type_id, noName); MGlobal.select(dirObj, MGlobal.ListAdjustment.kReplaceList); } catch (System.Exception ex) { throw new ApplicationException("Could not create a cameraSet node", ex); } return; } if (appendCameraUsed || appendCameraAndSetUsed || deleteLayerUsed || editUsed || cameraUsed || setUsed || layerTypeUsed || activeUsed || numLayersUsed) { throw new ArgumentException("Must specify a cameraSet node", "args"); } } else { if (createdUsed) { throw new ArgumentException("-create cannot have any object specified", "args"); } if (appendCameraUsed) { if (nObjs != 1) { throw new ArgumentException("-appendCamera must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-appendCamera must have a valid exCameraSet node specified", "args"); } // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-appendCamera must have a valid camera node specified", "args"); } // Call the MFnCameraSet method to append the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.appendLayer(camPath, MObject.kNullObj); return; } if (appendCameraAndSetUsed) { if (nObjs != 1) { throw new ArgumentException("-appendCameraAndSet must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-appendCameraAndSet must have a valid exCameraSet node specified", "args"); } // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-appendCameraAndSet must have a valid camera node specified", "args"); } // Get the specified set node. // MSelectionList setList = new MSelectionList(); setList.add(setName); MObject setObj = MObject.kNullObj; setList.getDependNode(0, setObj); if (setObj == MObject.kNullObj) { throw new ArgumentException("-appendCameraAndSet must have a valid set node specified", "args"); } // Call the MFnCameraSet method to append the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.appendLayer(camPath, setObj); return; } if (deleteLayerUsed) { if (nObjs != 1) { throw new ArgumentException("-deleteLayer must have a single cameraSet node specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-deleteLayer must have a valid exCameraSet node specified", "args"); } // Call the MFnCameraSet method to delete the layer. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.deleteLayer((uint)cameraLayer); return; } if (numLayersUsed) { if (queryUsed) { // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-numLayers must have a valid exCameraSet node specified", "args"); } // Call the MFnCameraSet method to get the number of layers. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); uint numLayers = dirFn.numLayers; setResult((int)numLayers); } else { throw new ArgumentException("-numLayers requires the query flag to be used", "args"); } return; } if (cameraUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-camera must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-camera must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Get a dag path to the specified camera. // MSelectionList camList = new MSelectionList(); camList.add(camName); MDagPath camPath = new MDagPath(); camList.getDagPath(0, camPath); if (!camPath.isValid) { throw new ArgumentException("-camera must have a valid camera node specified", "args"); } // Call the MFnCameraSet method to set the camera. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerCamera((uint)cameraLayer, camPath); } else if (queryUsed) { // Call the MFnCameraSet method to get the camera. // MDagPath camPath = new MDagPath(); MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.getLayerCamera((uint)cameraLayer, camPath); MObject camNode = camPath.node; MFnDependencyNode nodeFn = new MFnDependencyNode(camNode); setResult(nodeFn.name); } } if (setUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-set must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-set must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Get the specified set node. // MObject setObj = MObject.kNullObj; if (setName != "") { MSelectionList setList = new MSelectionList(); setList.add(setName); setList.getDependNode(0, setObj); if (setObj == MObject.kNullObj) { throw new ArgumentException("-set must have a valid set node specified", "args"); } } // Call the MFnCameraSet method to set the set node. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerSceneData((uint)cameraLayer, setObj); } else if (queryUsed) { // Call the MFnCameraSet method to get the set node. // MObject setObj = new MObject(); MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.getLayerSceneData((uint)cameraLayer, setObj); MFnDependencyNode nodeFn = new MFnDependencyNode(setObj); setResult(nodeFn.name); } } if (layerTypeUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-layerType must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-layerType must have a valid exCameraSet node specified", "args"); } MFnDependencyNode nodeFn = new MFnDependencyNode(dirNode); exCameraSet exDir = nodeFn.userNode as exCameraSet; if (editUsed) { // Get the specified layer type. // int pt = -1; if (layerTypeVal == "Mono") pt = 0; else if (layerTypeVal == "Left") pt = 1; else if (layerTypeVal == "Right") pt = 2; else { throw new ArgumentException("-layerType must have a valid type specified", "args"); } // Call the exCameraSet method to set the layer type. // exDir.setLayerType((uint)cameraLayer, pt); } else if (queryUsed) { // Call the exCameraSet method to get the layer type. // try { int lt = exDir.getLayerType((uint)cameraLayer); if (lt == 0) setResult("Mono"); else if (lt == 1) setResult("Left"); else if (lt == 2) setResult("Right"); } catch (System.Exception ex) { throw new ApplicationException("exCameraSet node does not have a valid layer type", ex); } } } if (activeUsed) { if ((nObjs != 1) || (!layerUsed)) { throw new ArgumentException("-active must have a cameraSet node and layer specified", "args"); } // Get the specified cameraSet node. // MObject dirNode = MObject.kNullObj; if (!getExCameraSetNode(dirNode)) { throw new ArgumentException("-active must have a valid exCameraSet node specified", "args"); } if (editUsed) { // Call the MFnCameraSet method to set the set node. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); dirFn.setLayerActive((uint)cameraLayer, activeVal); } else if (queryUsed) { // Call the MFnCameraSet method to get the active value. // MFnCameraSet dirFn = new MFnCameraSet(dirNode); activeVal = dirFn.isLayerActive((uint)cameraLayer); setResult(activeVal); } } } return; }
public override void doIt(MArgList args) { MSelectionList list = new MSelectionList(); if ( args.length > 0 ) { // Arg list is > 0 so use objects that were passes in // uint last = args.length; for ( uint i = 0; i < last; i++ ) { // Attempt to find all of the objects matched // by the string and add them to the list // string argStr = args.asString(i); list.add(argStr); } } else { // Get arguments from Maya's selection list. MGlobal.getActiveSelectionList(list); } MObject node = new MObject(); MObjectArray nodePath = new MObjectArray(); MFnDependencyNode nodeFn = new MFnDependencyNode(); MFnDependencyNode dgNodeFnSet = new MFnDependencyNode(); for (MItSelectionList iter = new MItSelectionList(list); !iter.isDone; iter.next()) { iter.getDependNode(node); // // The following code shows how to navigate the DG manually without // using an iterator. First, find the attribute that you are // interested. Then connect a plug to it and see where the plug // connected to. Once you get all the connections, you can choose // which route you want to go. // // In here, we wanted to get to the nodes that instObjGroups connected // to since we know that the shadingEngine connects to the instObjGroup // attribute. // nodeFn.setObject( node ); MObject iogAttr = null; try { iogAttr = nodeFn.attribute("instObjGroups"); } catch (Exception) { MGlobal.displayInfo(nodeFn.name + ": is not a renderable object, skipping"); continue; } MPlug iogPlug = new MPlug(node, iogAttr); MPlugArray iogConnections = new MPlugArray(); // // instObjGroups is a multi attribute. In this example, just the // first connection will be tried. // if (!iogPlug.elementByLogicalIndex(0).connectedTo(iogConnections, false, true)) { MGlobal.displayInfo(nodeFn.name + ": is not in a shading group, skipping"); continue; } // // Now we would like to traverse the DG starting from the shadingEngine // since most likely all file texture nodes will be found. Note the // filter used to initialize the DG iterator. There are lots of filter // type available in MF.Type that you can choose to suite your needs. // bool foundATexture = false; for ( int i=0; i < iogConnections.length; i++ ) { MObject currentNode = iogConnections[i].node; // // Note that upon initialization, the current pointer of the // iterator already points to the first valid node. // MItDependencyGraph dgIt = new MItDependencyGraph(currentNode, MFn.Type.kFileTexture, MItDependencyGraph.Direction.kUpstream, MItDependencyGraph.Traversal.kBreadthFirst, MItDependencyGraph.Level.kNodeLevel); if (dgIt == null) { continue; } dgIt.disablePruningOnFilter(); for ( ; !dgIt.isDone; dgIt.next() ) { MObject thisNode = dgIt.thisNode(); dgNodeFnSet.setObject(thisNode); try { dgIt.getNodePath(nodePath); } catch (Exception) { MGlobal.displayInfo("getNodePath"); continue; } // // append the starting node. // nodePath.append(node); dumpInfo( thisNode, dgNodeFnSet, nodePath ); foundATexture = true; } } if ( !foundATexture ) { MGlobal.displayInfo(nodeFn.name + ": is not connected to a file texture"); } } return; }
public override void doIt(MArgList args) { MSelectionList list = new MSelectionList(); MArgDatabase argData; argData = new MArgDatabase(syntax, args); argData.getObjects(list); // Get the flags // bool allDagUsed = argData.isFlagSet(kAllDagFlag); bool parentAddedUsed = argData.isFlagSet(kParentAddedFlag); bool parentRemovedUsed = argData.isFlagSet(kParentRemovedFlag); bool childAddedUsed = argData.isFlagSet(kChildAddedFlag); bool childRemovedUsed = argData.isFlagSet(kChildRemovedFlag); bool childReorderedUsed = argData.isFlagSet(kChildReorderedFlag); bool helpUsed = argData.isFlagSet(kHelpFlag); bool nothingSet = (!allDagUsed && !parentAddedUsed && !parentRemovedUsed && !childAddedUsed && !childRemovedUsed && !childReorderedUsed && !helpUsed); if (nothingSet) { throw new ArgumentException("-A flag must be used. dagMessage -help for available flags.", "args"); } if (argData.isFlagSet(kHelpFlag)) { MGlobal.displayInfo("dagMessage -help"); MGlobal.displayInfo("\tdagMessage adds a callback to the selected nodes,"); MGlobal.displayInfo("\tor if no nodes are selected, to all nodes. The callback"); MGlobal.displayInfo("\tprints a message when called. When the plug-in is unloaded"); MGlobal.displayInfo("\tthe callbacks are removed."); MGlobal.displayInfo(""); MGlobal.displayInfo("\t-h -help : This message is printed"); MGlobal.displayInfo("\t-ad -allDag : parent changes and child reorders"); MGlobal.displayInfo("\t-pa -parentAdded : A parent is added"); MGlobal.displayInfo("\t-pr -parentRemoved : A parent is removed"); MGlobal.displayInfo("\t-ca -childAdded : A child is added (only for individual nodes)"); MGlobal.displayInfo("\t-cr -childRemoved : A child is removed (only for individual nodes)"); MGlobal.displayInfo("\t-cro -childReordered : A child is reordered"); MGlobal.displayInfo(""); } uint nObjs = list.length; if (nObjs == 0) { // Add the callback for all changes of the specified type. // if (allDagUsed) { try { MDagMessage.AllDagChangesEvent += userDAGGenericCB; } catch (Exception) { throw new ApplicationException("Could not add a -allDag callback"); } } if (parentAddedUsed) { addGenericCallback(null, MDagMessage.DagMessage.kParentAdded, " parent added "); } if (parentRemovedUsed) { addGenericCallback(null, MDagMessage.DagMessage.kParentRemoved, " parent removed "); } if (childAddedUsed) { throw new ArgumentException("-childAdded can only be used when a node is selected", "args"); } if (childRemovedUsed) { throw new ArgumentException("-childRemoved can only be used when a node is selected", "args"); } if (childReorderedUsed) { addGenericCallback(null, MDagMessage.DagMessage.kChildReordered, " child reordered "); } } else { for (uint i = 0; i < nObjs; i++) { MDagPath dagPath = new MDagPath(); list.getDagPath(i, dagPath); if (!dagPath.isValid) { continue; } // Add the callback for all changes of the specified type. // if (allDagUsed) { // we don't use obsolete function // addAllDagChangesCallback // use addAllDagChangesDagPathCallback instead try { dagPath.AllDagChangesDagPath += userDAGGenericCB; string infoStr = string.Format("Added a callback for all Dag changes on {0}", dagPath.fullPathName); MGlobal.displayInfo(infoStr); } catch (Exception) { throw new ApplicationException("Could not add a -allDag callback"); } } if (parentAddedUsed) { addGenericCallback(dagPath, MDagMessage.DagMessage.kParentAdded, " parent added "); } if (parentRemovedUsed) { addGenericCallback(dagPath, MDagMessage.DagMessage.kParentRemoved, " parent removed "); } if (childAddedUsed) { addGenericCallback(dagPath, MDagMessage.DagMessage.kChildAdded, " child added "); } if (childRemovedUsed) { addGenericCallback(dagPath, MDagMessage.DagMessage.kChildRemoved, " child removed "); } if (childReorderedUsed) { addGenericCallback(dagPath, MDagMessage.DagMessage.kChildReordered, " child reordered "); } } } return; }
public override void doIt(MArgList args) { // parse the command arguments // parseArgs(args); uint count = 0; // if the character flag was used, create the clip on the specified // character, otherwise, create a character // MFnCharacter fnCharacter = new MFnCharacter(); if (fCharacter.isNull) { MSelectionList activeList = new MSelectionList(); MGlobal.getActiveSelectionList(activeList); if (0 == activeList.length) { throw new ApplicationException("Empty Active Selection List."); } // create a character using the selection list // fCharacter = fnCharacter.create(activeList, MFnSet.Restriction.kNone); } else fnCharacter.setObject(fCharacter); // Get the array of members of the character. We will create a clip // for them. // MPlugArray plugs = new MPlugArray(); fnCharacter.getMemberPlugs(plugs); // Now create a animCurves to use as a clip for the character. // The curves will be set up between frames 0 and 10; // MTime start = new MTime(0.0); MTime duration = new MTime(10.0); MObjectArray clipCurves = new MObjectArray(); for (count = 0; count < plugs.length; ++count) { // Now create a bunch of animCurves to use as a clip for the // character // MFnAnimCurve fnCurve = new MFnAnimCurve(); MObject curve = fnCurve.create(MFnAnimCurve.AnimCurveType.kAnimCurveTL); // plugType); fnCurve.addKeyframe(start, 5.0); fnCurve.addKeyframe(duration, 15.0); clipCurves.append(curve); } // Create a source clip node and add the animation to it // MFnClip fnClipCreate = new MFnClip(); MObject sourceClip = fnClipCreate.createSourceClip(start, duration, fMod); fnCharacter.attachSourceToCharacter(sourceClip, fMod); for (count = 0; count < plugs.length; ++count) { MPlug animPlug = plugs[(int)count]; fnCharacter.addCurveToClip(clipCurves[(int)count], sourceClip, animPlug, fMod); } // instance the clip // MTime schedStart = new MTime(15.0); MObject instancedClip = fnClipCreate.createInstancedClip(sourceClip, schedStart, fMod); fnCharacter.attachInstanceToCharacter(instancedClip, fMod); // instance the clip a second time, at time 30 // schedStart.value = 30.0; MObject instancedClip2 = fnClipCreate.createInstancedClip(sourceClip, schedStart, fMod); fnCharacter.attachInstanceToCharacter(instancedClip2, fMod); return; }
public override void componentToPlugs(MObject component, MSelectionList list) // // Description // // Converts the given component values into a selection list of plugs. // This method is used to map components to attributes. // // Arguments // // component - the component to be translated to a plug/attribute // list - a list of plugs representing the passed in component // { if ( component.hasFn(MFn.Type.kSingleIndexedComponent) ) { MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent( component ); MObject thisNode = thisMObject(); MPlug plug = new MPlug( thisNode, mControlPoints ); // If this node is connected to a tweak node, reset the // plug to point at the tweak node. // convertToTweakNodePlug(plug); int len = fnVtxComp.elementCount; for ( int i = 0; i < len; i++ ) { plug.selectAncestorLogicalIndex((uint)fnVtxComp.element(i), plug.attribute); list.add(plug); } } }
// // Description // // Converts the given component values into a selection list of plugs. // This method is used to map components to attributes. // // Arguments // // component - the component to be translated to a plug/attribute // list - a list of plugs representing the passed in component // public override void componentToPlugs(MObject component, MSelectionList list) { if ( component.hasFn(MFn.Type.kSingleIndexedComponent) ) { MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent( component ); MObject thisNode = thisMObject(); MPlug plug = new MPlug( thisNode, mControlPoints ); // If this node is connected to a tweak node, reset the // plug to point at the tweak node. // convertToTweakNodePlug(plug); int len = fnVtxComp.elementCount; for ( int i = 0; i < len; i++ ) { plug.selectAncestorLogicalIndex((uint)fnVtxComp.element(i), plug.attribute); list.add(plug); } } }
public override MatchResult matchComponent(MSelectionList item, MAttributeSpecArray spec, MSelectionList list) // // Description: // // Component/attribute matching method. // This method validates component names and indices which are // specified as a string and adds the corresponding component // to the passed in selection list. // // For instance, select commands such as "select shape1.vtx[0:7]" // are validated with this method and the corresponding component // is added to the selection list. // // Arguments // // item - DAG selection item for the object being matched // spec - attribute specification object // list - list to add components to // // Returns // // the result of the match // { MatchResult result = MatchResult.kMatchOk; MAttributeSpec attrSpec = spec[0]; int dim = attrSpec.dimensions; // Look for attributes specifications of the form : // vtx[ index ] // vtx[ lower:upper ] // if ( (1 == spec.length) && (dim > 0) && (attrSpec.name == "vtx") ) { int numVertices = (int)meshGeom().vertices.length; MAttributeIndex attrIndex = attrSpec[0]; int upper = 0; int lower = 0; if ( attrIndex.hasLowerBound ) { attrIndex.getLower( out lower ); } if ( attrIndex.hasUpperBound ) { attrIndex.getUpper( out upper ); } // Check the attribute index range is valid // if ( (lower > upper) || (upper >= numVertices) ) { result = MatchResult.kMatchInvalidAttributeRange; } else { MDagPath path = new MDagPath(); item.getDagPath( 0, path ); MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent(); MObject vtxComp = fnVtxComp.create( MFn.Type.kMeshVertComponent ); for ( int i=lower; i<=upper; i++ ) { fnVtxComp.addElement( i ); } list.add( path, vtxComp ); } } else { // Pass this to the parent class return base.matchComponent( item, spec, list ); } return result; }
public bool importAim(string fileName, string flags) { MAnimCurveClipboard.theAPIClipboard.clear(); // If the selection list is empty, there is nothing to import. // MSelectionList sList = new MSelectionList(); MGlobal.getActiveSelectionList(sList); if (sList.isEmpty) { string msg = MStringResource.getString(RegisterMStringResources.kNothingSelected); MGlobal.displayError(msg); return false; } StreamReaderExt readExt = new StreamReaderExt(fileName); fReader.readClipboard(ref readExt, MAnimCurveClipboard.theAPIClipboard); if (MAnimCurveClipboard.theAPIClipboard.isEmpty) return false; string command = "pasteKey -cb api "; command += pasteFlags; try { int result = -1; MGlobal.executeCommand(command, out result, false, true); } catch (System.Exception) { string msg = MStringResource.getString(RegisterMStringResources.kPasteFailed); MGlobal.displayError(msg); return false; } readExt.Close(); return true; }
// get the DAG node MDagPath getDagNode(string node_name) { MSelectionList sl = new MSelectionList(); sl.add(node_name, true); MDagPath dp = new MDagPath(); sl.getDagPath(0, dp); return dp; }
//====================================================================== // // Check the parsed arguments and do/undo/redo the command as appropriate // void checkArgs(ref MArgDatabase argsDb) { //---------------------------------------- // -structure flag // fStructureFlag.parse(ref argsDb, flagStructure); if (fStructureFlag.isSet()) { if (!fStructureFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } string structureName = fStructureFlag.arg(); try { fStructure = Structure.structureByName(structureName); } catch (System.Exception) { string msgFmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataStructureNotFound); throw new ArgumentException(String.Format(msgFmt, structureName), "argsDb"); } } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // -streamName flag // fStreamNameFlag.parse(ref argsDb, flagStreamName); if (fStreamNameFlag.isSet()) { if (!fStreamNameFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } fStreamName = fStreamNameFlag.arg(); } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // -channelType flag // fChannelTypeFlag.parse(ref argsDb, flagChannelType); if (fChannelTypeFlag.isSet()) { if (!fChannelTypeFlag.isArgValid()) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kInvalidString); throw new ArgumentException(errMsg, "argsDb"); } fChannelType = fChannelTypeFlag.arg(); } else { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataNoStructureName); throw new ArgumentException(errMsg, "argsDb"); } //---------------------------------------- // (selection list) // // Commands need at least one node on which to operate so gather up // the list of nodes specified and/or selected. // // Empty out the list of nodes on which to operate so that it can be // populated from the selection or specified lists. fNodes.clear(); MSelectionList objects = new MSelectionList(); argsDb.getObjects(objects); for (uint i = 0; i < objects.length; ++i) { MDagPath dagPath = new MDagPath(); objects.getDagPath((uint)i, dagPath); MFnDagNode dagNode = new MFnDagNode(dagPath.node); MObject obj = dagNode.child(0); if (obj.apiTypeStr == "kMesh") { if (obj == MObject.kNullObj) { throw new ApplicationException("Error: objects.getDependNode() "); } fNodes.append(dagPath.node); } else { String fmt = MStringResource.getString(MetaDataRegisterMStringResources.kObjectTypeError); String msg = String.Format(fmt, dagPath.fullPathName + "[" + obj.apiTypeStr + "]"); displayError(msg); throw new System.InvalidOperationException(msg); } } if (fNodes.length == 0) { string errMsg = MStringResource.getString(MetaDataRegisterMStringResources.kObjectNotFoundError); throw new ArgumentException(errMsg, "argsDb"); } }
// get the dependency node MObject getDependNode(string node_name) { MSelectionList sl = new MSelectionList(); sl.add(node_name, true); MObject o = new MObject(); sl.getDependNode(0, o); return o; }
// // Description: // // Vertex selection. // // Arguments: // // selectInfo - the selection state information // selectionList - the list of selected items to add to // worldSpaceSelectPts - // public bool selectVertices( MSelectInfo selectInfo, MSelectionList selectionList, MPointArray worldSpaceSelectPts) { bool selected = false; M3dView view = selectInfo.view; MPoint xformedPoint = new MPoint(); MPoint selectionPoint = new MPoint(); double z = 0.0; double previousZ = 0.0; int closestPointVertexIndex = -1; MDagPath path = selectInfo.multiPath; // Create a component that will store the selected vertices // MFnSingleIndexedComponent fnComponent = new MFnSingleIndexedComponent(); MObject surfaceComponent = fnComponent.create( MFn.Type.kMeshVertComponent ); uint vertexIndex; // if the user did a single mouse click and we find > 1 selection // we will use the alignmentMatrix to find out which is the closest // MMatrix alignmentMatrix = new MMatrix(); MPoint singlePoint = new MPoint(); bool singleSelection = selectInfo.singleSelection; if( singleSelection ) { alignmentMatrix = selectInfo.alignmentMatrix; } // Get the geometry information // apiMesh meshNode = (apiMesh)surfaceShape; apiMeshGeom geom = meshNode.meshGeom(); // Loop through all vertices of the mesh and // see if they lie withing the selection area // uint numVertices = geom.vertices.length; for ( vertexIndex=0; vertexIndex<numVertices; vertexIndex++ ) { MPoint currentPoint = geom.vertices[ (int)vertexIndex ]; // Sets OpenGL's render mode to select and stores // selected items in a pick buffer // view.beginSelect(); OpenGL.glBegin(OpenGL.GL_POINTS); OpenGL.glVertex3f((float)currentPoint[0], (float)currentPoint[1], (float)currentPoint[2] ); OpenGL.glEnd(); if ( view.endSelect() > 0 ) // Hit count > 0 { selected = true; if ( singleSelection ) { xformedPoint = currentPoint; xformedPoint.homogenize(); xformedPoint.multiplyEqual( alignmentMatrix ); z = xformedPoint.z; if ( closestPointVertexIndex < 0 || z > previousZ ) { closestPointVertexIndex = (int)vertexIndex; singlePoint = currentPoint; previousZ = z; } } else { // multiple selection, store all elements // fnComponent.addElement( (int)vertexIndex ); } } } // If single selection, insert the closest point into the array // if ( selected && selectInfo.singleSelection ) { fnComponent.addElement(closestPointVertexIndex); // need to get world space position for this vertex // selectionPoint = singlePoint; selectionPoint.multiplyEqual( path.inclusiveMatrix ); } // Add the selected component to the selection list // if ( selected ) { MSelectionList selectionItem = new MSelectionList(); selectionItem.add( path, surfaceComponent ); MSelectionMask mask = new MSelectionMask( MSelectionMask.SelectionType.kSelectComponentsMask ); selectInfo.addSelection( selectionItem, selectionPoint, selectionList, worldSpaceSelectPts, mask, true ); } return selected; }
// // Description: // // Main selection routine // // Arguments: // // selectInfo - the selection state information // selectionList - the list of selected items to add to // worldSpaceSelectPts - // // Main selection routine // public override bool select(MSelectInfo selectInfo, MSelectionList selectionList, MPointArray worldSpaceSelectPts) { bool selected = false; bool componentSelected = false; bool hilited = false; hilited = (selectInfo.displayStatus == M3dView.DisplayStatus.kHilite); if ( hilited ) { componentSelected = selectVertices( selectInfo, selectionList, worldSpaceSelectPts ); selected = selected || componentSelected; } if ( !selected ) { apiMesh meshNode = (apiMesh)surfaceShape; // NOTE: If the geometry has an intersect routine it should // be called here with the selection ray to determine if the // the object was selected. selected = true; MSelectionMask priorityMask = new MSelectionMask( MSelectionMask.SelectionType.kSelectNurbsSurfaces ); MSelectionList item = new MSelectionList(); item.add( selectInfo.selectPath ); MPoint xformedPt = new MPoint(); if ( selectInfo.singleSelection ) { MPoint center = meshNode.boundingBox().center; xformedPt = center; xformedPt.multiplyEqual( selectInfo.selectPath.inclusiveMatrix ); } selectInfo.addSelection( item, xformedPt, selectionList, worldSpaceSelectPts, priorityMask, false ); } return selected; }
// // Description: // // Component/attribute matching method. // This method validates component names and indices which are // specified as a string and adds the corresponding component // to the passed in selection list. // // For instance, select commands such as "select shape1.vtx[0:7]" // are validated with this method and the corresponding component // is added to the selection list. // // Arguments // // item - DAG selection item for the object being matched // spec - attribute specification object // list - list to add components to // // Returns // // the result of the match // public override MatchResult matchComponent(MSelectionList item, MAttributeSpecArray spec, MSelectionList list) { MatchResult result = MatchResult.kMatchOk; MAttributeSpec attrSpec = spec[0]; int dim = attrSpec.dimensions; // Look for attributes specifications of the form : // vtx[ index ] // vtx[ lower:upper ] // if ( (1 == spec.length) && (dim > 0) && (attrSpec.name == "vtx") ) { int numVertices = (int)meshGeom().vertices.length; MAttributeIndex attrIndex = attrSpec[0]; int upper = 0; int lower = 0; if ( attrIndex.hasLowerBound ) { attrIndex.getLower( out lower ); } if ( attrIndex.hasUpperBound ) { attrIndex.getUpper( out upper ); } // Check the attribute index range is valid // if ( (lower > upper) || (upper >= numVertices) ) { result = MatchResult.kMatchInvalidAttributeRange; } else { MDagPath path = new MDagPath(); item.getDagPath( 0, path ); MFnSingleIndexedComponent fnVtxComp = new MFnSingleIndexedComponent(); MObject vtxComp = fnVtxComp.create( MFn.Type.kMeshVertComponent ); for ( int i=lower; i<=upper; i++ ) { fnVtxComp.addElement( i ); } list.add( path, vtxComp ); } } else { // Pass this to the parent class return base.matchComponent( item, spec, list ); } return result; }
/* override */ public override bool select(MSelectInfo selectInfo, MSelectionList selectionList, MPointArray worldSpaceSelectPts) // // Select function. Gets called when the bbox for the object is selected. // This function just selects the object without doing any intersection tests. // { MSelectionMask priorityMask = new MSelectionMask(MSelectionMask.SelectionType.kSelectObjectsMask); MSelectionList item = new MSelectionList(); item.add(selectInfo.selectPath); MPoint xformedPt = new MPoint(); selectInfo.addSelection(item, xformedPt, selectionList, worldSpaceSelectPts, priorityMask, false); return true; }