예제 #1
0
        public static Brep ToBrep(this NXOpen.Body value)
        {
            var rhino = RawDecoder.ToRhinoBrep(value);

            UnitConverter.Scale(rhino, UnitConverter.NXToRhinoUnitsRatio);
            return(rhino);
        }
예제 #2
0
        /// <summary>
        /// 将 NX 体导出为 STEP 242 格式
        /// </summary>
        /// <param name="bodyToExport"></param>
        /// <returns></returns>
        public static string NXExport(NXOpen.Body bodyToExport, bool forceUpate = false)
        {
            var bodyHashCode = bodyToExport.GetHandle().GetHashCode();

            string targetFile = Path.Combine(Path.GetTempPath(), bodyHashCode.ToString() + ".stp");

            if (System.IO.File.Exists(targetFile) && !forceUpate)
            {
                return(targetFile);
            }

            NXOpen.StepCreator stepCreator = TheSession.DexManager.CreateStepCreator();

            stepCreator.ExportAs = NXOpen.StepCreator.ExportAsOption.Ap242;

            stepCreator.ColorAndLayers = true;

            var currentNXProcessFile = new System.IO.FileInfo(Process.GetCurrentProcess().MainModule.FileName);        // NXBIN\ugraf.exe

            var nxRootPath = currentNXProcessFile.Directory.Parent;

            stepCreator.SettingsFile = System.IO.Path.Combine(nxRootPath.FullName, "translators", "step242", "ugstep242.def");

            stepCreator.ExportSelectionBlock.SelectionScope = NXOpen.ObjectSelector.Scope.SelectedObjects;

            stepCreator.ExportSelectionBlock.SelectionComp.Add(bodyToExport);

            stepCreator.OutputFile = targetFile;

            stepCreator.FileSaveFlag = false;

            stepCreator.LayerMask = "1-256";

            stepCreator.ProcessHoldFlag = true;

            stepCreator.ExportSolidsAndSurfacesAs = NXOpen.StepCreator.ExportSolidsAndSurfacesAsOption.Precise;

#if !NX1847 && !NX1872 && !NX1899 && !NX1926
            stepCreator.ExportConvergentAs = NXOpen.StepCreator.ExportConvergentAsOption.SplitPreciseAndTessellated;
#endif

            NXOpen.NXObject nXObject1 = stepCreator.Commit();

            stepCreator.Destroy();

            return(targetFile);
        }
예제 #3
0
        public static Brep ToRhinoBrep(NXOpen.Body body)
        {
            if (false)
            {
                Brep brep = new Brep();

                for (int i = 0; i < body.GetFaces().Length; i++)
                {
                    AddNXFace(body.GetFaces()[i], brep);
                }

                return(brep);
            }
            else
            {
                return(JoinAndMerge(body.GetFaces().Select(x => ToRhinoBrep(x)).ToArray(), Globals.DistanceTolerance));
            }
        }
예제 #4
0
        /// <summary>
        /// 将面转换为未修剪的曲面
        /// </summary>
        /// <param name="nurbsSurface"></param>
        /// <returns></returns>
        public static unsafe NXOpen.Body ToHost(NurbsSurface nurbsSurface)
        {
            // TODO: Implement conversion from other Rhino surface types like PlaneSurface, RevSurface and SumSurface.
            try
            {
                NXOpen.Body bSurfaceBody = null;
                var         domainU      = nurbsSurface.Domain(0);
                var         domainV      = nurbsSurface.Domain(1);

                var knotsU        = ToHost(nurbsSurface.KnotsU);
                var knotsV        = ToHost(nurbsSurface.KnotsV);
                var controlPoints = ToHost(nurbsSurface.Points);
                var bboxUV        = new BoundingBox2D(domainU.Min, domainV.Min, domainU.Max, domainV.Max);

#if DEBUG
                Console.WriteLine($"U 方向封闭性:{nurbsSurface.IsClosed(0)}");
                Console.WriteLine($"V 方向封闭性:{nurbsSurface.IsClosed(1)}");
                Console.WriteLine($"U 方向阶次:{nurbsSurface.Degree(0)}");
                Console.WriteLine($"V 方向阶次:{nurbsSurface.Degree(1)}");
                Console.WriteLine($"U 方向结点数:{knotsU.Length}");
                Console.WriteLine($"V 方向结点数:{knotsV.Length}");
                Console.WriteLine($"U 方向控制点个数:{nurbsSurface.Points.CountU}");
                Console.WriteLine($"V 方向控制点个数:{nurbsSurface.Points.CountV}");
#endif
                #region 使用修剪曲面方式创建,报错,无法创建曲面
                //double[] poles = new double[nurbsSurface.Points.CountU * nurbsSurface.Points.CountV * 4];

                //for (int i = 0; i < nurbsSurface.Points.CountV; i++)
                //{
                //    for (int j = 0; j < nurbsSurface.Points.CountU; j++)
                //    {
                //        int currentIndex = (nurbsSurface.Points.CountU * i + j);
                //        var currentControlPoint = nurbsSurface.Points.GetControlPoint(j, i);
                //        var pt = WorkPart.Points.CreatePoint(currentControlPoint.Location.ToXYZ());
                //        pt.SetVisibility(NXOpen.SmartObject.VisibilityOption.Visible);
                //        pt.SetUserAttribute("UV", -1, $"{i},{j}", NXOpen.Update.Option.Now);
                //        poles[currentIndex * 4] = currentControlPoint.X;
                //        poles[currentIndex * 4 + 1] = currentControlPoint.Y;
                //        poles[currentIndex * 4 + 2] = currentControlPoint.Z;
                //        poles[currentIndex * 4 + 3] = currentControlPoint.Weight;
                //    }
                //}

                //int[] edge_counts = new int[face.Loops.Count];
                //List<int> edge_senses = new List<int>();
                //List<Tag> edge_curves = new List<Tag>();
                //for (int i = 0; i < face.Loops.Count; i++)
                //{
                //    var trims = face.Loops[i].Trims;

                //    List<Tag> currentTrimEdgeCurves = new List<Tag>();
                //    List<int> currentTrimEdgeSenses = new List<int>();
                //    int ss = 0;
                //    for (int j = 0; j < trims.Count; j++)
                //    {
                //        if (trims[j].TrimType != BrepTrimType.Boundary && trims[j].TrimType != BrepTrimType.Mated)
                //            continue;

                //        BrepEdge edge = trims[j].Edge;

                //        ss += trims[j].ProxyCurveIsReversed ? 1 : 0;

                //        if (edge is null)
                //            continue;

                //        var currentEdgeCurve = edge.EdgeCurve.ToCurve();

                //        currentEdgeCurve.SetUserAttribute("Index", -1, j, Update.Option.Now);

                //        currentTrimEdgeCurves.Add(currentEdgeCurve.Tag);

                //        currentTrimEdgeSenses.Add(trims[j].IsReversed() ? -1 : 1);
                //    }

                //    edge_counts[i] = currentTrimEdgeCurves.Count;
                //    edge_senses.AddRange(currentTrimEdgeSenses);
                //    edge_curves.AddRange(currentTrimEdgeCurves);

                //}

                //face.Loops.Count.ToString().ConsoleWriteLine();

                //Tag bSurfaceTag = Tag.Null;
                //try
                //{
                //    theUfSession.Modl.CreTrimBsurf(
                //        nurbsSurface.Points.CountU,
                //        nurbsSurface.Points.CountV,
                //        nurbsSurface.OrderU,
                //        nurbsSurface.OrderV,
                //        knotsU,
                //        knotsV,
                //        poles,
                //        face.Loops.Count,
                //        edge_counts,
                //        edge_senses.ToArray(),
                //        edge_curves.ToArray(),
                //        0,
                //        DistanceTolerance,
                //        out bSurfaceTag,
                //        out int knotFixup,
                //        out int poleFixup
                //        );
                //}
                //catch (Exception ex)
                //{
                //    ex.ToString().ConsoleWriteLine();
                //}
                #endregion

                #region 使用拟合方式创建,误差较大
                //NXOpen.UF.UFModl.BsurfRowInfo[] bSurfRowInfo = new NXOpen.UF.UFModl.BsurfRowInfo[nurbsSurface.Points.CountV];
                //for (int i = 0; i < bSurfRowInfo.Length; i++)
                //{
                //    double[] currentRowPoint = new double[nurbsSurface.Points.CountU * 3];
                //    double[] weights = new double[nurbsSurface.Points.CountU];
                //    for (int j = 0; j < nurbsSurface.Points.CountU; j++)
                //    {
                //        var currentControlPoint = nurbsSurface.Points.GetControlPoint(j, i);

                //        var pt = WorkPart.Points.CreatePoint(currentControlPoint.Location.ToXYZ());
                //        pt.SetVisibility(NXOpen.SmartObject.VisibilityOption.Visible);
                //        pt.SetUserAttribute("UV", -1, $"{j},{i}", NXOpen.Update.Option.Now);

                //        currentRowPoint[j * 3] = currentControlPoint.Location.X;
                //        currentRowPoint[j * 3 + 1] = currentControlPoint.Location.Y;
                //        currentRowPoint[j * 3 + 2] = currentControlPoint.Location.Z;
                //        weights[j] = currentControlPoint.Weight;
                //    }

                //    bSurfRowInfo[i] = new NXOpen.UF.UFModl.BsurfRowInfo
                //    {
                //        num_points = nurbsSurface.Points.CountU,
                //        points = currentRowPoint,
                //        weight = weights,
                //    };
                //}

                //theUfSession.Modl.CreateBsurfThruPts(1,
                //    nurbsSurface.IsClosed(0) ? 1 : 0,
                //    nurbsSurface.IsClosed(1) ? 1 : 0,
                //    nurbsSurface.Degree(0),
                //    nurbsSurface.Degree(1),
                //    nurbsSurface.Points.CountV,
                // bSurfRowInfo,
                // out NXOpen.Tag bSurfaceTag);
                #endregion

                #region CreateBsurf
                double[] poles = new double[nurbsSurface.Points.CountU * nurbsSurface.Points.CountV * 4];

#if DEBUG
                List <NXOpen.Point> polePoints = new List <NXOpen.Point>();
#endif
                for (int i = 0; i < nurbsSurface.Points.CountV; i++)
                {
                    for (int j = 0; j < nurbsSurface.Points.CountU; j++)
                    {
                        int currentIndex        = (nurbsSurface.Points.CountU * i + j);
                        var currentControlPoint = nurbsSurface.Points.GetControlPoint(j, i);

                        poles[currentIndex * 4]     = currentControlPoint.X;
                        poles[currentIndex * 4 + 1] = currentControlPoint.Y;
                        poles[currentIndex * 4 + 2] = currentControlPoint.Z;
                        poles[currentIndex * 4 + 3] = currentControlPoint.Weight;
#if DEBUG
                        var pt = WorkPart.Points.CreatePoint(currentControlPoint.Location.ToXYZ());
                        pt.SetVisibility(NXOpen.SmartObject.VisibilityOption.Visible);
                        pt.SetUserAttribute("UV", -1, $"{j},{i}", NXOpen.Update.Option.Now);
                        polePoints.Add(pt);
#endif
                    }
                }

                TheUfSession.Modl.CreateBsurf(
                    nurbsSurface.Points.CountU,
                    nurbsSurface.Points.CountV,
                    nurbsSurface.OrderU,
                    nurbsSurface.OrderV,
                    knotsU,
                    knotsV,
                    poles,
                    out NXOpen.Tag bSurfaceTag,
                    out int knotFixup,
                    out int poleFixup);
                #endregion

                #region CreateBsurface 报错,指定结构必须能直接复制到本机结构中
                //double[,] vertices = new double[nurbsSurface.Points.CountU * nurbsSurface.Points.CountV, 4];

                //for (int i = 0; i < nurbsSurface.Points.CountV; i++)
                //{
                //    for (int j = 0; j < nurbsSurface.Points.CountU; j++)
                //    {
                //        var currentIndex = (nurbsSurface.Points.CountU * i + j);
                //        var currentControlPoint = nurbsSurface.Points.GetControlPoint(j, i);

                //        vertices[currentIndex, 0] = currentControlPoint.X;
                //        vertices[currentIndex, 1] = currentControlPoint.Y;
                //        vertices[currentIndex, 2] = currentControlPoint.Z;
                //        vertices[currentIndex, 3] = currentControlPoint.Weight;
                //    }
                //}

                //NXOpen.UF.UFModl.Bsurface surfaceInfo = new NXOpen.UF.UFModl.Bsurface()
                //{
                //    is_rational = nurbsSurface.IsRational ? 1 : 0,
                //    order_u = nurbsSurface.OrderU,
                //    order_v = nurbsSurface.OrderV,
                //    knots_u = knotsU,
                //    knots_v = knotsV,
                //    num_poles_u = nurbsSurface.Points.CountU,
                //    num_poles_v = nurbsSurface.Points.CountV,
                //    poles = vertices,
                //};

                //double[,] poles = new double[nurbsSurface.Points.Count(), 4];

                //for (int i = 0; i < nurbsSurface.Points.CountU; i++)
                //{
                //    for (int j = 0; j < nurbsSurface.Points.CountV; j++)
                //    {
                //        var currentPoint3d = nurbsSurface.Points.GetControlPoint(i, j);
                //        poles[nurbsSurface.Points.CountV * i + j, 0] = currentPoint3d.X;
                //        poles[nurbsSurface.Points.CountV * i + j, 1] = currentPoint3d.Y;
                //        poles[nurbsSurface.Points.CountV * i + j, 2] = currentPoint3d.Z;
                //        poles[nurbsSurface.Points.CountV * i + j, 3] = nurbsSurface.IsRational ? currentPoint3d.Weight : 1.0;
                //    }
                //}

                //theUfSession.Modl.CreateBsurface(
                //ref surfaceInfo,
                //out NXOpen.Tag bSurfaceTag,
                //out int numStates,
                //out NXOpen.UF.UFCurve.State[] states);
                #endregion

                #region Snap

                //                Snap.Position[,] poles = new Snap.Position[nurbsSurface.Points.CountU, nurbsSurface.Points.CountV];

                //#if DEBUG
                //                List<NXOpen.Point> polePoints = new List<NXOpen.Point>();
                //#endif
                //                for (int i = 0; i < nurbsSurface.Points.CountU; i++)
                //                {
                //                    for (int j = 0; j < nurbsSurface.Points.CountV; j++)
                //                    {
                //                        var currentControlPoint = nurbsSurface.Points.GetControlPoint(i, j);
                //#if DEBUG
                //                        var pt = WorkPart.Points.CreatePoint(currentControlPoint.Location.ToXYZ());
                //                        pt.SetVisibility(NXOpen.SmartObject.VisibilityOption.Visible);
                //                        pt.SetUserAttribute("UV", -1, $"{i},{j}", NXOpen.Update.Option.Now);
                //                        polePoints.Add(pt);
                //#endif
                //                        poles[i, j] = new Snap.Position(currentControlPoint.Location.ToXYZ());
                //                    }
                //                }

                //                var snapBSurface = Snap.Create.Bsurface(poles, knotsU, knotsV);

                //                bSurfaceBody = snapBSurface.NXOpenBody;
                #endregion

                bSurfaceBody = bSurfaceTag.GetTaggedObject() as NXOpen.Body;
#if DEBUG
                polePoints.ToArray().Delete();
#endif
                return(bSurfaceBody);
            }
            catch (Exception ex)
            {
                ex.ToString().ConsoleWriteLine();
                return(null);
            }
        }
예제 #5
0
        //internal static Brep ToRawBrep(/*const*/ Brep brep, double scaleFactor)
        //{
        //    brep = brep.DuplicateShallow() as Brep;
        //    return EncodeRaw(ref brep, scaleFactor) ? brep : default;
        //}

        //internal static bool EncodeRaw(ref Brep brep, double scaleFactor)
        //{
        //    if (scaleFactor != 1.0 && !brep.Scale(scaleFactor))
        //        return default;

        //    var bbox = brep.GetBoundingBox(false);
        //    if (!bbox.IsValid || bbox.Diagonal.Length < Revit.ShortCurveTolerance)
        //        return default;

        //    return SplitFaces(ref brep);
        //}

        //static bool SplitFaces(ref Brep brep)
        //{
        //    Brep brepToSplit = null;
        //    while (!ReferenceEquals(brepToSplit, brep))
        //    {
        //        brepToSplit = brep;

        //        foreach (var face in brepToSplit.Faces)
        //        {
        //            var splitters = new List<Curve>();

        //            var trimsBBox = BoundingBox.Empty;
        //            foreach (var trim in face.OuterLoop.Trims)
        //                trimsBBox.Union(trim.GetBoundingBox(true));

        //            var domainUV = new Interval[]
        //            {
        //    new Interval(trimsBBox.Min.X, trimsBBox.Max.X),
        //    new Interval(trimsBBox.Min.Y, trimsBBox.Max.Y),
        //            };

        //            // Compute splitters
        //            var splittedUV = new bool[2] { false, false };
        //            for (int d = 0; d < 2; d++)
        //            {
        //                var domain = domainUV[d];
        //                var t = domain.Min;

        //                while (face.GetNextDiscontinuity(d, Continuity.Gsmooth_continuous, t, domain.Max, out t))
        //                {
        //                    splitters.AddRange(face.TrimAwareIsoCurve(1 - d, t));
        //                    splittedUV[d] = true;
        //                }
        //            }

        //            var closedUV = new bool[2] { face.IsClosed(0), face.IsClosed(1) };
        //            if (!splittedUV[0] && closedUV[0])
        //            {
        //                splitters.AddRange(face.TrimAwareIsoCurve(1, face.Domain(0).Mid));
        //                splittedUV[0] = true;
        //            }
        //            if (!splittedUV[1] && closedUV[1])
        //            {
        //                splitters.AddRange(face.TrimAwareIsoCurve(0, face.Domain(1).Mid));
        //                splittedUV[1] = true;
        //            }

        //            if (splitters.Count > 0)
        //            {
        //                var surfaceIndex = face.SurfaceIndex;
        //                var splitted = face.Split(splitters, Revit.ShortCurveTolerance);
        //                if (splitted is null)
        //                {
        //                    Debug.Fail("BrepFace.Split", "Failed to split a closed face.");
        //                    return false;
        //                }

        //                if (brepToSplit.Faces.Count == splitted.Faces.Count)
        //                {
        //                    // Split was ok but for tolerance reasons no new faces were created.
        //                    // Too near from the limits.
        //                }
        //                else
        //                {

        //                    foreach (var f in splitted.Faces)
        //                    {
        //                        if (f.SurfaceIndex != surfaceIndex)
        //                            continue;

        //                        if (splittedUV[0] && splittedUV[1])
        //                            f.ShrinkFace(BrepFace.ShrinkDisableSide.ShrinkAllSides);
        //                        else if (splittedUV[0])
        //                            f.ShrinkFace(BrepFace.ShrinkDisableSide.DoNotShrinkSouthSide | BrepFace.ShrinkDisableSide.DoNotShrinkNorthSide);
        //                        else if (splittedUV[1])
        //                            f.ShrinkFace(BrepFace.ShrinkDisableSide.DoNotShrinkEastSide | BrepFace.ShrinkDisableSide.DoNotShrinkWestSide);
        //                    }

        //                    // Start again until no face is splitted
        //                    brep = splitted;
        //                    break;
        //                }
        //            }
        //        }
        //    }

        //    return brep is object;
        //}
        #endregion

        #region Transfer
        /// <summary>
        /// Replaces <see cref="Raw.RawEncoder.ToHost(Brep)"/> to catch Revit Exceptions
        /// </summary>
        /// <param name="brep"></param>
        /// <returns></returns>
        public static NXOpen.Body ToSolid(/*const*/ Brep brep)
        {
            try
            {
                BodyStyle brepType;
                switch (brep.SolidOrientation)
                {
                case BrepSolidOrientation.Inward: brepType = BodyStyle.Sheet; break;

                case BrepSolidOrientation.Outward: brepType = BodyStyle.Solid; break;
                }

                List <NXOpen.Body> faceBodies = new List <NXOpen.Body>();
                foreach (var face in brep.Faces)
                {
                    using (var nurbSurface = face.ToNurbsSurface())
                    {
                        List <(List <NXOpen.Curve> edgeCurves, List <int> directions)> boundaryEdgeCurves = new List <(List <NXOpen.Curve>, List <int>)>();
                        for (int i = 0; i < face.Loops.Count; i++)
                        {
                            List <NXOpen.Curve> currentEdgeCurves = new List <NXOpen.Curve>();

                            List <int> currentDirections = new List <int>();

                            var trims = face.Loops[i].Trims;
                            for (int j = 0; j < trims.Count; j++)
                            {
                                if (trims[j].TrimType != BrepTrimType.Boundary && trims[j].TrimType != BrepTrimType.Mated)
                                {
                                    continue;
                                }

                                BrepEdge edge = trims[j].Edge;

                                if (edge is null)
                                {
                                    continue;
                                }

                                var currentEdgeCurve = edge.Trim(edge.Domain).ToCurve();

                                currentEdgeCurves.Add(currentEdgeCurve);
                                currentDirections.Add(edge.ProxyCurveIsReversed ? -1 : 1);
                            }

                            boundaryEdgeCurves.Add((currentEdgeCurves, currentDirections));
                        }

                        if (nurbSurface.IsPlanar())
                        {
                            // 使用有界平面创建
                            var boundaryCurves   = boundaryEdgeCurves.SelectMany(obj => obj.edgeCurves).ToArray();
                            var boundedPlaneBody = _theSession.Parts.Work.Features.CreateBoundedPlane(boundaryCurves).GetBodies()[0];
                            boundedPlaneBody.RemoveParameter();
                            faceBodies.Add(boundedPlaneBody);
                            //boundaryCurves.Delete();

                            //NXOpen.UF.StringList bplaneBoundaries = new NXOpen.UF.StringList()
                            //{
                            //    num = boundaryEdgeCurves.Count,
                            //    id = boundaryEdgeCurves.SelectMany(obj => obj.edgeCurveTags).ToArray(),
                            //    dir = boundaryEdgeCurves.SelectMany(obj => obj.directions).ToArray(),
                            //    _string = boundaryEdgeCurves.Select(obj => obj.edgeCurveTags.Count).ToArray()
                            //};

                            //double[] tolerrances = new double[bplaneBoundaries.dir.Length];
                            //for (int i = 0; i < tolerrances.Length; i++)
                            //    tolerrances[i] = DistanceTolerance;
                            //theUfSession.Modl.CreateBplane(ref bplaneBoundaries, tolerrances, out NXOpen.Tag body);

                            //bplaneBoundaries.id.Select(obj => obj.GetTaggedObject() as NXOpen.NXObject).ToArray().Delete();
                        }
                        else
                        {
                            var faceBody = RawEncoder.ToHost(nurbSurface);

                            #region 找到一个位于面上的点
                            Point3d point3dOnFace     = new Point3d();
                            bool    findInteriorPoint = false;
                            if (face.IsPointOnFace(face.Domain(0).Mid, face.Domain(1).Mid) == PointFaceRelation.Interior)
                            {
                                face.Evaluate(face.Domain(0).Mid, face.Domain(1).Mid, 0, out point3dOnFace, out _);
                                findInteriorPoint = true;
                            }
                            else
                            {
                                var firstEdge = face.Loops.ElementAt(0).Trims.ElementAt(0).Edge;

                                Point3d ptOnFirstEdge = firstEdge.PointAt(firstEdge.Domain.Mid);

                                face.ClosestPoint(ptOnFirstEdge, out double u, out double v);

                                double offsetValue = 0.02;

                                u += offsetValue;
                                v += offsetValue;
                                if (face.IsPointOnFace(u, v) == PointFaceRelation.Interior)
                                {
                                    face.Evaluate(u, v, 0, out point3dOnFace, out _);
                                    findInteriorPoint = true;
                                }
                                else
                                {
                                    u -= 2 * offsetValue;
                                    v -= 2 * offsetValue;
                                    if (face.IsPointOnFace(u, v) == PointFaceRelation.Interior)
                                    {
                                        face.Evaluate(u, v, 0, out point3dOnFace, out _);
                                        findInteriorPoint = true;
                                    }
                                }
                            }

                            if (!findInteriorPoint)
                            {
                                findInteriorPoint.ToString().ListingWindowWriteLine();
                                var copiedFaceBody = faceBody.CopyAndPaste()[0] as NXOpen.Body;
                                copiedFaceBody.SetColor(216);
                            }
                            #endregion

                            for (int i = 0; i < boundaryEdgeCurves.Count; i++)
                            {
                                NXOpen.UF.UFModl.TrimObject[] trimBoundaryObjects = new NXOpen.UF.UFModl.TrimObject[boundaryEdgeCurves[i].edgeCurves.Count];

                                for (int j = 0; j < trimBoundaryObjects.Length; j++)
                                {
                                    trimBoundaryObjects[j] = new NXOpen.UF.UFModl.TrimObject {
                                        object_tag = boundaryEdgeCurves[i].edgeCurves[j].Tag, curve_project_method = boundaryEdgeCurves[i].directions[j]
                                    };
                                }

                                _theUfSession.Modl.TrimSheet(faceBody.Tag, trimBoundaryObjects.Length, trimBoundaryObjects, null, 1, 1, point3dOnFace.ToXYZ().ToArray(), 0.01, out int numGapPoints, out double[] gapPoints);
                            }

                            faceBodies.Add(faceBody);
                        }
#if !DEBUG
                        boundaryEdgeCurves.SelectMany(obj => obj.edgeCurves).ToArray().Delete();
#endif
                    }
                }

                NXOpen.Body resultBody = null;
                if (faceBodies.Count > 1)
                {
                    var sewFeature = WorkPart.Features.CreateSew(faceBodies.ToArray());
                    resultBody = sewFeature.GetBodies()[0];
#if !DEBUG
                    resultBody.RemoveParameter();
#endif
                }
                else
                {
                    resultBody = faceBodies[0];
                }

                var brepArea = brep.GetArea();
                var bodyArea = resultBody.GetArea();
                resultBody.SetUserAttribute("Area", -1, bodyArea, NXOpen.Update.Option.Now);
                var error = Math.Abs(brepArea - bodyArea) / brepArea;
                resultBody.SetUserAttribute("Error", -1, error, NXOpen.Update.Option.Now);
                if (error > 0.001)
                {
                    resultBody.SetColor(186);
                }
            }
            catch (NXOpen.NXException e)
            {
                Logger.Error(e.ToString());
            }

            return(null);
        }
예제 #6
0
    NXOpen.DisplayableObject GeomcopyElec(bool isPreview, NXOpen.Body body, NXOpen.Plane plane)
    {
        Snap.NX.Body SnapBody    = body;
        var          oldWorkPart = theSession.Parts.Work;
        var          objs        = new List <NXOpen.NXObject> {
            body
        };

        Snap.NX.Body newBody = null;

        if (body.OwningComponent != null && body.Prototype != null)
        {
            //析出
            SnapEx.Create.ExtractObject(objs, oldWorkPart.FullPath, false, false);
            newBody = oldWorkPart.Bodies.ToArray().FirstOrDefault(u => u.Name == body.Name);
        }
        else
        {
            newBody = SnapBody.Copy();
        }

        if (newBody == null)
        {
            return(newBody);
        }

        var guid = Guid.NewGuid().ToString();

        var tempElecOrigin = SnapEx.Helper.GetElecMidPosition(oldWorkPart, body);

        if (tempElecOrigin == null)
        {
            theUI.NXMessageBox.Show("提示", NXOpen.NXMessageBox.DialogType.Information, "该电极未发现基准点!");
            return(null);
        }

        var transRef       = Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal));
        var topFace        = SnapEx.Helper.GetTopFace(newBody);
        var bottomFace     = SnapEx.Helper.GetBottomFace(newBody);
        var minU           = topFace.BoxUV.MinU;
        var minV           = topFace.BoxUV.MinV;
        var maxU           = topFace.BoxUV.MaxU;
        var maxV           = topFace.BoxUV.MaxV;
        var centerPosition = (Snap.Position)tempElecOrigin;
        var movePosition   = centerPosition.Copy(transRef);

        bool isJC = toggle0.Value && topFace.NXOpenTag != bottomFace.NXOpenTag;

        if (isJC) //继承
        {
            var markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "reflectionBody");
            var normal  = topFace.Normal(minU, minV);
            var point   = topFace.Position(minU, minV);

            var datumPlane     = Snap.Create.DatumPlane(point, normal);
            var splitBody      = Snap.Create.SplitBody(newBody, datumPlane);
            var topBody        = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) == null).Copy();
            var reflectionBody = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) != null).Copy();
            splitBody.Delete();
            newBody.Delete();
            topBody.Move(transRef);
            reflectionBody.Move(Snap.Geom.Transform.CreateTranslation(movePosition - centerPosition));
            var result = Snap.Create.Unite(reflectionBody, topBody);
            result.Orphan();

            datumPlane.Delete();

            theSession.UpdateManager.DoUpdate(markId1);
            theSession.DeleteUndoMark(markId1, null);

            newBody = reflectionBody;
        }
        else
        {
            newBody.Move(transRef);
        }

        var x     = expressionX.Value;
        var y     = expressionY.Value;
        var z     = expressionZ.Value;
        var trans = Snap.Geom.Transform.CreateTranslation(new Snap.Vector(x, y, z));

        newBody.Move(trans);
        if (!isPreview)
        {
            newBody.SetStringAttribute("EACT_MIRROR_ELECT", "Y");
            if (topFace != null)
            {
                //SetJZJAttr(topFace, newBody);
                SetGeomcopyAttr(newBody, plane, isJC);
            }
            var oldPoint = SnapEx.Helper.GetElecMidPointInPart(Snap.Globals.WorkPart, body);
            var newPoint = SnapEx.Helper.GetElecMidPoint(Snap.Globals.WorkPart, body);

            if (newPoint != null)
            {
                //newPoint.SetStringAttribute(SnapEx.EactConstString.EACT_ELECT_GROUP, guid);
                newPoint.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                newPoint.Move(trans);
            }

            if (body.OwningComponent != null && body.Prototype != null)
            {
            }
            else
            {
                if (oldPoint != null)
                {
                    oldPoint.Delete();
                }
                SnapBody.Delete();
            }
        }

        return(newBody);
    }
예제 #7
0
    NXOpen.DisplayableObject GeomcopyElec(bool isPreview, NXOpen.Body body, NXOpen.Plane plane, int order)
    {
        Snap.NX.Body SnapBody    = body;
        var          oldWorkPart = theSession.Parts.Work;
        var          objs        = new List <NXOpen.NXObject> {
            body
        };

        Snap.NX.Body newBody = null;

        if (body.OwningComponent != null && body.Prototype != null)
        {
            //析出
            SnapEx.Create.ExtractObject(objs, oldWorkPart.FullPath, false, false);
            newBody = oldWorkPart.Bodies.ToArray().FirstOrDefault(u => u.Name == body.Name);
        }
        else
        {
            newBody = Snap.NX.Body.Wrap(oldWorkPart.Bodies.ToArray().FirstOrDefault(u => u.Name == body.Name).Tag).Copy();
        }

        if (newBody == null)
        {
            return(newBody);
        }

        var guid = Guid.NewGuid().ToString();

        //TODO 修改名称 修改属性
        newBody.Name = GetElecName(order - 1);
        newBody.SetStringAttribute("EACT_ELEC_NAME", newBody.Name);
        newBody.SetStringAttribute("EACT_ELECT_GROUP", guid);
        newBody.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
        newBody.Layer = order;
        Snap.Globals.LayerStates[order] = isPreview ? Snap.Globals.LayerState.Visible : Snap.Globals.LayerState.Selectable;

        if (toggle0.Value) //继承
        {
            var markId1        = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "reflectionBody");
            var topFace        = SnapEx.Helper.GetTopFace(newBody);
            var minU           = topFace.BoxUV.MinU;
            var minV           = topFace.BoxUV.MinV;
            var maxU           = topFace.BoxUV.MaxU;
            var maxV           = topFace.BoxUV.MaxV;
            var centerPosition = topFace.Position((minU + maxU) / 2, (minV + maxV) / 2);
            var normal         = topFace.Normal(minU, minV);
            var point          = topFace.Position(minU, minV);

            var datumPlane = Snap.Create.DatumPlane(point, normal);
            var splitBody  = Snap.Create.SplitBody(newBody, datumPlane);
            var topBody    = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) == null);

            var reflectionBody = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) != null);
            var newDatumPlane  = Snap.Create.DatumPlane(centerPosition, new Snap.Orientation(normal).AxisY);
            reflectionBody.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(centerPosition, newDatumPlane.Normal)));
            var result = Snap.Create.Unite(reflectionBody, topBody);
            result.Orphan();

            datumPlane.Delete();
            newDatumPlane.Delete();

            theSession.UpdateManager.DoUpdate(markId1);
            theSession.DeleteUndoMark(markId1, null);

            newBody = reflectionBody;
        }

        var x     = expressionX.Value;
        var y     = expressionY.Value;
        var z     = expressionZ.Value;
        var trans = Snap.Geom.Transform.CreateTranslation(new Snap.Vector(x, y, z));

        newBody.Move(trans);
        if (!isPreview)
        {
            newBody.SetStringAttribute("EACT_MIRROR_ELECT", "Y");
            var topFace = SnapEx.Helper.GetTopFace(newBody);
            if (topFace != null)
            {
                SetJZJAttr(topFace, newBody);
            }
            var newPoint = SnapEx.Helper.GetElecMidPoint(Snap.Globals.WorkPart, body);
            if (newPoint != null)
            {
                newPoint.SetStringAttribute(SnapEx.EactConstString.EACT_ELECT_GROUP, guid);
                newPoint.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                newPoint.Move(trans);
            }

            if (toggleJiaju.Value && selectionJiaju.Show)
            {
                Snap.NX.Body jiaju = selectionJiaju.GetSelectedObjects().FirstOrDefault() as NXOpen.Body;
                if (jiaju != null)
                {
                    jiaju       = jiaju.Copy();
                    jiaju.Layer = order;
                    jiaju.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                    jiaju.SetStringAttribute("EACT_MIRROR_ELECT", "Y");
                    jiaju.Move(trans);
                }
            }
        }

        return(newBody);
    }
예제 #8
0
    NXOpen.DisplayableObject GeomcopyElec(bool isPreview, NXOpen.Body body, NXOpen.Plane plane, int order)
    {
        Snap.NX.Body SnapBody    = body;
        var          oldWorkPart = theSession.Parts.Work;
        var          objs        = new List <NXOpen.NXObject> {
            body
        };

        Snap.NX.Body newBody = null;

        if (body.OwningComponent != null && body.Prototype != null)
        {
            //析出
            SnapEx.Create.ExtractObject(objs, oldWorkPart.FullPath, false, false);
            newBody = oldWorkPart.Bodies.ToArray().FirstOrDefault(u => u.Name == body.Name);
        }
        else
        {
            newBody = SnapBody.Copy();
        }

        if (newBody == null)
        {
            return(newBody);
        }

        var tempElecOrigin = SnapEx.Helper.GetElecMidPosition(oldWorkPart, body);

        if (tempElecOrigin == null)
        {
            theUI.NXMessageBox.Show("提示", NXOpen.NXMessageBox.DialogType.Information, "该电极未发现基准点!");
            return(null);
        }

        var guid = Guid.NewGuid().ToString();

        //TODO 修改名称 修改属性
        newBody.Name = GetElecName(order - 1);
        newBody.SetStringAttribute("EACT_ELEC_NAME", newBody.Name);
        newBody.SetStringAttribute("EACT_ELECT_GROUP", guid);
        newBody.Layer = order;
        Snap.Globals.LayerStates[order] = isPreview ? Snap.Globals.LayerState.Visible : Snap.Globals.LayerState.Selectable;

        var transRef       = Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal));
        var topFace        = SnapEx.Helper.GetTopFace(newBody);
        var bottomFace     = SnapEx.Helper.GetBottomFace(newBody);
        var minU           = topFace.BoxUV.MinU;
        var minV           = topFace.BoxUV.MinV;
        var maxU           = topFace.BoxUV.MaxU;
        var maxV           = topFace.BoxUV.MaxV;
        var centerPosition = (Snap.Position)tempElecOrigin;
        var movePosition   = centerPosition.Copy(transRef);

        bool isJC = toggle0.Value && topFace.NXOpenTag != bottomFace.NXOpenTag;

        if (isJC) //继承
        {
            var markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "reflectionBody");

            var normal = topFace.Normal(minU, minV);
            var point  = topFace.Position(minU, minV);

            var datumPlane     = Snap.Create.DatumPlane(point, normal);
            var splitBody      = Snap.Create.SplitBody(newBody, datumPlane);
            var topBody        = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) == null).Copy();
            var reflectionBody = splitBody.Bodies.FirstOrDefault(b => SnapEx.Helper.GetTopFace(b) != null).Copy();
            splitBody.Delete();
            newBody.Delete();
            topBody.Move(transRef);
            reflectionBody.Move(Snap.Geom.Transform.CreateTranslation(movePosition - centerPosition));
            var result = Snap.Create.Unite(reflectionBody, topBody);
            result.Orphan();

            datumPlane.Delete();

            theSession.UpdateManager.DoUpdate(markId1);
            theSession.DeleteUndoMark(markId1, null);

            newBody = reflectionBody;
        }
        else
        {
            newBody.Move(transRef);
        }

        var x     = expressionX.Value;
        var y     = expressionY.Value;
        var z     = expressionZ.Value;
        var trans = Snap.Geom.Transform.CreateTranslation(new Snap.Vector(x, y, z));

        newBody.Move(trans);
        if (!isPreview)
        {
            newBody.SetStringAttribute("EACT_MIRROR_ELECT", "Y");
            topFace = SnapEx.Helper.GetTopFace(newBody);
            if (topFace != null)
            {
                SetGeomcopyAttr(newBody, plane, isJC);
            }
            var newPoint = SnapEx.Helper.GetElecMidPoint(Snap.Globals.WorkPart, body);
            if (newPoint != null)
            {
                newPoint.SetStringAttribute(SnapEx.EactConstString.EACT_ELECT_GROUP, guid);
                newPoint.Layer = order;
                newPoint.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                newPoint.Move(trans);
            }

            if (toggleJiaju.Value && selectionJiaju.Show)
            {
                var          tempJiaju = selectionJiaju.SelectedObjects.FirstOrDefault();
                Snap.NX.Body jiaju     = tempJiaju == null ? null : Snap.NX.Body.Wrap(tempJiaju.NXOpenTag);
                if (jiaju != null)
                {
                    jiaju       = jiaju.Copy();
                    jiaju.Layer = order;
                    jiaju.Move(Snap.Geom.Transform.CreateTranslation(movePosition - centerPosition));
                    //if (toggle0.Value) //继承
                    //{
                    //    var firstPos = new Snap.Position((jiaju.Box.MinX + jiaju.Box.MaxX) / 2, (jiaju.Box.MinY + jiaju.Box.MaxY) / 2, (jiaju.Box.MinZ + jiaju.Box.MaxZ) / 2);
                    //    var twoPos = firstPos.Copy(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                    //    jiaju.Move(Snap.Geom.Transform.CreateTranslation(twoPos - firstPos));
                    //}
                    //else
                    //{
                    //    jiaju.Move(Snap.Geom.Transform.CreateReflection(new Snap.Geom.Surface.Plane(plane.Origin, plane.Normal)));
                    //}
                    jiaju.SetStringAttribute("EACT_MIRROR_ELECT", "Y");
                    jiaju.Move(trans);
                }
            }
        }

        return(newBody);
    }
예제 #9
0
        static RevSurface ToRhinoRevSurface(NXOpen.Face face, FaceEx.FaceData faceData)
        {
            var bodyFeatures = face.GetBody().GetFeatures();

            var revolveFeature = bodyFeatures.FirstOrDefault(obj => obj is NXOpen.Features.Revolve);

            Curve  faceSectionCurve = default;
            double startRadian      = 0.0;
            double endRadian        = Math.PI * 2;

            if (revolveFeature != null)
            {
                NXOpen.Features.RevolveBuilder revolveBuilder = WorkPart.Features.CreateRevolveBuilder(revolveFeature);
                revolveBuilder.Section.GetOutputCurves(out var sectionCurves);

                startRadian = revolveBuilder.Limits.StartExtend.Value.Value * Math.PI / 180.0;

                endRadian = revolveBuilder.Limits.EndExtend.Value.Value * Math.PI / 180.0;

                revolveBuilder.Destroy();

                for (int i = 0; i < sectionCurves.Length; i++)
                {
                    var baseCurve = sectionCurves[i] as NXOpen.IBaseCurve;

                    var curveMidPt = baseCurve.GetPoint(0.5);
                    if (curveMidPt.DistanceTo(face.Tag).Distance < DistanceTolerance)
                    {
                        faceSectionCurve = baseCurve.ToRhinoCurve();
                        break;
                    }
                }
            }
            else
            {
                var faceBoundingBox = face.GetAlignedBoundingBox(faceData.Direction);

                var point1 = faceData.Point.Move(faceData.Direction, faceBoundingBox.Height * 1.5);

                var faceMidPoint = face.GetPoint();

                // 求与旋转方向垂直,并且位于面上的方向
                var verticalDirection = faceData.Direction.CrossProduct(faceMidPoint.Subtract(faceData.Point)).CrossProduct(faceData.Direction);

                var point2 = point1.Move(verticalDirection, faceBoundingBox.Length * 1.5);

                var point3 = point2.Move(faceData.Direction.Reverse(), faceBoundingBox.Height * 3);

                var point4 = point3.Move(verticalDirection.Reverse(), faceBoundingBox.Length * 1.5);

                NXOpen.Session.UndoMarkId undoMarkId = TheSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Calc Rev Profile");

                NXOpen.Body fourPointSurface = WorkPart.Features.CreateFourPointSurface(point1, point2, point3, point4);

                try
                {
                    NXOpen.Features.IntersectionCurve intersectionCurveFeature = WorkPart.Features.CreateIntersectionCurve(fourPointSurface.GetFaces(), face);

                    faceSectionCurve = (intersectionCurveFeature.GetEntities()[0] as NXOpen.Curve).ToRhino();

                    intersectionCurveFeature.Delete();

                    fourPointSurface.Delete();
                }
                catch (Exception)
                {
                    TheSession.UndoToMark(undoMarkId, "Calc Rev Profile");

                    Console.WriteLine($"无法创建面 {face.Tag} 的交线");

                    return(null);
                }
                finally
                {
                    TheSession.DeleteUndoMark(undoMarkId, "Calc Rev Profile");
                }
            }

            return(RevSurface.Create(faceSectionCurve, new Line(faceData.Point.ToRhino(), faceData.Point.Move(faceData.Direction, 10.0).ToRhino()), startRadian, endRadian));
        }