示例#1
0
        public override void doIt(MArgList args)
        {
            // Draw a circle and get its dagPath
	        // using an iterator
	        MGlobal.executeCommand("circle");
	        MFnNurbsCurve circle = new MFnNurbsCurve();

            MDagPath dagPath = new MDagPath();
	        MItDependencyNodes iter = new MItDependencyNodes( MFn.Type.kNurbsCurve);

            for (iter.reset(); !iter.isDone; iter.next())
            {
                MObject item = iter.item;
                if (item.hasFn(MFn.Type.kNurbsCurve))
                {
                    circle.setObject(item);
                    circle.getPath(dagPath);
                    MGlobal.displayInfo("DAG_PATH is " + dagPath.fullPathName);

                    if (dagPath.isValid)
                    {
                        // register callback for instance add AND remove
                        //
                        dagPath.InstanceAddedDagPath += userDAGChildAddedCB;
                        dagPath.InstanceRemovedDagPath += userDAGChildRemovedCB;

                        // C# SDK will cleanup events, when this plugin is unloaded
                        // callbacks.append(node);

                        MGlobal.displayInfo("CALLBACK ADDED FOR INSTANCE ADD/REMOVE");
                    }
                }
            }
        }
        public static Object SpecializeObject(MDagPath inObj)
        {
            if (inObj != null)
            {
                switch (inObj.node.apiTypeStr)
                {
                    case "kMesh":
                        return new MFnMesh(inObj);

                    case "kNurbsSurface":
                        return new MFnNurbsSurface(inObj);

                    case "kNurbsCurve":
                        return new MFnNurbsCurve(inObj);

                    case "kTransform":
                        return new MFnTransform(inObj);

                    case "kCamera":
                        return new MFnCamera(inObj);

                    case "kSubdiv":
                        return new MFnSubd(inObj);
                }
            }

            return null;
        }
		//======================================================================
		//
		// 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");
			}
		}
示例#4
0
        private void userDAGInstanceRemovedCB(object sender, MParentChildFunctionArgs arg)
        {
            MDagPath child  = arg.child;
            MDagPath parent = arg.parent;
            string   dagStr = userDAGCBHelper("DAG Changed - Unknown Type: ", child, parent);

            MGlobal.displayInfo(dagStr);
        }
示例#5
0
        public static MDagPath Duplicate(MDagPath targetDag)
        {
            string resultName = MGlobal.executePythonCommandStringResult(string.Format("cmds.duplicate(\"{0}\",rr = 1)", targetDag.fullPathName), true);

            Debug.Log("duplicate result:" + resultName);
            resultName = SubUShell(resultName);
            return(GetDagPathByName(resultName));
        }
示例#6
0
 public DMMesh(MDagPath dagPath, MSpace.Space mspace = MSpace.Space.kWorld)
 {
     DagPath = dagPath;
     AddEvents(dagPath);
     DagNode = new MFnDagNode(dagPath);
     dagName = DagPath.partialPathName;
     space   = mspace.ToString();
 }
示例#7
0
 public DMSurface(MDagPath dagPath, string mspace)
     : base(dagPath, mspace)
 {
     // MayaMesh = new MFnMesh(dagPath);
     DagShape = dagPath;
     AddEvents(dagPath);
     DagNode = new MFnDagNode(dagPath);
 }
示例#8
0
        internal static Surface mNurbsSurfaceToDynamoSurfaceFromName(string dagName, string space)
        {
            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            return(mNurbsSurfaceToDynamoSurfaceFromDag(dagPath, mspace));
        }
示例#9
0
        private void userDAGChildReorderedCB(object sender, MParentChildFunctionArgs arg)
        {
            MDagPath child  = arg.child;
            MDagPath parent = arg.parent;
            string   dagStr = userDAGCBHelper("DAG Changed - Child Reordered: ", child, parent);

            MGlobal.displayInfo(dagStr);
        }
示例#10
0
        //======================================================================
        //
        // 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);
            }
        }
示例#11
0
        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);
            //}
        }
示例#12
0
        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);
        }
示例#13
0
        internal static Mesh MTDMeshFromName(string dagName, string space)
        {
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);


            return(MTDMeshFromDag(dagPath, mspace));
        }
示例#14
0
        public static List <MFnTransform> GetHierachyAllTrans(MDagPath startDag, MFn.Type filterType = MFn.Type.kInvalid)
        {
            MFnTransform currentTrans = new MFnTransform(startDag);
            //no need for trans data , so mfntransform(mobject) is used
            List <MFnTransform> result = new List <MFnTransform>();

            AddChildrenToList(result, currentTrans, filterType);

            return(result);
        }
示例#15
0
 public static void PrintDags(MSelectionList list)
 {
     for (int i = 0; i < list.length; i++)
     {
         uint     index = (uint)i;
         MDagPath mdp   = new MDagPath();
         list.getDagPath(index, mdp);
         Debug.Log(index + ":" + mdp.fullPathName);
     }
 }
示例#16
0
        // 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);
        }
示例#17
0
 public static MDagPath AddParentCircle(MObject targetObject, bool createParallelGrp)
 {
     if (targetObject.hasFn(MFn.Type.kTransform))
     {
         return(AddParentCircle(MDagPath.getAPathTo(targetObject), createParallelGrp));
     }
     else
     {
         return(null);
     }
 }
示例#18
0
 public static bool SetJointLimit(MObject mobject, JointType jointType)
 {
     if (mobject.hasFn(MFn.Type.kTransform))
     {
         return(SetJointLimit(new MFnTransform(MDagPath.getAPathTo(mobject)), jointType));
     }
     else
     {
         return(false);
     }
 }
示例#19
0
        //======================================================================
        //
        // 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);
            }
        }
示例#20
0
        double twistFromHandle(MDagPath handlePath)
        // This method returns the twist of the IK handle.
        //
        {
            MFnIkHandle handleFn   = new MFnIkHandle(handlePath);
            MPlug       twistPlug  = handleFn.findPlug("twist");
            double      twistValue = 0.0;

            twistPlug.getValue(twistValue);
            return(twistValue);
        }
示例#21
0
        public static MDagPath DuplicateMesh(MDagPath targetDag)
        {
            if (targetDag == null)
            {
                return(null);
            }
            MFnMesh newMesh = new MFnMesh();

            targetDag.extendToShape();
            return(MDagPath.getAPathTo(newMesh.copy(targetDag.node)));
        }
示例#22
0
        public static void BeautifulPole(MDagPath middleDag = null, bool clearFlag_x = true, bool clearFlag_y = true, bool clearFlag_z = true, bool useMoveSkinJointsTool = true)
        {
            if (middleDag == null || middleDag.node.isNull)
            {
                middleDag = BasicFunc.GetSelectedDagPath(0);
                if (middleDag == null || middleDag.node.isNull)
                {
                    Debug.Log("please select middle joint");
                    return;
                }
            }

            MFnTransform middleTrans = new MFnTransform(middleDag);

            if (middleTrans.parentCount == 0 || middleTrans.childCount == 0)
            {
                return;
            }
            MDagPath     parentDag      = MDagPath.getAPathTo(middleTrans.parent(0));
            MDagPath     childDag       = MDagPath.getAPathTo(middleTrans.child(0));
            MFnTransform parentTrans    = new MFnTransform(parentDag);
            MFnTransform childTrans     = new MFnTransform(childDag);
            MVector      parentWorldPos = parentTrans.getTranslation(MSpace.Space.kWorld);
            MVector      middleWorldPos = middleTrans.getTranslation(MSpace.Space.kWorld);
            MVector      childWorldPos  = childTrans.getTranslation(MSpace.Space.kWorld);
            //MVector vec_middleToParent = parentWorldPos - middleWorldPos;
            //MVector vec_childToMiddle = middleWorldPos - childWorldPos;
            //MVector verticalBack = BasicFunc.Cross(vec_middleToParent, vec_childToMiddle);

            float   length0     = (float)(middleWorldPos - parentWorldPos).length;
            float   length1     = (float)(middleWorldPos - childWorldPos).length;
            MVector posByWeight = BasicFunc.Lerp(parentWorldPos, childWorldPos, length0 / (length0 + length1));

            if (useMoveSkinJointsTool)
            {
                MoveSkinJointsTool(middleDag);
            }
            //middleTrans.setTranslation(posByWeight, MSpace.Space.kWorld);
            if (!clearFlag_x)
            {
                posByWeight.x = middleWorldPos.x;
            }
            if (!clearFlag_y)
            {
                posByWeight.y = middleWorldPos.y;
            }
            if (!clearFlag_z)
            {
                posByWeight.z = middleWorldPos.z;
            }
            middleTrans.setTranslation(posByWeight, MSpace.Space.kWorld);
            childTrans.setTranslation(childWorldPos, MSpace.Space.kWorld);
            //MFnIkJoint middleJoint = new MFnIkJoint(middleDag);
        }
示例#23
0
 public static MDagPath AddChildCircle(MObject targetObject)
 {
     if (targetObject.hasFn(MFn.Type.kTransform))
     {
         return(AddChildCircle(MDagPath.getAPathTo(targetObject)));
     }
     else
     {
         return(null);
     }
 }
示例#24
0
        public static MDagPath GetDagPathByName(string name, int index = 0)
        {
            MSelectionList matched  = GetObjectsByName(name);
            MDagPath       mDagPath = new MDagPath();

            if (index < matched.length)
            {
                matched.getDagPath((uint)index, mDagPath);
            }
            return(mDagPath);
        }
示例#25
0
        public static string[] AddIKHandle(MDagPath startJointDagPath, MDagPath endJointDagPath, IKSolverType solverType = IKSolverType.RotatePlane, string curveName = "")
        {
            //string typeStr = "";
            string resultStr = "";

            CmdStrConstructor csc = new CmdStrConstructor("ikHandle", CmdStrConstructor.CmdType.Python);

            csc.UpdateParm("sj", startJointDagPath.fullPathName);
            csc.UpdateParm("ee", endJointDagPath.fullPathName);

            string ikMainName = startJointDagPath.partialPathName + "_" + endJointDagPath.partialPathName;

            switch (solverType)
            {
            case IKSolverType.SingleChain:
            {
                csc.UpdateParm("sol", "ikSCsolver");
                csc.UpdateParm("n", "ik_" + ikMainName);
                string excuteStr = csc.ToString();
                resultStr = MGlobal.executePythonCommandStringResult(excuteStr);
                //typeStr = "ikSCsolver";
                //resultStr = MGlobal.executePythonCommandStringResult("cmds.ikHandle(sj='" + startJointDagPath.fullPathName + "',ee='" + endJointDagPath.fullPathName + "',sol='" + typeStr + "',n='ik_" + ikMainName + "')");
                break;
            }

            case IKSolverType.RotatePlane:
            {
                csc.UpdateParm("sol", "ikRPsolver");
                csc.UpdateParm("n", "ik_" + ikMainName);
                string excuteStr = csc.ToString();
                resultStr = MGlobal.executePythonCommandStringResult(excuteStr);
                //typeStr = "ikRPsolver";
                //resultStr = MGlobal.executePythonCommandStringResult("cmds.ikHandle(sj='" + startJointDagPath.fullPathName + "',ee='" + endJointDagPath.fullPathName + "',sol='" + typeStr + "',n='ik_" + ikMainName + "')");
                break;
            }

            case IKSolverType.Spline:
            {
                csc.UpdateParm("sol", "ikSplineSolver");
                csc.UpdateParm("n", "ik_" + ikMainName);
                csc.UpdateParm("ccv", curveName == null || curveName.Length == 0);
                csc.UpdateParm("c", curveName);
                csc.UpdateParm("pcv", false);
                string excuteStr = csc.ToString();
                resultStr = MGlobal.executePythonCommandStringResult(excuteStr);
                //resultStr = MGlobal.executePythonCommandStringResult("cmds.ikHandle(sj='" + startJointDagPath.fullPathName + "',ee='" + endJointDagPath.fullPathName + "',sol='" + typeStr + "',c='" + curveName + "',n='ik_" + ikMainName + "')",true);
                break;
            }
            }
            //[u'ik_joint1_joint4', u'effector1']
            string[] resultArr = BasicFunc.SplitPythonResultStr(resultStr);

            return(resultArr);
        }
示例#26
0
        public static MFnMesh GetMayaMesh(string dagName, string space)
        {
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);

            MFnMesh mayaMesh = new MFnMesh(dagPath);

            return(mayaMesh);
        }
示例#27
0
        internal static MDagPath GetObjectDagPath(MObject Object)
        {
            var SelectionList = new MSelectionList();

            SelectionList.add(new MFnDagNode(Object).fullPathName);

            var Result = new MDagPath();

            SelectionList.getDagPath(0, Result);

            return(Result);
        }
示例#28
0
        public static void BindBodySplineIK(MSelectionList jointList = null)
        {
            if (jointList == null)
            {
                jointList = BasicFunc.GetSelectedList();
            }
            //check if all of selected objects are joint
            int count = (int)jointList.length;

            if (count < 2)
            {
                return;
            }
            MDagPath dag_breastJoint = new MDagPath(), dag_hipJoint = new MDagPath();

            for (int i = 0; i < count; i++)
            {
                MDagPath jtDagPath = new MDagPath();
                jointList.getDagPath((uint)i, jtDagPath);
                if (jtDagPath != null)
                {
                    if (!jtDagPath.hasFn(MFn.Type.kJoint))
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            jointList.getDagPath((uint)(count - 1), dag_breastJoint);
            jointList.getDagPath(0, dag_hipJoint);

            MFnIkJoint     breastJoint       = new MFnIkJoint(dag_breastJoint);
            MFnIkJoint     hipJoint          = new MFnIkJoint(dag_hipJoint);
            MDagPath       dag_curve         = JointProcess.CreateJointsCurve(jointList);
            MDagPath       dag_jtctl_breast  = JointProcess.CreateJoint(breastJoint, "jtctl_breast");
            MDagPath       dag_jtctl_hip     = JointProcess.CreateJoint(hipJoint, "jtctl_hip");
            MSelectionList bindSelectionList = new MSelectionList();

            bindSelectionList.add(dag_curve);
            bindSelectionList.add(dag_jtctl_breast);
            bindSelectionList.add(dag_jtctl_hip);
            BasicFunc.Select(bindSelectionList);

            MGlobal.executeCommand("SmoothBindSkin");
            string   ikName = JointProcess.AddIKHandle(dag_hipJoint, dag_breastJoint, JointProcess.IKSolverType.Spline, dag_curve.fullPathName)[0];
            MDagPath dag_ik = BasicFunc.GetDagPathByName(ikName);

            BasicFunc.ConnectAttr(dag_jtctl_breast.fullPathName + ".rotate.rotateY", dag_ik.fullPathName + ".twist", true, true);
        }
示例#29
0
        public static MDagPath CreateLocator(MVector worldPos, string locatorName)
        {
            string cmdStr = "cmds.spaceLocator(n='" + locatorName + "')";

            locatorName = SubUShell(MGlobal.executePythonCommandStringResult(cmdStr));
            MDagPath     locDagPath   = BasicFunc.GetDagPathByName(locatorName);
            MFnTransform locatorTrans = new MFnTransform(locDagPath);

            //Debug.Log(locatorName+"dag:"+locDagPath.fullPathName);
            locatorTrans.setTranslation(worldPos, MSpace.Space.kWorld);
            return(locDagPath);
        }
示例#30
0
        public static MFnNurbsSurface GetMayaObject(string dagName, string space)
        {
            MDagPath dagPath = DMInterop.getDagNode(dagName);

            MSpace.Space mspace = MSpace.Space.kWorld;
            Enum.TryParse(space, out mspace);

            MFnNurbsSurface mayaObject = new MFnNurbsSurface(dagPath);


            return(mayaObject);
        }
示例#31
0
        public void Create()
        {
            MItDag jointIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kJoint);

            //Create Joints and collect their DAG Paths
            short jointID = 0;

            for (; !jointIterator.isDone; jointIterator.next())
            {
                MFnIkJoint ikJoint      = new MFnIkJoint();
                MDagPath   jointDagPath = new MDagPath();

                jointIterator.getPath(jointDagPath);
                this.JointDagPaths.Add(jointDagPath);
                ikJoint.setObject(jointDagPath);

                MTransformationMatrix local         = new MTransformationMatrix(ikJoint.transformationMatrix);
                MTransformationMatrix inverseGlobal = new MTransformationMatrix(jointDagPath.inclusiveMatrixInverse);

                this.Joints.Add(new SKLJoint(jointID, ikJoint.name, local, inverseGlobal));
                this.JointIndices.Add(ELF.Hash(ikJoint.name), jointID);
                jointID++;
            }

            //Set Joint parents
            for (int i = 0; i < this.Joints.Count; i++)
            {
                MFnIkJoint ikJoint = new MFnIkJoint(this.JointDagPaths[i]);
                if (ikJoint.parentCount == 1 && ikJoint.parent(0).apiType == MFn.Type.kJoint)
                {
                    MFnIkJoint parentJoint   = new MFnIkJoint(ikJoint.parent(0));
                    MDagPath   parentDagPath = new MDagPath();

                    parentJoint.getPath(parentDagPath);

                    //Find index of parent
                    for (int j = 0; j < this.JointDagPaths.Count; j++)
                    {
                        if (parentDagPath.equalEqual(this.JointDagPaths[j]))
                        {
                            this.Joints[i].ParentID = (short)j;
                        }
                    }
                }
                else
                {
                    this.Joints[i].ParentID = -1;
                }
            }

            MGlobal.displayInfo("SKLFile:Create - Created SKL File");
        }
示例#32
0
        public static List <object> MelCommand(string MelCommand)
        {
            MStringArray   stringResults = new MStringArray();
            MIntArray      intResults    = new MIntArray();
            MDoubleArray   doubleResults = new MDoubleArray();
            MVectorArray   vectorResults = new MVectorArray();
            List <object>  results       = new List <object>();
            MCommandResult mcr           = new MCommandResult();


            MDagPath dag = new MDagPath();

            try
            {
                MGlobal.executeCommand(MelCommand, mcr);
                //   MGlobal.executeCommand(MelCommand, stringResults);
            }
            catch (MemberAccessException e)
            {
                MGlobal.displayWarning(e.Message);
            }

            switch (mcr.resultType)
            {
            case MCommandResult.Type.kStringArray:
                mcr.getResult(stringResults);
                results.AddRange(stringResults);
                break;

            case MCommandResult.Type.kIntArray:
                mcr.getResult(intResults);
                results.AddRange(intResults.Cast <object>());
                break;

            case MCommandResult.Type.kDoubleArray:
                mcr.getResult(doubleResults);
                results.AddRange(doubleResults.Cast <object>());
                break;

            case MCommandResult.Type.kVectorArray:
                mcr.getResult(vectorResults);
                results.AddRange(vectorResults.Cast <object>());
                break;

            default:
                mcr.getResult(stringResults);
                results.AddRange(stringResults);
                break;
            }
            mcr.Dispose();
            return(results);
        }
示例#33
0
        /// <summary>
        /// Extract the vertices, normals and triangles of a mesh into the M2 collision data fields.
        /// </summary>
        /// <param name="wowModel"></param>
        private static void InjectCollisionMesh(M2 wowModel)
        {
            var collisionFound = false;

            for (var meshIter = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kMesh);
                 !meshIter.isDone; meshIter.next())
            {
                var meshPath = new MDagPath();
                meshIter.getPath(meshPath);

                var meshFn = new MFnMesh(meshPath);
                // only want non-history items
                if (meshFn.isIntermediateObject)
                {
                    continue;
                }
                var name = meshFn.name;
                if (name != "Collision")
                {
                    continue;                     //TODO use custom attribute
                }
                if (collisionFound)
                {
                    throw new Exception("More than one collision box has been found. One supported.");
                }
                MGlobal.displayInfo("\t Collision mesh detected.");

                wowModel.CollisionBox = new CAaBox(AxisInvert(meshFn.boundingBox.min),
                                                   AxisInvert(meshFn.boundingBox.max));
                wowModel.CollisionSphereRadius =
                    (float)Math.Max(meshFn.boundingBox.depth / 2, meshFn.boundingBox.width / 2);

                //TODO fixme better iterate through faces
                var collisionPoints = new MFloatPointArray();
                meshFn.getPoints(collisionPoints, MSpace.Space.kWorld);
                var collisionNormals = new MFloatVectorArray();
                meshFn.getNormals(collisionNormals, MSpace.Space.kWorld);
                var collisionTriangles = new MIntArray();
                meshFn.getTriangles(new MIntArray(), collisionTriangles);
                for (var i = 0; i < collisionPoints.Count; i++)
                {
                    wowModel.CollisionVertices.Add(AxisInvert(collisionPoints[i]));
                    wowModel.CollisionNormals.Add(AxisInvert(collisionNormals[i]));
                }
                foreach (var vertIndex in collisionTriangles)
                {
                    wowModel.CollisionTriangles.Add((ushort)vertIndex);
                }

                collisionFound = true;
            }
        }
示例#34
0
        public static MDagPath GetSelectedDagPath(int index)
        {
            MSelectionList selected = new MSelectionList();

            MGlobal.getActiveSelectionList(selected);
            MDagPath dagPath = new MDagPath();

            if (index < selected.length)
            {
                selected.getDagPath((uint)index, dagPath);
            }
            return(dagPath);
        }
        //======================================================================
		//
		// 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");
			}
		}
示例#36
0
		protected void initTests(MPx3dModelView view)
		{
			MGlobal.displayInfo("exampleCameraSetViewCmd::initTests");

			clearResults(view);

			//	Add every camera into the scene. Don't change the main camera,
			//	it is OK that it gets reused.
			//
			MFnCameraSet cstFn = new MFnCameraSet();
			MObject cstObj = cstFn.create();
			MDagPath cameraPath = null;
			
			MItDag dagIterator = new MItDag(MItDag.TraversalType.kDepthFirst, MFn.Type.kCamera);
			for (; !dagIterator.isDone; dagIterator.next())
			{
				cameraPath = new MDagPath();

				MFnCamera camera;

				try
				{
					dagIterator.getPath(cameraPath);
					camera = new MFnCamera(cameraPath);
				}
				catch (Exception)
				{
					continue;
				}

				fCameraList.append(cameraPath);

				cstFn.appendLayer(cameraPath, MObject.kNullObj);

				MGlobal.displayInfo(camera.fullPathName());
			}

			view.setCameraSet(cstObj);
			view.refresh();
		}
示例#37
0
        public override bool filterNode( MDagPath traversalItem )
        {
            bool prune = false;
            if( traversalItem.childCount == 0 )
            {
                switch( Filter )
                {
                case TraversalFilter.kMeshes:
                    {
                        if( !hasMeshes(traversalItem) )
                        {
                            prune = true;
                        }
                        break;
                    }

                case TraversalFilter.kLights:
                    {
                        if( !hasLights(traversalItem) )
                        {
                            prune = true;
                        }
                        break;
                    }

                case TraversalFilter.kAll:
                    {
                        if( !hasMeshes(traversalItem) && !hasLights(traversalItem) )
                        {
                            prune = true;
                        }
                        break;
                    }
                }
            }
            return prune;
        }
示例#38
0
		//
		// Write out a 'parent' command to parent one DAG node under another.
		//
		protected void writeParent(
				FileStream f, MDagPath parent, MDagPath child, bool addIt
		)
		{
			string result = "";
			result += "parent -s -nc -r ";
 
			//
			// If this is not the first parent then we have to include the "-a/add"
			// flag.
			//
			if (addIt) 
				result += "-a ";

			//
			// If the parent is the world, then we must include the "-w/world" flag.
			//
			if (parent.length == 0) 
				result += "-w ";

			result += ("\"" + child.partialPathName + "\"");

			//
			// If the parent is NOT the world, then give the parent's name.
			//
			if (parent.length != 0)
				result += (" \"" + parent.partialPathName + "\"");

			result +=  (";" + "\n");

			writeString(f, result);
		}
 // The implementation here is a bit different from its counterpart C++ sample because
 // .NET SDK decides not to support the obsolete C++ API:
 //
 // bool connectTargetAttribute (void *opaqueTarget, int index, MObject &constraintAttr);
 //
 protected override bool connectTarget( MDagPath targetPath, int index )
 {
     try
     {
         MObject targetObject = new MObject(targetPath.node);
         MFnDagNode targetDagNode = new MFnDagNode(targetObject);
         connectTargetAttribute(targetPath, index, targetDagNode.attribute("worldMesh"),
             GeometrySurfaceConstraint.targetGeometry);
     }
     catch (Exception)
     {
         MGlobal.displayError("Failed to connect target.");
         return false;
     }
     return true;
 }
示例#40
0
		protected void writeDagNodes(FileStream f)
		{
			fParentingRequired.clear();

			MItDag	dagIter = new MItDag();

			dagIter.traverseUnderWorld(true);

			MDagPath worldPath = new MDagPath();

			dagIter.getPath(worldPath);

			//
			// We step over the world node before starting the loop, because it
			// doesn't get written out.
			//
			for (dagIter.next(); !dagIter.isDone; dagIter.next())
			{
				MDagPath	path = new MDagPath();
				dagIter.getPath(path);

				//
				// If the node has already been written, then all of its descendants
				// must have been written, or at least checked, as well, so prune
				// this branch of the tree from the iteration.
				//
				MFnDagNode	dagNodeFn = new MFnDagNode(path);

				if (dagNodeFn.isFlagSet(fCreateFlag))
				{
					dagIter.prune();
					continue;
				}

				//
				// If this is a default node, it will be written out later, so skip
				// it.
				//
				if (dagNodeFn.isDefaultNode) continue;

				//
				// If this node is not writable, and is not a shared node, then mark
				// it as having been written, and skip it.
				//
				if (!dagNodeFn.canBeWritten && !dagNodeFn.isShared)
				{
					dagNodeFn.setFlag(fCreateFlag, true);
					continue;
				}

				uint numParents = dagNodeFn.parentCount;

				if (dagNodeFn.isFromReferencedFile)
				{
					//
					// We don't issue 'creatNode' commands for nodes from referenced
					// files, but if the node has any parents which are not from
					// referenced files, other than the world, then make a note that
					// we'll need to issue extra 'parent' commands for it later on.
					//
					uint i;

					for (i = 0; i < numParents; i++)
					{
						MObject		altParent = dagNodeFn.parent(i);
						MFnDagNode	altParentFn = new MFnDagNode(altParent);

						if (!altParentFn.isFromReferencedFile
						&&	(altParentFn.objectProperty.notEqual(worldPath.node)))
						{
							fParentingRequired.append(path);
							break;
						}
					}
				}
				else
				{
					//
					// Find the node's parent.
					//
					MDagPath parentPath = new MDagPath(worldPath);

					if (path.length > 1)
					{
						//
						// Get the parent's path.
						//
						parentPath.assign(path);
						parentPath.pop();

						//
						// If the parent is in the underworld, then find the closest
						// ancestor which is not.
						//
						if (parentPath.pathCount > 1)
						{
							//
							// The first segment of the path contains whatever
							// portion of the path exists in the world.  So the closest
							// worldly ancestor is simply the one at the end of that
							// first path segment.
							//
							path.getPath(parentPath, 0);
						}
					}

					MFnDagNode	parentNodeFn = new MFnDagNode(parentPath);

					if (parentNodeFn.isFromReferencedFile)
					{
						//
						// We prefer to parent to a non-referenced node.  So if this
						// node has any other parents, which are not from referenced
						// files and have not already been processed, then we'll
						// skip this instance and wait for an instance through one
						// of those parents.
						//
						uint i;

						for (i = 0; i < numParents; i++)
						{
							if (dagNodeFn.parent(i).notEqual(parentNodeFn.objectProperty))
							{
								MObject		altParent = dagNodeFn.parent(i);
								MFnDagNode	altParentFn = new MFnDagNode(altParent);

								if (!altParentFn.isFromReferencedFile
								&&	!altParentFn.isFlagSet(fCreateFlag))
								{
									break;
								}
							}
						}

						if (i < numParents) continue;

						//
						// This node only has parents within referenced files, so
						// create it without a parent and note that we need to issue
						// 'parent' commands for it later on.
						//
						writeCreateNode(f, path, worldPath);

						fParentingRequired.append(path);
					}
					else
					{
						writeCreateNode(f, path, parentPath);

						//
						// Let's see if this node has any parents from referenced
						// files, or any parents other than this one which are not
						// from referenced files.
						//
						uint i;
						bool hasRefParents = false;
						bool hasOtherNonRefParents = false;

						for (i = 0; i < numParents; i++)
						{
							if (dagNodeFn.parent(i).notEqual(parentNodeFn.objectProperty))
							{
								MObject		altParent = dagNodeFn.parent(i);
								MFnDagNode	altParentFn = new MFnDagNode(altParent);

								if (altParentFn.isFromReferencedFile)
									hasRefParents = true;
								else
									hasOtherNonRefParents = true;

								//
								// If we've already got positives for both tests,
								// then there's no need in continuing.
								//
								if (hasRefParents && hasOtherNonRefParents) break;
							}
						}

						//
						// If this node has parents from referenced files, then
						// make note that we will have to issue 'parent' commands
						// later on.
						//
						if (hasRefParents) fParentingRequired.append(path);

						//
						// If this node has parents other than this one which are
						// not from referenced files, then make note that the
						// parenting for the other instances still has to be done.
						//
						if (hasOtherNonRefParents)
						{
							fInstanceChildren.append(path);
							fInstanceParents.append(parentPath);
						}
					}

					//
					// Write out the node's 'addAttr', 'setAttr' and 'lockNode'
					// commands.
					//
					writeNodeAttrs(f, path.node, true);
					writeLockNode(f, path.node);
				}

				//
				// Mark the node as having been written.
				//
				dagNodeFn.setFlag(fCreateFlag, true);
			}

			//
			// Write out the parenting for instances.
			//
			writeInstances(f);
		}
示例#41
0
		//
		// If a DAG node is instanced (i.e. has multiple parents), this method
		// will put it under its remaining parents.  It will already have been put
		// under its first parent when it was created.
		//
		protected void writeInstances(FileStream f)
		{
			uint numInstancedNodes = fInstanceChildren.length;
			int i;

			for (i = 0; i < numInstancedNodes; i++)
			{
                MFnDagNode nodeFn = new MFnDagNode(fInstanceChildren[i]);

                uint numParents = nodeFn.parentCount;
                uint p;

                for (p = 0; p < numParents; p++)
                {
                    //
                    // We don't want to issue a 'parent' command for the node's
                    // existing parent.
                    //
                    try
                    {
                        if (nodeFn.parent((uint)i).notEqual(fInstanceParents[i].node))
                        {
                            MObject parent = nodeFn.parent((uint)i);
                            MFnDagNode parentFn = new MFnDagNode(parent);

                            if (!parentFn.isFromReferencedFile)
                            {
                                //
                                // Get the first path to the parent node.
                                //
                                MDagPath parentPath = new MDagPath();

                                MDagPath.getAPathTo(parentFn.objectProperty, parentPath);

                                writeParent(f, parentPath, fInstanceChildren[i], true);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }

			//
			// We don't need this any more, so free up the space.
			//
			fInstanceChildren.clear();
			fInstanceParents.clear();
		}
示例#42
0
		//
		// Write out a 'createNode' command for a DAG node.
		//
		protected void writeCreateNode(FileStream f, MDagPath nodePath, MDagPath parentPath)
		{
			MObject node = new MObject(nodePath.node);
			MFnDagNode	nodeFn = new MFnDagNode(node);

			string result = "";
			//
			// Write out the 'createNode' command for this node.
			//
			result += ("createNode " + nodeFn.typeName);

			//
			// If the node is shared, then add a "-s/shared" flag to the command.
			//
			if (nodeFn.isShared) result += " -s";

			result += (" -n \"" + nodeFn.name + "\"");

			//
			// If this is not a top-level node, then include its first parent in the
			// command.
			//
			if (parentPath.length > 0)
				result += (" -p \"" + parentPath.partialPathName + "\"");

			result += (";" + "\n");

			writeString(f, result);
		}
示例#43
0
		//
		// Deal with nodes whose parenting is between referenced and non-referenced
		// nodes.
		//
		protected void writeRefNodeParenting(FileStream f)
		{
			uint numNodes = fParentingRequired.length;
			int i;

			for (i = 0; i < numNodes; i++)
			{
				MFnDagNode	nodeFn = new MFnDagNode(fParentingRequired[i]);

				//
				// Find out if this node has any parents from referenced or
				// non-referenced files.
				//
				bool hasRefParents = false;
				bool hasNonRefParents = false;
				uint numParents = nodeFn.parentCount;
				uint p;

				for (p = 0; p < numParents; p++)
				{
					MObject		parent = nodeFn.parent(p);
					MFnDagNode	parentFn = new MFnDagNode(parent);

					if (parentFn.isFromReferencedFile)
						hasRefParents = true;
					else
						hasNonRefParents = true;

					if (hasRefParents && hasNonRefParents) break;
				}

				//
				// If this node is from a referenced file and it has parents which
				// are also from a referenced file, then it already has its first
				// parent and all others are added instances.
				//
				// Similarly if the node is not from a referenced file and has
				// parents which are also not from referenced files.
				//
				bool	alreadyHasFirstParent =
					(nodeFn.isFromReferencedFile ? hasRefParents : hasNonRefParents);

				//
				// Now run through the parents again and output any parenting
				// which involves a non-referenced node, either as parent or child.
				//
				for (p = 0; p < numParents; p++)
				{
					MObject		parent = nodeFn.parent(p);
					MFnDagNode	parentFn = new MFnDagNode(parent);

					if (parentFn.isFromReferencedFile != nodeFn.isFromReferencedFile)
					{
						//
						// Get the first path to the parent.
						//
						MDagPath	parentPath = new MDagPath();
						MDagPath.getAPathTo(parentFn.objectProperty, parentPath);

						writeParent(
							f, parentPath, fParentingRequired[i], alreadyHasFirstParent
						);

						//
						// If it didn't have its first parent before, it does now.
						//
						alreadyHasFirstParent = true;
					}
				}
			}
		}
        public override void doIt(MArgList args)
        {
            // parse args to get the file name from the command-line
            //
            parseArgs(args);
            uint count = 0;

            // Iterate through graph and search for skinCluster nodes
            //
            MItDependencyNodes iter = new MItDependencyNodes( MFn.Type.kInvalid);
            for ( ; !iter.isDone; iter.next() )
            {
                MObject obj = iter.item;
                if (obj.apiType == MFn.Type.kSkinClusterFilter)
                {
                    count++;

                    // For each skinCluster node, get the list of influence objects
                    //
                    MFnSkinCluster skinCluster = new MFnSkinCluster(obj);
                    MDagPathArray infs = new MDagPathArray();
                    uint nInfs;
                    try
                    {
                        nInfs = skinCluster.influenceObjects(infs);
                    }
                    catch (Exception)
                    {
                        MGlobal.displayInfo("Error getting influence objects.");
                        continue;
                    }
                    if (0 == nInfs)
                    {
                        MGlobal.displayInfo("Error: No influence objects found.");
                        continue;
                    }

                    // loop through the geometries affected by this cluster
                    //
                    uint nGeoms = skinCluster.numOutputConnections;
                    for (uint ii = 0; ii < nGeoms; ++ii)
                    {
                        uint index;
                        try
                        {
                            index = skinCluster.indexForOutputConnection(ii);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry index.");
                            continue;
                        }

                        // get the dag path of the ii'th geometry
                        //
                        MDagPath skinPath = new MDagPath();
                        try{
                        skinCluster.getPathAtIndex(index,skinPath);
                        }
                        catch (Exception)
                        {
                            MGlobal.displayInfo("Error getting geometry path.");
                            continue;
                        }

                        // iterate through the components of this geometry
                        //
                        MItGeometry gIter = new MItGeometry(skinPath);

                        // print out the path name of the skin, vertexCount & influenceCount
                        //
                        UnicodeEncoding uniEncoding = new UnicodeEncoding();
                        string res = String.Format("{0} {1} {2}\n",skinPath.partialPathName,gIter.count,nInfs);
                        file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));

                        // print out the influence objects
                        //
                        for (int kk = 0; kk < nInfs; ++kk)
                        {
                            res = String.Format("{0} ", infs[kk].partialPathName);
                            file.Write(uniEncoding.GetBytes(res),0,uniEncoding.GetByteCount(res));
                        }
                        res = "\n";
                        file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));

                        for ( /* nothing */ ; !gIter.isDone; gIter.next() ) {
                            MObject comp;
                            try
                            {
                                comp = gIter.component;
                            }
                            catch (Exception)
                            {
                                MGlobal.displayInfo("Error getting geometry path.");
                                continue;
                            }

                            // Get the weights for this vertex (one per influence object)
                            //
                            MDoubleArray wts = new MDoubleArray();
                            uint infCount = 0;
                            try
                            {
                                skinCluster.getWeights(skinPath, comp, wts, ref infCount);
                            }
                            catch (Exception)
                            {
                                displayError("Error getting weights.");
                                continue;
                            }
                            if (0 == infCount)
                            {
                                displayError("Error: 0 influence objects.");
                            }

                            // Output the weight data for this vertex
                            //
                            res = String.Format("{0} ",gIter.index);
                            file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            for (int jj = 0; jj < infCount ; ++jj )
                            {
                                res = String.Format("{0} ", wts[jj]);
                                file.Write(uniEncoding.GetBytes(res), 0, uniEncoding.GetByteCount(res));
                            }
                            file.Write(uniEncoding.GetBytes("\n"), 0, uniEncoding.GetByteCount("\n"));
                        }
                    }
                }
            }

            if (0 == count)
            {
                displayError("No skinClusters found in this scene.");
            }
            file.Close();
            return;
        }
示例#45
0
		public override void draw(M3dView view, MDagPath path, M3dView.DisplayStyle style, M3dView.DisplayStatus status)
		{
			// Are we in the right view
			MDagPath dpath = new MDagPath();
			view.getCamera(dpath);
			MFnCamera viewCamera = new MFnCamera(dpath);
			string nameBuffer = viewCamera.name;
			if (nameBuffer == null)
				return;
			if (nameBuffer.IndexOf("persp") == -1 && nameBuffer.IndexOf("front") == -1)
				return;
			//
			bool rightLine = !affectTranslate;

			// Populate the point arrays which are in local space
			MPoint top = lineGeometry.topPoint();
			MPoint bottom = lineGeometry.bottomPoint();

			// Depending on what's active, we modify the
			// end points with mouse deltas in local
			// space
			uint active = 0;
			try
			{
				glActiveName(ref active);
			}
			catch (System.Exception)
			{
				return;
			}

			if (active == lineName && active != 0)
			{
				top[0] += (float)mousePointGlName.x; top[1] += (float)mousePointGlName.y; top[2] += (float)mousePointGlName.z;
				bottom[0] += (float)mousePointGlName.x; bottom[1] += (float)mousePointGlName.y; bottom[2] += (float)mousePointGlName.z;
			}

			// Begin the drawing
			view.beginGL();

			// Get the starting value of the pickable items
			uint glPickableItem = 0;
			glFirstHandle(ref glPickableItem);

			// Top
			lineName = glPickableItem;
			// Place before you draw the manipulator component that can
			// be pickable.
			colorAndName(view, glPickableItem, true, mainColor());
			OpenGL.glBegin((uint)libOpenMayaRenderNet.MGL_LINES);
			OpenGL.glVertex3d(top.x, top.y, top.z);
			OpenGL.glVertex3d(bottom.x, bottom.y, bottom.z);
			OpenGL.glEnd();

			// End the drawing
			view.endGL();
		}
示例#46
0
 public Form1(MDagPath dp)
 {
     InitializeComponent ();
     mdp = dp;
 }
示例#47
0
		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;
		}
示例#48
0
        public void UpdateMeshSelection(TriMesh mesh)
        {
            var selected = MGlobal.activeSelectionList;
            var it = new MItSelectionList(selected, MFn.Type.kMeshVertComponent);

            MObject vertice = new MObject();
            for (; !it.isDone; it.next())
            {

                var path = new MDagPath();
                it.getDagPath(path, vertice);
                MGlobal.displayInfo(path.fullPathName);

                if (!vertice.isNull)
                {

                    MItMeshVertex itvertex = new MItMeshVertex(path, vertice);

                    for (; !itvertex.isDone; itvertex.next())
                    {
                        int index = itvertex.index();

                        mesh.Vertices[index].Traits.SelectedFlag = 1;
                    }

                }

            }

            TriMeshUtil.GroupVertice(mesh);

        }
示例#49
0
 public override void draw(M3dView view, MDagPath path, M3dView.DisplayStyle style, M3dView.DisplayStatus status)
 {
     base.draw(view, path, style, status);
 }
示例#50
0
		public override void draw(M3dView view, MDagPath path, M3dView.DisplayStyle style, M3dView.DisplayStatus status)
		{
			base.draw(view, path, style, status);

			//
			view.beginGL(); 

			//MPoint textPos = new MPoint(nodeTranslation());
			MPoint textPos = new MPoint(0,0,0);
			String distanceText = "Two custom line manipulators";
			view.drawText(distanceText, textPos, M3dView.TextPosition.kLeft);

			// 
			view.endGL();
		}
示例#51
0
		//======================================================================
		//
		// 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");
			}
		}
示例#52
0
        // 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;
        }
示例#53
0
       public void GetVerticeSelected()
       { 
           var selected = MGlobal.activeSelectionList;
           var it = new MItSelectionList(selected,MFn.Type.kMeshVertComponent);

           MObject vertice=new MObject();
           for(; !it.isDone; it.next())
		   {
             
                var path = new MDagPath();
                it.getDagPath(path,vertice);
                MGlobal.displayInfo(path.fullPathName);

                if (!vertice.isNull)
                {

                    MItMeshVertex itvertex = new MItMeshVertex(path, vertice);

                    for (; !itvertex.isDone; itvertex.next())
                    {
                           int index=  itvertex.index();

                           MGlobal.displayInfo(index.ToString()+"\n");
                    }

                } 

           }
           
       }
示例#54
0
 public MObject GetFirstSelectedObject()
 {
     var selected = MGlobal.activeSelectionList;
     var it = new MItSelectionList(selected);
     if (it.isDone) return null;
     var path = new MDagPath();
     MObject mesh=new MObject();
     it.getDagPath(path, mesh);
     return mesh;
 }
示例#55
0
		private void doSimpleSolver()
		//
		// Solve single joint in the x-y plane
		//
		// - first it calculates the angle between the handle and the end-effector.
		// - then it determines which way to rotate the joint.
		//
		{
			// Get the handle and create a function set for it
			//
			MIkHandleGroup handle_group = handleGroup;
			if (null == handle_group) {
				throw new System.InvalidOperationException("invalid handle group.");
			}

			MObject handle = handle_group.handle( 0 );
			MDagPath handlePath = MDagPath.getAPathTo( handle );
			MFnIkHandle fnHandle = new MFnIkHandle( handlePath );

			// Get the position of the end_effector
			//
			MDagPath end_effector = new MDagPath();
			fnHandle.getEffector(end_effector);
			MFnTransform tran = new MFnTransform( end_effector );
			MPoint effector_position = tran.rotatePivot( MSpace.Space.kWorld );

			// Get the position of the handle
			//
			MPoint handle_position = fnHandle.rotatePivot( MSpace.Space.kWorld );

			// Get the start joint position
			//
			MDagPath start_joint = new MDagPath();
			fnHandle.getStartJoint( start_joint );
			MFnTransform start_transform = new MFnTransform( start_joint );
			MPoint start_position = start_transform.rotatePivot( MSpace.Space.kWorld );

			// Calculate the rotation angle
			//
			MVector v1 = start_position.minus( effector_position );
			MVector v2 = start_position.minus( handle_position );
			double angle = v1.angle( v2 );

			// -------- Figure out which way to rotate --------
			//
			//  define two vectors U and V as follows
			//  U   =   EndEffector(E) - StartJoint(S)
			//  N   =   Normal to U passing through EndEffector
			//
			//  Clip handle_position to half-plane U to determine the region it
			//  lies in. Use the region to determine  the rotation direction.
			//
			//             U
			//             ^              Region      Rotation
			//             |  B           
			//            (E)---N            A          C-C-W
			//         A   |                 B           C-W
			//             |  B
			//             |
			//            (S)
			//
			double rot = 0.0;	// Rotation about Z-axis

			// U and N define a half-plane to clip the handle against
			//
			MVector U = effector_position.minus( start_position );
			U.normalize();

			// Get a normal to U
			//
			MVector zAxis = new MVector( 0.0, 0.0, 1.0 );
			MVector N = U.crossProduct( zAxis );	// Cross product
			N.normalize();

			// P is the handle position vector
			//
			MVector P = handle_position.minus( effector_position );

			// Determine the rotation direction
			//
			double PdotN = P[0]*N[0] + P[1]*N[1];
			if ( PdotN < 0 ) {
				// counter-clockwise
				rot = angle;
			} else {
				// clockwise
				rot = -1.0 * angle;
			}

			// get and set the Joint Angles 
			//
			MDoubleArray jointAngles = new MDoubleArray();
			getJointAngles( jointAngles );
			jointAngles.set( jointAngles[0] + rot, 0 );
			setJointAngles( jointAngles );
		}
示例#56
0
 bool hasLights( MDagPath path )
 {
     return path.hasFn(MFn.Type.kDirectionalLight) ||
                  path.hasFn(MFn.Type.kPointLight) ||
                  path.hasFn(MFn.Type.kSpotLight);
 }
示例#57
0
 // Utility method
 // Get the first item of the selection list
 private static MDagPath GetFirstSelected()
 {
     var selected = MGlobal.activeSelectionList;
     var it = new MItSelectionList(selected);
     if (it.isDone) return null;
     var path = new MDagPath();
     it.getDagPath(path);
     return path;
 }
示例#58
0
 bool hasMeshes( MDagPath path )
 {
     return path.hasFn(MFn.Type.kMesh);
 }
示例#59
0
        //
        // 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;
        }
示例#60
0
 // 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;
 }