Ejemplo n.º 1
0
        /// <summary>
        /// Generates selection list for cell oritentation.
        /// </summary>
        /// <param name="index">Component input index. (first input is index 0)</param>
        /// <param name="offset">Vertical offset of the menu, to help with positioning.</param>
        public static void OrientSelect(ref IGH_Component Component, ref GH_Document GrasshopperDocument, int index, float offset)
        {
            // Instantiate  new value list
            var vallist = new Grasshopper.Kernel.Special.GH_ValueList();
            vallist.ListMode = Grasshopper.Kernel.Special.GH_ValueListMode.Cycle;
            vallist.CreateAttributes();

            // Customise value list position
            float xCoord = (float)Component.Attributes.Pivot.X - 200;
            float yCoord = (float)Component.Attributes.Pivot.Y + index * 40 - offset;
            PointF cornerPt = new PointF(xCoord, yCoord);
            vallist.Attributes.Pivot = cornerPt;

            // Populate value list with our own data
            vallist.ListItems.Clear();
            var items = new List<Grasshopper.Kernel.Special.GH_ValueListItem>();
            items.Add(new Grasshopper.Kernel.Special.GH_ValueListItem("Default", "0"));
            items.Add(new Grasshopper.Kernel.Special.GH_ValueListItem("RotateZ", "1"));
            items.Add(new Grasshopper.Kernel.Special.GH_ValueListItem("RotateY", "2"));
            items.Add(new Grasshopper.Kernel.Special.GH_ValueListItem("RotateX", "3"));

            vallist.ListItems.AddRange(items);

            // Until now, the slider is a hypothetical object.
            // This command makes it 'real' and adds it to the canvas.
            GrasshopperDocument.AddObject(vallist, false);

            //Connect the new slider to this component
            Component.Params.Input[index].AddSource(vallist);
            Component.Params.Input[index].CollectData();
        }
Ejemplo n.º 2
0
        public void CheckAndSetupActions()
        {
            if (_orphan)
            {
                _orphan = false;
                GC.ReRegisterForFinalize(this);
            }

            if (!_initializationDone)
            {
                if (_doc == null)
                {
                    _doc = OnPingDocument();

                    if (_doc == null) return;
                }

                _doc.ObjectsDeleted += GrasshopperObjectsDeleted;
                Instances.DocumentServer.DocumentRemoved += GrasshopperDocumentClosed;
                _doc.SolutionStart += AfterDocumentChanged;

                _initializationDone = true;
                Initialize();
            }
        }
Ejemplo n.º 3
0
        public void CheckIfSetupActionsAreNecessary()
        {
            if (m_afterDisposal) return;

              if (m_orphan)
              {
            m_orphan = false;
            GC.ReRegisterForFinalize(this);
              }

              if (!m_initializationDone)
              {
            if (m_doc == null)
            {
              m_doc = OnPingDocument();

              if (m_doc == null) return;
            }

            m_doc.ObjectsDeleted += GrasshopperObjectsDeleted;
            Instances.DocumentServer.DocumentRemoved += GrasshopperDocumentClosed;
            m_doc.SolutionStart += AfterDocumentChanged;

            m_initializationDone = true;
            Initialize();
              }
        }
Ejemplo n.º 4
0
        /// <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)
        {
            // 0. Setup input
            Component = this;
            GrasshopperDocument = this.OnPingDocument();
            //    Generate default input menu
            if (Component.Params.Input[0].SourceCount == 0) InputTools.GradientSelect(ref Component, ref GrasshopperDocument, 0, 11);

            // 1. Retrieve input
            int gradientType = 0;
            if (!DA.GetData(0, ref gradientType)) { return; }

            // 2. Initialize 
            string mathString = null;

            // 3. Define gradients here
            // Assume unitized domain ( 0<x<1 , 0<y<1, 0<z<1), where radius values range from minRadius (mathString=0) to maxRadius (mathString=1)
            // Based on this assumption, the actual values are scaled to the size of the bounding box of the lattice
            switch (gradientType)
            {
                case 0:     // Linear (X)
                    mathString = "Abs(x)";
                    break;
                case 1:     // Linear (Y)
                    mathString = "Abs(y)";
                    break;
                case 2:     // Linear (Z)
                    mathString = "Abs(z)";
                    break;
                case 3:     // Centered (X)
                    mathString = "Abs(2*x-1)";
                    break;
                case 4:     // Centered (Y)
                    mathString = "Abs(2*y-1)";
                    break;
                case 5:     // Centered (Z)
                    mathString = "Abs(2*z-1)";
                    break;
                case 6:     // Cylindrical (X)
                    mathString = "Sqrt(Abs(2*y-1)^2 + Abs(2*z-1)^2)/Sqrt(2)";
                    break;
                case 7:     // Cylindrical (Y)
                    mathString = "Sqrt(Abs(2*x-1)^2 + Abs(2*z-1)^2)/Sqrt(2)";
                    break;
                case 8:     // Cylindrical (Z)
                    mathString = "Sqrt(Abs(2*x-1)^2 + Abs(2*y-1)^2)/Sqrt(2)";
                    break;
                case 9:     // Spherical
                    mathString = "Sqrt(Abs(2*x-1)^2 + Abs(2*y-1)^2 + Abs(2*z-1)^2)/Sqrt(3)";
                    break;
                // If you add a new gradient, don't forget to add it in the value list (GradientSelect method)
            }

            // Output report
            DA.SetData(0, mathString);

        }
Ejemplo n.º 5
0
        /// <summary>
        /// Do not use this constructor for initialization, but always use the Initialize() method, which will run only once.
        /// This constructor is called more times at startup for indexing the picture and some other external reasons.
        /// </summary>
        protected SafeComponent(string name, string abbreviation, string description, string category, string subCategory)
            : base(name, abbreviation, description, category, subCategory)
        {
            if (Instances.DocumentServer.DocumentCount > 0)
              {
            m_doc = Instances.DocumentServer[0];

            CheckIfSetupActionsAreNecessary();
              }
        }
Ejemplo n.º 6
0
        public IGH_DocumentObject Upgrade(IGH_DocumentObject target, GH_Document document)
        {
            PythonComponent_OBSOLETE component_OBSOLETE = target as PythonComponent_OBSOLETE;
              if (component_OBSOLETE == null)
            return null;

              ZuiPythonComponent component_new = new ZuiPythonComponent();

              bool show_code_input = false;
              if (component_OBSOLETE.CodeInputVisible)
              {
            // see if the "code" input on the old component really has anything
            // hooked up to it.  If not, don't show the input
            show_code_input = component_OBSOLETE.Params.Input[0].SourceCount > 0;
              }
              component_new.CodeInputVisible = show_code_input;

              component_new.HideCodeOutput = component_OBSOLETE.HideCodeOutput;

              if (component_new.HideCodeOutput)
            component_new.Params.Output.RemoveAt(0);

              if (!component_new.CodeInputVisible)
            component_new.CodeInput = component_OBSOLETE.CodeInput;

              component_OBSOLETE.Dispose();

              if (GH_UpgradeUtil.SwapComponents(component_OBSOLETE, component_new))
              {
            bool toRhinoScript = (component_OBSOLETE.DocStorageMode == DocReplacement.DocStorage.AutomaticMarshal);
            {
              foreach (var c in component_new.Params.Input)
              {
            var sc = c as Param_ScriptVariable;
            if (sc == null) continue;

            if (toRhinoScript)
            {
              IGH_TypeHint newHint;
              if (PythonHints.ToNewRhinoscriptHint(sc.TypeHint, out newHint))
                sc.TypeHint = newHint;
            }
            else
            {
              PythonHints.ToNewRhinoCommonHint(sc);
            }
              }
            }

            component_new.CodeInputVisible = show_code_input;
            return component_new;
              }
              return null;
        }
Ejemplo n.º 7
0
        public RunForm(GH_Document doc, LemmingsComponent prnt)
        {
            InitializeComponent();
            this.GHDoc = doc;
            this.LemmingComponentParent = prnt;

            this.Initializing = true;
            this.checkBox3dm.Checked = this.LemmingComponentParent.Output3DM;
            this.checkBoxWRL.Checked = this.LemmingComponentParent.OutputWRL;
            this.checkBoxOBJ.Checked = this.LemmingComponentParent.OutputOBJ;
            this.checkBoxPNG.Checked = this.LemmingComponentParent.OutputPNG;
            this.Initializing = false;

            //this.rh_app = app;
            //int n = gh_doc.ObjectCount;

            //LemmingsIntParameter test = (LemmingsIntParameter) doc.FindComponent(new LemmingsIntParameter().ComponentGuid);
            //int ee = (int) test.VolatileData.get_Branch(0)[0];

            // finds LemmingsMeshComponents and LemmingsJSONComponents in current document
            this.MeshComponents = new List<MeshListener>();
            this.JSONComponents = new List<DataListener>();
            Guid mshid = new MeshListener().ComponentGuid;
            Guid jsonid = new DataListener().ComponentGuid;
            foreach (IGH_DocumentObject docobj in doc.Objects){
                if (docobj.ComponentGuid == mshid) MeshComponents.Add((MeshListener)docobj);
                if (docobj.ComponentGuid == jsonid) JSONComponents.Add((DataListener)docobj);
            }

            for (int i = 0; i < this.LemmingComponentParent.veng.VarCount; i++) {
                VarControl varControlA;
                varControlA = new Lemmings.VarControl(i,this.LemmingComponentParent.veng.names[i],this.LemmingComponentParent.veng.ivals[i], this.LemmingComponentParent.veng.GetStepsAt(i));
                this.flowLayoutPanel1.Controls.Add(varControlA);
                varControlA.CountChangedEvent += new EventHandler(VarControl_CountChanged);
            }

            this.PermutationCountLabel.Text = this.LemmingComponentParent.veng.Permutations.Count.ToString() + " Permutations";

            //JSONComponents[0].toJSON();
            // setup dicionary, one key for each int_param found
            // see this: http://james.newtonking.com/json
        }
Ejemplo n.º 8
0
        public IGH_DocumentObject Upgrade(IGH_DocumentObject target, GH_Document document)
        {
            PythonComponent_OBSOLETE component_OBSOLETE = target as PythonComponent_OBSOLETE;
              if (component_OBSOLETE == null)
            return null;

              ZuiPythonComponent component_new = new ZuiPythonComponent();

              component_new.HiddenCodeInput = component_OBSOLETE.HiddenCodeInput;
              component_new.HiddenOutOutput = component_OBSOLETE.HiddenOutOutput;

              if (!component_new.HiddenCodeInput)
            component_new.Code = component_OBSOLETE.Code;

              if (GH_UpgradeUtil.SwapComponents(component_OBSOLETE, component_new))
              {
            bool toRhinoScript = (component_OBSOLETE.DocStorageMode == DocReplacement.DocStorage.AutomaticMarshal);
            {
              foreach (var c in component_new.Params.Input)
              {
            var sc = c as Param_ScriptVariable;
            if (sc == null) continue;

            if (toRhinoScript)
            {
              IGH_TypeHint newHint;
              if (PythonHints.ToNewRhinoscriptHint(sc.TypeHint, out newHint))
                sc.TypeHint = newHint;
            }
            else
            {
              PythonHints.ToNewRhinoCommonHint(sc);
            }
              }
            }

            component_OBSOLETE.Dispose();

            return component_new;
              }
              return null;
        }
Ejemplo n.º 9
0
 public override void MovedBetweenDocuments(GH_Document oldDocument, GH_Document newDocument)
 {
     base.MovedBetweenDocuments(oldDocument, newDocument);
     SetUniqueNameletter(newDocument);
 }
Ejemplo n.º 10
0
        public override void AddedToDocument(GH_Document document)
        {
            base.AddedToDocument(document);
            Document = OnPingDocument();

            if (Client == null)
            {
                NickName = "Initialising...";
                Locked   = true;

                var myForm = new SpecklePopup.MainWindow(false, true);

                var some = new System.Windows.Interop.WindowInteropHelper(myForm)
                {
                    Owner = Rhino.RhinoApp.MainWindowHandle()
                };

                myForm.ShowDialog();

                if (myForm.restApi != null && myForm.apitoken != null)
                {
                    Client  = new SpeckleApiClient(myForm.restApi);
                    RestApi = myForm.restApi;
                    Client.IntializeSender(myForm.apitoken, Document.DisplayName, "Grasshopper", Document.DocumentID.ToString()).ContinueWith(task =>
                    {
                        Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
                    });
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Account selection failed");
                    return;
                }
            }
            else
            {
            }

            Client.OnReady += (sender, e) =>
            {
                StreamId = Client.StreamId;
                if (!WasSerialised)
                {
                    Locked   = false;
                    NickName = "Anonymous Stream";
                }
                ////this.UpdateMetadata();
                Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
            };

            Client.OnWsMessage += OnWsMessage;

            Client.OnLogData += (sender, e) =>
            {
                Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n";
            };

            Client.OnError += (sender, e) =>
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.EventName + ": " + e.EventData);
                Log += DateTime.Now.ToString("dd:HH:mm:ss ") + e.EventData + "\n";
            };

            ExpireComponentAction = () => ExpireSolution(true);

            ObjectChanged += (sender, e) => UpdateMetadata();

            foreach (var param in Params.Input)
            {
                param.ObjectChanged += (sender, e) => UpdateMetadata();
            }

            MetadataSender = new System.Timers.Timer(1000)
            {
                AutoReset = false, Enabled = false
            };
            MetadataSender.Elapsed += MetadataSender_Elapsed;

            DataSender = new System.Timers.Timer(2000)
            {
                AutoReset = false, Enabled = false
            };
            DataSender.Elapsed += DataSender_Elapsed;

            ObjectCache = new Dictionary <string, SpeckleObject>();

            Grasshopper.Instances.DocumentServer.DocumentRemoved += DocumentServer_DocumentRemoved;
        }
 public override void RemovedFromDocument(GH_Document document)
 {
     // let's be polite and pick up our garbage
     if (wormDoc != null)
     {
         wormDoc.Enabled = false;
         wormDoc.RemoveObject(wormCluster, false);
         wormDoc.Dispose();
         wormDoc = null;
     }
     base.RemovedFromDocument(document);
 }
Ejemplo n.º 12
0
 public override void RemovedFromDocument(GH_Document document)
 {
     Params.ParameterChanged -= Params_ParameterChanged;
     base.RemovedFromDocument(document);
 }
Ejemplo n.º 13
0
        /// <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)
        {
            ghdoc = this.OnPingDocument();
            ghdoc.ContextChanged += new GH_Document.ContextChangedEventHandler(CheckDisplay);

            Model input = null;

            DA.GetData(0, ref input);
            if (input.Mesh == null)
            {
                return;
            }
            Model model = input.Clone() as Model;

            Grasshopper.Kernel.Types.GH_ObjectWrapper type0D = null;
            Grasshopper.Kernel.Types.GH_ObjectWrapper type1D = null;
            Grasshopper.Kernel.Types.GH_ObjectWrapper type2D = null;
            DA.GetData(1, ref type0D);
            DA.GetData(2, ref type1D);
            DA.GetData(3, ref type2D);

            type0D.Value.CheckResultDimension(0);
            type1D.Value.CheckResultDimension(1);
            type2D.Value.CheckResultDimension(2);
            string nodeResultType = type0D.ToString();
            string barResType     = type1D.ToString();
            string panelResType   = type2D.ToString();

            bool showVals, showNds, showEdgs, deformed, showLCS, showLoads, showSupports, showCNs, showNNs, showENs, showLVals;

            showVals = showNds = showEdgs = deformed = showLCS = showLoads = showSupports = showCNs = showNNs = showENs = showLVals = false;
            double TFactor, GFactor, Dfactor;

            TFactor = GFactor = Dfactor = 0;
            DA.GetData(4, ref showVals);
            DA.GetData(5, ref showNds);
            DA.GetData(6, ref showEdgs);
            DA.GetData(7, ref deformed);
            DA.GetData(8, ref showLCS);
            DA.GetData(9, ref showLoads);
            DA.GetData(10, ref showSupports);
            DA.GetData(11, ref showCNs);
            DA.GetData(12, ref showNNs);
            DA.GetData(13, ref showENs);
            DA.GetData(14, ref showLVals);
            DA.GetData(15, ref TFactor);
            DA.GetData(16, ref GFactor);
            DA.GetData(17, ref Dfactor);

            List <int> panelIds = new List <int>();
            List <int> barIds   = new List <int>();

            DA.GetDataList(18, barIds);
            DA.GetDataList(19, panelIds);

            double[] sizeFactors = model.sizeFactors();
            double   EFactor     = sizeFactors[0];
            double   FFactor     = sizeFactors[1];

            if (deformed)
            {
                model.Mesh.Deform(Dfactor);
            }

            m_display = new Rhino.Display.CustomDisplay(!this.Hidden);
            Grasshopper.GUI.Gradient.GH_Gradient gradient = PreviewUtil.CreateStandardGradient();

            HashSet <int> nodeIds = new HashSet <int>();
            HashSet <int> barNodeIds;
            HashSet <int> panelNodeIds;

            m_display.AddBarPreview(model, barIds, out barNodeIds, GFactor, EFactor, TFactor, showCNs, showENs, showLCS, false, barResType, showVals);
            m_display.AddPanelPreview(model, panelIds, out panelNodeIds, GFactor, EFactor, TFactor, FFactor, showCNs, showENs, showLCS, showLoads, showLVals, showEdgs, false, gradient, panelResType, showVals);

            nodeIds.UnionWith(panelNodeIds);
            nodeIds.UnionWith(barNodeIds);
            m_display.AddNodePreview(model, nodeIds, GFactor, EFactor, TFactor, FFactor, showNds, showNNs, showLoads, showLVals, gradient, nodeResultType, showVals);

            if (showSupports)
            {
                m_display.AddSupportPreview(model, nodeIds, EFactor, GFactor);
            }
        }
    private int runCount;                                   //Legacy field.

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List <object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component           = owner;
        this.Iteration           = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument       = rhinoDocument as Rhino.RhinoDoc;

        this.owner    = this.Component;
        this.runCount = this.Iteration;
        this.doc      = this.RhinoDocument;

        //2. Assign input parameters
        List <Brep> Blocks = null;

        if (inputs[0] != null)
        {
            Blocks = GH_DirtyCaster.CastToList <Brep>(inputs[0]);
        }
        Curve Boundary = default(Curve);

        if (inputs[1] != null)
        {
            Boundary = (Curve)(inputs[1]);
        }

        List <Line> RdA = null;

        if (inputs[2] != null)
        {
            RdA = GH_DirtyCaster.CastToList <Line>(inputs[2]);
        }
        double HalfWA = default(double);

        if (inputs[3] != null)
        {
            HalfWA = (double)(inputs[3]);
        }

        List <Line> RdB = null;

        if (inputs[4] != null)
        {
            RdB = GH_DirtyCaster.CastToList <Line>(inputs[4]);
        }
        double HalfWB = default(double);

        if (inputs[5] != null)
        {
            HalfWB = (double)(inputs[5]);
        }

        List <Line> RdC = null;

        if (inputs[6] != null)
        {
            RdC = GH_DirtyCaster.CastToList <Line>(inputs[6]);
        }
        double HalfWC = default(double);

        if (inputs[7] != null)
        {
            HalfWC = (double)(inputs[7]);
        }

        double PedOff = default(double);

        if (inputs[8] != null)
        {
            PedOff = (double)(inputs[8]);
        }



        //3. Declare output parameters
        object BuildingSetback   = null;
        object PedestrianOutline = null;


        //4. Invoke RunScript
        RunScript(Blocks, Boundary, RdA, HalfWA, RdB, HalfWB, RdC, HalfWC, PedOff, ref BuildingSetback, ref PedestrianOutline);

        try
        {
            //5. Assign output parameters to component...
            if (BuildingSetback != null)
            {
                if (GH_Format.TreatAsCollection(BuildingSetback))
                {
                    IEnumerable __enum_BuildingSetback = (IEnumerable)(BuildingSetback);
                    DA.SetDataList(1, __enum_BuildingSetback);
                }
                else
                {
                    if (BuildingSetback is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(BuildingSetback));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, BuildingSetback);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
            if (PedestrianOutline != null)
            {
                if (GH_Format.TreatAsCollection(PedestrianOutline))
                {
                    IEnumerable __enum_PedestrianOutline = (IEnumerable)(PedestrianOutline);
                    DA.SetDataList(2, __enum_PedestrianOutline);
                }
                else
                {
                    if (PedestrianOutline is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(2, (Grasshopper.Kernel.Data.IGH_DataTree)(PedestrianOutline));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(2, PedestrianOutline);
                    }
                }
            }
            else
            {
                DA.SetData(2, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
Ejemplo n.º 15
0
 public void DocumentContextChanged(GH_Document document, GH_DocumentContext context)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 16
0
    private int runCount;                              //Legacy field.

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List <object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component           = owner;
        this.Iteration           = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument       = rhinoDocument as Rhino.RhinoDoc;

        this.owner    = this.Component;
        this.runCount = this.Iteration;
        this.doc      = this.RhinoDocument;

        //2. Assign input parameters
        Point3d P0 = default(Point3d);

        if (inputs[0] != null)
        {
            P0 = (Point3d)(inputs[0]);
        }

        int n = default(int);

        if (inputs[1] != null)
        {
            n = (int)(inputs[1]);
        }

        double evap = default(double);

        if (inputs[2] != null)
        {
            evap = (double)(inputs[2]);
        }

        bool wrap = default(bool);

        if (inputs[3] != null)
        {
            wrap = (bool)(inputs[3]);
        }

        bool reset = default(bool);

        if (inputs[4] != null)
        {
            reset = (bool)(inputs[4]);
        }

        bool go = default(bool);

        if (inputs[5] != null)
        {
            go = (bool)(inputs[5]);
        }

        bool MT = default(bool);

        if (inputs[6] != null)
        {
            MT = (bool)(inputs[6]);
        }



        //3. Declare output parameters
        object P        = null;
        object cPind    = null;
        object nIndexes = null;
        object S        = null;


        //4. Invoke RunScript
        RunScript(P0, n, evap, wrap, reset, go, MT, ref P, ref cPind, ref nIndexes, ref S);

        try
        {
            //5. Assign output parameters to component...
            if (P != null)
            {
                if (GH_Format.TreatAsCollection(P))
                {
                    IEnumerable __enum_P = (IEnumerable)(P);
                    DA.SetDataList(1, __enum_P);
                }
                else
                {
                    if (P is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(P));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, P);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
            if (cPind != null)
            {
                if (GH_Format.TreatAsCollection(cPind))
                {
                    IEnumerable __enum_cPind = (IEnumerable)(cPind);
                    DA.SetDataList(2, __enum_cPind);
                }
                else
                {
                    if (cPind is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(2, (Grasshopper.Kernel.Data.IGH_DataTree)(cPind));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(2, cPind);
                    }
                }
            }
            else
            {
                DA.SetData(2, null);
            }
            if (nIndexes != null)
            {
                if (GH_Format.TreatAsCollection(nIndexes))
                {
                    IEnumerable __enum_nIndexes = (IEnumerable)(nIndexes);
                    DA.SetDataList(3, __enum_nIndexes);
                }
                else
                {
                    if (nIndexes is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(3, (Grasshopper.Kernel.Data.IGH_DataTree)(nIndexes));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(3, nIndexes);
                    }
                }
            }
            else
            {
                DA.SetData(3, null);
            }
            if (S != null)
            {
                if (GH_Format.TreatAsCollection(S))
                {
                    IEnumerable __enum_S = (IEnumerable)(S);
                    DA.SetDataList(4, __enum_S);
                }
                else
                {
                    if (S is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(4, (Grasshopper.Kernel.Data.IGH_DataTree)(S));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(4, S);
                    }
                }
            }
            else
            {
                DA.SetData(4, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
Ejemplo n.º 17
0
 private void CanvasCreatedEvent(GH_DocumentServer server, GH_Document doc)
 {
     AddSpeckleMenu(null, null);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Component           = this;
            GrasshopperDocument = this.OnPingDocument();
            if (Component.Params.Input[8].SourceCount == 0)
            {
                //instantiate  new value list
                var vallist = new Grasshopper.Kernel.Special.GH_ValueList();
                vallist.CreateAttributes();

                //customise value list position
                int inputcount = this.Component.Params.Input[8].SourceCount;
                //vallist.Attributes.Pivot = new PointF((float)this.Component.Attributes.DocObject.Attributes.Bounds.Left - vallist.Attributes.Bounds.Width - 30,
                //    (float)this.Component.Params.Input[1].Attributes.Bounds.Y + inputcount * 30);
                vallist.Attributes.Pivot = new PointF(Component.Attributes.DocObject.Attributes.Bounds.Left - vallist.Attributes.Bounds.Width - 30, Component.Params.Input[8].Attributes.Bounds.Y + inputcount * 30);
                //populate value list with our own data
                vallist.ListItems.Clear();
                var item1 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 24h", "0");
                var item2 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 28h", "1");
                var item3 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 32h", "2");
                var item4 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 24c", "3");
                var item5 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 28c", "4");
                var item6 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL 32c", "5");
                var item7 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL CROSSLAM", "6");
                var item8 = new Grasshopper.Kernel.Special.GH_ValueListItem("GL ITA", "7");
                vallist.ListItems.Add(item1);
                vallist.ListItems.Add(item2);
                vallist.ListItems.Add(item3);
                vallist.ListItems.Add(item4);
                vallist.ListItems.Add(item5);
                vallist.ListItems.Add(item6);
                vallist.ListItems.Add(item7);
                vallist.ListItems.Add(item8);

                //Until now, the slider is a hypothetical object.
                // This command makes it 'real' and adds it to the canvas.
                GrasshopperDocument.AddObject(vallist, false);

                //Connect the new slider to this component
                this.Component.Params.Input[8].AddSource(vallist);
            }
            string text = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);

            text = Path.Combine(Directory.GetParent(text).FullName, "Plug-ins");
            var reader = new StreamReader(File.OpenRead(text + "\\Madeira\\MLCPROP.csv"));
            //inputs
            double Nd    = 0;
            double Myd   = 0;
            double Mzd   = 0;
            double b     = 0;
            double h     = 0;
            double l     = 0;
            double kflam = 0;
            double Kmod  = 0;
            double Km    = 0.7;
            double Ym    = 0;
            double fc0k  = 0;
            double fmk   = 0;
            double E05   = 0;
            double Bc    = 0.2;
            int    test  = 0;

            if (!DA.GetData <double>(0, ref Nd))
            {
                return;
            }
            if (!DA.GetData <double>(1, ref Myd))
            {
                return;
            }
            if (!DA.GetData <double>(2, ref Mzd))
            {
                return;
            }
            if (!DA.GetData <double>(3, ref b))
            {
                return;
            }
            if (!DA.GetData <double>(4, ref h))
            {
                return;
            }
            if (!DA.GetData <double>(5, ref l))
            {
                return;
            }
            if (!DA.GetData <double>(6, ref kflam))
            {
                return;
            }
            if (!DA.GetData <int>(8, ref test))
            {
                return;
            }
            if (!DA.GetData <double>(7, ref Kmod))
            {
                return;
            }
            int  cont = -1;
            bool stop = false;

            while (!reader.EndOfStream || stop == false)
            {
                var line   = reader.ReadLine();
                var values = line.Split(',');
                if (cont == test)
                {
                    Ym   = Double.Parse(values[12]);
                    fc0k = Double.Parse(values[1]);
                    fmk  = Double.Parse(values[3]);
                    E05  = Double.Parse(values[9]);
                    if (values[13] == "MLC")
                    {
                        Bc = 0.1;
                    }
                    stop = true;
                }
                cont++;
            }
            //Definição de valores geométricos
            double A    = h * b;
            double Iy   = b * Math.Pow(h, 3) / 12;
            double Iz   = h * Math.Pow(b, 3) / 12;
            double Wy   = Iy * (2 / h);
            double Wz   = Iz * (2 / b);
            double ry   = Math.Sqrt(Iy / A);
            double rz   = Math.Sqrt(Iz / A);
            double lamy = ry / (100 * l);
            double lamz = rz / (100 * l);
            double lef  = kflam * l * 100;

            //Definição de valores do material (ver se os sigmas devem mesmo serem multiplicados por 100)
            double lampi   = Math.Sqrt(fc0k / E05) / Math.PI;
            double fc0d    = Kmod * fc0k / Ym;
            double fmd     = Kmod * fmk / Ym;
            double lamyrel = lamy * lampi;
            double lamzrel = lamz * lampi;
            double sigN    = Nd / A;
            double sigMy   = 100 * Myd / Wy;
            double sigMz   = 100 * Mzd / Wz;
            double G05     = E05 / 16;

            //Definição dos valores de cálculo necessários para verificação em pilares ou vigas (exclui parte em que dizia que lamrely=lamm e lamrelz=sgmcrit)
            double sigMcrit = (Math.PI * Math.Pow(b, 2) * Math.Sqrt(E05 * G05 * (1 - 0.63 * (b / h)))) / (h * lef);
            double lamm     = Math.Sqrt(fmk / sigMcrit);
            double ky       = 0.5 * (1 + Bc * (lamyrel - 0.3) + Math.Pow(lamyrel, 2));
            double kz       = 0.5 * (1 + Bc * (lamzrel - 0.3) + Math.Pow(lamzrel, 2));
            double kyc      = 1 / (ky + Math.Sqrt(Math.Pow(ky, 2) - Math.Pow(lamyrel, 2)));
            double kzc      = 1 / (kz + Math.Sqrt(Math.Pow(kz, 2) - Math.Pow(lamzrel, 2)));

            //Verificação de comportamento de Pilares
            if (lamm < 0.75)
            {
                if (lamyrel <= 0.3 && lamzrel <= 0.3)
                {
                    double DIVY = Math.Pow(sigN / fc0d, 2) + (sigMy / fmd) + Km * (sigMz / fmd);
                    double DIVZ = Math.Pow(sigN / fc0d, 2) + Km * (sigMy / fmd) + (sigMz / fmd);
                    DA.SetData(0, DIVY);
                    DA.SetData(1, DIVZ);
                }
                else
                {
                    List <double> divs = new List <double>();
                    double        DIVY = (sigN / (kyc * fc0d)) + (sigMy / fmd) + Km * (sigMz / fmd);
                    double        DIVZ = (sigN / (kzc * fc0d)) + Km * (sigMy / fmd) + (sigMz / fmd);
                    DA.SetData(0, DIVY);
                    DA.SetData(1, DIVZ);
                }
            }
            //Verificação de comportamento de Vigas
            else
            {
                if (lamm >= 0.75 && lamm < 1.4)
                {
                    double kcrit = 1.56 - 0.75 * lamm;
                    double DIVY  = Math.Pow(sigMy / (kcrit * fmd), 2) + (sigN / (kzc * fc0d));
                    double DIVZ  = 0;
                    DA.SetData(0, DIVY);
                    DA.SetData(1, DIVZ);
                }
                if (lamm >= 1.4)
                {
                    double kcrit = 1 / Math.Pow(lamm, 2);
                    double DIVY  = Math.Pow(sigMy / (kcrit * fmd), 2) + (sigN / (kzc * fc0d));
                    double DIVZ  = 0;
                    DA.SetData(0, DIVY);
                    DA.SetData(1, DIVZ);
                }
            }

            //Outros Outputs
            DA.SetData(2, lamm);
        }
 public override void AddedToDocument(GH_Document document)
 {
     SetDefaultKitAndConverter();
     base.AddedToDocument(document);
 }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Sets inputs
            GH_Structure <GH_String>  names;
            GH_Structure <GH_Boolean> fineps;
            GH_Structure <GH_Number>  pzone_tcps;
            GH_Structure <GH_Number>  pzone_oris;
            GH_Structure <GH_Number>  pzone_eaxs;
            GH_Structure <GH_Number>  zone_oris;
            GH_Structure <GH_Number>  zone_leaxs;
            GH_Structure <GH_Number>  zone_reaxs;

            // Catch the input data
            if (!DA.GetDataTree(0, out names))
            {
                return;
            }
            if (!DA.GetDataTree(1, out fineps))
            {
                return;
            }
            if (!DA.GetDataTree(2, out pzone_tcps))
            {
                return;
            }
            if (!DA.GetDataTree(3, out pzone_oris))
            {
                return;
            }
            if (!DA.GetDataTree(4, out pzone_eaxs))
            {
                return;
            }
            if (!DA.GetDataTree(5, out zone_oris))
            {
                return;
            }
            if (!DA.GetDataTree(6, out zone_leaxs))
            {
                return;
            }
            if (!DA.GetDataTree(7, out zone_reaxs))
            {
                return;
            }

            // Clear tree and list
            _tree = new GH_Structure <GH_ZoneData>();
            _list = new List <GH_ZoneData>();

            // Create the datatree structure with an other component (in the background, this component is not placed on the canvas)
            ZoneDataComponentDataTreeGenerator component = new ZoneDataComponentDataTreeGenerator();

            component.Params.Input[0].AddVolatileDataTree(names);
            component.Params.Input[1].AddVolatileDataTree(fineps);
            component.Params.Input[2].AddVolatileDataTree(pzone_tcps);
            component.Params.Input[3].AddVolatileDataTree(pzone_oris);
            component.Params.Input[4].AddVolatileDataTree(pzone_eaxs);
            component.Params.Input[5].AddVolatileDataTree(zone_oris);
            component.Params.Input[6].AddVolatileDataTree(zone_leaxs);
            component.Params.Input[7].AddVolatileDataTree(zone_reaxs);

            component.ExpireSolution(true);
            component.Params.Output[0].CollectData();

            _tree = component.Params.Output[0].VolatileData as GH_Structure <GH_ZoneData>;

            // Update the variable names in the data trees
            UpdateVariableNames();

            // Make a list
            for (int i = 0; i < _tree.Branches.Count; i++)
            {
                _list.AddRange(_tree.Branches[i]);
            }

            // Sets Output
            DA.SetDataTree(0, _tree);

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears zoneDataNames
            for (int i = 0; i < _zoneDataNames.Count; i++)
            {
                _objectManager.ZoneDataNames.Remove(_zoneDataNames[i]);
            }
            _zoneDataNames.Clear();

            // Removes lastName from zoneDataNameList
            if (_objectManager.ZoneDataNames.Contains(_lastName))
            {
                _objectManager.ZoneDataNames.Remove(_lastName);
            }

            // Adds Component to ZoneDataByGuid Dictionary
            if (!_objectManager.ZoneDatasByGuid.ContainsKey(this.InstanceGuid))
            {
                _objectManager.ZoneDatasByGuid.Add(this.InstanceGuid, this);
            }

            // Checks if Zone Data name is already in use and counts duplicates
            #region Check name in object manager
            _namesUnique = true;
            for (int i = 0; i < _list.Count; i++)
            {
                if (_objectManager.ZoneDataNames.Contains(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Zone Data Name already in use.");
                    _namesUnique = false;
                    _lastName    = "";
                }
                else
                {
                    // Adds Zone Data Name to list
                    _zoneDataNames.Add(_list[i].Value.Name);
                    _objectManager.ZoneDataNames.Add(_list[i].Value.Name);

                    // Run SolveInstance on other Zone Data with no unique Name to check if their name is now available
                    foreach (KeyValuePair <Guid, ZoneDataComponent> entry in _objectManager.ZoneDatasByGuid)
                    {
                        if (entry.Value.LastName == "")
                        {
                            entry.Value.ExpireSolution(true);
                        }
                    }
                    _lastName = _list[i].Value.Name;
                }

                // Check variable name: character limit
                if (HelperMethods.VariableExeedsCharacterLimit32(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Zone Data Name exceeds character limit of 32 characters.");
                    break;
                }

                // Check variable name: start with number is not allowed
                if (HelperMethods.VariableStartsWithNumber(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Zone Data Name starts with a number which is not allowed in RAPID Code.");
                    break;
                }
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers Zone Data and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
Ejemplo n.º 21
0
 public override void AddedToDocument(GH_Document document)
 {
     base.AddedToDocument(document);
     SetUniqueNameletter(document);
 }
Ejemplo n.º 22
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Variables
            GH_Structure <GH_String>                names;
            GH_Structure <GH_RobotJointPosition>    robotJointPositions;
            GH_Structure <GH_ExternalJointPosition> externalJointPositions;

            // Catch input data
            if (!DA.GetDataTree(0, out names))
            {
                return;
            }
            if (!DA.GetDataTree(1, out robotJointPositions))
            {
                robotJointPositions = new GH_Structure <GH_RobotJointPosition>();
            }
            if (!DA.GetDataTree(2, out externalJointPositions))
            {
                externalJointPositions = new GH_Structure <GH_ExternalJointPosition>();
            }

            // Clear tree and list
            _tree = new GH_Structure <GH_JointTarget>();
            _list = new List <GH_JointTarget>();

            // Create the datatree structure with an other component (in the background, this component is not placed on the canvas)
            JointTargetComponentDataTreeGenerator component = new JointTargetComponentDataTreeGenerator();

            component.Params.Input[0].AddVolatileDataTree(names);
            component.Params.Input[1].AddVolatileDataTree(robotJointPositions);
            component.Params.Input[2].AddVolatileDataTree(externalJointPositions);

            component.ExpireSolution(true);
            component.Params.Output[0].CollectData();

            _tree = component.Params.Output[0].VolatileData as GH_Structure <GH_JointTarget>;

            // Update the variable names in the data trees
            UpdateVariableNames();

            // Make a list
            for (int i = 0; i < _tree.Branches.Count; i++)
            {
                _list.AddRange(_tree.Branches[i]);
            }

            // Sets Output
            DA.SetDataTree(0, _tree);

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears targetNames
            for (int i = 0; i < _targetNames.Count; i++)
            {
                _objectManager.TargetNames.Remove(_targetNames[i]);
            }
            _targetNames.Clear();

            // Removes lastName from targetNameList
            if (_objectManager.TargetNames.Contains(_lastName))
            {
                _objectManager.TargetNames.Remove(_lastName);
            }

            // Adds Component to TargetByGuid Dictionary
            if (!_objectManager.JointTargetsByGuid.ContainsKey(this.InstanceGuid))
            {
                _objectManager.JointTargetsByGuid.Add(this.InstanceGuid, this);
            }

            // Checks if target name is already in use and counts duplicates
            #region Check name in object manager
            _namesUnique = true;
            for (int i = 0; i < _list.Count; i++)
            {
                if (_objectManager.TargetNames.Contains(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name already in use.");
                    _namesUnique = false;
                    _lastName    = "";
                    break;
                }
                else
                {
                    // Adds Target Name to list
                    _targetNames.Add(_list[i].Value.Name);
                    _objectManager.TargetNames.Add(_list[i].Value.Name);

                    // Run SolveInstance on other Targets with no unique Name to check if their name is now available
                    _objectManager.UpdateTargets();

                    _lastName = _list[i].Value.Name;
                }

                // Checks if variable name exceeds max character limit for RAPID Code
                if (HelperMethods.VariableExeedsCharacterLimit32(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name exceeds character limit of 32 characters.");
                    break;
                }

                // Checks if variable name starts with a number
                if (HelperMethods.VariableStartsWithNumber(_list[i].Value.Name))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name starts with a number which is not allowed in RAPID Code.");
                    break;
                }
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers target and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
Ejemplo n.º 23
0
 public bool RelinkProxySources(GH_Document document)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 24
0
        /// <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)
        {
            int    type   = 0;
            string subDir = null;

            DA.GetData(0, ref type);
            DA.GetData(1, ref subDir);

            String S    = "";
            String root = "";
            String end  = "\\";
            String eol  = Environment.NewLine;

            // __________________ autoList part __________________

            // variable for the list
            Grasshopper.Kernel.Special.GH_ValueList vList;
            // tries to cast input as list
            try
            {
                // if the list is not the first parameter then change Input[0] to the corresponding value
                vList = (Grasshopper.Kernel.Special.GH_ValueList)Params.Input[0].Sources[0];

                if (!vList.NickName.Equals("Path Type"))
                {
                    vList.ClearData();
                    vList.ListItems.Clear();
                    vList.NickName = "Path Type";
                    var item1 = new Grasshopper.Kernel.Special.GH_ValueListItem("Desktop", "0");
                    var item2 = new Grasshopper.Kernel.Special.GH_ValueListItem("Documents", "1");
                    var item3 = new Grasshopper.Kernel.Special.GH_ValueListItem("GH file path", "2");
                    var item4 = new Grasshopper.Kernel.Special.GH_ValueListItem("C:", "3");
                    vList.ListItems.Add(item1);
                    vList.ListItems.Add(item2);
                    vList.ListItems.Add(item3);
                    vList.ListItems.Add(item4);

                    vList.ListItems[0].Value.CastTo(out type);
                }
            }
            catch
            {
                // handles anything that is not a value list
            }


            switch (type)
            {
            case 0:
                root = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + end;
                S    = "Desktop";
                break;

            case 1:
                root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + end;
                S    = "Documents";
                break;

            case 2:
                GH_Document ghDoc = OnPingDocument();

                if (ghDoc.IsFilePathDefined)
                {
                    int nameLen = ghDoc.DisplayName.TrimEnd('*').Length + 3;     // +3 accounts for the '.gh' extension
                    int fileLen = ghDoc.FilePath.TrimEnd('*').Length;
                    root = ghDoc.FilePath.Substring(0, fileLen - nameLen);
                    S    = "GH File Path";
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No GH Path defined. Saving to Desktop until then");
                    root = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    S    = "Desktop";
                }
                break;

            case 3:
                root = "C:" + end;
                S    = root;
                break;
            }

            Message = S;

            DA.SetData(0, root + (subDir != null ? (subDir + end) : ""));
        }
Ejemplo n.º 25
0
 private void ScheduleDelegate(GH_Document doc)
 {
     ExpireSolution(false);
 }
Ejemplo n.º 26
0
        public void Export()
        {
            if (INSTANCECOUNT > 4242)
            {
                string message = "Warning: There are " + INSTANCECOUNT + " iterations.\nIt might take a lot of time and / or Rhino might crash.\nAre you sure you want to proceed?";

                DialogResult largeinstancewarning = MessageBox.Show(message, "Warning", MessageBoxButtons.YesNo);
                if (largeinstancewarning == DialogResult.No)
                {
                    EMERGENCY_BREAK = true;
                    return;
                }
            }

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            fbd.Description = "Please select an empty folder where the export file should be saved.";
            DialogResult result = fbd.ShowDialog();

            if (result == DialogResult.OK)
            {
                string[] files = Directory.GetFiles(fbd.SelectedPath);

                if (files.Length > 0)
                {
                    System.Windows.Forms.MessageBox.Show("This is not an empty folder!");
                }
                else
                {
                    this.PATHISSET      = true;
                    this.FOLDERLOCATION = fbd.SelectedPath;
                    GHDEFNAME           = new DirectoryInfo(fbd.SelectedPath).Name;
                    EMERGENCY_BREAK     = false;
                }
            }

            if (result == DialogResult.Cancel)
            {
                EMERGENCY_BREAK = true;
                return;
            }



            // Sanity checks
            IGH_Component component = Component;
            GH_Document   doc       = GrasshopperDocument;

            if (!PATHISSET)
            {
                return;
            }
            if (component == null)
            {
                return;
            }
            if (doc == null)
            {
                return;
            }


            /// flushing up them arrays
            geometries   = new List <List <System.Object> >();
            geometrySets = new List <string>();
            sliderNames  = new List <string>();

            currentCount = 0;

            // Collect all sliders that are plugged into the first input parameter of the script component.
            List <Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List <Grasshopper.Kernel.Special.GH_NumberSlider>();

            foreach (IGH_Param param in component.Params.Input[0].Sources)
            {
                Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                if (slider != null)
                {
                    sliders.Add(slider);
                    sliderNames.Add(slider.NickName);
                }
            }

            if (sliders.Count == 0)
            {
                return;
            }

            // generate the Matrix File
            myMatrix = constructMatrixFromSliders((GH_Component)component);

            // update the instance count
            INSTANCECOUNT = myMatrix.Count;

            // go generate stuff
            foreach (List <double> instance in myMatrix)
            {
                // pause the solver while set up the sliders
                doc.Enabled = false;

                // update the currentInstanceName - top level var
                currentInstanceName = "";

                foreach (double tempvar in instance)
                {
                    currentInstanceName += tempvar + ",";
                }

                // set sliders up

                for (int i = 0; i < sliders.Count; i++)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider mySlider = sliders[i];
                    mySlider.Slider.Value = (decimal)instance[i];
                }

                //renable solver
                doc.Enabled = true;

                //compute new solution
                doc.NewSolution(false);
            }
        }
Ejemplo n.º 27
0
    private int runCount;                              //Legacy field.

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List <object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component           = owner;
        this.Iteration           = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument       = rhinoDocument as Rhino.RhinoDoc;

        this.owner    = this.Component;
        this.runCount = this.Iteration;
        this.doc      = this.RhinoDocument;

        //2. Assign input parameters
        List <Point3d> P = null;

        if (inputs[0] != null)
        {
            P = GH_DirtyCaster.CastToList <Point3d>(inputs[0]);
        }
        List <Vector3d> V = null;

        if (inputs[1] != null)
        {
            V = GH_DirtyCaster.CastToList <Vector3d>(inputs[1]);
        }
        List <Vector3d> vF = null;

        if (inputs[2] != null)
        {
            vF = GH_DirtyCaster.CastToList <Vector3d>(inputs[2]);
        }
        double pR = default(double);

        if (inputs[3] != null)
        {
            pR = (double)(inputs[3]);
        }

        double cI = default(double);

        if (inputs[4] != null)
        {
            cI = (double)(inputs[4]);
        }

        double aI = default(double);

        if (inputs[5] != null)
        {
            aI = (double)(inputs[5]);
        }

        double sI = default(double);

        if (inputs[6] != null)
        {
            sI = (double)(inputs[6]);
        }

        object fI = default(object);

        if (inputs[7] != null)
        {
            fI = (object)(inputs[7]);
        }

        double mF = default(double);

        if (inputs[8] != null)
        {
            mF = (double)(inputs[8]);
        }



        //3. Declare output parameters
        object Planes = null;


        //4. Invoke RunScript
        RunScript(P, V, vF, pR, cI, aI, sI, fI, mF, ref Planes);

        try
        {
            //5. Assign output parameters to component...
            if (Planes != null)
            {
                if (GH_Format.TreatAsCollection(Planes))
                {
                    IEnumerable __enum_Planes = (IEnumerable)(Planes);
                    DA.SetDataList(1, __enum_Planes);
                }
                else
                {
                    if (Planes is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(Planes));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, Planes);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Warning that this component is OBSOLETE
            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "This component is OBSOLETE and will be removed " +
                              "in the future. Remove this component from your canvas and replace it by picking the new component " +
                              "from the ribbon.");

            // Input variables
            List <string>            names = new List <string>();
            GH_Structure <GH_Number> internalAxisValuesTree = new GH_Structure <GH_Number>();
            GH_Structure <GH_Number> externalAxisValuesTree = new GH_Structure <GH_Number>();
            List <GH_SpeedData>      speedDataGoos          = new List <GH_SpeedData>();
            List <int>       precisions = new List <int>();
            List <RobotTool> robotTools = new List <RobotTool>();

            // Create an empty Robot Tool
            RobotTool emptyRobotTool = new RobotTool();

            emptyRobotTool.Clear();

            // Catch the input data from the fixed parameters
            if (!DA.GetDataList(0, names))
            {
                return;
            }
            if (!DA.GetDataTree(1, out internalAxisValuesTree))
            {
                return;
            }
            if (!DA.GetDataTree(2, out externalAxisValuesTree))
            {
                return;
            }
            if (!DA.GetDataList(3, speedDataGoos))
            {
                return;
            }
            if (!DA.GetDataList(4, precisions))
            {
                return;
            }

            // Catch the input data from the variable parameteres
            if (Params.Input.Any(x => x.Name == variableInputParameters[0].Name))
            {
                if (!DA.GetDataList(variableInputParameters[0].Name, robotTools))
                {
                    robotTools = new List <RobotTool>()
                    {
                        new RobotTool(emptyRobotTool)
                    };
                }
            }

            // Make sure variable input parameters have a default value
            if (robotTools.Count == 0)
            {
                robotTools.Add(new RobotTool(emptyRobotTool)); // Empty Robot Tool
            }

            // Get longest Input List
            int[] sizeValues = new int[6];
            sizeValues[0] = names.Count;
            sizeValues[1] = internalAxisValuesTree.PathCount;
            sizeValues[2] = externalAxisValuesTree.PathCount;
            sizeValues[3] = speedDataGoos.Count;
            sizeValues[4] = precisions.Count;
            sizeValues[5] = robotTools.Count;

            int biggestSize = HelperMethods.GetBiggestValue(sizeValues);

            // Keeps track of used indicies
            int namesCounter         = -1;
            int internalValueCounter = -1;
            int externalValueCounter = -1;
            int speedDataGooCounter  = -1;
            int precisionCounter     = -1;
            int robotToolGooCounter  = -1;

            // Clear list
            _jointMovements.Clear();

            // Creates movements
            for (int i = 0; i < biggestSize; i++)
            {
                string        name;
                List <double> internalAxisValues = new List <double>();
                List <double> externalAxisValues = new List <double>();

                SpeedData speedData;
                int       precision;
                RobotTool robotTool;

                // Target counter
                if (i < sizeValues[0])
                {
                    name = names[i];
                    namesCounter++;
                }
                else
                {
                    name = names[namesCounter] + "_" + (i - namesCounter);
                }

                // internal axis values counter
                if (i < sizeValues[1])
                {
                    internalAxisValues = internalAxisValuesTree[i].ConvertAll(x => (double)x.Value);
                    internalValueCounter++;
                }
                else
                {
                    internalAxisValues = internalAxisValuesTree[internalValueCounter].ConvertAll(x => (double)x.Value);
                }

                // External axis values counter
                if (sizeValues[2] == 0) // In case no external axis values are defined.
                {
                    externalAxisValues = new List <double>()
                    {
                    };
                }

                else
                {
                    if (i < sizeValues[2])
                    {
                        externalAxisValues = externalAxisValuesTree[i].ConvertAll(x => (double)x.Value);
                        externalValueCounter++;
                    }
                    else
                    {
                        externalAxisValues = externalAxisValuesTree[externalValueCounter].ConvertAll(x => (double)x.Value);
                    }
                }

                // SpeedData counter
                if (i < sizeValues[3])
                {
                    speedData = speedDataGoos[i].Value;
                    speedDataGooCounter++;
                }
                else
                {
                    speedData = speedDataGoos[speedDataGooCounter].Value;
                }

                // Precision counter
                if (i < sizeValues[4])
                {
                    precision = precisions[i];
                    precisionCounter++;
                }
                else
                {
                    precision = precisions[precisionCounter];
                }

                // Robot tool counter
                if (i < sizeValues[5])
                {
                    robotTool = robotTools[i];
                    robotToolGooCounter++;
                }
                else
                {
                    robotTool = robotTools[robotToolGooCounter];
                }

                // JointMovement constructor
                AbsoluteJointMovement jointMovement = new AbsoluteJointMovement(name, internalAxisValues, externalAxisValues, speedData, precision, robotTool);
                _jointMovements.Add(jointMovement);
            }

            // Check if a right value is used for the input of the precision
            for (int i = 0; i < precisions.Count; i++)
            {
                if (HelperMethods.PrecisionValueIsValid(precisions[i]) == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Precision value <" + i + "> is invalid. " +
                                      "In can only be set to -1, 0, 1, 5, 10, 15, 20, 30, 40, 50, 60, 80, 100, 150 or 200. " +
                                      "A value of -1 will be interpreted as fine movement in RAPID Code.");
                    break;
                }
            }

            // Check if an exact predefined speeddata value is used
            for (int i = 0; i < speedDataGoos.Count; i++)
            {
                if (speedDataGoos[i].Value.ExactPredefinedValue == false & speedDataGoos[i].Value.PreDefinied == true)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Predefined speeddata value <" + i + "> is invalid. " +
                                      "The nearest valid predefined speeddata value is used. Valid predefined speeddata values are 5, 10, " +
                                      "20, 30, 40, 50, 60, 80, 100, 150, 200, 300, 400, 500, 600, 800, 1000, 1500, 2000, 2500, 3000, 4000, " +
                                      "5000, 6000 and 7000.");
                    break;
                }
            }

            // Output
            DA.SetDataList(0, _jointMovements);

            #region Object manager
            // Gets ObjectManager of this document
            _objectManager = DocumentManager.GetDocumentObjectManager(this.OnPingDocument());

            // Clears targetNames
            for (int i = 0; i < _targetNames.Count; i++)
            {
                _objectManager.TargetNames.Remove(_targetNames[i]);
            }
            _targetNames.Clear();

            // Removes lastName from targetNameList
            if (_objectManager.TargetNames.Contains(_lastName))
            {
                _objectManager.TargetNames.Remove(_lastName);
            }

            // Adds Component to OldJointTargetsByGuid Dictionary
            if (!_objectManager.OldJointTargetsByGuid.ContainsKey(this.InstanceGuid))
            {
                _objectManager.OldJointTargetsByGuid.Add(this.InstanceGuid, this);
            }

            // Checks if target name is already in use and counts duplicates
            #region Check name in object manager
            _namesUnique = true;
            for (int i = 0; i < names.Count; i++)
            {
                if (_objectManager.TargetNames.Contains(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name already in use.");
                    _namesUnique = false;
                    _lastName    = "";
                    break;
                }
                else
                {
                    // Adds Target Name to list
                    _targetNames.Add(names[i]);
                    _objectManager.TargetNames.Add(names[i]);

                    // Run SolveInstance on other Targets with no unique Name to check if their name is now available
                    _objectManager.UpdateTargets();

                    _lastName = names[i];
                }

                // Checks if variable name exceeds max character limit for RAPID Code
                if (HelperMethods.VariableExeedsCharacterLimit32(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name exceeds character limit of 32 characters.");
                    break;
                }

                // Checks if variable name starts with a number
                if (HelperMethods.VariableStartsWithNumber(names[i]))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Target Name starts with a number which is not allowed in RAPID Code.");
                    break;
                }
            }
            #endregion

            // Recognizes if Component is Deleted and removes it from Object Managers target and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
Ejemplo n.º 29
0
 public static IEnumerable <IGH_ElementIdBakeAwareObject> GetObjectsToBake(GH_Document definition, BakeOptions options) => ElementIdBakeAwareObject.OfType(definition.SelectedObjects().OfType <IGH_ActiveObject>().Where(x => !x.Locked)).Where(x => x.CanBake(options));
Ejemplo n.º 30
0
    private int runCount;                              //Legacy field.

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List <object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component           = owner;
        this.Iteration           = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument       = rhinoDocument as Rhino.RhinoDoc;

        this.owner    = this.Component;
        this.runCount = this.Iteration;
        this.doc      = this.RhinoDocument;

        //2. Assign input parameters
        object x = default(object);

        if (inputs[0] != null)
        {
            x = (object)(inputs[0]);
        }

        object y = default(object);

        if (inputs[1] != null)
        {
            y = (object)(inputs[1]);
        }



        //3. Declare output parameters
        object A = null;


        //4. Invoke RunScript
        RunScript(x, y, ref A);

        try
        {
            //5. Assign output parameters to component...
            if (A != null)
            {
                if (GH_Format.TreatAsCollection(A))
                {
                    IEnumerable __enum_A = (IEnumerable)(A);
                    DA.SetDataList(1, __enum_A);
                }
                else
                {
                    if (A is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(A));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, A);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
        public void InitCluster()
        {
            debugText = "";

            // if we had a previous document, then let's delete it and start over
            if (wormDoc != null)
            {
                wormDoc.Enabled = false;
                wormDoc.RemoveObject(wormCluster, false);
                wormDoc.Dispose();
                wormDoc = null;
            }

            ////////////////////////
            // get clusterFileURL param again, since inputs may not have run if invalid
            ////////////////////////
            string clusterName = Params.Input[0].VolatileData.get_Branch(0)[0].ToString();

            ////////////////////////
            // get clustername and process/validate into URL
            ////////////////////////
            string clusterUrl = processValidateClusterName(clusterName);

            ////////////////////////
            // set path for temporary file location
            ////////////////////////
            string tempPath = System.IO.Path.GetTempPath();
            Uri uri = new Uri(clusterUrl);
            string filename = System.IO.Path.GetFileName(uri.LocalPath);
            fullTempFilePath = tempPath + filename;

            ////////////////////////
            // attempt to downloadCluster file
            ////////////////////////

            using (WebClient Client = new WebClient())
            {
                try {
                    Client.DownloadFile(clusterUrl, fullTempFilePath);
                }
                catch(WebException webEx)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Network error: " + webEx.Message);

                }
            }
            debugText += "Downloaded file " + clusterUrl + ", " + filename + "\n";
            debugText += "into " + fullTempFilePath + "\n";

            // if gh file doesn't exist in temporary location, abort
            if (!File.Exists(fullTempFilePath)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "File does not exist!"); }

            ////////////////////////
            // Create a cluster
            ////////////////////////

            // create cluster
            wormCluster = new GH_Cluster();
            wormCluster.CreateFromFilePath(fullTempFilePath);

            // set cluster parameter count
            clusterParamNumInput = wormCluster.Params.Input.Count;
            clusterParamNumOutput = wormCluster.Params.Output.Count;
            debugText += "\ncluster input params # = " + clusterParamNumInput;
            debugText += "\ncluster output params # = " + clusterParamNumOutput;

            // add/remove/rename parameters to match cluster parameter count.
            MatchParameterCount();

            // change hairworm name to match cluster name
            if(wormCluster.Name == "Cluster") {
                HairwormClusterName = System.IO.Path.GetFileNameWithoutExtension(uri.LocalPath);
                HairwormClusterNickName = System.IO.Path.GetFileNameWithoutExtension(uri.LocalPath);
            } else {
                HairwormClusterName = wormCluster.Name;
                HairwormClusterNickName = wormCluster.NickName;
            }
            Name = HairwormBaseName + " (" + HairwormClusterName + ")";
            NickName = HairwormBaseName + " (" + this.HairwormClusterNickName + ")";
            debugText += "cluster is named = " + wormCluster.Name;
            debugText += "cluster is nicknamed = " + wormCluster.NickName;

            //get new document, enable it, and add cluster to it
            wormDoc = new GH_Document();
            wormDoc.Enabled = true;
            wormDoc.AddObject(wormCluster, true, 0);

            // loading cluster worked. (it's important that this is almost last, because MatchParameterCount scans this to know when to disconnect params)
            loadedClusterUrlParam = clusterUrlParam;

            ExpireSolution(true);
        }
Ejemplo n.º 32
0
        // Event Handlers

        private void ActiveCanvas_DocumentChanged(Grasshopper.GUI.Canvas.GH_Canvas sender, Grasshopper.GUI.Canvas.GH_CanvasDocumentChangedEventArgs e)
        {
            Debug.WriteLine("GH: Doc Changed");
            definition              = e.NewDocument;
            definition.SolutionEnd += Definition_SolutionEnd;
        }
Ejemplo n.º 33
0
 public override void DocumentContextChanged(GH_Document document, GH_DocumentContext context)
 {
     base.DocumentContextChanged(document, context);
 }
Ejemplo n.º 34
0
        Rhino.Geometry.Mesh GetDocumentPreview(GH_Document document)
        {
            var meshPreview = new Rhino.Geometry.Mesh();

            foreach (var obj in document.Objects.OfType <IGH_ActiveObject>())
            {
                if (obj.Locked)
                {
                    continue;
                }

                if (obj is IGH_PreviewObject previewObject)
                {
                    if (previewObject.IsPreviewCapable)
                    {
                        //primitivesBoundingBox = Rhino.Geometry.BoundingBox.Union(primitivesBoundingBox, previewObject.ClippingBox);

                        if (obj is IGH_Component component)
                        {
                            if (!component.Hidden)
                            {
                                foreach (var param in component.Params.Output)
                                {
                                    foreach (var value in param.VolatileData.AllData(true))
                                    {
                                        if (value is IGH_PreviewData)
                                        {
                                            switch (value.ScriptVariable())
                                            {
                                            case Rhino.Geometry.Mesh mesh:
                                                //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(mesh, GeometryResolver.Settings));
                                                // cb?.Invoke(Newtonsoft.Json.JsonConvert.SerializeObject(mesh, GeometryResolver.Settings));
                                                meshPreview.Append(mesh);
                                                break;

                                            case Rhino.Geometry.Brep brep:
                                                var previewMesh = new Rhino.Geometry.Mesh();
                                                previewMesh.Append(Rhino.Geometry.Mesh.CreateFromBrep(brep, Rhino.Geometry.MeshingParameters.Default));
                                                //Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(previewMesh, GeometryResolver.Settings));
                                                // cb?.Invoke(Newtonsoft.Json.JsonConvert.SerializeObject(previewMesh, GeometryResolver.Settings));
                                                meshPreview.Append(previewMesh);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (obj is IGH_Param param)
                        {
                            foreach (var value in param.VolatileData.AllData(true))
                            {
                                if (value is IGH_PreviewData)
                                {
                                    switch (value.ScriptVariable())
                                    {
                                    case Rhino.Geometry.Mesh mesh:
                                        // Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(mesh, GeometryResolver.Settings));
                                        // cb?.Invoke(Newtonsoft.Json.JsonConvert.SerializeObject(mesh, GeometryResolver.Settings));
                                        meshPreview.Append(mesh);
                                        break;

                                    case Rhino.Geometry.Brep brep:
                                        var previewMesh = new Rhino.Geometry.Mesh();
                                        previewMesh.Append(Rhino.Geometry.Mesh.CreateFromBrep(brep, Rhino.Geometry.MeshingParameters.Default));
                                        // Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(previewMesh, GeometryResolver.Settings));
                                        // cb?.Invoke(Newtonsoft.Json.JsonConvert.SerializeObject(previewMesh, GeometryResolver.Settings));
                                        meshPreview.Append(previewMesh);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(meshPreview);
        }
        /// <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)
        {
            // Get inputs.
            Connection connect = null;

            if (!DA.GetData(0, ref connect))
            {
                return;
            }
            //////////////////////////////////////////////////////
            // Process data.
            if (connect.status)
            {
                // If connection open start acting.
                // Prepare to receive UI data.
                try {
                    if (connect.udpReceiver.dataMessages.Count > 0)
                    {
                        UIReceiver.currentInput = connect.udpReceiver.dataMessages.Peek();
                        UIReceiver.currentInput = EncodeUtilities.StripSplitter(UIReceiver.currentInput);
                        if (UIReceiver.lastInputs != UIReceiver.currentInput)
                        {
                            UIReceiver.lastInputs = UIReceiver.currentInput;
                            UniversalDebug("New Message without Message Splitter removed: " + currentInput);
                            string[] messageComponents = UIReceiver.currentInput.Split(new string[] { EncodeUtilities.headerSplitter }, 2, StringSplitOptions.RemoveEmptyEntries);
                            if (messageComponents.Length > 1)
                            {
                                string header = messageComponents[0], content = messageComponents[1];
                                UniversalDebug("Header: " + header + ", content: " + content);
                                if (header == "UIDATA")
                                {
                                    // If any new data received - process it.
                                    UIData data = JsonConvert.DeserializeObject <UIData>(content);
                                    UIReceiver.currentBools  = new List <bool> (data.bools);
                                    UIReceiver.currentInts   = new List <int> (data.ints);
                                    UIReceiver.currentFloats = new List <float> (data.floats);
                                    UniversalDebug("Data Received!");
                                    connect.udpReceiver.dataMessages.Dequeue();                                     // Actually remove from the queue since it has been processed.
                                }
                                // else
                                //	UniversalDebug("Header Not Recognized!", GH_RuntimeMessageLevel.Warning);
                            }
                            else
                            {
                                UniversalDebug("Data not Received!", GH_RuntimeMessageLevel.Warning);
                            }
                        }
                        else
                        {
                            UniversalDebug("Improper Message!", GH_RuntimeMessageLevel.Warning);
                        }
                    }
                    else
                    {
                        UniversalDebug("No data received.");
                    }
                } catch {
                    UniversalDebug("Error Processing Data.", GH_RuntimeMessageLevel.Error);
                }
            }
            else
            {
                // If connection disabled - reset memoty.
                UIReceiver.lastInputs    = string.Empty;
                UIReceiver.currentBools  = new List <bool>();
                UIReceiver.currentInts   = new List <int>();
                UIReceiver.currentFloats = new List <float>();
                UniversalDebug("Set 'Send' on true in HoloFab 'HoloConnect'", GH_RuntimeMessageLevel.Warning);
            }
            //////////////////////////////////////////////////////
            // Output.
            DA.SetDataList(0, UIReceiver.currentBools);
            DA.SetDataList(1, UIReceiver.currentInts);
            DA.SetDataList(2, UIReceiver.currentFloats);
                        #if DEBUG
            DA.SetData(3, this.debugMessages[this.debugMessages.Count - 1]);
                        #endif

            // Expire Solution.
            if (connect.status)
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(UIReceiver.expireDelay, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 36
0
 private void ScheduleCallback(GH_Document doc)
 {
     this.ExpireSolution(false);
 }
Ejemplo n.º 37
0
        private void SetUniqueNameletter(GH_Document document)
        {
            // finds other NameableComponents in current document
            List<String> existingNames = new List<String>();
            Guid componentid = this.ComponentGuid;
            foreach (IGH_DocumentObject docobj in document.Objects) if (docobj.ComponentGuid == componentid) existingNames.Add(((NameableComponent)docobj).nameLetter);

            this.nameLetter = GH_ComponentParamServer.InventUniqueNickname("abcdefghijklmnopqrstuv", existingNames);
            if (!customNameSet) this.ComponentName = this.namePrefix + this.nameLetter;
        }
Ejemplo n.º 38
0
        /// <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)
        {
            // Fields
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            string           varRead        = "";
            bool             triggerRead    = false;
            int refreshRate = 0;

            bool getSocket = DA.GetData(0, ref abstractSocket);

            //Check input
            if (_clientSocket == null)
            {
                if (!getSocket)
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !getSocket)
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref varRead))
            {
                return;
            }
            if (!DA.GetData(2, ref triggerRead))
            {
                return;
            }
            if (!DA.GetData(3, ref refreshRate))
            {
                return;
            }

            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try more in the region of ~20-70 ms");
                return;
            }

            //If trigger is pressed, read data and output.
            if (triggerRead)
            {
                string response = Util.ReadVariable(ref _clientSocket, varRead, this);
                DA.SetData(0, response);
                if (this.Params.Input[2].Sources[0].GetType() == typeof(GH_BooleanToggle))
                {
                    GH_Document doc = OnPingDocument();
                    doc?.ScheduleSolution(refreshRate, ScheduleCallback);
                }
            }
        }
Ejemplo n.º 39
0
    private List<string> __out = new List<string>(); //Do not modify this list directly.

    #endregion Fields

    #region Methods

    public override void InvokeRunScript(IGH_Component owner, object rhinoDocument, int iteration, List<object> inputs, IGH_DataAccess DA)
    {
        //Prepare for a new run...
        //1. Reset lists
        this.__out.Clear();
        this.__err.Clear();

        this.Component = owner;
        this.Iteration = iteration;
        this.GrasshopperDocument = owner.OnPingDocument();
        this.RhinoDocument = rhinoDocument as Rhino.RhinoDoc;

        this.owner = this.Component;
        this.runCount = this.Iteration;
        this. doc = this.RhinoDocument;

        //2. Assign input parameters
        Mesh Profile = default(Mesh);
        if (inputs[0] != null)
        {
          Profile = (Mesh)(inputs[0]);
        }

        List<Mesh> x = null;
        if (inputs[1] != null)
        {
          x = GH_DirtyCaster.CastToList<Mesh>(inputs[1]);
        }
        bool y = default(bool);
        if (inputs[2] != null)
        {
          y = (bool)(inputs[2]);
        }

        //3. Declare output parameters
          object A = null;

        //4. Invoke RunScript
        RunScript(Profile, x, y, ref A);

        try
        {
          //5. Assign output parameters to component...
            if (A != null)
          {
        if (GH_Format.TreatAsCollection(A))
        {
          IEnumerable __enum_A = (IEnumerable)(A);
          DA.SetDataList(1, __enum_A);
        }
        else
        {
          if (A is Grasshopper.Kernel.Data.IGH_DataTree)
          {
            //merge tree
            DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(A));
          }
          else
          {
            //assign direct
            DA.SetData(1, A);
          }
        }
          }
          else
          {
        DA.SetData(1, null);
          }

        }
        catch (Exception ex)
        {
          this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
          //Add errors and messages...
          if (owner.Params.Output.Count > 0)
          {
        if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
        {
          List<string> __errors_plus_messages = new List<string>();
          if (this.__err != null) { __errors_plus_messages.AddRange(this.__err); }
          if (this.__out != null) { __errors_plus_messages.AddRange(this.__out); }
          if (__errors_plus_messages.Count > 0)
            DA.SetDataList(0, __errors_plus_messages);
        }
          }
        }
    }
Ejemplo n.º 40
0
 public void RemovedFromDocument(GH_Document document)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 41
0
 public void AddedToDocument(GH_Document document)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 42
0
 private void CallBack(GH_Document doc)
 {
     ExpireSolution(false);
 }
Ejemplo n.º 43
0
 public void MovedBetweenDocuments(GH_Document oldDocument, GH_Document newDocument)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 44
0
        /// <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)
        {
            //Get imput curve
            Curve refCurve = null;

            DA.GetData(0, ref refCurve);

            //Get document

            docu = this.OnPingDocument();

            //Add all components to a new list and then filter to only selected elements
            List <IGH_DocumentObject> objects = new List <IGH_DocumentObject>();

            try
            {
                objects = docu.Objects.ToList <IGH_DocumentObject>();

                objects = GH_Document.FilterSelected(objects);
            }
            catch
            {
            }


            //If more than one component are selected run main logic

            if (objects.Count > 1)
            {
                int elements = objects.Count();

                //Get max and min coordinates of the existing components, this values will be used to remap
                // the points from the input curve

                float minX = objects[0].Attributes.Pivot.X;
                float maxX = objects[0].Attributes.Pivot.X;
                float minY = objects[0].Attributes.Pivot.Y;
                float maxY = objects[0].Attributes.Pivot.Y;



                foreach (IGH_DocumentObject obj in objects)
                {
                    if (obj != this)
                    {
                        if (obj.Attributes.Pivot.X < minX)
                        {
                            minX = obj.Attributes.Pivot.X;
                        }
                        if (obj.Attributes.Pivot.X > maxX)
                        {
                            maxX = obj.Attributes.Pivot.X;
                        }
                        if (obj.Attributes.Pivot.Y < minY)
                        {
                            minY = obj.Attributes.Pivot.Y;
                        }
                        if (obj.Attributes.Pivot.Y > maxY)
                        {
                            maxY = obj.Attributes.Pivot.Y;
                        }
                    }
                }


                //Only max amplitude (x or y) will be used to remap curve
                float xAmplitude = Math.Abs(minX - maxX);
                float yAmplitude = Math.Abs(minY - maxY);

                float minMapping;
                float maxMapping;

                if (xAmplitude >= yAmplitude)
                {
                    minMapping = minX;
                    maxMapping = maxX;
                }

                else
                {
                    minMapping = minY;
                    maxMapping = maxY;
                }


                //Get points along input curve
                refCurve.Domain = new Interval(0, 1);
                List <double> parameters = new List <double>();
                for (double i = 0; i < 1; i += 1.0 / elements)
                {
                    parameters.Add(i);
                }

                List <Point3d> insertionPoints = new List <Point3d>();



                List <double> Xs = new List <double>();
                List <double> Ys = new List <double>();

                //Add coordinates of the points
                foreach (double param in parameters)
                {
                    Point3d pt = refCurve.PointAt(param);
                    Xs.Add(pt.X);
                    Ys.Add(pt.Y);
                }

                List <double> mappedXs = new List <double>();
                List <double> mappedYs = new List <double>();

                double minFX = Xs.Min();
                double maxFX = Xs.Max();
                double minFY = Ys.Min();
                double maxFY = Ys.Max();

                //Remap values to the domain extracted from the components coordinates
                foreach (double x in Xs)
                {
                    mappedXs.Add(x.Remap(minFX, maxFX, minMapping, maxMapping));
                }

                foreach (double y in Ys)
                {
                    mappedYs.Add(y.Remap(minFY, maxFY, maxMapping, minMapping));
                }


                //Set the coordiantes of the components

                for (int i = 0; i < objects.Count(); i++)
                {
                    objects[i].Attributes.Pivot = new System.Drawing.PointF((float)mappedXs[i], (float)mappedYs[i]);
                }
            }
        }
Ejemplo n.º 45
0
 public override void DocumentContextChanged(GH_Document document, GH_DocumentContext context)
 {
     base.DocumentContextChanged(document, context);
     if (context == GH_DocumentContext.Loaded)
     {
         myControlPanel = new controlPanel();
     }
 }
Ejemplo n.º 46
0
        public override void RemovedFromDocument(GH_Document document)
        {
            base.RemovedFromDocument(document);

              Dispose();
        }
Ejemplo n.º 47
0
 public override void RemovedFromDocument(GH_Document document)
 {
     videoSource.NewFrame -= frameHandler;
     videoSource.SignalToStop();
     base.RemovedFromDocument(document);
 }
Ejemplo n.º 48
0
        /// <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)
        {
            // Get the Grasshopper document
            _doc = this.OnPingDocument();

            // Input variables
            Robot robot = null;

            // Catch the input data
            if (!DA.GetData(0, ref robot))
            {
                return;
            }

            // Check if the input is valid
            if (!robot.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The Robot Info is not Valid");
            }

            // Output meshes (only link meshes, no robot tool)
            List <Mesh> meshes = new List <Mesh>();

            // Add display meshes
            _meshes.Clear();
            if (robot.Meshes != null)
            {
                for (int i = 0; i < 7; i++)
                {
                    _meshes.Add(robot.Meshes[i]);
                    meshes.Add(robot.Meshes[i]);
                }
            }

            if (robot.Tool.IsValid)
            {
                _meshes.Add(robot.Tool.Mesh);
            }
            else
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The Robot Tool is not Valid");
            }

            for (int i = 0; i < robot.ExternalAxes.Count; i++)
            {
                if (robot.ExternalAxes[i].IsValid)
                {
                    _meshes.Add(robot.ExternalAxes[i].BaseMesh);
                    _meshes.Add(robot.ExternalAxes[i].LinkMesh);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The External Axis is not Valid");
                }
            }

            // Output
            DA.SetData(0, robot.Name);
            DA.SetDataList(1, meshes);
            DA.SetDataList(2, robot.InternalAxisPlanes);
            DA.SetDataList(3, robot.InternalAxisLimits);
            DA.SetData(4, robot.BasePlane);
            DA.SetData(5, robot.MountingFrame);
            DA.SetData(6, robot.Tool);
            DA.SetDataList(7, robot.ExternalAxes);
        }
Ejemplo n.º 49
0
        /// <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)
        {
            // 0. Generate input menu list
            Component = this;
            GrasshopperDocument = this.OnPingDocument();
            // Only generate it if the input has no source
            if (Component.Params.Input[0].SourceCount == 0)
            {
                InputTools.TopoSelect(ref Component, ref GrasshopperDocument, 0, 11);
            }

            // 1. Retrieve input
            int cellType = 0;
            if (!DA.GetData(0, ref cellType)) { return; }

            // 2. Instantiate line list
            var lines = new List<Line>();

            // 3. Set cell size
            double d = 5;

            // 4. Switch statement for the different cell types
            switch (cellType)
            {
                // "GRID"
                case 0:
                    lines = GridLines(d);
                    break;
                // "X"
                case 1:
                    lines = XLines(d);
                    break;
                // "STAR"
                case 2:
                    lines = StarLines(d);
                    break;
                // "CROSS"
                case 3:
                    lines = CrossLines(d);                        
                    break;
                // "TESSERACT"
                case 4:
                    lines = TesseractLines(d);
                    break;
                // "VINTILES"
                case 5:
                    lines = VintileLines(d);
                    break;
                // "OCTET"
                case 6:
                    lines = OctetLines(d);
                    break;
                // "DIAMOND"
                case 7:
                    lines = DiamondLines(d);
                    break;
                // "HONEYCOMB"
                case 8:
                    lines = Honeycomb(d);
                    break;
                // "AUXETIC HONEYCOMB"
                case 9:
                    lines = AuxeticHoneycomb(d);
                    break;
            }

            // 5. Instantiate UnitCell object and check validity.
            var cell = new UnitCell(lines);
            if (!cell.isValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid cell - this is embarassing.");
            }

            // 6. Construct normalized cell lines (for optional output)
            var lines2 = new List<Line>();
            foreach (IndexPair nodePair in cell.NodePairs)
            {
                lines2.Add(new Line(cell.Nodes[nodePair.I], cell.Nodes[nodePair.J]));
            }

            // 7. Set output (as LatticeCellGoo)
            DA.SetData(0, new UnitCellGoo(cell));
            DA.SetDataList(1, lines2);
        }
Ejemplo n.º 50
0
 public override void AddedToDocument(GH_Document document)
 {
     this.Message = "v" + GetPluginVersion();
     base.AddedToDocument(document);
 }
Ejemplo n.º 51
0
 private void GrasshopperDocumentClosed(GH_DocumentServer sender, GH_Document doc)
 {
     if (doc != null && (m_doc != null && doc.DocumentID == m_doc.DocumentID))
       {
     Dispose();
       }
 }
Ejemplo n.º 52
0
 public override void RemovedFromDocument(GH_Document document)
 {
     CleanApiClient();
     base.RemovedFromDocument(document);
 }
 /// <summary>
 /// Trigger change in the face of the component name to match the Machina Core API.
 /// </summary>
 /// <param name="document"></param>
 public override void AddedToDocument(GH_Document document)
 {
     base.AddedToDocument(document);
     this.UpdateComponentNames();
 }
Ejemplo n.º 54
0
        /// <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)
        {
            // Fields
            GH_ObjectWrapper abstractSocket = new GH_ObjectWrapper();
            bool             triggerRead    = false;
            int refreshRate = 0;

            E6POS  currentPos    = new E6POS();
            E6AXIS currentAngles = new E6AXIS();

            bool getSocket = DA.GetData(0, ref abstractSocket);

            //Check input
            if (_clientSocket == null)
            {
                if (!getSocket)
                {
                    return;
                }
                abstractSocket.CastTo(ref _clientSocket);
            }
            else if (_clientSocket != null && !getSocket)
            {
                try
                {
                    _clientSocket = null;
                    return;
                }
                catch
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Waiting For Connection...");
                    return;
                }
            }
            if (!DA.GetData(1, ref triggerRead))
            {
                return;
            }
            if (!DA.GetData(2, ref refreshRate))
            {
                return;
            }
            if (refreshRate < 15)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "WARNING: Refresh rate too low, this can cause performance issues for grasshopper. The maximum robot read speed is 5ms (for all messages)");
            }
            if (refreshRate < 5)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Refresh Rate too low. Absolute maximum speed is 5ms. This is not recommended. Try to stay in the region of ~20-70 ms");
                return;
            }

            //If trigger is pressed, read data and output.
            if (triggerRead)
            {
                string response = Util.ReadVariable(ref _clientSocket, "$POS_ACT", this);
                currentPos.DeserializeE6POS(response);
                CurrentPos = currentPos;

                string response2 = Util.ReadVariable(ref _clientSocket, "$AXIS_ACT", this);
                currentAngles.DeserializeE6AXIS(response2);
                CurrentAngles = currentAngles;
            }

            if (!CurrentAngles.IsNull() && !CurrentPos.IsNull())
            {
                DA.SetDataList(0, CurrentAngles.GetAxisValues());
                DA.SetData(1, new GH_Plane(CurrentPos.GetPlane()));
                DA.SetDataList(2, new List <double> {
                    CurrentPos.X, CurrentPos.Y, CurrentPos.Z
                });
                DA.SetDataList(3, new List <double> {
                    CurrentPos.A, CurrentPos.B, CurrentPos.C
                });
                DA.SetData(4, CurrentPos.SerializedString);
                DA.SetData(5, CurrentAngles.SerializedString);
            }

            if (this.Params.Input[1].Sources[0].GetType() == typeof(GH_BooleanToggle) && triggerRead)
            {
                GH_Document doc = OnPingDocument();
                doc?.ScheduleSolution(refreshRate, ScheduleCallback);
            }
        }