Quantcast
Channel: Grasshopper Developer - McNeel Forum
Viewing all 3626 articles
Browse latest View live

Assigning List with Points from one C# class into another C# class

$
0
0

@Baris wrote:

Hi everyone,
I was doing the ICD-Course from 2017 today and tried to make some changes,where the problem occured.

I have a class relying on the standard Grasshopper template to harvest the values from Grasshopper and than pass them to another class.


I am getting the Points read in correctly, but when I want to use them in the other class, the list comes in as null.

I cant understand how to assing the List correctly?

Thanks in advance!

Posts: 3

Participants: 2

Read full topic


Multithreading in a C# component in Visual Studio

$
0
0

@gieljan_vantyghem wrote:

Hi all

I have a general question regarding ‘Multitreading’ in a C# component.

In one of my recently-developed plugin components I’ve replace some ‘for loops’ with the ‘parallel.For loop’ alternative using information that I’ve found on the following webpage by James Ramsden: http://james-ramsden.com/multithreading-a-foreach-loop-in-a-grasshopper-components-in-c/

This seems to work great as you can see my component speed is several orders of magnitude faster now: (This example was performed on a pc with 24 cores)
imgpsh_mobile_save

So now my question: What are the differences / disadvantages comparing this techniques with the ‘IGH_TaskCapableComponent’ interface. Information here: https://developer.rhino3d.com/guides/grasshopper/programming-task-capable-component/

Should I remove the component that is single threaded from my plugin with release? Or will some users prefer not to use multithreading? Should I combine both and use ‘AppendAdditionalComponentMenuItems’ to let the user decide. Or should I look further into making a TaskCapableComponent.

Thanks in advance for any comments!
Kind regards
-Gieljan

Posts: 1

Participants: 1

Read full topic

Access Enumeration by integer for example "CurveEnd Enumeration"

Landesgartenschau Planar Remeshing

$
0
0

@matteo996 wrote:

Hello, my name is Matteo and i’m trying to reverse engeneer the Landesgartenschau exhibition hall.

Searcing on the web i’ve found an old discussion were the PlanarHex comand was used to generate the surfaces but there are many issues with that method and the result is not good.

The old discussion: https://www.grasshopper3d.com/forum/topics/planar-remeshing-landesgartenschau-exhibition-hall?page=1&commentId=2985220%3AComment%3A1590045&x=1#2985220Comment1590045

As you can see in the pictures 1 and 2 there are the wrong number of polygons in each side of the structure

To make a better solution i’ve decided to remodelling all the surface and to make the division of it i’ve used the “sphere” comand to make a better “population division” of the surface as you can see in the pictures 4 and 5

The problem is that i don’t know how to continue with the work; do you have any suggestions?
I found also this (https://www.grasshopper3d.com/profiles/blogs/planar-remeshing) but that plug-in is nowhere to be found.

Thanks for the attention!

Exhibition Hall surface: Surface.3dm (152.1 KB)

Circle Pattern: Prova cerchi 3.gh (12.2 KB)

Old Discussion File: PlanarHex_re.gh (20.9 KB)

Posts: 3

Participants: 3

Read full topic

Can I use the original component in gh as a function when I write a gh plug-in in c#?[C#]

$
0
0

@18664777743 wrote:

Can I use the original component in gh as a function when I write a gh plug-in in c# and how?
for examle:I want to make the surface closest point which is a component that grasshopper alread has had as a funtion in C#.

Posts: 3

Participants: 3

Read full topic

C# numericUpDown & button Issue

$
0
0

@warmheartedarchi wrote:

Q : When I type numbers inside numericUpDown slides and click “Apply” button, the numbers are imported inside the grasshopper parameter, “That’s a great news !!”. However, Whenever I saved the grasshopper file, closed the rhino file, and then reopened the rhino and grasshopper file, the numericUpDown values, and the values inside the grasshopper parameter are reset.

But I want to persist all these numbers after I click “Apply” button and save the grasshopper file.

How can I solve this problem??

Here are the images and codes.


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Grasshopper.GUI;
using Grasshopper.Kernel;
using Grasshopper.GUI.Canvas;
using Grasshopper.Kernel.Attributes;

namespace RFD
{
public class Toolinfo : GH_Component
{
#region constructor
///


/// Initializes a new instance of the MyComponent1 class.
///
///
///

public Toolinfo()
: base(“Toolinfo”, “Toolinfo”,
“This Parameter gets informations of the tool. Please read the instruction before using this parameter.”,
“RFD”, “2.Toolinfo”)
{
ToolValue = 0;
XValue = 0;
YValue = 0;
ZValue = 0;
AValue = 0;
BValue = 0;
CValue = 0;
}

    /// <summary>
    /// Registers all the input parameters for this component.
    /// </summary>
    protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
    {

    }

    /// <summary>
    /// Registers all the output parameters for this component.
    /// </summary>
    protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
    {
        pManager.AddNumberParameter("Toolinfo", "Toolinfo", "Toolinfo", GH_ParamAccess.list);

    }
    #endregion

    #region attributes
    /////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////
    ////////<Winidow Form Start>/////////////////////////////

    public override void CreateAttributes()
    {
        m_attributes = new MySpecialComponentAttributes(this);
    }

    public class MySpecialComponentAttributes : GH_ComponentAttributes
    {
        public MySpecialComponentAttributes(IGH_Component component) : base(component) { }

        public override GH_ObjectResponse RespondToMouseDoubleClick(GH_Canvas sender, GH_CanvasMouseEvent e)
        {

            (Owner as Toolinfo)?.DisplayForm();

            return GH_ObjectResponse.Handled;

        }

    }

    #endregion

    #region UI overrides

    RFD.Form1 _form;

    public void DisplayForm()
    {

        // Don't show the form more than once per component.
        //if (_form != null)
        //  return;

        if (_form != null)
        { return; }

        _form = new Form1();



        _form.FormClosed += OnFormClosed;


        _form.button1.Click += button1_Click;


        /// ""Use these line if you want to use TrackBar as a realtime input""
        ///
        /// _form.trackBar1.ValueChanged += trackBar1_ValueChanged;
        ///

        GH_WindowsFormUtil.CenterFormOnCursor(_form, true);
        _form.Show(Grasshopper.Instances.DocumentEditor);

    }

    private void button1_Click(object sender, EventArgs e)
    {

        Button button = sender as Button;

        ToolValue = Math.Round((double)_form.numericUpDown1.Value);
        XValue = Math.Round((double)_form.numericUpDown2.Value, 1);
        YValue = Math.Round((double)_form.numericUpDown3.Value, 1);
        ZValue = Math.Round((double)_form.numericUpDown4.Value, 1);
        AValue = Math.Round((double)_form.numericUpDown5.Value, 1);
        BValue = Math.Round((double)_form.numericUpDown6.Value, 1);
        CValue = Math.Round((double)_form.numericUpDown7.Value, 1);


        ExpireSolution(true);
    }

    /// ""Use these line if you want to use TrackBar as a realtime input""
    /// 
    /// 
    /// private void trackBar1_ValueChanged(object sender, EventArgs e)
    /// {

    /// TrackBar trackBar = sender as TrackBar;
    ///   if (trackBar != null)
    ///    {
    ///     Value = trackBar.Value;
    ///     ExpireSolution(true);
    ///    }
    /// }
    ///


    private void OnFormClosed(object sender, FormClosedEventArgs formClosedEventArgs)
    {
        _form = null;
    }

    /// <summary>
    /// Override this function if you want to insert some custom menu items in your derived Component class.
    /// Items will be added between List Matching items and parameter menus.
    /// </summary>
    protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu)
    {
        Menu_AppendItem(menu, "Show UI", ShowUiClicked, null, true, false);
    }
    private void ShowUiClicked(object sender, EventArgs e)
    {
        DisplayForm();
    }

    ////////<Winidow Form End>///////////////////////////////
    /////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////
    #endregion

    /// <summary>
    /// This is the method that actually does the work.
    /// </summary>
    /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>

    protected override void SolveInstance(IGH_DataAccess DA)
    {



        double ToolNumber = Math.Round(ToolValue);
        double Xmove = Math.Round(XValue, 1);
        double Ymove = Math.Round(YValue, 1);
        double Zmove = Math.Round(ZValue, 1);
        double Aangle = Math.Round(AValue, 1);
        double Bangle = Math.Round(BValue, 1);
        double Cangle = Math.Round(CValue, 1);




        List<double> toolInfo = new List<double>();

        toolInfo.Add(Xmove);
        toolInfo.Add(Ymove);
        toolInfo.Add(Zmove);
        toolInfo.Add(Aangle);
        toolInfo.Add(Bangle);
        toolInfo.Add(Cangle);
        toolInfo.Add(ToolNumber);

        DA.SetDataList("Toolinfo", toolInfo);
    }


    public double ToolValue { get; set; }
    public double XValue { get; set; }
    public double YValue { get; set; }
    public double ZValue { get; set; }
    public double AValue { get; set; }
    public double BValue { get; set; }
    public double CValue { get; set; }


    /// <summary>
    /// Provides an Icon for the component.
    /// </summary>
    protected override System.Drawing.Bitmap Icon
    {
        get
        {
            return RFD.Properties.Resources.ICON_8_ToolInfo;
        }
    }

    /// <summary>
    /// Gets the unique ID for this component. Do not change this ID after release.
    /// </summary>
    public override Guid ComponentGuid
    {
        get { return new Guid("b72bb830-a0b4-4d53-98a2-81834631d33c"); }
    }
}

}

Posts: 5

Participants: 2

Read full topic

Passing And Using Custom Classes

$
0
0

@duanemclemore wrote:

[[EDIT: SEE SECOND POST]]

Hi All,

Here’s an easy one that is a C# problem not a Grasshopper one - per se - but I’ve been banging my head on it and your GH specific advice would probably break the logjam more quickly than I’ve been able to.

The question, put simply, is how do I index with [] on a method group?

I’ve followed this tutorial and it works well for packaging up the data and sending it to the next component using GH_ObjectWrapper.

So here’s the relevant code snippet:

    internal static GH_Structure<GH_Point> CellRootNodesArrayBased()
    {
//  A class containing data describing the whole lattice - generated upstream
        Lattice l = new Lattice();

//  A class containing attributes of an individual cell of the lattice - generated upstream
        LatticeCell lc = new LatticeCell();

//  A string describing the cell "centering" 
        string classCentering = lc.Centering;

//  DataTree of the cartesian locations of the points
        Grasshopper.DataTree<double[]> nodeTree = l.LocationTree;

//  DataTree containing lists of paths to the points within the lattice which describe the 
//  vertices of a cell. 
        Grasshopper.DataTree<GH_Path> lCIT = lc.CellIndexTree;    

//  THIS LINE IS WHERE MY ERROR IS HAPPENING               
        GH_Path localPath = lCIT[(lCIT.Branch[0]),0];

//  Local Root Vertex – the point to be determined from this program and inserted to a tree to be passed
        GH_Point lRV = new GH_Point();

//  NOTE, this code for the assignment of values to the points is all old, 
//  based on looking up x,y,and z from a 3 element array that was on a list. 
//  This will change based on the syntax to access the proper branch of the tree I’m 
//  asking for your help on above, but I wanted to include it so you understand the goal. 
//  Obviously I need to be able to access the right Branch {x;y;z} before I access the right 
//  list item (double[3])and element of that array.
        var p00 = new Point3d(lCIT[0][0], lCIT[0][1], lCIT[0][2]);
        var p06 = new Point3d(lCIT[6][0], lCIT[6][1], lCIT[6][2]);

//  I creates a point at the center of the cell
        if (classCentering == "I")
        {
            var p14 = (p00 + p06) / 2;
            GH_Convert.ToGHPoint(p14, 0, ref lRV);
        }

        else
        {
        }

//   lRVT = Local Root Vertex Tree
        var = new GH_Structure<GH_Point>();
        lRVT.Insert(lRV, localPath, 0);
        lc.RootVertexTree = lRVT;
        return lc.RootVertexTree;
        }

So obviously, I’m getting “no argument given” errors re: the path in the point creation. Once I fix the big problem that’ll sort out.

The one that’s tripping me up is "Cannot Apply indexing with [] to an expression of type ‘method group’ on the line where I assign a value to localPath from the (local) Cell Index Tree, which is referenced in from the class Lattice Cell, which has been invoked locally as lc.

The core issue seems to be just a simple syntax mistake, and your patience and help is very appreciated.
Thanks in advance!

Duane

Posts: 3

Participants: 2

Read full topic

Some technical problem with AddGenericParameter();


Using GH_CustomPreviewItem

$
0
0

@looslennert wrote:

Dear all,

Is there possibly a way to use GH_CustomPreviewItem for previewing (DrawViewportMeshes) of custom components made in Visual Studio?

At this moment I’m stuck because of the “inaccessibility due to the protection level”. I would like however to manage the preview of all sorts of geometries without manually sorting them into groups (GH_Curve, GH_Mesh, GH_Point…) Additionally, the preview as executed by the CustomPreview component in Grasshopper is very slick and allows a rendered preview as well. I would like to go along with this approach if possible.

Regards,
Lennert

Posts: 1

Participants: 1

Read full topic

A very very strange problem

$
0
0

@andrealu2012 wrote:

I am doing udpclient these days,
just want to get a UDPclient instance by a port number(int).
it sounds easy.
but I find a strange problem…and it problem take several days and still unsolved…

this my code:

  protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
    {
        pManager.AddIntegerParameter("LocalPort", "", "", GH_ParamAccess.item);
    }
    protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
    {
        pManager.AddGenericParameter("UDPClient", "", "", GH_ParamAccess.item);
    }
    UdpClient udpClient;
    int localPort;

    protected override void SolveInstance(IGH_DataAccess DA)
    {
        if (!DA.GetData("LocalPort", ref localPort))
        {
            return;
        }
        udpClient = new UdpClient(localPort);//put a breakpoint here
        DA.SetData("UDPClient", udpClient);
    }


the error message in English is:“Only one usage of each socket address(protocol/network address/port) is normally permitted “.
i use “netstate -a” to check the net socket usage ,i am sure every time the “59153"port is available to use before launch Rhino and grasshopper.
so I go to debug ,i add a break point at"udpClient = new UdpClient(localPort);”,then i find when this breakpoint is hit, i see the udpClient is null and then be given a newUdpClient(localPort) ,it is i want and nothing error happens when be given a newudpclient.so in normally,the solveinstance() should stop after " DA.SetData(“UDPClient”, udpClient);”…but no…when i press continue …the program stop at breakpoint second time!,so udpclient is null again!(it should be not null because already has been set),and it will be given again with same portNumber,this is the source of error"collision of port”.
I just donnot know why the solveinstance run twice …
(and i found solveinstance sometime run one time,and sometime run twice…)
Thank you for explain!

Posts: 3

Participants: 2

Read full topic

Need to create lines every 5 degrees in Azimuth and Elevation

$
0
0

@phil.nevitt wrote:

Hi guys I am new to grasshopper and after some advice. I would like to be able to create lines coming from a known point let’s say 0,0,0 in the centre of a dome. I would like to specify the spacing of the lines but it’s probable going to be every 5 degrees in the Azimuth and Elevation. I would also like to be able to specify the radius of the dome. I would then like to intersect the lines with the sphere to produce points on the sphere itself. So, I will be left with a point cloud effectively on the dome surface every 5 degrees. It would be even better if I could specify the angle of the dome to so I can switch between a partial dome and a full dome.

I am sure its easily achievable but my knowledge is zero currently with Grasshopper so any help would be appreciated.

thanks

Posts: 2

Participants: 2

Read full topic

Python code for rule 30 of Stephen Wolfram

GhPython output format

$
0
0

@ivelin.peychev wrote:

Hi @piac,

I remember discussion regarding how the print displays within the GhPython editor.

Are we getting a fix any time soon? I’d like to see the prints line by line with a scroll bar at the side as currently I cannot see and check the complete result.

e.g.:

I wish to see the complete list there and not to have to hook a panel component. Line by line with two scroll bars (bottom and right) would be ideal.

Thanks.

Posts: 4

Participants: 2

Read full topic

Latest grasshopper update causing problems with UDP?

$
0
0

@zcftfg3 wrote:

Hello,
I was using the UDP receiver written in C# by Giulio as linked to on this page:
http://www.giuliopiacentino.com/grasshopper-tools/
and
UDP.ghx (79.8 KB)

It was working very well (yesterday on Rhino 6) until I got a new machine + installed the latest version of Rhino. Could it be a problem with an update to Grasshopper? I’m trying to send long lists of numbers from Processing to Grasshopper via this neat C# tool - but it’s no longer receiving anything. Pls help if anyone knows why this might be happening!

(GHowl and Firefly weren’t giving me the outputs that I needed which is why I was using the above tool)

Thanks!
EK

Posts: 2

Participants: 1

Read full topic

C# how to project points to polyline (or curve)

$
0
0

@daniel.c wrote:

Hi,

I want to project points to polyline the way picture shows. What is the optimal approach with rhinocommon in C#?
I found Intersection.ProjectPointsToBreps Method but I seem to have a problem implementing it. I was following logic of project point in grasshopper.


project points.gh (6.7 KB)

Regards,
Dan.

Posts: 5

Participants: 3

Read full topic


"Runtime error (TypeErrorException): expected index value, got float" obtained in GHPython node

$
0
0

@renatogcruz2 wrote:

GA_grasshopper.gh (13.8 KB) original.py (3.9 KB)

Dear, I am trying to implement a python 3 genetic algorithm (original attached) for grasshopper (attached as GH_grasshopper) and I have been encountering an error. I believe there is some difference between the python versions (3.x to 2.x) or even a python x ironpython incompatibility. The code is described below. It also follows the error message.

#####Algorithm:

from random import random

class Produto():
def init(self, nome, espaco, valor):
self.nome = nome
self.espaco = espaco
self.valor = valor

class Individuo():
def init(self, espacos, valores, limite_espacos, geracao=0):
self.espacos = espacos
self.valores = valores
self.limite_espacos = limite_espacos
self.nota_avaliacao = 0
self.espaco_usado = 0
self.geracao = geracao
self.cromossomo =

    for i in range(len(espacos)):
        if random() < 0.5:
            self.cromossomo.append("0")
        else:
            self.cromossomo.append("1")
            
def avaliacao(self):
    nota = 0
    soma_espacos = 0
    for i in range(len(self.cromossomo)):
       if self.cromossomo[i] == '1':
           nota += self.valores[i]
           soma_espacos += self.espacos[i]
    if soma_espacos > self.limite_espacos:
        nota = 1
    self.nota_avaliacao = nota
    self.espaco_usado = soma_espacos
    
def crossover(self, outro_individuo):
    corte = round(random()  * len(self.cromossomo))
    
    filho1 = outro_individuo.cromossomo[0:corte] + self.cromossomo[corte::]
    filho2 = self.cromossomo[0:corte] + outro_individuo.cromossomo[corte::]
    
    filhos = [Individuo(self.espacos, self.valores, self.limite_espacos, self.geracao + 1),
              Individuo(self.espacos, self.valores, self.limite_espacos, self.geracao + 1)]
    filhos[0].cromossomo = filho1
    filhos[1].cromossomo = filho2
    return filhos

if name == ‘main’:
#p1 = Produto(“Iphone 6”, 0.0000899, 2199.12)
lista_produtos =
lista_produtos.append(Produto(“Geladeira Dako”, 0.751, 999.90))
lista_produtos.append(Produto(“Iphone 6”, 0.0000899, 2911.12))
lista_produtos.append(Produto("TV 55’ ", 0.400, 4346.99))
lista_produtos.append(Produto("TV 50’ ", 0.290, 3999.90))
lista_produtos.append(Produto("TV 42’ ", 0.200, 2999.00))
lista_produtos.append(Produto(“Notebook Dell”, 0.00350, 2499.90))
lista_produtos.append(Produto(“Ventilador Panasonic”, 0.496, 199.90))
lista_produtos.append(Produto(“Microondas Electrolux”, 0.0424, 308.66))
lista_produtos.append(Produto(“Microondas LG”, 0.0544, 429.90))
lista_produtos.append(Produto(“Microondas Panasonic”, 0.0319, 299.29))
lista_produtos.append(Produto(“Geladeira Brastemp”, 0.635, 849.00))
lista_produtos.append(Produto(“Geladeira Consul”, 0.870, 1199.89))
lista_produtos.append(Produto(“Notebook Lenovo”, 0.498, 1999.90))
lista_produtos.append(Produto(“Notebook Asus”, 0.527, 3999.00))
#for produto in lista_produtos:
# print(produto.nome)

espacos = []
valores = []
nomes = []
for produto in lista_produtos:
    espacos.append(produto.espaco)
    valores.append(produto.valor)
    nomes.append(produto.nome)
limite = 3

individuo1 = Individuo(espacos, valores, limite)
print("\nIndivíduo 1")
for i in range(len(lista_produtos)):
    if individuo1.cromossomo[i] == '1':
        print("Nome: %s R$ %s " % (lista_produtos[i].nome, lista_produtos[i].valor))
individuo1.avaliacao()
print("Nota = %s" % individuo1.nota_avaliacao)
print("Espaço usado = %s" % individuo1.espaco_usado)

individuo2 = Individuo(espacos, valores, limite)
print("\nIndivíduo 2")
for i in range(len(lista_produtos)):
    if individuo2.cromossomo[i] == '1':
        print("Nome: %s R$ %s " % (lista_produtos[i].nome, lista_produtos[i].valor))
individuo2.avaliacao()
print("Nota = %s" % individuo2.nota_avaliacao)
print("Espaço usado = %s" % individuo2.espaco_usado)

individuo1.crossover(individuo2)

#####output

Indivíduo 1

Nome: TV 42’ R$ 2999.0
Nome: Microondas Panasonic R$ 299.29
Nome: Geladeira Brastemp R$ 849.0
Nome: Notebook Lenovo R$ 1999.9
Nota = 6147.19
Espaço usado = 1.3649

Indivíduo 2
Nome: Iphone 6 R$ 2911.12
Nome: TV 55’ R$ 4346.99
Nome: TV 50’ R$ 3999.9
Nome: Microondas Electrolux R$ 308.66
Nome: Microondas LG R$ 429.9
Nome: Notebook Lenovo R$ 1999.9
Nome: Notebook Asus R$ 3999.0
Nota = 17995.47
Espaço usado = 1.8118899
Runtime error (TypeErrorException): expected index value, got float
Traceback:
line 40, in crossover, “”
line 96, in script

Posts: 3

Participants: 2

Read full topic

Debugging Grasshopper Component while loading Grasshopper

$
0
0

@Petras_Vestartas wrote:

Hi,

@DavidRutten I have an issue with grasshopper plugin loading. The plugin works on some windows computers and on some not, with the same newest rhino installed.

It is not possible to debug the component, since the grasshopper gives error while loading grasshopper below, and wont load the half of components.

I quite sure that is because of some file directory issue, but not sure which line of code is causing that.

Any suggestions how to debug components at the start of Grasshopper would be much appreciated.

The error while loading:

    Object: ComponentDrilling (level 1)
    {
      Exception has been thrown by the target of an invocation.
      TargetInvocationException
    }

    Object: ComponentDrilling (level 2)
    {
      The path is not of a legal form.
      ArgumentException
    }

    Object: ComponentCutting2Polylines (level 1)
    {
      Exception has been thrown by the target of an invocation.
      TargetInvocationException
    }

    Object: ComponentCutting2Polylines (level 2)
    {
      The path is not of a legal form.
      ArgumentException
    }

    Object: ComponentOpenPolyline (level 1)
    {
      Exception has been thrown by the target of an invocation.
      TargetInvocationException
    }

Full code of one class that is causing the issue is here:

using Grasshopper.Kernel;
using System.Drawing;
using System.Drawing.Text;
using System;
using System.Collections.Generic;
using Rhino.Geometry;
using System.Windows.Forms;

namespace IBOIS.Components {
    public class ComponentIBOIS : GH_Component {

        public IBOIS.PreviewObject preview;
        public BoundingBox bbox = Utilities.MakaDimensions.MakaBBox();
        public Rhino.Display.DisplayMaterial m = new Rhino.Display.DisplayMaterial(Color.White);
        public override BoundingBox ClippingBox => bbox;
        public double tolerance = 0.01;

        public List<Line> lines = new List<Line>();
        public List<Polyline> polylines = new List<Polyline>();
        public List<Curve> badCurves = new List<Curve>();
        public string directory;
        public List<string> GCode = new List<string>();
        public string filename = "P1234567";
        public double zero1 = 54;
        public double toolr = 5;
        public double toolID = 57;
        public double Zsec = 350;
        public double XYfeed = 5000;
        public double Zfeed = 1500;
        public double Retreat = 60;
        public double infeed = 2;
        public bool notch = true;

        public Dictionary<int,IBOIS.GCode.ToolParameters> tools = IBOIS.GCode.Tool.ToolsFromAssembly();

        public ComponentIBOIS(string Name, string Nick, string Desc) : base(Name, Nick, Desc, "IBOIS", "CNC") { }

        public ComponentIBOIS(string Name, string Nick, string Desc, string subCategory) : base(Name, Nick, Desc, "IBOIS", subCategory) { }


        public override void DrawViewportWires(IGH_PreviewArgs args) {

            if (this.Hidden || this.Locked ) return;

            //Travelling path
            if (preview.PreviewLines0 != null) {
                args.Display.DrawLines(preview.PreviewLines0, Color.Orange, 2);
                //args.Display.DrawArrows(lines, Color.MediumVioletRed);
            }
            //drilling path
            if (preview.PreviewLines1 != null)
                args.Display.DrawLines(preview.PreviewLines1, Color.Orange, 1);
            //Works only with an angle
            if (preview.PreviewLines2 != null)
                args.Display.DrawLines(preview.PreviewLines2, Color.Black, 3);



            if (preview.PreviewPolyline != null)
                args.Display.DrawPolyline(preview.PreviewPolyline, Color.Orange, 2);

            if (preview.badCurves != null)
        
                foreach (Curve c in preview.badCurves) {
                    args.Display.DrawCurve(c, Color.Red, 5);
                }
               
        }

 

        protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) {

            for (int i = 0; i < pManager.ParamCount; i++)
                pManager.HideParameter(i);
        }

        protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) {
            for (int i = 0; i < pManager.ParamCount; i++)
                pManager.HideParameter(i);
        }

        protected override void SolveInstance(IGH_DataAccess DA) {


        }

        public override Guid ComponentGuid => new Guid("e6eda5fb-6967-425f-8cee-15eade0f26f1"); 

        //https://stackoverflow.com/questions/439007/extracting-path-from-openfiledialog-path-filename
        //https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx
        //https://discourse.mcneel.com/t/save-file-directory/62784/2
        protected override void AppendAdditionalComponentMenuItems(ToolStripDropDown menu) {
        
                Menu_AppendItem(menu, "Select Directory with Address...", (_, __) => {

                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();

                    saveFileDialog1.FileName = filename;
                    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    saveFileDialog1.FilterIndex = 2;
                    saveFileDialog1.RestoreDirectory = true;

                    if (saveFileDialog1.ShowDialog() == DialogResult.OK) {

                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(saveFileDialog1.FileName)) {
                            int i = 0;
                            foreach (string s in GCode) {
                                if (i == 0) {
                                    sw.WriteLine(System.IO.Path.GetFileName(saveFileDialog1.FileName));
                                } else {
                                    sw.WriteLine(s);
                                }
                                i++;
                            }
                            //GCode
                        }

                        ExpireSolution(true);

                    }

                });

  

            Menu_AppendItem(menu, "Select Directory...", (_, __) => {

                var folderDialog = new FolderBrowserDialog();
                var run = folderDialog.ShowDialog();

                if (run == DialogResult.OK) {
                    directory = folderDialog.SelectedPath;
                    System.IO.File.WriteAllLines(folderDialog.SelectedPath + "/" + filename, GCode);
                    Rhino.RhinoApp.WriteLine(directory);
                    Rhino.RhinoApp.WriteLine((GCode.Count > 0).ToString());
                    ExpireSolution(true);
                }

            });

        }



        protected override System.Drawing.Bitmap Icon {
            get {
                return IBOIS.Components.ComponentIBOIS.GetIcon(this); 
            }
        }


        internal static Bitmap GetIcon(GH_ActiveObject comp) {
            string nickName = comp.NickName;
            Bitmap bitmap = new Bitmap(24, 24);
            using (Graphics graphic = Graphics.FromImage(bitmap)) {
                graphic.TextRenderingHint = TextRenderingHint.AntiAlias;
                graphic.DrawString(nickName, new Font(FontFamily.GenericSansSerif, 6f), Brushes.Black, new RectangleF(-1f, -1f, 26f, 26f));
            }
            return bitmap;
        }




    }
}

Posts: 1

Participants: 1

Read full topic

Call external python from within Grasshopper

$
0
0

@Konrad.Kobayashi wrote:

Hi,

sorry if this has been asked before – but I could find any working solution.

Is it possible to call a external script, (python or .bat) form within Grasshopper? Ideally while passing arguments and output of the script.

Mock-up:

thanks!

Posts: 3

Participants: 2

Read full topic

"Remark" overrides "Warning" in component color

$
0
0

@andheum wrote:

I have a param in a component that’s adding a “Remark” runtime message. The component is also adding a “Warning” runtime message. I would expect the component to be “warning” orange — but because of the presence of the “Remark” it looks normal hunky-dory gray. I would expect the precedence to happen Error > Warning > Remark in terms of setting the component color, but it appears to be Error > Remark > Warning. But maybe I am misusing “Remark”?

Posts: 2

Participants: 2

Read full topic

Which Parameter controls whether MeshWires are drawn or not?

$
0
0

@dchristev wrote:

Struggling to understand how to make a custom geometry draw mesh wires when Grasshopper’s -Preview Mesh Edges- option is enabled disabled.

I assume there’s some line of code I need to add into one of the draw methods in the GH_GeometricGoo class, currently mine looks like this:

public void DrawViewportWires(GH_PreviewWireArgs args)
    {
        if (Value == null || !Value.IsValid) { return; }

        if (args.Viewport.DisplayMode.EnglishName.ToLower() == "wireframe")
            args.Pipeline.DrawMeshWires(Value, args.Color);
    }

Posts: 3

Participants: 2

Read full topic

Viewing all 3626 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>