protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            OptionDouble  amountOption = new OptionDouble(amount, 0.001, 300);
            OptionInteger triesOption  = new OptionInteger(tries, 1, 1000);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select meshes to Randomize");
            go.AddOptionDouble("Amount", ref amountOption);
            go.AddOptionInteger("Tries", ref triesOption);
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Mesh;

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

                if (res == GetResult.Option)
                {
                    tries  = triesOption.CurrentValue;
                    amount = amountOption.CurrentValue;
                    continue;
                }

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

                break;
            }

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

            foreach (var obj in go.Objects())
            {
                var rhinoMesh = obj.Mesh();

                if (rhinoMesh == null || !rhinoMesh.IsValid)
                {
                    continue;
                }

                var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh());

                g3.DMesh3 outputMeshRandom;
                GopherUtil.RandomizeMesh(mesh, out outputMeshRandom, amount, tries);

                var rhinoOutputMeshRandom = GopherUtil.ConvertToRhinoMesh(outputMeshRandom);
                doc.Objects.Replace(obj, rhinoOutputMeshRandom);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Ejemplo n.º 2
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            this.widthOpt       = new OptionInteger(Properties.Settings.Default.Width);
            this.heightOpt      = new OptionInteger(Properties.Settings.Default.Height);
            this.dpiOpt         = new OptionInteger(Properties.Settings.Default.DPI);
            this.ratioToggle    = new OptionToggle(Properties.Settings.Default.KeepRatio, "Yes", "No");
            this.gridAxesToggle = new OptionToggle(Properties.Settings.Default.GridAndAxes, "Hide", "Show");
            this.portraitToggle = new OptionToggle(Properties.Settings.Default.Portrait, "Landscape", "Portrait");

            GetOption go = new GetOption();

            go.AcceptNothing(true);

            int selectedResolution = Properties.Settings.Default.Resolution;

            this.RestoreOptions(ref go, selectedResolution);

            GetResult res = go.Get();

            while (res == GetResult.Option)
            {
                if (go.Option().CurrentListOptionIndex >= 0)
                {
                    selectedResolution = go.Option().CurrentListOptionIndex;
                }

                this.RestoreOptions(ref go, selectedResolution);
                res = go.Get();
            }

            if (res != GetResult.Nothing)
            {
                return(Result.Cancel);
            }

            Properties.Settings.Default.Resolution  = selectedResolution;
            Properties.Settings.Default.Width       = widthOpt.CurrentValue;
            Properties.Settings.Default.Height      = heightOpt.CurrentValue;
            Properties.Settings.Default.KeepRatio   = ratioToggle.CurrentValue;
            Properties.Settings.Default.GridAndAxes = gridAxesToggle.CurrentValue;
            Properties.Settings.Default.Portrait    = portraitToggle.CurrentValue;
            Properties.Settings.Default.Save();

            RhinoHelpers.CustomScreenshot();

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometry_filter = ObjectType.Surface | ObjectType.PolysrfFilter | ObjectType.Mesh;
            var integer1 = 300;
            var integer2 = 300;

            var option_integer1 = new OptionInteger(integer1, 200, 900);
            var option_integer2 = new OptionInteger(integer2, 200, 900);

            var go = new GetObject();

            go.SetCommandPrompt("Select surfaces, polysurfaces, or meshes");
            go.GeometryFilter = geometry_filter;
            go.AddOptionInteger("Option1", ref option_integer1);
            go.AddOptionInteger("Option2", ref option_integer2);
            go.GroupSelect     = true;
            go.SubObjectSelect = false;

            var have_preselected_objects = false;

            while (true)
            {
                var res = go.GetMultiple(1, 0);

                if (res == GetResult.Option)
                {
                    go.EnablePreSelect(false, true);
                    go.AlreadySelectedObjectSelect = true;
                    go.EnableClearObjectsOnEntry(false);
                    go.DeselectAllBeforePostSelect = false;
                    go.EnableUnselectObjectsOnExit(false);
                    continue;
                }

                if (res != GetResult.Object)
                {
                    return(Result.Cancel);
                }

                if (go.ObjectsWerePreselected)
                {
                    have_preselected_objects = true;
                    go.EnablePreSelect(false, true);
                    go.AlreadySelectedObjectSelect = true;
                    go.EnableClearObjectsOnEntry(false);
                    go.DeselectAllBeforePostSelect = false;
                    go.EnableUnselectObjectsOnExit(false);
                    continue;
                }

                break;
            }

            if (have_preselected_objects)
            {
                // 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 (var i = 0; i < go.ObjectCount; i++)
                {
                    var rhino_object = go.Object(i).Object();
                    rhino_object?.Select(false);
                }
                doc.Views.Redraw();
            }

            var object_count = go.ObjectCount;

            integer1 = option_integer1.CurrentValue;
            integer2 = option_integer2.CurrentValue;

            RhinoApp.WriteLine("Select object count: {0}", object_count);
            RhinoApp.WriteLine("Value of integer1: {0}", integer1);
            RhinoApp.WriteLine("Value of integer2: {0}", integer2);

            return(Result.Success);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Command.RunCommand override
        /// </summary>
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            Potrace.Clear();

            // Prompt the user for the name of the image file to vectorize.
            string path = GetImageFileName(mode);

            if (string.IsNullOrEmpty(path))
            {
                return(Result.Cancel);
            }

            // Creates a bitmap from the specified file.
            var bitmap = Image.FromFile(path) as Bitmap;

            if (null == bitmap)
            {
                RhinoApp.WriteLine("The specified file cannot be identifed as a supported type.");
                return(Result.Failure);
            }

            // Verify bitmap size
            if (0 == bitmap.Width || 0 == bitmap.Height)
            {
                RhinoApp.WriteLine("Error reading the specified file.");
                return(Result.Failure);
            }

            // Calculate scale factor so curves of a reasonable size are added to Rhino
            var unit_scale = (doc.ModelUnitSystem != UnitSystem.Inches)
        ? RhinoMath.UnitScale(UnitSystem.Inches, doc.ModelUnitSystem)
        : 1.0;
            var scale = (double)(1.0 / bitmap.HorizontalResolution * unit_scale);

            // I'm not convinced this is useful...
            if (true)
            {
                var format = $"F{doc.DistanceDisplayPrecision}";

                // Print image size in pixels
                RhinoApp.WriteLine("Image size in pixels: {0} x {1}",
                                   bitmap.Width,
                                   bitmap.Height
                                   );

                // Print image size in inches
                var width  = (double)(bitmap.Width / bitmap.HorizontalResolution);
                var height = (double)(bitmap.Height / bitmap.VerticalResolution);
                RhinoApp.WriteLine("Image size in inches: {0} x {1}",
                                   width.ToString(format, CultureInfo.InvariantCulture),
                                   height.ToString(format, CultureInfo.InvariantCulture)
                                   );

                // Image size in in model units, if needed
                if (doc.ModelUnitSystem != UnitSystem.Inches)
                {
                    width  = (double)(bitmap.Width / bitmap.HorizontalResolution * unit_scale);
                    height = (double)(bitmap.Height / bitmap.VerticalResolution * unit_scale);
                    RhinoApp.WriteLine("Image size in {0}: {1} x {2}",
                                       doc.ModelUnitSystem.ToString().ToLower(),
                                       width.ToString(format, CultureInfo.InvariantCulture),
                                       height.ToString(format, CultureInfo.InvariantCulture)
                                       );
                }
            }

            // Convert the bitmap to an Eto bitmap
            var eto_bitmap = ConvertBitmapToEto(bitmap);

            if (null == eto_bitmap)
            {
                RhinoApp.WriteLine("Unable to convert image to Eto bitmap.");
                return(Result.Failure);
            }

            // 12-Jan-2021 Dale Fugier
            // This should prevent Eto.Drawing.BitmapData.GetPixels() from throwing an exception
            if (!IsCompatibleBitmap(eto_bitmap))
            {
                RhinoApp.WriteLine("The image has an incompatible pixel format. Please select an image with 24 or 32 bits per pixel, or 8 bit indexed.");
                return(Result.Failure);
            }

            // This bitmap is not needed anymore, so dispose of it
            bitmap.Dispose();

            // Gets the Potrace settings from the plug-in settings file
            GetPotraceSettings();

            // Create the conduit, which does most of the work
            var conduit = new VectorizeConduit(
                eto_bitmap,
                scale,
                doc.ModelAbsoluteTolerance,
                m_select_output
          ? Rhino.ApplicationSettings.AppearanceSettings.SelectedObjectColor
          : doc.Layers.CurrentLayer.Color
                )
            {
                Enabled = true
            };

            if (mode == RunMode.Interactive)
            {
                // Show the interactive dialog box
                var dialog = new VectorizeDialog(doc, conduit);
                dialog.RestorePosition();
                var result = dialog.ShowSemiModal(doc, RhinoEtoApp.MainWindow);
                dialog.SavePosition();
                if (result != Result.Success)
                {
                    conduit.Enabled = false;
                    Potrace.Clear();
                    doc.Views.Redraw();
                    return(Result.Cancel);
                }
            }
            else
            {
                // Show the command line options
                var go = new GetOption();
                go.SetCommandPrompt("Vectorization options. Press Enter when done");
                go.AcceptNothing(true);
                while (true)
                {
                    conduit.TraceBitmap();
                    doc.Views.Redraw();

                    go.ClearCommandOptions();

                    // IgnoreArea
                    var turdsize_opt = new OptionInteger(Potrace.turdsize, 2, 100);
                    var turdsize_idx = go.AddOptionInteger("FilterSize", ref turdsize_opt, "Filter speckles of up to this size in pixels");

                    // TurnPolicy
                    var turnpolicy_idx = go.AddOptionEnumList("TurnPolicy", Potrace.turnpolicy);

                    // Optimizing
                    var curveoptimizing_opt = new OptionToggle(Potrace.curveoptimizing, "No", "Yes");
                    var curveoptimizing_idx = go.AddOptionToggle("Optimizing", ref curveoptimizing_opt);

                    // Tolerance
                    var opttolerance_opt = new OptionDouble(Potrace.opttolerance, 0.0, 1.0);
                    var opttolerance_idx = go.AddOptionDouble("Tolerance", ref opttolerance_opt, "Optimizing tolerance");

                    // CornerThreshold
                    var alphamax_opt = new OptionDouble(Potrace.alphamax, 0.0, 100.0);
                    var alphamax_idx = go.AddOptionDouble("CornerRounding", ref alphamax_opt, "Corner rounding threshold");

                    // Threshold
                    var threshold_opt = new OptionDouble(Potrace.Treshold, 0.0, 100.0);
                    var threshold_idx = go.AddOptionDouble("Threshold", ref threshold_opt, "Threshold");

                    // RestoreDefaults
                    var defaults_idx = go.AddOption("RestoreDefaults");

                    var res = go.Get();

                    if (res == GetResult.Option)
                    {
                        var option = go.Option();
                        if (null != option)
                        {
                            if (turdsize_idx == option.Index)
                            {
                                Potrace.turdsize = turdsize_opt.CurrentValue;
                            }

                            if (turnpolicy_idx == option.Index)
                            {
                                var list = Enum.GetValues(typeof(TurnPolicy)).Cast <TurnPolicy>().ToList();
                                Potrace.turnpolicy = list[option.CurrentListOptionIndex];
                            }

                            if (curveoptimizing_idx == option.Index)
                            {
                                Potrace.curveoptimizing = curveoptimizing_opt.CurrentValue;
                            }

                            if (opttolerance_idx == option.Index)
                            {
                                Potrace.opttolerance = opttolerance_opt.CurrentValue;
                            }

                            if (alphamax_idx == option.Index)
                            {
                                Potrace.alphamax = alphamax_opt.CurrentValue;
                            }

                            if (threshold_idx == option.Index)
                            {
                                Potrace.Treshold = threshold_opt.CurrentValue;
                            }

                            if (defaults_idx == option.Index)
                            {
                                Potrace.RestoreDefaults();
                            }
                        }
                        continue;
                    }

                    if (res != GetResult.Nothing)
                    {
                        conduit.Enabled = false;
                        doc.Views.Redraw();
                        Potrace.Clear();
                        return(Result.Cancel);
                    }

                    break;
                }
            }

            // Group curves
            var attributes = doc.CreateDefaultAttributes();

            attributes.AddToGroup(doc.Groups.Add());
            for (var i = 0; i < conduit.OutlineCurves.Count; i++)
            {
                var rhobj_id = doc.Objects.AddCurve(conduit.OutlineCurves[i], attributes);
                if (m_select_output)
                {
                    var rhobj = doc.Objects.Find(rhobj_id);
                    if (null != rhobj)
                    {
                        rhobj.Select(true);
                    }
                }
            }

            conduit.Enabled = false;
            Potrace.Clear();
            doc.Views.Redraw();

            // Set the Potrace settings to the plug -in settings file.
            SetPotraceSettings();

            return(Result.Success);
        }
Ejemplo n.º 5
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var cities         = new OptionInteger(50, 3, 1000);
            var time           = new OptionInteger(10, 5, 120);
            var algorithmIndex = 0;

            var get = new GetOption();

            get.SetCommandPrompt("Optimize TSP");
            get.AddOptionInteger("Cities", ref cities);
            get.AddOptionInteger("Time", ref time);
            get.AddOptionList("Algorithm", new[] { "RandomSearch", "HillClimbing", "SimulatedAnnealing" }, 0);
            get.AddOption("Run");

            while (true)
            {
                get.Get();

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

                if (get.Option().EnglishName == "Algorithm")
                {
                    algorithmIndex = get.Option().CurrentListOptionIndex;
                }

                if (get.Option().EnglishName == "Run")
                {
                    RhinoApp.WriteLine("Optimization started...");
                    break;
                }
            }

            var optimizer = new Optimizer(cities.CurrentValue, time.CurrentValue);
            var conduit   = new OptimizeConduit(optimizer.Path)
            {
                Enabled = true
            };

            Task updateTask = null;

            optimizer.UpdatedCandidate += (o, e) =>
            {
                conduit.Path = optimizer.Path;
                conduit.Info = optimizer.Info;

                //doc.Views.Redraw();

                if (updateTask?.IsCompleted != false)
                {
                    updateTask = Task.Run(() => doc.Views.Redraw());
                }
            };

            optimizer.Finished += (o, e) =>
            {
                conduit.Enabled = false;
                doc.Objects.AddPolyline(optimizer.Path);
                doc.Views.Redraw();
                RhinoApp.WriteLine($"Optimization finished ({optimizer.Info}).");
            };

            var algorithms = new Action[]
            {
                optimizer.RandomSearch,
                optimizer.HillClimbing,
                optimizer.SimulatedAnnealing
            };

            Task.Run(algorithms[algorithmIndex]);

            return(Result.Success);
        }
Ejemplo n.º 6
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            if (!(RhinoApp.GetPlugInObject("Grasshopper") is GH_RhinoScriptInterface Grasshopper))
            {
                return(Result.Cancel);
            }

            GetOption go = null;

            while (true)
            {
                var port     = new OptionInteger(Port, 1024, 65535);
                var toggle   = new OptionToggle(ShowEditor, "Hide", "Show");
                var debugger = new OptionToggle(Debug, "Off", "On");

                go = new GetOption();

                go.SetCommandPrompt("Noah Server");
                go.AddOption("Connect");
                go.AddOption("Stop");
                go.AddOption("Observer");
                go.AddOptionInteger("Port", ref port);
                go.AddOptionToggle("Editor", ref toggle);
                go.AddOptionToggle("Debug", ref debugger);
                go.AddOption("Workspace");

                GetResult result = go.Get();
                if (result != GetResult.Option)
                {
                    break;
                }

                ShowEditor = toggle.CurrentValue;
                Debug      = debugger.CurrentValue;

                string whereToGo = go.Option().EnglishName;

                if (whereToGo == "Connect")
                {
                    if (Port == 0)
                    {
                        RhinoApp.WriteLine("Please set Port you want to connect!");
                        continue;
                    }

                    if (WorkDir == null)
                    {
                        RhinoApp.WriteLine("Noah can not work without workspace!");
                        continue;
                    }

                    if (Client == null)
                    {
                        try
                        {
                            Grasshopper.DisableBanner();

                            if (!Grasshopper.IsEditorLoaded())
                            {
                                Grasshopper.LoadEditor();
                            }

                            Client               = new NoahClient(Port, WorkDir);
                            Client.InfoEvent    += Client_MessageEvent;
                            Client.ErrorEvent   += Client_ErrorEvent;
                            Client.WarningEvent += Client_WarningEvent;
                            Client.DebugEvent   += Client_DebugEvent;
                        }
                        catch (Exception ex)
                        {
                            RhinoApp.WriteLine("Error: " + ex.Message);
                        }

                        Client.Connect();
                    }
                    else
                    {
                        Client.Reconnect();
                    }

                    if (Debug)
                    {
                        try
                        {
                            if (Logger == null)
                            {
                                Panels.OpenPanel(LoggerPanel.PanelId);
                            }
                            Logger = Panels.GetPanel <LoggerPanel>(doc);
                        }
                        catch (Exception ex)
                        {
                            RhinoApp.WriteLine("Error: " + ex.Message);
                        }
                    }

                    if (ShowEditor)
                    {
                        Grasshopper.ShowEditor();
                    }

                    break;
                }

                if (whereToGo == "Stop")
                {
                    if (Port == 0)
                    {
                        continue;
                    }

                    if (Client != null)
                    {
                        Client.Close();
                    }
                    break;
                }

                if (whereToGo == "Workspace")
                {
                    RhinoGet.GetString("Noah Workspace", false, ref WorkDir);
                }

                if (whereToGo == "Observer")
                {
                    if (Port == 0)
                    {
                        RhinoApp.WriteLine("Server connecting need a port!");
                        continue;
                    }

                    Process.Start("http://localhost:" + Port + "/data/center");
                    break;
                }

                if (whereToGo == "Port")
                {
                    Port = port.CurrentValue;
                    RhinoApp.WriteLine("Port is set to " + Port.ToString());
                    continue;
                }
            }

            return(Result.Nothing);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var           primal = new PFoam();
            var           dual   = new PFoam();
            ContainerType container;

            try
            {
                var guids = LoadData.LoadPrimalDual(out primal, out dual, out container);

                if (dual.Cells.Count < 1)
                {
                    RhinoApp.WriteLine("No dual data retrieved from the container!");
                    return(Result.Failure);
                }

                // Primal ( the perping geometry )
                // load the foam from the geometry option to update from the geometry if any changes occured
                // select the structure to be perped - if dual not present raise error

                // show a set of options
                // Max steps 10 000
                // maximum deviation in degrees from dual direction
                // Update dual data from geometry
                // set edge legth constraint
                // set point position constraint

                var averageLen = primal.Edges.Select(x => x.GetLength()).Average();

                var getOptions = new GetOption();
                getOptions.SetDefaultString("enter");

                getOptions.SetCommandPrompt("Set max number of steps and perping options");

                var  optionSteps      = new OptionInteger(1000, true, 0);
                var  optionMaxDev     = new OptionDouble(0.1, 0.0, 10.0);
                var  optionMinLen     = new OptionDouble(averageLen / 4, true, averageLen / 100);
                var  optionSetEdge    = new OptionToggle(false, "setE", "E_set");
                var  optionSetVert    = new OptionToggle(false, "setV", "V_set");
                var  optionSetDualGeo = new OptionToggle(false, "setG", "G_set");
                var  storedSteps      = 1000.0;
                var  storedMaxDev     = 0.1;
                var  storedMinLen     = averageLen / 4;
                bool storedEdgeSet    = false;
                bool storedVertSet    = false;
                bool storedDualGeoSet = false;

                getOptions.AddOptionInteger("MaxIterations", ref optionSteps);
                getOptions.AddOptionDouble("MaxDeviation", ref optionMaxDev);
                getOptions.AddOptionDouble("MinEdgeLenght", ref optionMinLen);
                getOptions.AddOptionToggle("SetEdgeLen", ref optionSetEdge);
                getOptions.AddOptionToggle("SetVertPos", ref optionSetVert);
                getOptions.AddOptionToggle("UpdatePrimalGeo", ref optionSetDualGeo);

                while (true)
                {
                    var preres = getOptions.Get();
                    var res    = getOptions.CommandResult();
                    //var numres = getOptions.

                    if (res == Result.Success)
                    {
                        if (optionSetEdge.CurrentValue != storedEdgeSet)
                        {
                            primal.PickEdges();
                        }
                        if (optionSetVert.CurrentValue != storedVertSet)
                        {
                            primal.PickVertex();
                        }
                        if (optionSetDualGeo.CurrentValue != storedDualGeoSet)
                        {
                            var updatedDual = new PFoam();



                            LoadData.LoadPrimalDual(out updatedDual, out PFoam notUsedPrimal, out ContainerType dummyContainer, false);
                            // get the container geometry from a dual from the document
                            // check to see if the id matches
                            // load the point geometry, centroids, meshes and update data in the dual

                            // transform the primal/dual getter into a method to reuse it more easily

                            if (updatedDual.Dual.Id == primal.Id)
                            {
                                dual = updatedDual;
                                Util.ConnectDuals(ref primal, ref updatedDual);
                            }
                        }



                        if (optionSetEdge.CurrentValue == storedEdgeSet &&
                            optionSetVert.CurrentValue == storedVertSet &&
                            optionSetDualGeo.CurrentValue == storedDualGeoSet &&
                            optionSteps.CurrentValue == storedSteps &&
                            optionMaxDev.CurrentValue == storedMaxDev &&
                            optionMinLen.CurrentValue == storedMinLen
                            )
                        {
                            break;
                        }


                        storedEdgeSet    = optionSetEdge.CurrentValue;
                        storedVertSet    = optionSetVert.CurrentValue;
                        storedDualGeoSet = optionSetDualGeo.CurrentValue;
                        storedSteps      = optionSteps.CurrentValue;
                        storedMaxDev     = optionMaxDev.CurrentValue;
                        storedMinLen     = optionMinLen.CurrentValue;
                    }
                    else
                    {
                        return(Result.Cancel);
                    }
                }
                //Util.ConnectDuals(ref primal, ref dual);
                foreach (var edge in primal.Edges)
                {
                    edge.MinLength = optionMinLen.CurrentValue;
                }

                // delete the input objects
                doc.Objects.Delete(guids, true);

                primal.PerpSoft(optionSteps.CurrentValue, optionMaxDev.CurrentValue / 180 * Math.PI);

                //primal.ParaPerp(optionSteps.CurrentValue, 0, optionMaxDev.CurrentValue / 180 * Math.PI, null, 1);


                primal.Show(true, true, false);



                var pepedPrimalJsonString = primal.SerializeJson();

                if (!primal.SaveToDocument(container))
                {
                    primal.Hide();
                    return(Result.Cancel);
                }
                primal.Hide();

                return(Result.Success);
            }
            catch (PolyFrameworkException pfE)
            {
                RhinoApp.WriteLine(pfE.Message);
                primal.Hide();
                dual.Hide();
                return(Result.Failure);
            }
            // TODO: complete command.
        }
Ejemplo n.º 9
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            //look at this for a summary of all the GET commands.

            // https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_Input_Custom_GetBaseClass.htm.

            /*System.Object
             * Rhino.Input.Custom.GetBaseClass
             *  Rhino.Input.Custom.GetInteger
             *  Rhino.Input.Custom.GetNumber
             *  Rhino.Input.Custom.GetObject
             *  Rhino.Input.Custom.GetOption
             *  Rhino.Input.Custom.GetPoint
             *  Rhino.Input.Custom.GetString
             *
             * */
            var gc = new GetObject();

            gc.SetCommandPrompt("Select objects");
            gc.GeometryFilter = ObjectType.AnyObject;

            OptionInteger intOption  = new OptionInteger(1, 1, 99);
            OptionDouble  dblOption  = new OptionDouble(2.2, 0, 99);
            OptionToggle  boolOption = new OptionToggle(true, "off", "on");

            gc.AddOptionInteger("Integer", ref intOption);
            gc.AddOptionDouble("Double", ref dblOption);
            gc.AddOptionToggle("Boolean", ref boolOption);

            int listIndex = 0;

            string[] listValues = new string[] { "Bran", "Bob", "Arya", "Sansa", "Rickon" };

            int optList = gc.AddOptionList("List", listValues, listIndex);

            while (true)
            {
                GetResult res = gc.GetMultiple(1, 0);

                //we can check if the user selected something
                if (gc.CommandResult() != Result.Success)
                {
                    return(gc.CommandResult());
                }

                if (res == Rhino.Input.GetResult.Object)
                {
                    RhinoApp.WriteLine("Command line option values are");
                    RhinoApp.WriteLine("Integer = {0}", intOption.CurrentValue);
                    RhinoApp.WriteLine("Double = {0}", dblOption.CurrentValue);
                    RhinoApp.WriteLine("Boolean = {0}", boolOption.CurrentValue);
                    RhinoApp.WriteLine("List = {0}", listValues[listIndex]);
                }
                else if (res == Rhino.Input.GetResult.Option)
                {
                    if (gc.OptionIndex() == optList)
                    {
                        listIndex = gc.Option().CurrentListOptionIndex; //this updates the list option to whatever index the user has picked
                    }
                    continue;
                }

                break;
            }

            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometryFilter = ObjectType.Mesh;

            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, 10000);
            OptionDouble  smoothSpeedOption     = new OptionDouble(smoothSpeed, 0.01, 1.0);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select meshes to remesh");
            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 = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;

            bool bHavePreselectedObjects = false;

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

                if (res == 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;

            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;

            foreach (var obj in go.Objects())
            {
                var rhinoMesh = obj.Mesh();

                if (rhinoMesh == null || !rhinoMesh.IsValid)
                {
                    continue;
                }

                var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh());

                var res = GopherUtil.RemeshMesh(mesh, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps);

                var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(mesh);

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    doc.Objects.Replace(obj, newRhinoMesh);
                }

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    result |= doc.Objects.Replace(obj, newRhinoMesh);
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Ejemplo n.º 11
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var getNumber = new GetNumber();

            getNumber.SetLowerLimit(2.0, false);
            getNumber.SetUpperLimit(uint.MaxValue, false);
            getNumber.SetDefaultInteger(RcCore.It.EngineSettings.Samples);
            getNumber.SetCommandPrompt("Set render samples");

            var showMaxPasses = new OptionToggle(RcCore.It.EngineSettings.ShowMaxPasses, "HideMaxPasses", "ShowMaxPasses");

            var maxBounce = new OptionInteger(RcCore.It.EngineSettings.MaxBounce, 0, 500);
            var tileX     = new OptionInteger(RcCore.It.EngineSettings.TileX, 0, 10000);
            var tileY     = new OptionInteger(RcCore.It.EngineSettings.TileY, 0, 10000);


            var maxDiffuseBounce      = new OptionInteger(RcCore.It.EngineSettings.MaxDiffuseBounce, 0, 200);
            var maxGlossyBounce       = new OptionInteger(RcCore.It.EngineSettings.MaxGlossyBounce, 0, 200);
            var maxTransmissionBounce = new OptionInteger(RcCore.It.EngineSettings.MaxTransmissionBounce, 0, 200);
            var maxVolumeBounce       = new OptionInteger(RcCore.It.EngineSettings.MaxVolumeBounce, 0, 200);

            var noCaustics = new OptionToggle(RcCore.It.EngineSettings.NoCaustics, "Caustics", "NoCaustics");

            var aaSamples     = new OptionInteger(RcCore.It.EngineSettings.AaSamples, 1, 100);
            var diffSamples   = new OptionInteger(RcCore.It.EngineSettings.DiffuseSamples, 1, 100);
            var glossySamples = new OptionInteger(RcCore.It.EngineSettings.GlossySamples, 1, 100);

            var seed = new OptionInteger(RcCore.It.EngineSettings.Seed, 0, int.MaxValue);

            var sensorWidth  = new OptionDouble(RcCore.It.EngineSettings.SensorWidth, 10.0, 100.0);
            var sensorHeight = new OptionDouble(RcCore.It.EngineSettings.SensorHeight, 10.0, 100.0);

            var transparentMaxBounce = new OptionInteger(RcCore.It.EngineSettings.TransparentMaxBounce, 0, 200);

            var filterGlossy            = new OptionDouble(RcCore.It.EngineSettings.FilterGlossy, 0.0, 100.0);
            var sampleClampDirect       = new OptionDouble(RcCore.It.EngineSettings.SampleClampDirect, 0.0, 100.0);
            var sampleClampIndirect     = new OptionDouble(RcCore.It.EngineSettings.SampleClampIndirect, 0.0, 100.0);
            var lightSamplingThreshold  = new OptionDouble(RcCore.It.EngineSettings.LightSamplingThreshold, 0.0, 1.0);
            var sampleAllLights         = new OptionToggle(RcCore.It.EngineSettings.SampleAllLights, "no", "yes");
            var sampleAllLightsIndirect = new OptionToggle(RcCore.It.EngineSettings.SampleAllLightsIndirect, "no", "yes");

            getNumber.AddOptionToggle("show_max_passes", ref showMaxPasses);
            getNumber.AddOptionInteger("max_bounces", ref maxBounce);
            getNumber.AddOptionInteger("tile_x", ref tileX);
            getNumber.AddOptionInteger("tile_y", ref tileY);
            getNumber.AddOptionToggle("no_caustics", ref noCaustics);

            getNumber.AddOptionInteger("max_diffuse_bounce", ref maxDiffuseBounce);
            getNumber.AddOptionInteger("max_glossy_bounce", ref maxGlossyBounce);
            getNumber.AddOptionInteger("max_transmission_bounce", ref maxTransmissionBounce);
            getNumber.AddOptionInteger("max_volume_bounce", ref maxVolumeBounce);

            getNumber.AddOptionInteger("transparent_max_bounce", ref transparentMaxBounce);

            getNumber.AddOptionInteger("aa_samples", ref aaSamples);
            getNumber.AddOptionInteger("diffuse_samples", ref diffSamples);
            getNumber.AddOptionInteger("glossy_samples", ref glossySamples);

            getNumber.AddOptionDouble("sensor_width", ref sensorWidth);
            getNumber.AddOptionDouble("sensor_height", ref sensorHeight);


            getNumber.AddOptionInteger("seed", ref seed, "Seed to use for sampling distribution");

            getNumber.AddOptionDouble("filter_glossy", ref filterGlossy);
            getNumber.AddOptionDouble("sample_clamp_direct", ref sampleClampDirect);
            getNumber.AddOptionDouble("sample_clamp_indirect", ref sampleClampIndirect);
            getNumber.AddOptionDouble("light_sampling_threshold", ref lightSamplingThreshold);
            getNumber.AddOptionToggle("sample_all_lights", ref sampleAllLights);
            getNumber.AddOptionToggle("sample_all_lights_indirect", ref sampleAllLightsIndirect);

            while (true)
            {
                var getRc = getNumber.Get();
                if (getNumber.CommandResult() != Result.Success)
                {
                    return(getNumber.CommandResult());
                }
                switch (getRc)
                {
                case GetResult.Number:
                    RhinoApp.WriteLine($"We got: {getNumber.Number()}, {maxBounce.CurrentValue}");
                    RcCore.It.EngineSettings.Samples                 = (int)getNumber.Number();
                    RcCore.It.EngineSettings.ShowMaxPasses           = showMaxPasses.CurrentValue;
                    RcCore.It.EngineSettings.Seed                    = seed.CurrentValue;
                    RcCore.It.EngineSettings.MaxBounce               = maxBounce.CurrentValue;
                    RcCore.It.EngineSettings.TileX                   = tileX.CurrentValue;
                    RcCore.It.EngineSettings.TileY                   = tileY.CurrentValue;
                    RcCore.It.EngineSettings.NoCaustics              = noCaustics.CurrentValue;
                    RcCore.It.EngineSettings.MaxDiffuseBounce        = maxDiffuseBounce.CurrentValue;
                    RcCore.It.EngineSettings.MaxGlossyBounce         = maxGlossyBounce.CurrentValue;
                    RcCore.It.EngineSettings.MaxTransmissionBounce   = maxTransmissionBounce.CurrentValue;
                    RcCore.It.EngineSettings.MaxVolumeBounce         = maxVolumeBounce.CurrentValue;
                    RcCore.It.EngineSettings.TransparentMaxBounce    = transparentMaxBounce.CurrentValue;
                    RcCore.It.EngineSettings.AaSamples               = aaSamples.CurrentValue;
                    RcCore.It.EngineSettings.DiffuseSamples          = diffSamples.CurrentValue;
                    RcCore.It.EngineSettings.GlossySamples           = glossySamples.CurrentValue;
                    RcCore.It.EngineSettings.SensorWidth             = (float)sensorWidth.CurrentValue;
                    RcCore.It.EngineSettings.SensorHeight            = (float)sensorHeight.CurrentValue;
                    RcCore.It.EngineSettings.FilterGlossy            = (float)filterGlossy.CurrentValue;
                    RcCore.It.EngineSettings.SampleClampDirect       = (float)sampleClampDirect.CurrentValue;
                    RcCore.It.EngineSettings.SampleClampIndirect     = (float)sampleClampIndirect.CurrentValue;
                    RcCore.It.EngineSettings.LightSamplingThreshold  = (float)lightSamplingThreshold.CurrentValue;
                    RcCore.It.EngineSettings.SampleAllLights         = sampleAllLights.CurrentValue;
                    RcCore.It.EngineSettings.SampleAllLightsIndirect = sampleAllLightsIndirect.CurrentValue;
                    break;

                case GetResult.Option:
                    continue;
                }

                break;
            }
            return(Result.Success);
        }
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometryFilter = ObjectType.Mesh;

            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, 1000);
            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 to remesh");
            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.AddOptionDouble("ProjectAmount", ref projectAmountOption);
            go.AddOptionDouble("ProjectDistance", ref projectedDistanceOption);

            go.GroupSelect     = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;

            bool bHavePreselectedObjects = false;

            for (;;)
            {
                GetResult res = go.Get();

                if (res == 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;
            }

            GetObject goProjected = new GetObject();

            goProjected.EnablePreSelect(false, true);
            goProjected.SetCommandPrompt("Select mesh to project to");
            goProjected.GeometryFilter = geometryFilter;
            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 res = goProjected.Get();

                if (res == 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);
            }

            foreach (var obj in go.Objects())
            {
                var rhinoMesh = obj.Mesh();

                if (rhinoMesh == null || !rhinoMesh.IsValid)
                {
                    continue;
                }

                var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh());


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

                if (rhinoMeshProject == null || !rhinoMeshProject.IsValid)
                {
                    continue;
                }

                var meshProjected = GopherUtil.ConvertToD3Mesh(rhinoMeshProject);

                var mesh2 = new DMesh3(mesh);
                var mesh3 = new DMesh3(mesh);

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

                var watch = System.Diagnostics.Stopwatch.StartNew();
                // the code that you want to measure comes here

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

                watch.Stop();

                var watch2 = System.Diagnostics.Stopwatch.StartNew();

                var res2 = GopherUtil.RemeshMeshNew(mesh2, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, meshProjected, (float)projectedAmount, (float)projectedDistance);

                watch2.Stop();


                Rhino.RhinoApp.WriteLine("Time 1: {0} Time 2: {1}", watch.ElapsedMilliseconds, watch2.ElapsedMilliseconds);

                var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(res);

                var newRhinoMesh2 = GopherUtil.ConvertToRhinoMesh(mesh2);

                newRhinoMesh2.Translate(new Rhino.Geometry.Vector3d(newRhinoMesh2.GetBoundingBox(true).Diagonal.X, 0, 0));

                doc.Objects.Add(newRhinoMesh2);

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    doc.Objects.Replace(obj, newRhinoMesh);
                }

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    result |= doc.Objects.Replace(obj, newRhinoMesh);
                }
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Ejemplo n.º 13
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometryFilter = ObjectType.Mesh;
            
            OptionDouble minEdgeLengthOption = new OptionDouble(minEdgeLength, 0.001, 200);
            OptionInteger maxTriangleCountOption = new OptionInteger(maxTriangleCount, 0, 100000000);
            
            GetObject go = new GetObject();
            go.SetCommandPrompt("Select meshes to reduce");
            go.GeometryFilter = geometryFilter;
            go.AddOptionDouble("MinEdge", ref minEdgeLengthOption);
            go.AddOptionInteger("MaxTriangle", ref maxTriangleCountOption);

            go.GroupSelect = true;
            go.SubObjectSelect = false;
            go.EnableClearObjectsOnEntry(false);
            go.EnableUnselectObjectsOnExit(false);
            go.DeselectAllBeforePostSelect = false;

            bool bHavePreselectedObjects = false;

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

                if (res == 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;
            }

            maxTriangleCount = maxTriangleCountOption.CurrentValue;
            minEdgeLength = minEdgeLengthOption.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;

            foreach (var obj in go.Objects())
            {
                var rhinoMesh = obj.Mesh();

                if (rhinoMesh == null || !rhinoMesh.IsValid)
                    continue;

                var mesh = GopherUtil.ConvertToD3Mesh(obj.Mesh());
                
                GopherUtil.ReduceMesh(mesh, (float)minEdgeLength, maxTriangleCount);

                double mine, maxe, avge;
                MeshQueries.EdgeLengthStats(mesh, out mine, out maxe, out avge);
                   RhinoApp.WriteLine("Edge length stats: {0} {1} {2}", mine, maxe, avge);

                var newRhinoMesh = GopherUtil.ConvertToRhinoMesh(mesh);

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    doc.Objects.Replace(obj, newRhinoMesh);
                }

                if (newRhinoMesh != null && newRhinoMesh.IsValid)
                {
                    result |= doc.Objects.Replace(obj, newRhinoMesh);
                }
            }

            doc.Views.Redraw();

            return Result.Success;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// RunCommand override
        /// </summary>
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            // Get persistent settings (from Registry)
            var bool_value = Settings.GetBool("BoolValue", BOOL_DEFAULT);
            var int_value  = Settings.GetInteger("IntValue", INT_DEFAULT);
            var dbl_value  = Settings.GetDouble("DblValue", DBL_DEFAULT);
            var list_value = Settings.GetInteger("ListValue", LIST_DEFAULT);

            var gp = new GetPoint();

            gp.SetCommandPrompt("GetPoint with options");

            var rc = Result.Cancel;

            while (true)
            {
                gp.ClearCommandOptions();

                var bool_option = new OptionToggle(bool_value, "Off", "On");
                var int_option  = new OptionInteger(int_value, 1, 99);
                var dbl_option  = new OptionDouble(dbl_value, 0, 99.9);
                var list_items  = new[] { "Item0", "Item1", "Item2", "Item3", "Item4" };

                var bool_index  = gp.AddOptionToggle("Boolean", ref bool_option);
                var int_index   = gp.AddOptionInteger("Integer", ref int_option);
                var dbl_index   = gp.AddOptionDouble("Double", ref dbl_option);
                var list_index  = gp.AddOptionList("List", list_items, list_value);
                var reset_index = gp.AddOption("Reset");

                var res = gp.Get();

                if (res == Rhino.Input.GetResult.Point)
                {
                    doc.Objects.AddPoint(gp.Point());
                    doc.Views.Redraw();
                    rc = Result.Success;
                }
                else if (res == Rhino.Input.GetResult.Option)
                {
                    var option = gp.Option();
                    if (null != option)
                    {
                        if (option.Index == bool_index)
                        {
                            bool_value = bool_option.CurrentValue;
                        }
                        else if (option.Index == int_index)
                        {
                            int_value = int_option.CurrentValue;
                        }
                        else if (option.Index == dbl_index)
                        {
                            dbl_value = dbl_option.CurrentValue;
                        }
                        else if (option.Index == list_index)
                        {
                            list_value = option.CurrentListOptionIndex;
                        }
                        else if (option.Index == reset_index)
                        {
                            bool_value = BOOL_DEFAULT;
                            int_value  = INT_DEFAULT;
                            dbl_value  = DBL_DEFAULT;
                            list_value = LIST_DEFAULT;
                        }
                    }
                    continue;
                }

                break;
            }

            if (rc == Result.Success)
            {
                // Set persistent settings (to Registry)
                Settings.SetBool("BoolValue", bool_value);
                Settings.SetInteger("IntValue", int_value);
                Settings.SetDouble("DblValue", dbl_value);
                Settings.SetInteger("ListValue", list_value);
            }

            return(rc);
        }
Ejemplo n.º 15
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            const ObjectType geometryFilter = ObjectType.MeshEdge;

            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, 1000);
            OptionDouble  smoothSpeedOption     = new OptionDouble(smoothSpeed, 0.01, 1.0);

            GetObject go = new GetObject();

            go.SetCommandPrompt("Select mesh edges to constrain during remesh");
            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 res = go.GetMultiple(1, 0);

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

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

                break;
            }

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

            System.Collections.Generic.List <g3.Line3d>   constrain = new System.Collections.Generic.List <g3.Line3d>();
            System.Collections.Generic.List <System.Guid> meshes    = new System.Collections.Generic.List <System.Guid>();

            foreach (var obj in go.Objects())
            {
                if (!meshes.Contains(obj.ObjectId))
                {
                    meshes.Add(obj.ObjectId);
                }

                ObjRef objref = new ObjRef(obj.ObjectId);

                var mesh = objref.Mesh();

                var line = mesh.TopologyEdges.EdgeLine(obj.GeometryComponentIndex.Index);

                var dir = line.Direction;

                constrain.Add(new g3.Line3d(new Vector3d(line.FromX, line.FromY, line.FromZ), new Vector3d(dir.X, dir.Y, dir.Z)));
            }

            foreach (var guid in meshes)
            {
                var objref = new ObjRef(guid);

                var mesh    = GopherUtil.ConvertToD3Mesh(objref.Mesh());
                var res     = GopherUtil.RemeshMesh(mesh, (float)minEdgeLength, (float)maxEdgeLength, (float)constriantAngle, (float)smoothSpeed, smoothSteps, constrain);
                var newMesh = GopherUtil.ConvertToRhinoMesh(res);

                doc.Objects.Replace(objref, newMesh);
            }

            doc.Views.Redraw();

            return(Result.Success);
        }
Ejemplo n.º 16
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            var     pack_algorithm    = PackingAlgorithm.Fast;
            Point3d base_point        = new Point3d();
            var     option_count      = new OptionInteger(100, true, 2);
            var     option_min_radius = new OptionDouble(0.1, true, 0.001);
            var     option_max_radius = new OptionDouble(1.0, true, 0.001);
            var     option_iterations = new OptionInteger(10000, false, 100);

            bool done_looping = false;

            while (!done_looping)
            {
                var gp = new GetPoint();
                gp.SetCommandPrompt("Center of fitting solution");
                gp.AddOptionInteger("Count", ref option_count);
                gp.AddOptionDouble("MinRadius", ref option_min_radius);
                gp.AddOptionDouble("MaxRadius", ref option_max_radius);
                gp.AddOptionInteger("IterationLimit", ref option_iterations);
                int index_option_packing = gp.AddOption("Packing", pack_algorithm.ToString());
                gp.AcceptNumber(true, true);

                switch (gp.Get())
                {
                case GetResult.Point:
                    base_point   = gp.Point();
                    done_looping = true;
                    break;

                case GetResult.Option:
                    if (index_option_packing == gp.OptionIndex())
                    {
                        var get_algorithm = new GetOption();
                        get_algorithm.SetCommandPrompt("Packing");
                        get_algorithm.SetDefaultString(pack_algorithm.ToString());
                        var opts          = new string[] { "Fast", "Double", "Random", "Simple" };
                        int current_index = 0;
                        switch (pack_algorithm)
                        {
                        case PackingAlgorithm.Fast:
                            current_index = 0;
                            break;

                        case PackingAlgorithm.Double:
                            current_index = 1;
                            break;

                        case PackingAlgorithm.Random:
                            current_index = 2;
                            break;

                        case PackingAlgorithm.Simple:
                            current_index = 3;
                            break;
                        }
                        int index_list = get_algorithm.AddOptionList("algorithm", opts, current_index);
                        get_algorithm.AddOption("Help");
                        while (get_algorithm.Get() == GetResult.Option)
                        {
                            if (index_list == get_algorithm.OptionIndex())
                            {
                                int index = get_algorithm.Option().CurrentListOptionIndex;
                                if (0 == index)
                                {
                                    pack_algorithm = PackingAlgorithm.Fast;
                                }
                                if (1 == index)
                                {
                                    pack_algorithm = PackingAlgorithm.Double;
                                }
                                if (2 == index)
                                {
                                    pack_algorithm = PackingAlgorithm.Simple;
                                }
                                if (3 == index)
                                {
                                    pack_algorithm = PackingAlgorithm.Random;
                                }
                                break;
                            }
                            // if we get here, the user selected help
                            const string help =
                                @"Fast: fast packing prevents collisions by moving one
circle away from all its intersectors. After every collision
iteration, all circles are moved towards the centre of the
packing to reduce the amount of wasted space. Collision
detection proceeds from the center outwards.

Double: similar to Fast, except that both circles are moved
in case of a collision.

Random: similar to Fast, except that collision detection is
randomized rather than sorted.

Simple: similar to Fast, but without a contraction pass
after every collision iteration.";
                            Rhino.UI.Dialogs.ShowMessageBox(help, "Packing algorithm description", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                        }
                    }
                    break;

                default:
                    return(Result.Cancel);
                }
            }
            int    count      = option_count.CurrentValue;
            double min_radius = option_min_radius.CurrentValue;
            double max_radius = option_max_radius.CurrentValue;
            int    iterations = option_iterations.CurrentValue;

            // TODO: try setting up a background worker thread and
            // communicate with the GetString through messages
            //GetString gs = new GetString();
            //gs.SetCommandPrompt("Press escape to cancel");

            using (var all_circles = new PackCircles(base_point, count, min_radius, max_radius))
            {
                double damping = 0.1;
                for (int i = 1; i <= iterations; i++)
                {
                    RhinoApp.SetCommandPrompt(string.Format("Performing circle packing iteration {0}...  (Press Shift+Ctrl to abort)", i));

                    if (System.Windows.Forms.Control.ModifierKeys == (System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift))
                    {
                        RhinoApp.WriteLine("Circle fitting process aborted at iteration {0}...", i);
                        break;
                    }

                    if (!all_circles.Pack(pack_algorithm, damping, doc.ModelAbsoluteTolerance))
                    {
                        RhinoApp.WriteLine("Circle fitting process completed at iteration {0}...", i);
                        break;
                    }

                    damping *= 0.98;
                    doc.Views.Redraw();
                    RhinoApp.Wait();
                }
                all_circles.Add(doc);
            }
            doc.Views.Redraw();
            return(Result.Success);
        }