Beispiel #1
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var getObject = new GetObject();

            getObject.SetCommandPrompt($"Pick Object To Improve");
            var getRc = getObject.Get();

            if (getObject.CommandResult() != Result.Success)
            {
                return(getObject.CommandResult());
            }
            if (getRc == GetResult.Object)
            {
                //vpi.UserData.Add(nvud);
                foreach (var o in getObject.Objects())
                {
                    var nud = new RcTestUserData();
                    o.Object().Attributes.UserData.Add(nud);
                }
                return(Result.Success);
            }

            return(Result.Nothing);
        }
        private bool SelectFace()
        {
            using (var cmd = new GetObject())
            {
                cmd.SetCommandPrompt("Select the face");
                cmd.GeometryFilter  = ObjectType.Surface;
                cmd.SubObjectSelect = true;
                cmd.Get();

                if (cmd.CommandResult() != Result.Success)
                {
                    return(false);
                }

                if (cmd.ObjectCount == 0)
                {
                    return(false);
                }

                m_objref = cmd.Object(0);

                return(true);
            }
        }
Beispiel #3
0
        private void Btn_GetPlot_Click(object sender, RoutedEventArgs e)
        {
            var gcc = new GetObject();

            gcc.SetCommandPrompt("select closed curve");
            gcc.GeometryFilter          = Rhino.DocObjects.ObjectType.Curve;
            gcc.GeometryAttributeFilter = GeometryAttributeFilter.ClosedCurve;
            gcc.DisablePreSelect();
            //gcc.SubObjectSelect = false;
            gcc.Get();

            if (gcc.CommandResult() != Result.Success)
            {
                return;
            }
            if (null == gcc.Object(0).Curve())
            {
                return;
            }

            Curve boundary = gcc.Object(0).Curve();

            TuringAndCorbusierPlugIn.InstanceClass.plot = new TuringAndCorbusier.Plot(boundary);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // 1 - Select a site curve

            GetObject obj = new GetObject();

            obj.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;
            obj.SetCommandPrompt("Please select a curve representing your site");

            GetResult res = obj.Get();

            Curve site;

            if (res != GetResult.Object)
            {
                RhinoApp.WriteLine("The user did not select a curve");
                return(Result.Failure); // Failed to get a curve
            }
            if (obj.ObjectCount == 1)
            {
                site = obj.Object(0).Curve();
            }
            else
            {
                return(Result.Failure); //Failed to get a curve
            }



            // 2 - Extract the border from the precinct surface
            //Offset for Shop
            Curve[] offsets      = site.Offset(Plane.WorldXY, -2.5, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffset = Curve.JoinCurves(offsets); //join offset curves

            //Offset for Apartment
            Curve[] offsetBst       = site.Offset(Plane.WorldXY, -4, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffsetBst = Curve.JoinCurves(offsetBst); //join offset curves

            //Offset for Base
            Curve[] offsetTop       = site.Offset(Plane.WorldXY, -3, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.Chamfer);
            Curve[] joinedoffsetTop = Curve.JoinCurves(offsetTop); //join offset curves

            //List of offset curves
            List <Curve> buildingsCrv = new List <Curve>();

            buildingsCrv.AddRange(offsets);
            buildingsCrv.AddRange(offsetBst);
            buildingsCrv.AddRange(offsetTop);



            // 3 - Extrude all the offset curves
            //Extrusions
            Extrusion Shop = Extrusion.Create(buildingsCrv[0], 3.1, true);
            Extrusion Apa  = Extrusion.Create(buildingsCrv[1], 18.6, true);
            Extrusion Base = Extrusion.Create(buildingsCrv[2], -3.1, true);

            //List of extrusions
            List <Extrusion> buildingsExt = new List <Extrusion>();

            buildingsExt.Add(Shop);
            buildingsExt.Add(Apa);
            buildingsExt.Add(Base);

            //Draw all the extrusions
            foreach (Extrusion itExt in buildingsExt)
            {
                RhinoDoc.ActiveDoc.Objects.Add(itExt);
            }



            // 4 - Create contour lines on extrusions to represent floors
            //Define extrusions as Breps for contours
            Brep ShopBrep = Shop.ToBrep();
            Brep BrepApa  = Apa.ToBrep();

            //List of Breps
            List <Brep> BuildingBreps = new List <Brep>();

            BuildingBreps.Add(ShopBrep);
            BuildingBreps.Add(BrepApa);

            //Points to define contours
            Point3d start = new Point3d(0, 0, 0);
            Point3d end   = new Point3d(0, 0, 30);

            //Contours
            Curve[] Shopflr = Brep.CreateContourCurves(ShopBrep as Brep, start, end, 3.1);
            Curve[] ApaFlr  = Brep.CreateContourCurves(BrepApa as Brep, start, end, 3.1);

            //List of Contour Curves
            List <Curve> Floors = new List <Curve>();

            Floors.AddRange(Shopflr);
            Floors.AddRange(ApaFlr);

            //Draw all the Contour curves
            foreach (Curve itCrv in Floors)
            {
                RhinoDoc.ActiveDoc.Objects.Add(itCrv);
            }



            RhinoDoc.ActiveDoc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #5
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.
            MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance;

            if (p.if_painted_object_set_ == false)
            {
                RhinoApp.WriteLine("No mesh");
                return(Result.Failure);
            }
            Mesh my_mesh = p.painted_object_;

            Stopwatch watch = new Stopwatch();

            GetObject gbrep = new GetObject();

            gbrep.SetCommandPrompt("get the brep");
            gbrep.GeometryFilter  = Rhino.DocObjects.ObjectType.Brep;
            gbrep.SubObjectSelect = false;
            gbrep.Get();
            if (gbrep.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gbrep.CommandResult());
            }
            Rhino.DocObjects.ObjRef      my_objref = gbrep.Object(0);
            Rhino.DocObjects.RhinoObject my_obj    = my_objref.Object();
            if (my_obj == null)
            {
                return(Rhino.Commands.Result.Failure);
            }
            Brep brep = my_objref.Brep();

            if (brep == null)
            {
                return(Result.Failure);
            }
            my_obj.Select(false);

            GetObjectPosition gp = new GetObjectPosition(brep, my_mesh);

            gp.SetCommandPrompt("Get the object position on mesh: ");
            gp.Constrain(my_mesh, false);
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            Brep     moved_brep     = brep.DuplicateBrep();
            Point3d  Origin         = brep.UserDictionary.GetPoint3d("CurrentPosition");
            Vector3d OriginVector   = brep.UserDictionary.GetVector3d("CurrentDirection");
            Point3d  new_position   = gp.Point();
            Vector3d normal_on_mesh = my_mesh.NormalAt(my_mesh.ClosestMeshPoint(new_position, 0));

            if (OriginVector.IsParallelTo(normal_on_mesh) == 0)
            {
                double   RotationAngle = Vector3d.VectorAngle(OriginVector, normal_on_mesh);
                Vector3d RoationAxis   = Vector3d.CrossProduct(OriginVector, normal_on_mesh);
                moved_brep.Rotate(RotationAngle, RoationAxis, Origin);
            }

            moved_brep.Translate(new_position - Origin);
            moved_brep.UserDictionary.Set("CurrentPosition", new_position);
            moved_brep.UserDictionary.Set("CurrentDirection", normal_on_mesh);

            ObjectAttributes my_attributes = new ObjectAttributes();

            my_attributes.ObjectColor = Color.FromName(moved_brep.UserDictionary.GetString("Color"));
            my_attributes.ColorSource = ObjectColorSource.ColorFromObject;

            watch.Start();
            //delete all old paths
            IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve);

            foreach (RhinoObject path in path_objref)
            {
                doc.Objects.Delete(path, true);
            }
            watch.Stop();
            RhinoApp.WriteLine("time 1: {0}", watch.Elapsed);

            ObjectAttributes path_attributes = new ObjectAttributes();

            path_attributes.ObjectColor      = Color.Yellow;
            path_attributes.ColorSource      = ObjectColorSource.ColorFromObject;
            path_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject;
            path_attributes.PlotWeight       = 2.0;


            Guid      pin_1_id          = moved_brep.UserDictionary.GetGuid("PinID");
            MeshPoint current_meshpoint = my_mesh.ClosestMeshPoint(new_position, 0.0);

            watch.Restart();
            List <NurbsCurve> new_path_list = p.graph.DijkstraPath_Change(pin_1_id, current_meshpoint);

            watch.Stop();
            RhinoApp.WriteLine("time 2: {0}", watch.Elapsed);
            watch.Restart();
            for (int i = 0; i < new_path_list.Count; i++)
            {
                doc.Objects.Add(new_path_list[i], path_attributes);
            }

            doc.Objects.Delete(my_objref, true);
            brep.Dispose();
            doc.Objects.AddBrep(moved_brep, my_attributes);
            doc.Views.Redraw();
            watch.Stop();
            RhinoApp.WriteLine("time 3: {0}", watch.Elapsed);

            return(Result.Success);
        }
Beispiel #6
0
        public IList <PFVertex> PickVertex()
        {
            var innerVerts    = Vertices.Where(x => !x.External);
            var pickedVerts   = new List <PFVertex>();
            var doc           = Rhino.RhinoDoc.ActiveDoc;
            var vertexConduit = new DrawPFVertexConduit(innerVerts)
            {
                Enabled = true
            };

            doc.Views.Redraw();
            var gVert = new GetPFVertex(innerVerts);

            //var permOption = new OptionToggle(false, "temp", "perm");
            gVert.AddSnapPoints(innerVerts.Select(x => x.Point).ToArray());
            while (true)
            {
                gVert.SetCommandPrompt("select Vertex points. (<ESC> to exit");
                //gVert.AddOptionToggle("Remember", ref permOption);
                gVert.AcceptNothing(true);
                gVert.AcceptString(true);
                //gVert.SetCursor() // this we can change after switching to Rhino 6 - api

                gVert.SetDefaultString($"({pickedVerts.Count}) vertices selected press <Enter> to accept");
                gVert.Get(true);


                doc.Views.Redraw();
                var result    = gVert.CommandResult();
                var strResult = gVert.StringResult();
                pickedVerts = new List <PFVertex>();
                if (gVert.CommandResult() == Rhino.Commands.Result.Cancel)
                {
                    break;
                }
                foreach (var vrt in innerVerts)
                {
                    if (vrt.Picked)
                    {
                        pickedVerts.Add(vrt);
                    }
                }
                if (gVert.GotDefault())
                {
                    // here use a pick mechanism to get the geometry
                    if (pickedVerts.Count > 0)
                    {
                        var outside   = new OptionToggle(true, "true", "false");
                        var fixPoint  = new OptionToggle(false, "constrain", "fix");
                        var getRefGeo = new GetObject();
                        getRefGeo.SetCommandPrompt("Pick the constrain object for the selected vertices");

                        getRefGeo.AddOptionToggle("Outside", ref outside);
                        getRefGeo.AddOptionToggle("Fixed", ref fixPoint);
                        getRefGeo.AcceptNothing(true);
                        getRefGeo.DisablePreSelect();



                        if (getRefGeo.Get() == Rhino.Input.GetResult.Object)
                        {
                            var geoGet = getRefGeo.Object(0);
                            var idGet  = getRefGeo.Object(0).ObjectId;

                            SetVertexConstraints(pickedVerts, geoGet.Object(), 1, outside.CurrentValue);
                        }

                        else if (getRefGeo.Result() == Rhino.Input.GetResult.Nothing)
                        {
                            foreach (var vert in pickedVerts)
                            {
                                vert.RestrictPosition = null;
                                vert.RestrictSupport  = null;
                                vert.SupportGuid      = Guid.Empty;
                            }
                        }

                        else if (getRefGeo.Result() == Rhino.Input.GetResult.Option && fixPoint.CurrentValue == true)
                        {
                            foreach (var vert in pickedVerts)
                            {
                                vert.RestrictPosition = vert.ConstrainPoint;
                                vert.RestrictSupport  = new Rhino.Geometry.Point(vert.Point); // this is what keeps the vertex in place
                                vert.InfluenceCoef    = 100;                                  // this is what makes it relatively immovable
                                vert.SupportGuid      = Guid.Empty;
                                vert.Fixed            = true;                                 // this is just for serilization refference
                            }
                        }
                        doc.Objects.UnselectAll();
                        pickedVerts.ForEach(x => x.Picked = false);
                        doc.Views.Redraw();
                    }
                    else
                    {
                        break;
                    }
                }
            }
            vertexConduit.Enabled = false;
            doc.Views.Redraw();

            return(pickedVerts);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            GetObject go = new GetObject();

            go.SetCommandPrompt("Select curve to split");
            go.GeometryFilter          = ObjectType.Curve;
            go.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve;
            go.SubObjectSelect         = false;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            ObjRef      object_ref = go.Object(0);
            RhinoObject rh_object  = object_ref.Object();
            Curve       curve      = object_ref.Curve();

            if (null == rh_object || null == curve)
            {
                return(Result.Failure);
            }

            GetPoint gp = new GetPoint();

            gp.SetCommandPrompt("Point on curve to split at");
            gp.Constrain(curve, false);
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            Point3d point = gp.Point();
            double  t     = Rhino.RhinoMath.UnsetValue;

            if (!curve.ClosestPoint(point, out t))
            {
                return(Result.Failure);
            }

            List <double> curve_t = new List <double>(3);

            curve_t.Add(curve.Domain.Min);
            curve_t.Add(curve.Domain.Max);
            curve_t.Add(t);
            curve_t.Sort();

            List <double> culled_t = curve_t.Distinct().ToList();

            if (culled_t.Count < 3)
            {
                return(Result.Nothing);
            }

            ObjectAttributes attributes = rh_object.Attributes.Duplicate();

            attributes.ObjectId = Guid.Empty;

            for (int i = 0; i < culled_t.Count - 1; i++)
            {
                Interval domain = new Interval(culled_t[i], culled_t[i + 1]);
                if (curve.Domain.IncludesInterval(domain))
                {
                    Curve trim = curve.Trim(domain);
                    if (null != trim)
                    {
                        doc.Objects.Add(trim, attributes);
                    }
                }
            }

            doc.Objects.Delete(object_ref, false);
            doc.Views.Redraw();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go = new GetObject();

            go.SetCommandPrompt("Select curves");
            go.GeometryFilter = ObjectType.Curve;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var curve = go.Object(0).Curve();

            if (null == curve)
            {
                return(Result.Failure);
            }

            var continuity = Continuity.G1_continuous;

            var gd = new GetOption();

            gd.SetCommandPrompt("Discontinuity to search");
            gd.AddOptionEnumList("Discontinuity", continuity);
            gd.AcceptNothing(true);
            var res = gd.Get();

            if (res == GetResult.Option)
            {
                var option = gd.Option();
                if (null == option)
                {
                    return(Result.Failure);
                }

                var list = Enum.GetValues(typeof(Continuity)).Cast <Continuity>().ToList();
                continuity = list[option.CurrentListOptionIndex];
            }
            else if (res != GetResult.Nothing)
            {
                return(Result.Cancel);
            }

            var t0 = curve.Domain.Min;
            var t1 = curve.Domain.Max;

            var parameters = new List <double>();

            parameters.Add(t0);
            for (; ;)
            {
                double t;
                var    rc = curve.GetNextDiscontinuity(continuity, t0, t1, out t);
                if (rc)
                {
                    parameters.Add(t);
                    t0 = t;
                }
                else
                {
                    break;
                }
            }
            parameters.Add(t1);

            if (parameters.Count > 2)
            {
                for (var i = 0; i < parameters.Count - 1; i++)
                {
                    t0 = parameters[i];
                    t1 = parameters[i + 1];
                    var dom       = new Interval(t0, t1);
                    var new_curve = curve.Trim(dom);
                    if (null != new_curve)
                    {
                        doc.Objects.AddCurve(new_curve);
                    }
                }

                doc.Objects.Delete(go.Object(0), false);
            }

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.
            MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance;

            if (p.if_painted_object_set_ == false)
            {
                RhinoApp.WriteLine("No mesh");
                return(Result.Failure);
            }
            Mesh my_mesh = p.painted_object_;

            GetObject gbrep = new GetObject();

            gbrep.SetCommandPrompt("get the brep");
            gbrep.GeometryFilter  = Rhino.DocObjects.ObjectType.Brep;
            gbrep.SubObjectSelect = false;
            gbrep.Get();
            if (gbrep.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gbrep.CommandResult());
            }
            ObjRef      my_objref = gbrep.Object(0);
            RhinoObject my_obj    = my_objref.Object();

            if (my_obj == null)
            {
                return(Rhino.Commands.Result.Failure);
            }
            Brep brep = my_objref.Brep();

            if (brep == null)
            {
                return(Result.Failure);
            }
            my_obj.Select(false);

            int brep_number = 0;

            for (int i = 0; i < p.my_objects_list.Count; i++)
            {
                Brep an_object = p.my_objects_list[i];
                if (My_object_functions.GetComponentID(brep) == My_object_functions.GetComponentID(an_object))
                {
                    brep_number = i;
                    break;
                }
            }

            Point3d  position         = My_object_functions.GetPosition(brep);
            Vector3d normal_direction = My_object_functions.GetZ(brep);
            Plane    plane            = new Plane(position, normal_direction);

            /*
             * GetPoint gp = new GetPoint();
             * gp.Constrain(plane, false);
             * gp.Get();
             * if (gp.CommandResult() != Result.Success)
             *  return gp.CommandResult();
             * var start_point = gp.Point();
             * if (start_point == Point3d.Unset)
             *  return Result.Failure;
             */

            Vector3d horizontal_direction = My_object_functions.GetY(brep);
            Point3d  start_point          = position + 10 * horizontal_direction;

            GetRotationAngle gr = new GetRotationAngle(brep, my_mesh, start_point);

            gr.SetCommandPrompt("Get the rotation angle");
            gr.Constrain(plane, false);
            gr.Get();
            if (gr.CommandResult() != Result.Success)
            {
                return(gr.CommandResult());
            }

            Point3d end_point = gr.Point();
            Brep    new_brep  = GetRotationAngle.RotateBrep(brep, my_mesh, end_point, start_point);

            ObjectAttributes path_attributes = new ObjectAttributes();

            path_attributes.ObjectColor      = Color.Yellow;
            path_attributes.ColorSource      = ObjectColorSource.ColorFromObject;
            path_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject;
            path_attributes.PlotWeight       = 2.0;

            ObjectAttributes my_attributes = new ObjectAttributes();

            my_attributes.ObjectColor = My_object_functions.GetColor(new_brep);
            my_attributes.ColorSource = ObjectColorSource.ColorFromObject;

            int new_pin_number = My_object_functions.GetPinQuantity(new_brep);
            List <NurbsCurve> new_path_list = new List <NurbsCurve>();

            for (int i = 0; i < new_pin_number; i++)
            {
                Guid      pin_id       = My_object_functions.GetPinGuid(new_brep, i);
                Point3d   pin_position = My_object_functions.GetPinPosition(new_brep, i);
                MeshPoint pin_on_mesh  = my_mesh.ClosestMeshPoint(pin_position, 0);
                new_path_list = p.graph.DijkstraPath_Change(pin_id, pin_on_mesh);
            }

            IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve);

            foreach (RhinoObject path in path_objref)
            {
                doc.Objects.Delete(path, true);
            }

            for (int i = 0; i < new_path_list.Count; i++)
            {
                Guid path_id = new_path_list[i].UserDictionary.GetGuid("PathID");
                path_attributes.ObjectId = path_id;
                doc.Objects.AddCurve(new_path_list[i], path_attributes);
            }

            doc.Objects.Delete(my_objref, true);
            doc.Objects.AddBrep(new_brep, my_attributes);
            p.my_objects_list[brep_number] = new_brep;
            doc.Views.Redraw();


            return(Result.Success);
        }
Beispiel #10
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var view = doc.Views.ActiveView;

            if (null == view)
            {
                return(Result.Failure);
            }

            var page_view = view as RhinoPageView;

            if (null == page_view)
            {
                RhinoApp.WriteLine("The active view is neither a layout nor a detail view.");
                return(Result.Failure);
            }

            var go = new GetObject();

            go.SetCommandPrompt("Select point object");
            go.GeometryFilter = ObjectType.Point;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var point_obj = go.Object(0).Point();

            if (null == point_obj)
            {
                return(Result.Failure);
            }

            if (page_view.PageIsActive)
            {
                var gd = new GetDetailViewObject();
                gd.SetCommandPrompt("Select target detail view");
                gd.EnablePreSelect(false, true);
                gd.DeselectAllBeforePostSelect = false;
                gd.Get();
                if (gd.CommandResult() != Result.Success)
                {
                    return(gd.CommandResult());
                }

                var detail = gd.Object(0).Object() as DetailViewObject;
                if (null != detail)
                {
                    var point = point_obj.Location;
                    RhinoApp.WriteLine("Page location: {0}", point.ToString());
                    point.Transform(detail.PageToWorldTransform);
                    RhinoApp.WriteLine("World location: {0}", point.ToString());
                }
            }
            else
            {
                var detail = FindActiveDetailObject(page_view);
                if (null != detail)
                {
                    var point = point_obj.Location;
                    RhinoApp.WriteLine("World location: {0}", point.ToString());
                    point.Transform(detail.WorldToPageTransform);
                    RhinoApp.WriteLine("Page location: {0}", point.ToString());
                }
            }

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go = new GetObject();

            go.SetCommandPrompt("Select curve to intersect");
            go.GeometryFilter = ObjectType.Curve;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var curve = go.Object(0).Curve();

            if (null == curve)
            {
                return(Result.Failure);
            }

            var gp = new GetPoint();

            gp.SetCommandPrompt("First point of infinite intersecting line");
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            var from = gp.Point();

            gp.SetCommandPrompt("Second point of infinite intersecting line");
            gp.SetBasePoint(from, true);
            gp.DrawLineFromPoint(from, true);
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            var line = new Rhino.Geometry.Line(from, gp.Point());

            if (!line.IsValid || line.Length < Rhino.RhinoMath.SqrtEpsilon)
            {
                return(Result.Nothing);
            }

            var ccx = IntersectCurveLine(curve, line, doc.ModelAbsoluteTolerance, doc.ModelAbsoluteTolerance);

            if (null != ccx)
            {
                foreach (var x in ccx)
                {
                    if (x.IsPoint)
                    {
                        doc.Objects.AddPoint(x.PointA);
                    }
                }
                doc.Views.Redraw();
            }

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Select surface that look like a cylinder
            var go = new GetObject();

            go.SetCommandPrompt("Select surface that look like a cylinder");
            go.GeometryFilter = ObjectType.Surface;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var obj     = go.Object(0).Object();
            var surface = go.Object(0).Surface();

            if (null == obj || null == surface)
            {
                return(Result.Failure);
            }

            // Verify the surface looks like a cylinder
            Cylinder cylinder;

            if (!surface.TryGetCylinder(out cylinder, doc.ModelAbsoluteTolerance))
            {
                RhinoApp.WriteLine("Surface is not a cylinder");
                return(Result.Success);
            }

            var circle = cylinder.CircleAt(0.0);
            var plane  = circle.Plane;
            var origin = plane.Origin;

            // Calculate a plane-aligned bounding box.
            // Calculating the bounding box from the runtime object, instead
            // of a copy of the geometry, will produce a more accurate result.
            var world_to_plane = Transform.ChangeBasis(Plane.WorldXY, plane);
            var bbox           = obj.Geometry.GetBoundingBox(world_to_plane);

            // Move the cylinder's plane to the base of the bounding box.
            // Create a plane through the base of the bounding box.
            var bbox_plane = new Plane(
                bbox.Corner(true, true, true),
                bbox.Corner(false, true, true),
                bbox.Corner(true, false, true)
                );
            // Transform the plane to the world xy-plane
            var plane_to_world = Transform.ChangeBasis(plane, Plane.WorldXY);

            bbox_plane.Transform(plane_to_world);
            // Project the cylinder plane's origin onto the bounding box plane
            plane.Origin = bbox_plane.ClosestPoint(origin);

            // Cylinder height is bounding box height
            var pt0    = bbox.Corner(true, true, true);
            var pt1    = bbox.Corner(true, true, false);
            var height = pt0.DistanceTo(pt1);

            // Create a new cylinder
            var new_circle   = new Circle(plane, circle.Radius);
            var new_cylinder = new Cylinder(new_circle, height);
            var rev_surface  = new_cylinder.ToRevSurface();

            doc.Objects.AddSurface(rev_surface);
            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #13
0
        /// <summary>
        /// Called by Rhino when the user runs the command.
        /// </summary>
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go = new GetObject();

            go.SetCommandPrompt("Select object");
            go.SubObjectSelect = false;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var obj_ref = go.Object(0);
            var obj     = obj_ref.Object();

            if (null == obj)
            {
                return(Result.Failure);
            }

            var pre_selected = go.ObjectsWerePreselected;

            obj.Select(true);

            var gt = new GetOption();

            gt.SetCommandPrompt("Choose mobile plane option");
            gt.AcceptNothing(true);

            var attach_index  = gt.AddOption("Attach");
            var detach_index  = gt.AddOption("Detach");
            var enable_index  = gt.AddOption("Enable");
            var refresh_index = gt.AddOption("Refresh");
            var show_index    = gt.AddOption("Show");

            for (;;)
            {
                var res = gt.Get();
                if (res != GetResult.Option)
                {
                    break;
                }

                var rc    = Result.Cancel;
                var index = gt.OptionIndex();

                if (index == attach_index)
                {
                    rc = AttachOption(doc, obj);
                }
                else if (index == detach_index)
                {
                    rc = DetachOption(doc, obj);
                }
                else if (index == enable_index)
                {
                    rc = EnableOption(doc, obj);
                }
                else if (index == refresh_index)
                {
                    rc = RefreshOption(doc, obj);
                }
                else if (index == show_index)
                {
                    rc = ShowOption(doc, obj);
                }

                if (rc != Result.Success)
                {
                    break;
                }
            }

            if (!pre_selected)
            {
                doc.Objects.UnselectAll();
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #14
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.
            MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance;

            if (p.if_painted_object_set_ == false)
            {
                RhinoApp.WriteLine("No mesh");
                return(Result.Failure);
            }
            Mesh my_mesh = p.painted_object_;

            DijkstraGraph my_graph = p.graph;

            GetObject gbrep1 = new GetObject();

            gbrep1.SetCommandPrompt("get the brep");
            gbrep1.GeometryFilter  = Rhino.DocObjects.ObjectType.Brep;
            gbrep1.SubObjectSelect = false;
            gbrep1.Get();
            if (gbrep1.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gbrep1.CommandResult());
            }
            Rhino.DocObjects.ObjRef      my_objref1 = gbrep1.Object(0);
            Rhino.DocObjects.RhinoObject my_obj1    = my_objref1.Object();
            if (my_obj1 == null)
            {
                return(Rhino.Commands.Result.Failure);
            }
            Brep brep1 = my_objref1.Brep();

            if (brep1 == null)
            {
                return(Result.Failure);
            }
            my_obj1.Select(false);

            for (int i = 0; i < p.my_objects_list.Count; i++)
            {
                Guid brep1_id     = My_object_functions.GetComponentID(brep1);
                Guid my_object_id = My_object_functions.GetComponentID(p.my_objects_list[i]);
                if (brep1_id == my_object_id)
                {
                    p.my_objects_list.RemoveAt(i);
                }
            }

            IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve);

            foreach (RhinoObject path in path_objref)
            {
                doc.Objects.Delete(path, true);
            }

            List <NurbsCurve> new_path_list = new List <NurbsCurve>();
            int pin_number = My_object_functions.GetPinQuantity(brep1);

            for (int i = 0; i < pin_number; i++)
            {
                Guid pin_id = My_object_functions.GetPinGuid(brep1, i);
                new_path_list = p.graph.DijkstraPath_DeletePin(pin_id);
            }

            ObjectAttributes my_attributes = new ObjectAttributes();

            my_attributes.ObjectColor      = Color.Yellow;
            my_attributes.ColorSource      = ObjectColorSource.ColorFromObject;
            my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject;
            my_attributes.PlotWeight       = 2.0;

            doc.Objects.Delete(my_objref1, true);

            for (int i = 0; i < new_path_list.Count; i++)
            {
                Guid path_id = new_path_list[i].UserDictionary.GetGuid("PathID");
                my_attributes.ObjectId = path_id;
                doc.Objects.Add(new_path_list[i], my_attributes);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #15
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.

            MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance;

            if (p.if_painted_object_set_ == false)
            {
                RhinoApp.WriteLine("No mesh");
                return(Result.Failure);
            }
            Mesh my_mesh = p.painted_object_;

            DijkstraGraph my_graph = p.graph;

            GetObject gbrep1 = new GetObject();

            gbrep1.SetCommandPrompt("get the brep");
            gbrep1.GeometryFilter  = Rhino.DocObjects.ObjectType.Brep;
            gbrep1.SubObjectSelect = false;
            gbrep1.Get();
            if (gbrep1.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gbrep1.CommandResult());
            }
            Rhino.DocObjects.ObjRef      my_objref1 = gbrep1.Object(0);
            Rhino.DocObjects.RhinoObject my_obj1    = my_objref1.Object();
            if (my_obj1 == null)
            {
                return(Rhino.Commands.Result.Failure);
            }
            Brep brep1 = my_objref1.Brep();

            if (brep1 == null)
            {
                return(Result.Failure);
            }
            my_obj1.Select(false);

            GetObject gbrep2 = new GetObject();

            gbrep2.SetCommandPrompt("get the brep");
            gbrep2.GeometryFilter  = Rhino.DocObjects.ObjectType.Brep;
            gbrep2.SubObjectSelect = false;
            gbrep2.Get();
            if (gbrep2.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gbrep2.CommandResult());
            }
            Rhino.DocObjects.ObjRef      my_objref2 = gbrep2.Object(0);
            Rhino.DocObjects.RhinoObject my_obj2    = my_objref2.Object();
            if (my_obj2 == null)
            {
                return(Rhino.Commands.Result.Failure);
            }
            Brep brep2 = my_objref2.Brep();

            if (brep2 == null)
            {
                return(Result.Failure);
            }
            my_obj2.Select(false);

            Point3d pin_1_position = brep1.UserDictionary.GetPoint3d("CurrentPosition");
            Point3d pin_2_position = brep2.UserDictionary.GetPoint3d("CurrentPosition");
            Guid    pin_1_id       = brep1.UserDictionary.GetGuid("PinID");
            Guid    pin_2_id       = brep2.UserDictionary.GetGuid("PinID");

            MeshPoint pin_1_meshpoint = my_mesh.ClosestMeshPoint(pin_1_position, 0);
            MeshPoint pin_2_meshpoint = my_mesh.ClosestMeshPoint(pin_2_position, 0);
            Stopwatch watch           = new Stopwatch();

            watch.Start();
            NurbsCurve d_path = my_graph.DijkstraPath_Add(pin_1_meshpoint, pin_1_id, pin_2_meshpoint, pin_2_id);

            watch.Stop();
            if (d_path == null)
            {
                return(Result.Success);
            }
            RhinoApp.WriteLine("link time: {0}", watch.Elapsed);
            ObjectAttributes my_attributes = new ObjectAttributes();

            my_attributes.ObjectColor      = Color.Yellow;
            my_attributes.ColorSource      = ObjectColorSource.ColorFromObject;
            my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject;
            my_attributes.PlotWeight       = 2.0;

            doc.Objects.AddCurve(d_path, my_attributes);
            doc.Views.Redraw();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go = new GetObject();

            go.SetCommandPrompt("Select curves");
            go.GeometryFilter = ObjectType.Curve;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var curve = go.Object(0).Curve();

            if (null == curve)
            {
                return(Result.Failure);
            }

            var continuity = Continuity.G1_continuous;

            var gd = new GetOption();

            gd.SetCommandPrompt("Discontinuity to search");
            gd.AddOptionEnumList("Discontinuity", continuity);
            gd.AcceptNothing(true);
            var res = gd.Get();

            if (res == GetResult.Option)
            {
                var option = gd.Option();
                if (null == option)
                {
                    return(Result.Failure);
                }

                var list = Enum.GetValues(typeof(Continuity)).Cast <Continuity>().ToList();
                continuity = list[option.CurrentListOptionIndex];
            }
            else if (res != GetResult.Nothing)
            {
                return(Result.Cancel);
            }

            var t0 = curve.Domain.Min;
            var t1 = curve.Domain.Max;

            for (; ;)
            {
                double t;
                var    rc = curve.GetNextDiscontinuity(continuity, t0, t1, out t);
                if (rc)
                {
                    doc.Objects.AddPoint(curve.PointAt(t));
                    t0 = t;
                }
                else
                {
                    break;
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #17
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            GetObject go;

            go = new GetObject();
            go.AcceptNothing(true);
            go.AcceptEnterWhenDone(true);
            go.SetCommandPrompt("请选择边界");
            go.GeometryFilter = ObjectType.Curve;

            if (go.Get() != GetResult.Object)
            {
                return(Result.Failure);
            }
            Curve boundCrv = go.Object(0).Curve();

            if (!boundCrv.IsPlanar() || !boundCrv.IsPolyline() || !boundCrv.IsClosed)
            {
                return(Result.Failure);
            }

            boundCrv.GetBoundingBox(Plane.WorldXY, out Box bound);

            var dialog = new SelectFolderDialog()
            {
                Title = "保存位置"
            };

            DialogResult res = dialog.ShowDialog(Rhino.UI.RhinoEtoApp.MainWindow);

            if (res == DialogResult.Ok)
            {
                try
                {
                    Dictionary <string, string> pathMap = new Dictionary <string, string>();

                    foreach (var layer in doc.Layers)
                    {
                        var objects = doc.Objects.FindByLayer(layer);
                        if (!layer.IsVisible || !layer.IsValid || objects.Length == 0)
                        {
                            continue;
                        }

                        string name = layer.FullPath.Replace(Layer.PathSeparator, "$$");

                        string realPath = IOPath.Combine(dialog.Directory, name + ".eps");
                        string tmpPath  = IOPath.Combine(IOPath.GetTempPath(), layer.Id.ToString());

                        var eps = new EncapsulatedPostScript(bound);

                        var objs = SelectAllObjectsInBound(bound, objects);
                        if (objs.Count == 0)
                        {
                            continue;
                        }

                        eps.SaveEPS(objs, tmpPath);

                        pathMap.Add(tmpPath, realPath);
                    }

                    if (pathMap.Count == 0)
                    {
                        return(Result.Cancel);
                    }

                    foreach (KeyValuePair <string, string> item in pathMap)
                    {
                        System.IO.File.Move(item.Key, item.Value);
                        RhinoApp.WriteLine($"已写入, {item.Value}");
                    }

                    System.Diagnostics.Process.Start(dialog.Directory);
                }
                catch (Exception ex)
                {
                    RhinoApp.WriteLine(ex.Message);
                } finally
                {
                    doc.Objects.UnselectAll();
                    doc.Views.Redraw();
                }
            }

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var rails = new Guid[2];

            var go = new GetObject();

            go.SetCommandPrompt("Select first rail");
            go.GeometryFilter          = ObjectType.Curve;
            go.GeometryAttributeFilter = GeometryAttributeFilter.ClosedCurve;
            go.DisablePreSelect();
            go.SubObjectSelect = false;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var obj = go.Object(0).Object();

            if (null == obj)
            {
                return(Result.Failure);
            }
            rails[0] = obj.Id;

            go.SetCommandPrompt("Select second rail");
            go.DeselectAllBeforePostSelect = false;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            obj = go.Object(0).Object();
            if (null == obj)
            {
                return(Result.Failure);
            }
            rails[1] = obj.Id;

            var gc = new GetObject();

            gc.SetCommandPrompt("Select cross section curves");
            gc.GeometryFilter          = ObjectType.Curve;
            gc.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve;
            gc.DisablePreSelect();
            gc.DeselectAllBeforePostSelect = false;
            gc.SubObjectSelect             = false;
            gc.GetMultiple(1, 0);
            if (gc.CommandResult() != Result.Success)
            {
                return(gc.CommandResult());
            }

            var curves = new Guid[gc.ObjectCount];

            for (var i = 0; i < gc.ObjectCount; i++)
            {
                obj = gc.Object(i).Object();
                if (null == obj)
                {
                    return(Result.Failure);
                }
                curves[i] = obj.Id;
            }

            var object_ids = ScriptedSweep2(doc, rails[0], rails[1], curves);

            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #19
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var gp = new GetObject();

            gp.SetCommandPrompt("Select points to project");
            gp.GeometryFilter = ObjectType.Point;
            gp.GetMultiple(1, 0);
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            var gm = new GetObject();

            gm.SetCommandPrompt("Select mesh to project onto");
            gm.GeometryFilter  = ObjectType.Mesh;
            gm.SubObjectSelect = false;
            gm.EnablePreSelect(false, true);
            gm.DeselectAllBeforePostSelect = false;
            gm.Get();
            if (gm.CommandResult() != Result.Success)
            {
                return(gm.CommandResult());
            }

            var mesh = gm.Object(0).Mesh();

            if (null == mesh)
            {
                return(Result.Failure);
            }

            var meshes = new List <Mesh>(1)
            {
                mesh
            };

            var points = new List <Point3d>(gp.ObjectCount);

            for (var i = 0; i < gp.ObjectCount; i++)
            {
                var point = gp.Object(i).Point();
                if (null != point)
                {
                    points.Add(point.Location);
                }
            }

            var dir = -Vector3d.ZAxis;
            var tol = doc.ModelAbsoluteTolerance;

            int[] indices;
            var   project_points = Intersection.ProjectPointsToMeshesEx(meshes, points, dir, tol, out indices);

            if (null != project_points)
            {
                for (int i = 0; i < project_points.Length; i++)
                {
                    doc.Objects.AddPoint(project_points[i]);
                    doc.Objects.AddLine(project_points[i], points[indices[i]]);
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.
            GetObject go = new GetObject();

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;
            go.EnableSelPrevious(true);
            go.EnablePreSelect(true, false);
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve;

            go.SetCommandPrompt("Select All circles you want to filter:");
            GetResult result = go.GetMultiple(1, 0);

            if (go.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(go.CommandResult());
            }

            int fixingHoleCounter = go.ObjectCount;

            RhinoApp.WriteLine("circle selection counter = {0}", fixingHoleCounter);

            int i = 0;

            Point3d[]     fixingHole  = new Point3d[fixingHoleCounter];
            double[]      fixingHoleD = new double[fixingHoleCounter];
            RhinoObject[] references  = new RhinoObject[fixingHoleCounter];

            for (i = 0; i < go.ObjectCount; i++)
            {
                RhinoObject rhinoObject = go.Object(i).Object();
                Curve       curve       = (new ObjRef(rhinoObject)).Curve();
                if (curve == null)
                {
                    continue;
                }

                if (curve.IsClosed == false)
                {
                    continue;
                }

                if (curve.IsPlanar() == false)
                {
                    continue;
                }

                if (curve.IsCircle())
                {
                    BoundingBox boundingBox = curve.GetBoundingBox(true);
                    fixingHoleD[i] = boundingBox.Max.X - boundingBox.Min.X;
                    fixingHole[i]  = boundingBox.Center;
                    references[i]  = rhinoObject;
                }
            }

            //Get the gap clearance offset
            go.SetCommandPrompt("Enter detection radius:");
            go.AcceptNumber(true, false);
            go.Get();
            double offset = go.Number();

            double perforationHoldD;
            string layerName = "";


            //for testing purpose, draw the hole with offset using red color

            /*Curve[] circles = new Curve[fixingHole.Length];
             * for (i = 0; i < circles.Length; i++)
             * {
             *
             *  circles[i] = new ArcCurve(new Circle(fixingHole[i], offset));
             * }
             *
             *
             * if (circles != null)
             * {
             *  layerName = offset + "mm GAP CLEARANCE";
             *  RhinoUtilities.SetActiveLayer(layerName, System.Drawing.Color.Red);
             *
             *  foreach (Curve cv in circles)
             *  {
             *      Guid guid = RhinoDoc.ActiveDoc.Objects.AddCurve(cv);
             *  }
             * }*/

            string clashHoleLayerName = "HOLES CLASHED";
            Layer  clashHoleLayer     = new Layer();

            clashHoleLayer.Name  = clashHoleLayerName;
            clashHoleLayer.Color = System.Drawing.Color.Red;

            int clashHoleLayerIndex = doc.Layers.Add(clashHoleLayer);
            int currentHoleCounter;
            int flag;

            bool[] deletedCircles = new bool[fixingHole.Length];
            for (i = 0; i < deletedCircles.Length; i++)
            {
                deletedCircles[i] = false;
            }

            Curve circles;

            RhinoUtilities.SetActiveLayer(clashHoleLayerName, System.Drawing.Color.Red);
            for (i = 0; i < fixingHole.Length - 1; i++)
            {
                currentHoleCounter = 0;
                flag = 0;
                for (int j = i + 1; j < fixingHole.Length; j++)
                {
                    if (deletedCircles[j] == true)
                    {
                        continue;
                    }
                    if (fixingHole[i].DistanceTo(fixingHole[j]) < fixingHoleD[i] + offset)
                    {
                        if (currentHoleCounter == 0)
                        {
                            flag = j;
                            currentHoleCounter++;
                        }
                        else
                        {
                            currentHoleCounter++;
                            break;
                        }
                    }
                    if (currentHoleCounter == 1)
                    {
                        circles = new ArcCurve(new Circle(fixingHole[flag], fixingHoleD[flag] / 2));
                        Guid guid = RhinoDoc.ActiveDoc.Objects.AddCurve(circles);

                        RhinoDoc.ActiveDoc.Objects.Delete(references[flag], false);
                        deletedCircles[flag] = true;
                    }
                    else if (currentHoleCounter == 2)
                    {
                        circles = new ArcCurve(new Circle(fixingHole[i], fixingHoleD[i] / 2));
                        Guid guid = RhinoDoc.ActiveDoc.Objects.AddCurve(circles);

                        RhinoDoc.ActiveDoc.Objects.Delete(references[i], false);
                        deletedCircles[i] = true;
                    }
                }
            }


            RhinoUtilities.setLayerVisibility("HOLES CLASHED", true);

            RhinoUtilities.setLayerVisibility(layerName, false);

            doc.Views.Redraw();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var go = new GetObject();

            go.SetCommandPrompt("Selet surface or polysurface to serialize to a file.");
            go.GeometryFilter  = ObjectType.Surface | ObjectType.PolysrfFilter;
            go.SubObjectSelect = false;
            go.Get();
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            var brep = go.Object(0).Brep();

            if (null == brep)
            {
                return(Result.Failure);
            }

            string path = null;

            if (mode == RunMode.Interactive)
            {
                var dialog = new SaveFileDialog
                {
                    Title      = EnglishName,
                    Filter     = @"Bin Files (*.bin)|*.bin||",
                    DefaultExt = "bin"
                };

                if (!dialog.ShowSaveDialog())
                {
                    return(Result.Cancel);
                }

                path = dialog.FileName;
            }
            else
            {
                var result = RhinoGet.GetString("Save file name", false, ref path);
                if (result != Result.Success)
                {
                    return(result);
                }
            }

            path = path.Trim();
            if (string.IsNullOrEmpty(path))
            {
                return(Result.Nothing);
            }

            if (!Path.HasExtension(path))
            {
                path = Path.ChangeExtension(path, ".bin");
            }

            var rc = SampleCsGeometryHelper.WriteToFile(path, brep);

            return(rc ? Result.Success : Result.Failure);
        }
        /// <summary>
        /// Runs the command
        /// </summary>
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Select objects to orient
            var go = new GetObject();

            go.SetCommandPrompt("Select objects to orient");
            go.SubObjectSelect = false;
            go.GroupSelect     = true;
            go.GetMultiple(1, 0);
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            // Point to orient from
            var gp = new GetPoint();

            gp.SetCommandPrompt("Point to orient from");
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            // Define source plane
            var view = gp.View();

            if (view == null)
            {
                view = doc.Views.ActiveView;
                if (view == null)
                {
                    return(Result.Failure);
                }
            }

            var plane = view.ActiveViewport.ConstructionPlane();

            plane.Origin = gp.Point();

            // Curve to orient on
            var gc = new GetObject();

            gc.SetCommandPrompt("Curve to orient on");
            gc.GeometryFilter = ObjectType.Curve;
            gc.EnablePreSelect(false, true);
            gc.DeselectAllBeforePostSelect = false;
            gc.Get();
            if (gc.CommandResult() != Result.Success)
            {
                return(gc.CommandResult());
            }

            var objref = gc.Object(0);
            var obj    = objref.Object();
            var curve  = objref.Curve();

            if (obj == null || curve == null)
            {
                return(Result.Failure);
            }

            // Unselect curve
            obj.Select(false);

            // Point on surface to orient to
            var gx = new GetOrientPerpendicularPoint(curve, plane, go.Object(0).Object());

            gx.SetCommandPrompt("New base point on curve");
            gx.Get();
            if (gx.CommandResult() != Result.Success)
            {
                return(gx.CommandResult());
            }

            // One final calculation
            var xform = new Transform(1);

            if (gx.CalculateTransform(gx.View().ActiveViewport, gx.Point(), ref xform))
            {
                doc.Objects.Transform(go.Object(0).Object(), xform, true);
                doc.Views.Redraw();
            }

            return(Result.Success);
        }
Beispiel #23
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            bool bHavePreselectedObjects = false;

            const ObjectType geometryFilter = ObjectType.MeshFace;

            OptionDouble  minEdgeLengthOption     = new OptionDouble(minEdgeLength, 0.001, 200);
            OptionDouble  maxEdgeLengthOption     = new OptionDouble(maxEdgeLength, 0.001, 200);
            OptionDouble  constriantAngleOption   = new OptionDouble(constriantAngle, 0.001, 360);
            OptionInteger smoothStepsOptions      = new OptionInteger(smoothSteps, 0, 100);
            OptionDouble  smoothSpeedOption       = new OptionDouble(smoothSpeed, 0.01, 1.0);
            OptionDouble  projectAmountOption     = new OptionDouble(projectedAmount, 0.01, 1.0);
            OptionDouble  projectedDistanceOption = new OptionDouble(projectedDistance, 0.01, 100000.0);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select mesh faces to project onto another mesh");
            go.GeometryFilter = geometryFilter;

            go.AddOptionDouble("ConstraintAngle", ref constriantAngleOption);
            go.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            go.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption);
            go.AddOptionInteger("SmoothSteps", ref smoothStepsOptions);
            go.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption);

            go.GroupSelect     = true;
            go.SubObjectSelect = true;

            for (; ;)
            {
                GetResult faceres = go.GetMultiple(1, 0);

                if (faceres == GetResult.Option)
                {
                    go.EnablePreSelect(false, true);
                    continue;
                }

                else if (go.CommandResult() != Result.Success)
                {
                    return(go.CommandResult());
                }

                if (go.ObjectsWerePreselected)
                {
                    bHavePreselectedObjects = true;
                    go.EnablePreSelect(false, true);
                    continue;
                }

                break;
            }

            minEdgeLength   = minEdgeLengthOption.CurrentValue;
            maxEdgeLength   = maxEdgeLengthOption.CurrentValue;
            constriantAngle = constriantAngleOption.CurrentValue;
            smoothSteps     = smoothStepsOptions.CurrentValue;
            smoothSpeed     = smoothSpeedOption.CurrentValue;

            //System.Collections.Generic.List<System.Guid> meshes = new System.Collections.Generic.List<System.Guid>();

            System.Guid rhinoMesh = System.Guid.Empty;

            System.Collections.Generic.List <int> removeFaces = new System.Collections.Generic.List <int>();

            g3.DMesh3 projectFaces = new g3.DMesh3(true, false, false, false);

            Rhino.Geometry.Mesh rhinoInputMesh = new Rhino.Geometry.Mesh();

            for (int i = 0; i < go.ObjectCount; i++)
            {
                ObjRef obj = go.Object(i);

                if (rhinoMesh == System.Guid.Empty)
                {
                    rhinoMesh      = obj.ObjectId;
                    rhinoInputMesh = obj.Mesh();

                    for (int j = 0; j < rhinoInputMesh.Vertices.Count; j++)
                    {
                        var vertex = new g3.NewVertexInfo();
                        vertex.n = new g3.Vector3f(rhinoInputMesh.Normals[j].X, rhinoInputMesh.Normals[j].Y, rhinoInputMesh.Normals[j].Z);
                        vertex.v = new g3.Vector3d(rhinoInputMesh.Vertices[j].X, rhinoInputMesh.Vertices[j].Y, rhinoInputMesh.Vertices[j].Z);
                        projectFaces.AppendVertex(vertex);
                    }
                }

                var m = rhinoInputMesh;

                if (rhinoMesh != obj.ObjectId)
                {
                    continue;
                }

                removeFaces.Add(obj.GeometryComponentIndex.Index);

                var mf = rhinoInputMesh.Faces[obj.GeometryComponentIndex.Index];


                if (mf.IsQuad)
                {
                    double dist1 = m.Vertices[mf.A].DistanceTo(m.Vertices[mf.C]);
                    double dist2 = m.Vertices[mf.B].DistanceTo(m.Vertices[mf.D]);
                    if (dist1 > dist2)
                    {
                        projectFaces.AppendTriangle(mf.A, mf.B, mf.D);
                        projectFaces.AppendTriangle(mf.B, mf.C, mf.D);
                    }
                    else
                    {
                        projectFaces.AppendTriangle(mf.A, mf.B, mf.C);
                        projectFaces.AppendTriangle(mf.A, mf.C, mf.D);
                    }
                }
                else
                {
                    projectFaces.AppendTriangle(mf.A, mf.B, mf.C);
                }
            }

            if (rhinoInputMesh == null)
            {
                return(Result.Failure);
            }

            removeFaces.Sort();
            removeFaces.Reverse();

            foreach (var removeFace in removeFaces)
            {
                rhinoInputMesh.Faces.RemoveAt(removeFace);
            }

            rhinoInputMesh.Compact();

            GetObject goProjected = new GetObject();

            goProjected.EnablePreSelect(false, true);
            goProjected.SetCommandPrompt("Select mesh to project to");
            goProjected.GeometryFilter = ObjectType.Mesh;
            goProjected.AddOptionDouble("ConstraintAngle", ref constriantAngleOption);
            goProjected.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            goProjected.AddOptionDouble("MaxEdge", ref maxEdgeLengthOption);
            goProjected.AddOptionInteger("SmoothSteps", ref smoothStepsOptions);
            goProjected.AddOptionDouble("SmoothSpeed", ref smoothSpeedOption);
            goProjected.AddOptionDouble("ProjectAmount", ref projectAmountOption);
            goProjected.AddOptionDouble("ProjectDistance", ref projectedDistanceOption);

            goProjected.GroupSelect     = true;
            goProjected.SubObjectSelect = false;
            goProjected.EnableClearObjectsOnEntry(false);
            goProjected.EnableUnselectObjectsOnExit(false);


            for (; ;)
            {
                GetResult resProject = goProjected.Get();

                if (resProject == GetResult.Option)
                {
                    continue;
                }
                else if (goProjected.CommandResult() != Result.Success)
                {
                    return(goProjected.CommandResult());
                }

                break;
            }


            minEdgeLength     = minEdgeLengthOption.CurrentValue;
            maxEdgeLength     = maxEdgeLengthOption.CurrentValue;
            constriantAngle   = constriantAngleOption.CurrentValue;
            smoothSteps       = smoothStepsOptions.CurrentValue;
            smoothSpeed       = smoothSpeedOption.CurrentValue;
            projectedAmount   = projectAmountOption.CurrentValue;
            projectedDistance = projectedDistanceOption.CurrentValue;

            if (bHavePreselectedObjects)
            {
                // Normally, pre-selected objects will remain selected, when a
                // command finishes, and post-selected objects will be unselected.
                // This this way of picking, it is possible to have a combination
                // of pre-selected and post-selected. So, to make sure everything
                // "looks the same", lets unselect everything before finishing
                // the command.
                for (int i = 0; i < go.ObjectCount; i++)
                {
                    RhinoObject rhinoObject = go.Object(i).Object();
                    if (null != rhinoObject)
                    {
                        rhinoObject.Select(false);
                    }
                }
                doc.Views.Redraw();
            }

            bool result = false;

            if (goProjected.ObjectCount < 1)
            {
                return(Result.Failure);
            }


            var rhinoMeshProject = goProjected.Object(0).Mesh();

            if (rhinoMeshProject == null || !rhinoMeshProject.IsValid)
            {
                return(Result.Failure);
            }

            var meshProjected = GopherUtil.ConvertToD3Mesh(rhinoMeshProject);

            var res = GopherUtil.RemeshMesh(projectFaces, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance);

            var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(res);

            if (newRhinoMesh != null && newRhinoMesh.IsValid)
            {
                newRhinoMesh.Append(rhinoInputMesh);

                result |= doc.Objects.Replace(rhinoMesh, newRhinoMesh);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Beispiel #24
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: start here modifying the behaviour of your command.
            // ---
            RhinoApp.WriteLine("MeshMachine WIP test", EnglishName);

            Brep SB;

            using (GetObject getBrep = new GetObject())
            {
                getBrep.SetCommandPrompt("Please select the brep to remesh");
                getBrep.Get();
                SB = getBrep.Object(0).Brep();
            }

            //GetNumber TargetLength = new GetNumber();
            //double L = TargetLength.Number();

            Rhino.Input.Custom.GetNumber gn = new Rhino.Input.Custom.GetNumber();
            gn.SetCommandPrompt("Specify a Target Edge Length");
            gn.SetLowerLimit(0.5, false);
            gn.Get();
            if (gn.CommandResult() != Rhino.Commands.Result.Success)
            {
                return(gn.CommandResult());
            }
            double L = gn.Number();

            //Point3d pt0;
            //using (GetPoint getPointAction = new GetPoint())
            //{
            //    getPointAction.SetCommandPrompt("Please select the start point");
            //    if (getPointAction.Get() != GetResult.Point)
            //    {
            //        RhinoApp.WriteLine("No start point was selected.");
            //        return getPointAction.CommandResult();
            //    }
            //    pt0 = getPointAction.Point();
            //}

            //Point3d pt1;
            //using (GetPoint getPointAction = new GetPoint())
            //{
            //    getPointAction.SetCommandPrompt("Please select the end point");
            //    getPointAction.SetBasePoint(pt0, true);
            //    getPointAction.DynamicDraw +=
            //      (sender, e) => e.Display.DrawLine(pt0, e.CurrentPoint, System.Drawing.Color.DarkRed);
            //    if (getPointAction.Get() != GetResult.Point)
            //    {
            //        RhinoApp.WriteLine("No end point was selected.");
            //        return getPointAction.CommandResult();
            //    }
            //    pt1 = getPointAction.Point();
            //}

            //doc.Objects.AddLine(pt0, pt1);

            PlanktonMesh P = new PlanktonMesh();

            List <int> AnchorV        = new List <int>();
            List <int> FeatureV       = new List <int>();
            List <int> FeatureE       = new List <int>();
            double     FixT           = 0.00001;
            double     LengthTol      = 0.15; //a tolerance for when to split/collapse edges
            double     SmoothStrength = 0.8;  //smoothing strength
            double     PullStrength   = 0.8;  //pull to target mesh strength
            double     CurvDep        = 0;
            int        Flip           = 1;

            MeshingParameters MeshParams = new MeshingParameters();

            MeshParams.MaximumEdgeLength = 3 * L;
            MeshParams.MinimumEdgeLength = L;
            MeshParams.JaggedSeams       = false;
            MeshParams.SimplePlanes      = false;

            Mesh[] BrepMeshes = Mesh.CreateFromBrep(SB, MeshParams);
            Mesh   M          = new Mesh();

            foreach (var mesh in BrepMeshes)
            {
                M.Append(mesh);
            }

            M.Faces.ConvertQuadsToTriangles();
            P = M.ToPlanktonMesh();

            var FC = new List <Curve>();

            foreach (BrepEdge E in SB.Edges)
            {
                if (!E.IsSmoothManifoldEdge(0.01))
                {
                    FC.Add(E.ToNurbsCurve());
                }
            }
            var            Corners = SB.Vertices;
            List <Point3d> FV      = new List <Point3d>();

            foreach (Point Pt in Corners)
            {
                FV.Add(Pt.Location);
            }

            //Mark any vertices or edges lying on features
            for (int i = 0; i < P.Vertices.Count; i++)
            {
                Point3d Pt = P.Vertices[i].ToPoint3d();
                AnchorV.Add(-1);
                for (int j = 0; j < FV.Count; j++)
                {
                    if (Pt.DistanceTo(FV[j]) < FixT)
                    {
                        AnchorV[AnchorV.Count - 1] = j;
                    }
                }

                FeatureV.Add(-1);
                for (int j = 0; j < FC.Count; j++)
                {
                    double param = new double();
                    FC[j].ClosestPoint(Pt, out param);
                    if (Pt.DistanceTo(FC[j].PointAt(param)) < FixT)
                    {
                        FeatureV[FeatureV.Count - 1] = j;
                    }
                }
            }

            int EdgeCount = P.Halfedges.Count / 2;

            for (int i = 0; i < EdgeCount; i++)
            {
                FeatureE.Add(-1);
                int vStart = P.Halfedges[2 * i].StartVertex;
                int vEnd   = P.Halfedges[2 * i + 1].StartVertex;

                Point3d PStart = P.Vertices[vStart].ToPoint3d();
                Point3d PEnd   = P.Vertices[vEnd].ToPoint3d();

                for (int j = 0; j < FC.Count; j++)
                {
                    double paramS = new double();
                    double paramE = new double();
                    Curve  thisFC = FC[j];
                    thisFC.ClosestPoint(PStart, out paramS);
                    thisFC.ClosestPoint(PEnd, out paramE);
                    if ((PStart.DistanceTo(thisFC.PointAt(paramS)) < FixT) &&
                        (PEnd.DistanceTo(thisFC.PointAt(paramE)) < FixT))
                    {
                        FeatureE[FeatureE.Count - 1] = j;
                    }
                }
            }



            for (int iter = 0; iter < 30; iter++)
            {
                EdgeCount = P.Halfedges.Count / 2;
                double[]    EdgeLength = P.Halfedges.GetLengths();
                List <bool> Visited    = new List <bool>();
                Vector3d[]  Normals    = new Vector3d[P.Vertices.Count];

                for (int i = 0; i < P.Vertices.Count; i++)
                {
                    Visited.Add(false);
                    Normals[i] = Util.Normal(P, i);
                }

                double t      = LengthTol;      //a tolerance for when to split/collapse edges
                double smooth = SmoothStrength; //smoothing strength
                double pull   = PullStrength;   //pull to target mesh strength

                //    Split the edges that are too long
                for (int i = 0; i < EdgeCount; i++)
                {
                    if (P.Halfedges[2 * i].IsUnused == false)
                    {
                        int vStart = P.Halfedges[2 * i].StartVertex;
                        int vEnd   = P.Halfedges[2 * i + 1].StartVertex;

                        if ((Visited[vStart] == false) &&
                            (Visited[vEnd] == false))
                        {
                            double  L2  = L;
                            Point3d Mid = Util.MidPt(P, i);

                            //if (CurvDep > 0)
                            //{
                            //    double NormDiff = Vector3d.VectorAngle(Normals[vStart], Normals[vEnd]);
                            //    L2 = Math.Min((1.0 / (3.0 * NormDiff) * L), 5 * L);

                            //    if (CurvDep != 1)
                            //    {
                            //        L2 = L2 * (CurvDep) + L * (1.0 - CurvDep);
                            //    }

                            //}
                            //if (BoundScale != 1.0)
                            //{
                            //    double MinDist = 99954;

                            //    for (int j = 0; j < FC.Count; j++)
                            //    {
                            //        double param = new double();

                            //        FC[j].ClosestPoint(Mid, out param);
                            //        double ThisDist = Mid.DistanceTo(FC[j].PointAt(param));
                            //        if (ThisDist < MinDist)
                            //        { MinDist = ThisDist; }
                            //    }

                            //    if (MinDist < BoundDist)
                            //    {
                            //        L2 = L2 * BoundScale + (MinDist / BoundDist) * (L2 * (1 - BoundScale));
                            //    }
                            //}

                            //if (SizP.Count > 0)
                            //{
                            //    L2 = WeightedCombo(Mid, SizP, SizV, WExp, L2, BGW);
                            //    //  L2 = (WL * (1.0 - BGW)) + (BGW * L2);
                            //}

                            if (EdgeLength[2 * i] > (1 + t) * (4f / 3f) * L2)
                            {
                                int SplitHEdge = P.Halfedges.TriangleSplitEdge(2 * i);
                                if (SplitHEdge != -1)
                                {
                                    int SplitCenter = P.Halfedges[SplitHEdge].StartVertex;
                                    P.Vertices.SetVertex(SplitCenter, Util.MidPt(P, i));

                                    //update the feature information
                                    FeatureE.Add(FeatureE[i]);
                                    FeatureV.Add(FeatureE[i]);
                                    AnchorV.Add(-1);

                                    //2 additional new edges have also been created (or 1 if split was on a boundary)
                                    //mark these as non-features
                                    int CEdgeCount = P.Halfedges.Count / 2;
                                    while (FeatureE.Count < CEdgeCount)
                                    {
                                        FeatureE.Add(-1);
                                    }

                                    Visited.Add(true);
                                    int[] Neighbours = P.Vertices.GetVertexNeighbours(SplitCenter);
                                    foreach (int n in Neighbours)
                                    {
                                        Visited[n] = true;
                                    }
                                }
                            }
                        }
                    }
                }

                //Collapse the edges that are too short
                for (int i = 0; i < EdgeCount; i++)
                {
                    if (P.Halfedges[2 * i].IsUnused == false)
                    {
                        int vStart = P.Halfedges[2 * i].StartVertex;
                        int vEnd   = P.Halfedges[2 * i + 1].StartVertex;
                        if ((Visited[vStart] == false) &&
                            (Visited[vEnd] == false))
                        {
                            if (!(AnchorV[vStart] != -1 && AnchorV[vEnd] != -1)) // if both ends are anchored, don't collapse
                            {
                                int Collapse_option = 0;                         //0 for none, 1 for collapse to midpt, 2 for towards start, 3 for towards end
                                //if neither are anchorV
                                if (AnchorV[vStart] == -1 && AnchorV[vEnd] == -1)
                                {
                                    // if both on same feature (or neither on a feature)
                                    if (FeatureV[vStart] == FeatureV[vEnd])
                                    {
                                        Collapse_option = 1;
                                    }
                                    // if start is on a feature and end isn't
                                    if ((FeatureV[vStart] != -1) && (FeatureV[vEnd] == -1))
                                    {
                                        Collapse_option = 2;
                                    }
                                    // if end is on a feature and start isn't
                                    if ((FeatureV[vStart] == -1) && (FeatureV[vEnd] != -1))
                                    {
                                        Collapse_option = 3;
                                    }
                                }
                                else // so one end must be an anchor
                                {
                                    // if start is an anchor
                                    if (AnchorV[vStart] != -1)
                                    {
                                        // if both are on same feature, or if the end is not a feature
                                        if ((FeatureE[i] != -1) || (FeatureV[vEnd] == -1))
                                        {
                                            Collapse_option = 2;
                                        }
                                    }
                                    // if end is an anchor
                                    if (AnchorV[vEnd] != -1)
                                    {
                                        // if both are on same feature, or if the start is not a feature
                                        if ((FeatureE[i] != -1) || (FeatureV[vStart] == -1))
                                        {
                                            Collapse_option = 3;
                                        }
                                    }
                                }

                                double  L2  = L;
                                Point3d Mid = Util.MidPt(P, i);

                                if (CurvDep > 0)
                                {
                                    double NormDiff = Vector3d.VectorAngle(Normals[vStart], Normals[vEnd]);
                                    L2 = Math.Min((1.0 / (3.0 * NormDiff) * L), 5 * L);

                                    if (CurvDep != 1)
                                    {
                                        L2 = L2 * (CurvDep) + L * (1.0 - CurvDep);
                                    }
                                }

                                //if (BoundScale != 1.0)
                                //{
                                //    double MinDist = 99954;

                                //    for (int j = 0; j < FC.Count; j++)
                                //    {
                                //        double param = new double();

                                //        FC[j].ClosestPoint(Mid, out param);
                                //        double ThisDist = Mid.DistanceTo(FC[j].PointAt(param));
                                //        if (ThisDist < MinDist)
                                //        { MinDist = ThisDist; }
                                //    }

                                //    if (MinDist < BoundDist)
                                //    {
                                //        L2 = L2 * BoundScale + (MinDist / BoundDist) * (L2 * (1 - BoundScale));
                                //    }
                                //}

                                //if (SizP.Count > 0)
                                //{
                                //    L2 = WeightedCombo(Mid, SizP, SizV, WExp, L2, BGW);
                                //    //double WL = WeightedCombo(Mid, SizP, SizV, WExp);
                                //    //L2 = (WL * (1.0 - BGW)) + (BGW * L2);
                                //}

                                if ((Collapse_option != 0) && (EdgeLength[2 * i] < (1 - t) * 4f / 5f * L2))
                                {
                                    int Collapsed   = -1;
                                    int CollapseRtn = -1;
                                    if (Collapse_option == 1)
                                    {
                                        Collapsed = P.Halfedges[2 * i].StartVertex;
                                        P.Vertices.SetVertex(Collapsed, Util.MidPt(P, i));
                                        CollapseRtn = P.Halfedges.CollapseEdge(2 * i);
                                    }
                                    if (Collapse_option == 2)
                                    {
                                        Collapsed   = P.Halfedges[2 * i].StartVertex;
                                        CollapseRtn = P.Halfedges.CollapseEdge(2 * i);
                                    }
                                    if (Collapse_option == 3)
                                    {
                                        Collapsed   = P.Halfedges[2 * i + 1].StartVertex;
                                        CollapseRtn = P.Halfedges.CollapseEdge(2 * i + 1);
                                    }
                                    if (CollapseRtn != -1)
                                    {
                                        int[] Neighbours = P.Vertices.GetVertexNeighbours(Collapsed);
                                        foreach (int n in Neighbours)
                                        {
                                            Visited[n] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                EdgeCount = P.Halfedges.Count / 2;

                if ((Flip == 0) && (PullStrength > 0))
                {
                    //Flip edges to reduce valence error
                    for (int i = 0; i < EdgeCount; i++)
                    {
                        if (!P.Halfedges[2 * i].IsUnused &&
                            (P.Halfedges[2 * i].AdjacentFace != -1) &&
                            (P.Halfedges[2 * i + 1].AdjacentFace != -1) &&
                            (FeatureE[i] == -1)   // don't flip feature edges
                            )
                        {
                            int Vert1 = P.Halfedges[2 * i].StartVertex;
                            int Vert2 = P.Halfedges[2 * i + 1].StartVertex;
                            int Vert3 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i].NextHalfedge].NextHalfedge].StartVertex;
                            int Vert4 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i + 1].NextHalfedge].NextHalfedge].StartVertex;

                            int Valence1 = P.Vertices.GetValence(Vert1);
                            int Valence2 = P.Vertices.GetValence(Vert2);
                            int Valence3 = P.Vertices.GetValence(Vert3);
                            int Valence4 = P.Vertices.GetValence(Vert4);

                            if (P.Vertices.NakedEdgeCount(Vert1) > 0)
                            {
                                Valence1 += 2;
                            }
                            if (P.Vertices.NakedEdgeCount(Vert2) > 0)
                            {
                                Valence2 += 2;
                            }
                            if (P.Vertices.NakedEdgeCount(Vert3) > 0)
                            {
                                Valence3 += 2;
                            }
                            if (P.Vertices.NakedEdgeCount(Vert4) > 0)
                            {
                                Valence4 += 2;
                            }

                            int CurrentError =
                                Math.Abs(Valence1 - 6) +
                                Math.Abs(Valence2 - 6) +
                                Math.Abs(Valence3 - 6) +
                                Math.Abs(Valence4 - 6);
                            int FlippedError =
                                Math.Abs(Valence1 - 7) +
                                Math.Abs(Valence2 - 7) +
                                Math.Abs(Valence3 - 5) +
                                Math.Abs(Valence4 - 5);
                            if (CurrentError > FlippedError)
                            {
                                P.Halfedges.FlipEdge(2 * i);
                            }
                        }
                    }
                }
                else
                {
                    //Flip edges based on angle
                    for (int i = 0; i < EdgeCount; i++)
                    {
                        if (!P.Halfedges[2 * i].IsUnused &&
                            (P.Halfedges[2 * i].AdjacentFace != -1) &&
                            (P.Halfedges[2 * i + 1].AdjacentFace != -1) &&
                            (FeatureE[i] == -1)  // don't flip feature edges
                            )
                        {
                            int Vert1 = P.Halfedges[2 * i].StartVertex;
                            int Vert2 = P.Halfedges[2 * i + 1].StartVertex;
                            int Vert3 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i].NextHalfedge].NextHalfedge].StartVertex;
                            int Vert4 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i + 1].NextHalfedge].NextHalfedge].StartVertex;

                            Point3d P1 = P.Vertices[Vert1].ToPoint3d();
                            Point3d P2 = P.Vertices[Vert2].ToPoint3d();
                            Point3d P3 = P.Vertices[Vert3].ToPoint3d();
                            Point3d P4 = P.Vertices[Vert4].ToPoint3d();

                            double A1 = Vector3d.VectorAngle(new Vector3d(P3 - P1), new Vector3d(P4 - P1))
                                        + Vector3d.VectorAngle(new Vector3d(P4 - P2), new Vector3d(P3 - P2));

                            double A2 = Vector3d.VectorAngle(new Vector3d(P1 - P4), new Vector3d(P2 - P4))
                                        + Vector3d.VectorAngle(new Vector3d(P2 - P3), new Vector3d(P1 - P3));

                            if (A2 > A1)
                            {
                                P.Halfedges.FlipEdge(2 * i);
                            }
                        }
                    }
                }

                //if (Minim)
                //{
                //    Vector3d[] SmoothC = LaplacianSmooth(P, 1, smooth);

                //    for (int i = 0; i < P.Vertices.Count; i++)
                //    {
                //        if (AnchorV[i] == -1) // don't smooth feature vertices
                //        {
                //            P.Vertices.MoveVertex(i, 0.5 * SmoothC[i]);
                //        }
                //    }
                //}

                Vector3d[] Smooth = Util.LaplacianSmooth(P, 0, smooth);

                for (int i = 0; i < P.Vertices.Count; i++)
                {
                    if (AnchorV[i] == -1) // don't smooth feature vertices
                    {
                        // make it tangential only
                        Vector3d VNormal    = Util.Normal(P, i);
                        double   ProjLength = Smooth[i] * VNormal;
                        Smooth[i] = Smooth[i] - (VNormal * ProjLength);

                        P.Vertices.MoveVertex(i, Smooth[i]);

                        if (P.Vertices.NakedEdgeCount(i) != 0)//special smoothing for feature edges
                        {
                            int[]   Neighbours = P.Vertices.GetVertexNeighbours(i);
                            int     ncount     = 0;
                            Point3d Avg        = new Point3d();

                            for (int j = 0; j < Neighbours.Length; j++)
                            {
                                if (P.Vertices.NakedEdgeCount(Neighbours[j]) != 0)
                                {
                                    ncount++;
                                    Avg = Avg + P.Vertices[Neighbours[j]].ToPoint3d();
                                }
                            }
                            Avg = Avg * (1.0 / ncount);
                            Vector3d move = Avg - P.Vertices[i].ToPoint3d();
                            move = move * smooth;
                            P.Vertices.MoveVertex(i, move);
                        }

                        if (FeatureV[i] != -1)//special smoothing for feature edges
                        {
                            int[]   Neighbours = P.Vertices.GetVertexNeighbours(i);
                            int     ncount     = 0;
                            Point3d Avg        = new Point3d();

                            for (int j = 0; j < Neighbours.Length; j++)
                            {
                                if ((FeatureV[Neighbours[j]] == FeatureV[i]) || (AnchorV[Neighbours[j]] != -1))
                                {
                                    ncount++;
                                    Avg = Avg + P.Vertices[Neighbours[j]].ToPoint3d();
                                }
                            }
                            Avg = Avg * (1.0 / ncount);
                            Vector3d move = Avg - P.Vertices[i].ToPoint3d();
                            move = move * smooth;
                            P.Vertices.MoveVertex(i, move);
                        }

                        //projecting points onto the target along their normals

                        if (pull > 0)
                        {
                            Point3d  Point  = P.Vertices[i].ToPoint3d();
                            Vector3d normal = Util.Normal(P, i);
                            Ray3d    Ray1   = new Ray3d(Point, normal);
                            Ray3d    Ray2   = new Ray3d(Point, -normal);
                            double   RayPt1 = Rhino.Geometry.Intersect.Intersection.MeshRay(M, Ray1);
                            double   RayPt2 = Rhino.Geometry.Intersect.Intersection.MeshRay(M, Ray2);
                            Point3d  ProjectedPt;

                            if ((RayPt1 < RayPt2) && (RayPt1 > 0) && (RayPt1 < 1.0))
                            {
                                ProjectedPt = Point * (1 - pull) + pull * Ray1.PointAt(RayPt1);
                            }
                            else if ((RayPt2 < RayPt1) && (RayPt2 > 0) && (RayPt2 < 1.0))
                            {
                                ProjectedPt = Point * (1 - pull) + pull * Ray2.PointAt(RayPt2);
                            }
                            else
                            {
                                ProjectedPt = Point * (1 - pull) + pull * M.ClosestPoint(Point);
                            }

                            P.Vertices.SetVertex(i, ProjectedPt);
                        }


                        if (FeatureV[i] != -1) //pull feature vertices onto feature curves
                        {
                            Point3d Point     = P.Vertices[i].ToPoint3d();
                            Curve   CF        = FC[FeatureV[i]];
                            double  param1    = 0.0;
                            Point3d onFeature = new Point3d();
                            CF.ClosestPoint(Point, out param1);
                            onFeature = CF.PointAt(param1);
                            P.Vertices.SetVertex(i, onFeature);
                        }
                    }
                    else
                    {
                        P.Vertices.SetVertex(i, FV[AnchorV[i]]); //pull anchor vertices onto their points
                    }
                }



                AnchorV  = Util.CompactByVertex(P, AnchorV); //compact the fixed points along with the vertices
                FeatureV = Util.CompactByVertex(P, FeatureV);
                FeatureE = Util.CompactByEdge(P, FeatureE);

                P.Compact(); //this cleans the mesh data structure of unused elements
            }


            Mesh MR = P.ToRhinoMesh();

            MR.Unweld(0.4, true);

            doc.Objects.AddMesh(MR);

            doc.Views.Redraw();
            RhinoApp.WriteLine("The {0} command added one mesh to the document.", EnglishName);

            // ---

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Select planar surface
            var gs = new GetObject();

            gs.SetCommandPrompt("Select planar surface");
            gs.GeometryFilter  = ObjectType.Surface;
            gs.SubObjectSelect = false;
            gs.Get();
            if (gs.CommandResult() != Result.Success)
            {
                return(gs.CommandResult());
            }

            var brep_ref = gs.Object(0);
            var brep     = brep_ref.Brep();

            if (null == brep)
            {
                return(Result.Failure);
            }

            // Verify underlying surface is a PlaneSurface
            var plane_surface = brep.Faces[0].UnderlyingSurface() as PlaneSurface;

            if (null == plane_surface)
            {
                return(Result.Nothing);
            }

            // Select trimming curves on planar surface
            var gc = new GetObject();

            gc.SetCommandPrompt("Select trimming curves on planar surface");
            gc.GeometryFilter  = ObjectType.Curve;
            gc.GroupSelect     = true;
            gc.SubObjectSelect = false;
            gc.EnablePreSelect(false, true);
            gc.DeselectAllBeforePostSelect = false;
            gc.GetMultiple(1, 0);
            if (gc.CommandResult() != Result.Success)
            {
                return(gc.CommandResult());
            }

            // Make a copy of the selected Brep
            var new_brep = new Brep();

            new_brep.Append(brep);

            // Add each selected curve a a inner planar face loop
            var boundary = new Curve[1];

            for (var i = 0; i < gc.ObjectCount; i++)
            {
                var curve = gc.Object(i).Curve();
                if (null != curve)
                {
                    boundary[0] = curve;
                    new_brep.Loops.AddPlanarFaceLoop(0, BrepLoopType.Inner, boundary);
                }
            }

            new_brep.Compact();

            // IF all is well, then replace the selecte Brep with our new one
            if (new_brep.IsValid)
            {
                doc.Objects.Replace(brep_ref.ObjectId, new_brep);
                doc.Views.Redraw();
            }

            return(Result.Success);
        }
        /// <summary>
        /// Called by Rhino to 'run' this command
        /// </summary>
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Select objects to orient
            var go = new GetObject();

            go.SetCommandPrompt("Select objects to orient");
            go.SubObjectSelect = false;
            go.EnableIgnoreGrips(true);
            go.GetMultiple(1, 0);
            if (go.CommandResult() != Result.Success)
            {
                return(go.CommandResult());
            }

            // Point to move from
            var gp = new GetPoint();

            gp.SetCommandPrompt("Point to move from");
            gp.Get();
            if (gp.CommandResult() != Result.Success)
            {
                return(gp.CommandResult());
            }

            // Calculate source plane
            var plane = gp.View().ActiveViewport.ConstructionPlane();

            plane.Origin = gp.Point();

            // Mesh to orient on
            var gm = new GetObject();

            gm.SetCommandPrompt("Mesh to orient on");
            gm.GeometryFilter = ObjectType.Mesh;
            gm.EnablePreSelect(false, true);
            gm.DeselectAllBeforePostSelect = false;
            gm.Get();
            if (gm.CommandResult() != Result.Success)
            {
                return(gm.CommandResult());
            }

            var mesh = gm.Object(0).Mesh();

            if (null == mesh)
            {
                return(Result.Failure);
            }

            // Point on mesh to orient to
            var gpm = new GetPointOnMesh(mesh, plane);

            gpm.SetCommandPrompt("Point on mesh to orient to");
            gpm.AppendObjects(go);
            gpm.Get();
            if (gpm.CommandResult() != Result.Success)
            {
                return(gpm.CommandResult());
            }

            // One final calculation
            var xform = new Transform(1);

            if (gpm.CalculateTransform(gpm.View().ActiveViewport, gpm.Point(), ref xform))
            {
                foreach (var objRef in go.Objects())
                {
                    var obj = objRef.Object();
                    if (null != obj)
                    {
                        doc.Objects.Transform(obj, xform, true);
                    }
                }
                doc.Views.Redraw();
            }

            return(Result.Success);
        }
Beispiel #27
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // TODO: complete command.

            // get picture object
            ObjRef objRef = null;

            using (var go = new GetObject())
            {
                go.SetCommandPrompt("Select a picture object to sample");
                go.GeometryFilter = ObjectType.Surface;

                go.Get();
                if (go.CommandResult() != Result.Success)
                {
                    return(go.CommandResult());
                }

                objRef = go.Object(0);
            }

            // get rhino object
            RhinoObject rhinoObject = objRef.Object();

            // extract bitmap texture from render material Xml
            RenderMaterial renderMaterial = rhinoObject.RenderMaterial;
            XmlDocument    xml            = new XmlDocument();

            xml.LoadXml(renderMaterial.Xml);
            var node     = xml.SelectSingleNode("material/simulation/Texture-1-filename");
            var filePath = node.InnerText;
            var bitmap   = new Bitmap(Image.FromFile(filePath));

            // get bounding box
            var bbox = rhinoObject.Geometry.GetBoundingBox(Plane.WorldXY, out var worldBox);

            // get width / height of bbox
            double bboxWidth  = bbox.Corner(false, true, true).DistanceTo(bbox.Corner(true, true, true));
            double bboxHeight = bbox.Corner(true, false, true).DistanceTo(bbox.Corner(true, true, true));

            // get width / height of image
            int imgWidth  = bitmap.Width;
            int imgHeight = bitmap.Height;

            // Calculate stretch factor
            double stretchFactor = bboxWidth / imgWidth;

            // Test stretch factor consistency
            if (!(Math.Abs(imgHeight * stretchFactor - bboxHeight) < doc.ModelAbsoluteTolerance))
            {
                RhinoApp.WriteLine("Selected Picture object is scaled non-uniform! Aborting command");
                return(Result.Failure);
            }

            // get starting position
            var startPt = bbox.Min;

            // create grid of points
            var plane = worldBox.Plane;

            plane.Origin = startPt;
            Point3d[]  points  = new Point3d[imgWidth * imgHeight];
            Color[]    colors  = new Color[imgWidth * imgHeight];
            Vector3d[] normals = new Vector3d[imgWidth * imgHeight];
            Vector3d   normal  = Vector3d.ZAxis;

            for (int i = 0; i < imgHeight; i++)
            {
                for (int j = 0; j < imgWidth; j++)
                {
                    points[(i + 1) * j]  = plane.PointAt(j * stretchFactor, i * stretchFactor);
                    colors[(i + 1) * j]  = bitmap.GetPixel(j, i);
                    normals[(i + 1) * j] = normal;
                }
            }

            // create Point cloud from grid
            PointCloud pc = new PointCloud();

            pc.AddRange(points, normals, colors);

            // add point cloud to doc
            doc.Objects.AddPointCloud(pc);

            // redraw
            doc.Views.Redraw();

            // return success
            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            RhinoApp.WriteLine("The {0} command is under construction.", EnglishName);

            //Example code from https://github.com/Dan-Piker/Drop/blob/master/dropitlikeitshotCommand.cs

            Mesh M;

            GetObject getSomething = new GetObject();

            getSomething.SetCommandPrompt("Select a closed mesh");
            if (getSomething.Get() != GetResult.Object)
            {
                RhinoApp.WriteLine("No object selected");
                return(getSomething.CommandResult());
            }

            GetResult result = getSomething.Get();
            var       obj    = getSomething.Objects();

            M = obj[0].Mesh();

            var Pts = M.Vertices.ToPoint3dArray();

            var   VM  = Rhino.Geometry.VolumeMassProperties.Compute(M);
            Plane Pln = new Plane(VM.Centroid, Vector3d.ZAxis);

            Point3d[] PtArray = new Point3d[Pts.Length + 3];
            PtArray[0] = Pln.Origin;
            PtArray[1] = Pln.PointAt(1, 0);
            PtArray[2] = Pln.PointAt(0, 1);

            for (int i = 0; i < Pts.Length; i++)
            {
                PtArray[i + 3] = Pts[i];
            }

            var Ix = new int[PtArray.Length];

            for (int i = 0; i < PtArray.Length; i++)
            {
                Ix[i] = i;
            }

            var Goals = new List <KangarooSolver.IGoal>();
            var G     = new KangarooSolver.Goals.RigidBody(PtArray, M, 100);

            G.PIndex = Ix;
            Goals.Add(G);
            Goals.Add(new KangarooSolver.Goals.FloorPlane(100));

            for (int i = 3; i < PtArray.Length; i++)
            {
                Goals.Add(new KangarooSolver.Goals.Unary(i, new Vector3d(0, 0, -0.1))); //gravity
            }

            var PS = new KangarooSolver.PhysicalSystem();

            PS.SetParticleList(PtArray.ToList());

            int    counter   = 0;
            double threshold = 1e-9;

            do
            {
                PS.Step(Goals, true, threshold);                 // The step will iterate until either reaching 15ms or the energy threshold
                counter++;
            } while (PS.GetvSum() > threshold && counter < 200); //GetvSum returns the current kinetic energy

            Mesh A = PS.GetOutput(Goals)[0] as Mesh;

            doc.Objects.AddMesh(A);
            doc.Views.Redraw();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var gc1 = new GetObject();

            gc1.DisablePreSelect();
            gc1.SetCommandPrompt("Select first curve to fillet (close to the end you want to fillet)");
            gc1.GeometryFilter          = ObjectType.Curve;
            gc1.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve;
            gc1.Get();
            if (gc1.CommandResult() != Result.Success)
            {
                return(gc1.CommandResult());
            }
            var curve1_obj_ref = gc1.Object(0);
            var curve1         = curve1_obj_ref.Curve();

            if (curve1 == null)
            {
                return(Result.Failure);
            }
            var curve1_point_near_end = curve1_obj_ref.SelectionPoint();

            if (curve1_point_near_end == Point3d.Unset)
            {
                return(Result.Failure);
            }

            var gc2 = new GetObject();

            gc2.DisablePreSelect();
            gc2.SetCommandPrompt("Select second curve to fillet (close to the end you want to fillet)");
            gc2.GeometryFilter          = ObjectType.Curve;
            gc2.GeometryAttributeFilter = GeometryAttributeFilter.OpenCurve;
            gc2.Get();
            if (gc2.CommandResult() != Result.Success)
            {
                return(gc2.CommandResult());
            }
            var curve2_obj_ref = gc2.Object(0);
            var curve2         = curve2_obj_ref.Curve();

            if (curve2 == null)
            {
                return(Result.Failure);
            }
            var curve2_point_near_end = curve2_obj_ref.SelectionPoint();

            if (curve2_point_near_end == Point3d.Unset)
            {
                return(Result.Failure);
            }

            double radius = 0;
            var    rc     = RhinoGet.GetNumber("fillet radius", false, ref radius);

            if (rc != Result.Success)
            {
                return(rc);
            }

            var join          = false;
            var trim          = true;
            var arc_extension = true;
            var fillet_curves = Curve.CreateFilletCurves(curve1, curve1_point_near_end, curve2, curve2_point_near_end, radius,
                                                         join, trim, arc_extension, doc.ModelAbsoluteTolerance, doc.ModelAngleToleranceDegrees);

            if (fillet_curves == null /*|| fillet_curves.Length != 3*/)
            {
                return(Result.Failure);
            }

            foreach (var fillet_curve in fillet_curves)
            {
                doc.Objects.AddCurve(fillet_curve);
            }
            doc.Views.Redraw();
            return(rc);
        }
Beispiel #30
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Select curves to project
            var gc = new GetObject();

            gc.SetCommandPrompt("Select curves to project");
            gc.GeometryFilter = ObjectType.Curve;
            gc.GetMultiple(1, 0);
            if (gc.CommandResult() != Result.Success)
            {
                return(gc.CommandResult());
            }

            // Select planar surface to project onto
            var gs = new GetObject();

            gs.SetCommandPrompt("Select planar surface to project onto");
            gs.GeometryFilter = ObjectType.Surface;
            gs.EnablePreSelect(false, true);
            gs.DeselectAllBeforePostSelect = false;
            gs.Get();
            if (gs.CommandResult() != Result.Success)
            {
                return(gs.CommandResult());
            }

            // Get the Brep face
            var brep_face = gs.Object(0).Face();

            if (null == brep_face)
            {
                return(Result.Failure);
            }

            // Verify the Brep face is planar
            var tolerance = doc.ModelAbsoluteTolerance;

            if (!brep_face.IsPlanar(tolerance))
            {
                RhinoApp.WriteLine("Surface is not planar.");
                return(Result.Nothing);
            }

            // Get normal direction of Brep face
            var u      = brep_face.Domain(0).Min;
            var v      = brep_face.Domain(1).Min;
            var normal = brep_face.NormalAt(u, v);

            // If the Brep face's orientation is opposite of natural surface orientation,
            // then reverse the normal vector.
            if (brep_face.OrientationIsReversed)
            {
                normal.Reverse();
            }

            // Invert norma; direction of the vector for projection
            normal.Reverse();

            // Create a array of Breps to project onto
            var breps = new Brep[1];

            breps[0] = brep_face.DuplicateFace(true); // Create a single Brep, including trims

            // Create a collection of curves to project
            var curves = new List <Curve>(gc.ObjectCount);

            for (var i = 0; i < gc.ObjectCount; i++)
            {
                var curve = gc.Object(i).Curve();
                if (null != curve)
                {
                    curves.Add(curve);
                }
            }

            // Do the projection
            var projected_curves = Curve.ProjectToBrep(curves, breps, normal, tolerance);

            // Add the results to the document
            foreach (var crv in projected_curves)
            {
                doc.Objects.AddCurve(crv);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }