Beispiel #1
0
        public override bool CastFrom(object source)
        {
            if (source == null)
            {
                return(false);
            }
            if (source is Mesh)
            {
                Value = (Mesh)source;
                return(true);
            }
            GH_Mesh meshGoo = source as GH_Mesh;

            if (meshGoo != null)
            {
                Value = meshGoo.Value;
                return(true);
            }

            Mesh m = new Mesh();

            if (GH_Convert.ToMesh(source, ref m, GH_Conversion.Both))
            {
                Value = m;
                return(true);
            }

            return(false);
        }
Beispiel #2
0
        public override bool CastFrom(object source)
        {
            if (source == null)
            {
                return(false);
            }

            // Cast from Buckminster.Mesh
            if (typeof(Mesh).IsAssignableFrom(source.GetType()))
            {
                Value = (Mesh)source;
                return(true);
            }

            // Cast from Rhino.Geometry.Mesh
            Rhino.Geometry.Mesh mesh = null;
            if (GH_Convert.ToMesh(source, ref mesh, GH_Conversion.Primary))
            {
                Value = new Mesh(mesh);
                return(true);
            }

            // Ah well, at least we tried...
            return(false);
        }
Beispiel #3
0
        public override bool CastFrom(object source)
        {
            if (source == null)
            {
                return(false);
            }

            // Cast from Molecular
            if (typeof(Molecular).IsAssignableFrom(source.GetType()))
            {
                Value = (Molecular)source;
                return(true);
            }

            // Cast from Buckminster.Mesh
            if (typeof(Mesh).IsAssignableFrom(source.GetType()))
            {
                Value = ((Mesh)source).ToMolecular();
                return(true);
            }

            // Cast from GH_GeometricGoo<Buckminster.Mesh>
            if (typeof(MeshGoo).IsAssignableFrom(source.GetType()))
            {
                var target = (MeshGoo)source;
                Value = target.Value.ToMolecular();
                return(true);
            }

            // Cast from Rhino.Geometry.Mesh
            Rhino.Geometry.Mesh rmesh = null;
            if (GH_Convert.ToMesh(source, ref rmesh, GH_Conversion.Primary))
            {
                var target = new Molecular(rmesh.Vertices.Count);

                // add nodes
                foreach (var pt in rmesh.TopologyVertices)
                {
                    target.Add(pt.X, pt.Y, pt.Z);
                }

                // add bars (use edges from mesh)
                for (int i = 0; i < rmesh.TopologyEdges.Count; i++)
                {
                    var edge = rmesh.TopologyEdges.GetTopologyVertices(i);
                    target.Add(edge.I, edge.J);
                }

                Value = target;
                return(true);
            }

            // Ah well, at least we tried...
            return(false);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Mesh ghmesh = new GH_Mesh();

            if (DA.GetData(0, ref ghmesh))
            {
                if (ghmesh == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Mesh input is null");
                }
                Mesh mesh = new Mesh();
                if (GH_Convert.ToMesh(ghmesh, ref mesh, GH_Conversion.Both))
                {
                    GsaElement2d elem = new GsaElement2d(mesh);

                    // 1 section
                    GH_ObjectWrapper gh_typ = new GH_ObjectWrapper();
                    GsaProp2d        prop2d = new GsaProp2d();
                    if (DA.GetData(1, ref gh_typ))
                    {
                        if (gh_typ.Value is GsaProp2dGoo)
                        {
                            gh_typ.CastTo(ref prop2d);
                        }
                        else
                        {
                            if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both))
                            {
                                for (int i = 0; i < elem.Elements.Count; i++)
                                {
                                    elem.Elements[i].Property = idd;
                                }
                                prop2d = null;
                            }
                            else
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert PA input to a 2D Property of reference integer");
                                return;
                            }
                        }
                    }
                    else
                    {
                        prop2d = null;
                    }

                    List <GsaProp2d> prop2Ds = new List <GsaProp2d>();
                    for (int i = 0; i < elem.Elements.Count; i++)
                    {
                        prop2Ds.Add(prop2d);
                    }
                    elem.Properties = prop2Ds;

                    DA.SetData(0, new GsaElement2dGoo(elem));
                }
        public override bool CastFrom(object source)
        {
            // This function is called when Grasshopper needs to convert other data
            // into GsaMember.


            if (source == null)
            {
                return(false);
            }

            //Cast from GsaMember
            if (typeof(GsaMember3d).IsAssignableFrom(source.GetType()))
            {
                Value = (GsaMember3d)source;
                return(true);
            }

            //Cast from GsaAPI Member
            if (typeof(Member).IsAssignableFrom(source.GetType()))
            {
                Value.Member = (Member)source;
                return(true);
            }

            //Cast from Brep
            Brep brep = new Brep();

            if (GH_Convert.ToBrep(source, ref brep, GH_Conversion.Both))
            {
                GsaMember3d member = new GsaMember3d(brep);
                this.Value = member;
                return(true);
            }

            //Cast from Mesh
            Mesh mesh = new Mesh();

            if (GH_Convert.ToMesh(source, ref mesh, GH_Conversion.Both))
            {
                GsaMember3d member = new GsaMember3d(mesh);
                this.Value = member;
                return(true);
            }

            return(false);
        }
Beispiel #6
0
        private DataTree <object> CorrectMesh(
            Dictionary <string, Mesh> meshes,
            Dictionary <string, List <List <double> > > points,
            double distance
            )
        {
            var newMeshes = new DataTree <object>();
            var j         = 0;

            foreach (var key in meshes.Keys)
            {
                if (!points.ContainsKey(key))
                {
                    continue;
                }

                var patchPoints = points[key];
                var ghPoints    = patchPoints.Select(point => new Point3d(point[0], point[1], point[2])).ToList();
                var mesh        = new Mesh();

                // Check mesh normal. If the normal direction is fx Z, check that the points and mesh have the same value. If not throw an error.
                GH_Convert.ToMesh(meshes[key], ref mesh, GH_Conversion.Primary);
                var faceCenters = Enumerable.Range(0, mesh.Faces.Count())
                                  .Select(index => mesh.Faces.GetFaceCenter(index)).ToList();
                var faceIndices = RTree.Point3dClosestPoints(faceCenters, ghPoints, distance);

                var newMesh = new Mesh();
                newMesh.Vertices.AddVertices(mesh.Vertices);
                foreach (var face in faceIndices)
                {
                    if (face.Length > 0)
                    {
                        newMesh.Faces.AddFace(mesh.Faces[face[0]]);
                    }
                }

                newMesh.Normals.ComputeNormals();
                newMesh.UnifyNormals();
                newMesh.Compact();

                var path = new GH_Path(j);
                newMeshes.Add(newMesh, path);
                j++;
            }

            return(newMeshes);
        }
Beispiel #7
0
        public override bool CastFrom(object source)
        {
            // This function is called when Grasshopper needs to convert other data
            // into GsaElement.


            if (source == null)
            {
                return(false);
            }

            //Cast from GsaElement
            if (typeof(GsaElement2d).IsAssignableFrom(source.GetType()))
            {
                Value = (GsaElement2d)source;
                return(true);
            }

            //Cast from GsaAPI Member
            if (typeof(List <Element>).IsAssignableFrom(source.GetType()))
            {
                Value.Elements = (List <Element>)source;
                return(true);
            }

            if (typeof(Element).IsAssignableFrom(source.GetType()))
            {
                Value.Elements[0] = (Element)source; //If someone should want to just test if they can convert a Mesh face
                return(true);
            }

            //Cast from Mesh
            Mesh mesh = new Mesh();

            if (GH_Convert.ToMesh(source, ref mesh, GH_Conversion.Both))
            {
                GsaElement2d elem = new GsaElement2d(mesh);
                this.Value = elem;
                return(true);
            }

            return(false);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Mesh ghmesh = new GH_Mesh();

            if (DA.GetData(0, ref ghmesh))
            {
                Mesh mesh = new Mesh();
                if (GH_Convert.ToMesh(ghmesh, ref mesh, GH_Conversion.Both))
                {
                    GsaElement2d elem = new GsaElement2d(mesh);

                    // 1 section
                    GH_ObjectWrapper gh_typ = new GH_ObjectWrapper();
                    GsaProp2d        prop2d = new GsaProp2d();
                    if (DA.GetData(1, ref gh_typ))
                    {
                        if (gh_typ.Value is GsaProp2d)
                        {
                            gh_typ.CastTo(ref prop2d);
                        }
                        else if (gh_typ.Value is GH_Number)
                        {
                            if (GH_Convert.ToInt32((GH_Number)gh_typ.Value, out int idd, GH_Conversion.Both))
                            {
                                prop2d.ID = idd;
                            }
                        }
                    }
                    else
                    {
                        prop2d.ID = 1;
                    }
                    List <GsaProp2d> prop2Ds = new List <GsaProp2d>();
                    for (int i = 0; i < elem.Elements.Count; i++)
                    {
                        prop2Ds.Add(prop2d);
                    }
                    elem.Properties = prop2Ds;

                    DA.SetData(0, new GsaElement2dGoo(elem));
                }
            }
        }
Beispiel #9
0
        private DataTree <object> CorrectMesh(
            Dictionary <string, Mesh> meshes
            )
        {
            var newMeshes = new DataTree <object>();
            var j         = 0;

            foreach (var key in meshes.Keys)
            {
                var newMesh = new Mesh();

                // Check mesh normal. If the normal direction is fx Z, check that the points and mesh have the same value. If not throw an error.
                GH_Convert.ToMesh(meshes[key], ref newMesh, GH_Conversion.Primary);

                var path = new GH_Path(j);
                newMeshes.Add(newMesh, path);
                j++;
            }

            return(newMeshes);
        }
Beispiel #10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_ObjectWrapper gh_typ = new GH_ObjectWrapper();

            if (DA.GetData(0, ref gh_typ))
            {
                if (gh_typ == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Solid input is null");
                }
                GsaMember3d mem  = new GsaMember3d();
                Brep        brep = new Brep();
                Mesh        mesh = new Mesh();
                if (GH_Convert.ToBrep(gh_typ.Value, ref brep, GH_Conversion.Both))
                {
                    mem = new GsaMember3d(brep);
                }
                else if (GH_Convert.ToMesh(gh_typ.Value, ref mesh, GH_Conversion.Both))
                {
                    mem = new GsaMember3d(mesh);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert Geometry input to a 3D Member");
                    return;
                }

                // 1 prop3d to be implemented GsaAPI

                // 2 mesh size
                GH_Number ghmsz = new GH_Number();
                if (DA.GetData(2, ref ghmsz))
                {
                    GH_Convert.ToDouble(ghmsz, out double m_size, GH_Conversion.Both);
                    mem.Member.MeshSize = m_size;
                }

                DA.SetData(0, new GsaMember3dGoo(mem));
            }
        }
Beispiel #11
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)
        {
            #region INPUTS
            // import silkwormSettings file
            List <string> silkwormSettings = new List <string>();
            if (!DA.GetDataList(0, silkwormSettings))
            {
                return;
            }

            List <GH_ObjectWrapper> things = new List <GH_ObjectWrapper>();
            if (!DA.GetDataList(1, things))
            {
                return;
            }


            // import Silkworm Movement
            #endregion


            SilkwormUtility             sUtil    = new SilkwormUtility();
            Dictionary <string, string> Settings = sUtil.convertSettings(silkwormSettings);

            #region Optional Variables
            int shell = -999;
            if (!DA.GetData(4, ref shell))
            {
            }
            double layerheight = -999;
            if (!DA.GetData(3, ref layerheight))
            {
            }
            //bool detect = false;
            //if (!DA.GetData(5, ref detect)) { }
            List <Plane> sliceplanes = new List <Plane>();
            if (!DA.GetDataList(2, sliceplanes))
            {
            }

            if (shell == -999)
            {
                shell = int.Parse(Settings["perimeters"]);
            }
            if (layerheight == -999)
            {
                layerheight = double.Parse(Settings["layer_height"]);
            }
            if (sliceplanes.Count < 1)
            {
                sliceplanes.Add(Plane.WorldXY);
            }

            #endregion

            List <Brep> Breps = new List <Brep>();


            List <Mesh> Meshes = new List <Mesh>();

            SilkwormSkein skein = new SilkwormSkein();

            #region Sort Types
            foreach (GH_ObjectWrapper obj in things)
            {
                if (obj.Value is GH_Brep)
                {
                    Brep brep = null;
                    GH_Convert.ToBrep(obj.Value, ref brep, GH_Conversion.Both);

                    Breps.Add(brep);
                    continue;
                }

                if (obj.Value is GH_Mesh)
                {
                    Mesh mesh = null;
                    GH_Convert.ToMesh(obj.Value, ref mesh, GH_Conversion.Both);
                    Meshes.Add(mesh);

                    continue;
                }
            }
            #endregion


            if (Breps.Count > 0)
            {
                skein = new SilkwormSkein(Settings, Breps, sliceplanes, shell, layerheight);
                skein.BrepSlice(false);
            }


            if (Meshes.Count > 0)
            {
                //TODO
            }

            //Reflect Errors and Warnings

            foreach (string message in skein.ErrorMessages)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, message);
            }
            foreach (string message in skein.WarningMessages)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
            }

            List <Curve>[] openregions = skein.openRegions;

            List <Brep>[] rRegions    = skein.Regions;
            List <Brep>[] rPerimeterR = skein.regionPerimeter;
            List <Brep>[] rInfillR    = skein.regionInfill;

            GH_Structure <GH_Brep> Regions = new GH_Structure <GH_Brep>();

            GH_Structure <GH_Curve> openRegions = new GH_Structure <GH_Curve>();


            #region Add Regions to GH_Structure

            if (rRegions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rRegions.Length; i++)
                {
                    if (rRegions[i] != null)
                    {
                        for (int j = 0; j < rRegions[i].Count; j++)
                        {
                            GH_Brep gShapes = new GH_Brep(rRegions[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 0), j);
                        }
                    }
                }
            }
            if (rPerimeterR.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rPerimeterR.Length; i++)
                {
                    if (rPerimeterR[i] != null)
                    {
                        for (int j = 0; j < rPerimeterR[i].Count; j++)
                        {
                            GH_Brep gShapes = new GH_Brep(rPerimeterR[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 1), j);
                        }
                    }
                }
            }
            if (rInfillR.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < rInfillR.Length; i++)
                {
                    if (rInfillR[i] != null)
                    {
                        for (int j = 0; j < rInfillR[i].Count; j++)
                        {
                            GH_Brep gShapes = new GH_Brep(rInfillR[i][j]);
                            Regions.Insert(gShapes, new GH_Path(i, 2), j);
                        }
                    }
                }
            }

            if (openregions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < openregions.Length; i++)
                {
                    if (openregions[i] != null)
                    {
                        for (int j = 0; j < openregions[i].Count; j++)
                        {
                            GH_Curve gShapes = new GH_Curve(openregions[i][j]);
                            openRegions.Insert(gShapes, new GH_Path(i), j);
                        }
                    }
                }
            }
            //TODO
            //Add Overhang and Bridges

            #endregion


            #region Add Open Regions to GH_Structure
            if (openregions.GetUpperBound(0) > 1)
            {
                for (int i = 0; i < openregions.Length; i++)
                {
                    for (int j = 0; j < openregions[i].Count; j++)
                    {
                        if (openregions[i][j] != null)
                        {
                            SilkwormSegment segment = new SilkwormSegment(openregions[i][j]);
                            Curve           curve   = segment.Pline.ToNurbsCurve();
                            GH_Curve        gShapes = new GH_Curve(curve);
                            openRegions.Insert(gShapes, new GH_Path(i), j);
                        }
                    }
                }
            }
            #endregion

            #region OUTPUT

            if (!DA.SetDataTree(0, Regions))
            {
                return;
            }
            if (!DA.SetDataTree(1, openRegions))
            {
                return;
            }

            #endregion
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GsaMember3d gsaMember3d = new GsaMember3d();

            if (DA.GetData(0, ref gsaMember3d))
            {
                if (gsaMember3d == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Member3D input is null");
                }
                GsaMember3d mem = gsaMember3d.Duplicate();

                // #### inputs ####

                // 1 ID
                GH_Integer ghID = new GH_Integer();
                if (DA.GetData(1, ref ghID))
                {
                    if (GH_Convert.ToInt32(ghID, out int id, GH_Conversion.Both))
                    {
                        mem.ID = id;
                    }
                }

                // 2 geometry
                GH_ObjectWrapper gh_typ = new GH_ObjectWrapper();
                if (DA.GetData(2, ref gh_typ))
                {
                    GsaMember3d tempMem = new GsaMember3d();
                    Brep        brep    = new Brep();
                    Mesh        mesh    = new Mesh();
                    if (GH_Convert.ToBrep(gh_typ.Value, ref brep, GH_Conversion.Both))
                    {
                        tempMem = new GsaMember3d(brep);
                    }
                    else if (GH_Convert.ToMesh(gh_typ.Value, ref mesh, GH_Conversion.Both))
                    {
                        tempMem = new GsaMember3d(mesh);
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert Geometry input to a 3D Member");
                        return;
                    }
                    mem.SolidMesh = tempMem.SolidMesh;
                }

                // 3 prop3d -- to be implemented GsaAPI
                gh_typ = new GH_ObjectWrapper();
                if (DA.GetData(3, ref gh_typ))
                {
                    if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both))
                    {
                        mem.Member.Property = idd;
                    }
                    //GsaProp3d prop3d = new GsaProp3d();
                    //if (gh_typ.Value is GsaProp3dGoo)
                    //    gh_typ.CastTo(ref prop3d);
                    //else
                    //{
                    //    if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both))
                    //        prop3d.ID = idd;
                    //    else
                    //    {
                    //        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert PA input to a 3D Property of reference integer");
                    //        return;
                    //    }
                    //}
                    //mem.Property = prop3d;
                }

                // 4 mesh size
                GH_Number ghmsz = new GH_Number();
                if (DA.GetData(4, ref ghmsz))
                {
                    if (GH_Convert.ToDouble(ghmsz, out double msz, GH_Conversion.Both))
                    {
                        mem.Member.MeshSize = msz;
                    }
                }

                // 5 mesh with others
                GH_Boolean ghbool = new GH_Boolean();
                if (DA.GetData(5, ref ghbool))
                {
                    if (GH_Convert.ToBoolean(ghbool, out bool mbool, GH_Conversion.Both))
                    {
                        //mem.member.MeshWithOthers
                    }
                }

                // 6 name
                GH_String ghnm = new GH_String();
                if (DA.GetData(6, ref ghnm))
                {
                    if (GH_Convert.ToString(ghnm, out string name, GH_Conversion.Both))
                    {
                        mem.Member.Name = name;
                    }
                }

                // 7 Group
                GH_Integer ghgrp = new GH_Integer();
                if (DA.GetData(7, ref ghgrp))
                {
                    if (GH_Convert.ToInt32(ghgrp, out int grp, GH_Conversion.Both))
                    {
                        mem.Member.Group = grp;
                    }
                }

                // 8 Colour
                GH_Colour ghcol = new GH_Colour();
                if (DA.GetData(8, ref ghcol))
                {
                    if (GH_Convert.ToColor(ghcol, out System.Drawing.Color col, GH_Conversion.Both))
                    {
                        mem.Member.Colour = col;
                    }
                }

                // 9 Dummy
                GH_Boolean ghdum = new GH_Boolean();
                if (DA.GetData(9, ref ghdum))
                {
                    if (GH_Convert.ToBoolean(ghdum, out bool dum, GH_Conversion.Both))
                    {
                        mem.Member.IsDummy = dum;
                    }
                }

                // #### outputs ####

                DA.SetData(0, new GsaMember3dGoo(mem));
                DA.SetData(1, mem.ID);
                DA.SetData(2, mem.SolidMesh);

                //DA.SetData(3, mem.Property);

                DA.SetData(4, mem.Member.MeshSize);
                //DA.SetData(5, mem.Member.MeshWithOthers);

                DA.SetData(6, mem.Member.Name);
                DA.SetData(7, mem.Member.Group);
                DA.SetData(8, mem.Member.Colour);
                DA.SetData(9, mem.Member.IsDummy);
            }
        }
Beispiel #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)
        {
            #region INPUTS
            // import silkwormSettings file
            List <string> silkwormSettings = new List <string>();
            if (!DA.GetDataList(0, silkwormSettings))
            {
                return;
            }

            // import raw Grasshopper Geometry to convert to Silkworm Movements
            List <GH_ObjectWrapper> MovementList = new List <GH_ObjectWrapper>();
            if (!DA.GetDataList(1, MovementList))
            {
                return;
            }

            int sorted = new int();
            if (!DA.GetData(2, ref sorted))
            {
                return;
            }
            #endregion
            #region Utilities

            //Utility to convert list of strings to Settings Dictionary
            SilkwormUtility             sUtil    = new SilkwormUtility();
            Dictionary <string, string> Settings = sUtil.convertSettings(silkwormSettings);
            #endregion

            double layerHeight   = double.Parse(Settings["layer_height"]);
            int    layerHeightDP = CountDecimalPlaces(layerHeight);

            #region Output Holders
            //GCode Lines
            List <GH_String> sGCode = new List <GH_String>();

            //Unsorted Movements
            List <SilkwormMovement> unMovements = new List <SilkwormMovement>();

            //Movements sorted by Layer
            List <SilkwormMovement>[] sMovements = new List <SilkwormMovement> [0];

            #endregion

            //Wrapper List for all types to Parse
            GH_ObjectWrapper[] Movement = MovementList.ToArray();

            //Switch sorting routine by input
            switch (sorted)
            {
            case 1:

                #region Unsorted (Sort Order of Movements by z then x and y)
                if (sorted == 1)
                {
                    //Parse
                    #region Parse Input Type

                    List <Brep> solids = new List <Brep>();
                    List <Mesh> meshes = new List <Mesh>();

                    //Incomplete Silkworm Movements
                    List <SilkwormMovement> incmovements = new List <SilkwormMovement>();

                    List <Brep>     shapes = new List <Brep>();
                    List <Curve>    curves = new List <Curve>();
                    List <Polyline> plines = new List <Polyline>();
                    List <Line>     lines  = new List <Line>();



                    for (int i = 0; i < Movement.Length; i++)
                    {
                        //Sort Types into Container Lists
                        #region IfNull
                        if ((Movement[i].Value == null))
                        {
                            continue;
                        }
                        #endregion

                        #region SilkwormMovement

                        else if ((Movement[i].Value is Silkworm.Type.SilkwormMovement))
                        {
                            SilkwormMovement aMovement = (SilkwormMovement)Movement[i].Value;

                            if (aMovement.complete)
                            {
                                aMovement.Configuration = Settings;     //make sure it has a config field
                                unMovements.Add(aMovement);
                                continue;
                            }
                            else
                            {
                                incmovements.Add(aMovement);
                                continue;
                            }
                        }
                        #endregion
                        #region Solids
                        else if (Movement[i].Value is GH_Brep)
                        {
                            Brep solid = null;
                            GH_Convert.ToBrep(Movement[i].Value, ref solid, GH_Conversion.Both);
                            solids.Add(solid);
                            continue;
                        }
                        else if (Movement[i].Value is GH_Mesh)
                        {
                            Mesh mesh = null;
                            GH_Convert.ToMesh(Movement[i].Value, ref mesh, GH_Conversion.Both);
                            meshes.Add(mesh);
                            continue;
                        }

                        #endregion
                        #region Regions
                        //TODO
                        #endregion
                        #region Curves
                        else if (Movement[i].Value is GH_Curve)
                        {
                            Curve curve = null;
                            GH_Convert.ToCurve(Movement[i].Value, ref curve, GH_Conversion.Both);
                            curves.Add(curve);
                            continue;
                        }

                        #endregion


                        #region SilkwormLine
                        else if (Movement[i].Value is SilkwormLine)
                        {
                            List <SilkwormLine> slines = new List <SilkwormLine>();
                            slines.Add((SilkwormLine)Movement[i].Value);

                            //Check if complete
                            if (isCompleteLine((SilkwormLine)Movement[i].Value))
                            {
                                unMovements.Add(new SilkwormMovement(slines, new Delimiter()));
                            }
                            else
                            {
                                incmovements.Add(new SilkwormMovement(slines, new Delimiter()));
                            }
                            continue;
                        }

                        #endregion
                        #region Line

                        else if (Movement[i].Value is GH_Line)
                        {
                            Line line = new Line();
                            GH_Convert.ToLine(Movement[i].Value, ref line, GH_Conversion.Both);
                            lines.Add(line);

                            continue;
                        }

                        #endregion
                        #region Point
                        else if (Movement[i].Value is GH_Point)
                        {
                            //TODO
                            continue;
                        }

                        #endregion

                        #region Not Supported
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Datatype Not Supported!");
                            continue;
                        }
                        #endregion
                        #endregion
                    }
                    //Build Movements from Incomplete Parts
                    #region Build Movement

                    #region List<Brep>Add to unMovements

                    if (solids.Count > 0)
                    {
                        List <SilkwormMovement> solidMovements = addsolidBrep(Settings, solids);

                        unMovements.AddRange(solidMovements);
                    }

                    #endregion

                    #region List<Mesh> Add to unMovements
                    //TODO
                    #endregion

                    #region List<Shapes> Add to unMovements
                    //TODO

                    #endregion

                    #region List<Curve> Add to unMovements
                    foreach (Curve curve in curves)
                    {
                        SilkwormMovement movement = new SilkwormMovement(Settings, curve);
                        unMovements.Add(movement);
                    }
                    #endregion

                    #region List<Line> Add to unMovements

                    foreach (Line line in lines)
                    {
                        List <Line> _lines = new List <Line>();
                        _lines.Add(line);
                        unMovements.Add(new SilkwormMovement(Settings, _lines));
                    }
                    #endregion


                    #region List<IncompleteSilkwormMovement> Add to unMovements
                    foreach (SilkwormMovement movement in incmovements)
                    {
                        unMovements.Add(completeMovement(Settings, movement));;
                        continue;
                    }

                    #endregion

                    #endregion
                }
                goto SortZ;
                #endregion
                break;

            case 2:
                #region Partially Sorted (Sort Movements by z only)

                if (sorted == 2)
                {
                    for (int u = 0; u < Movement.Length; u++)
                    {
                        #region IfNull
                        if ((Movement[u].Value == null))
                        {
                            continue;
                        }
                        #endregion

                        #region SilkwormMovement

                        else if ((Movement[u].Value is Silkworm.Type.SilkwormMovement))
                        {
                            SilkwormMovement aMovement = (SilkwormMovement)Movement[u].Value;

                            if (aMovement.complete)
                            {
                                aMovement.Configuration = Settings;     //make sure it has a config field
                                unMovements.Add(aMovement);
                                continue;
                            }
                            else
                            {
                                unMovements.Add(completeMovement(Settings, aMovement));
                                continue;
                            }
                        }
                        #endregion
                        #region Solids
                        else if (Movement[u].Value is GH_Brep)
                        {
                            Brep        solid  = null;
                            List <Brep> solids = new List <Brep>();

                            GH_Convert.ToBrep(Movement[u].Value, ref solid, GH_Conversion.Both);
                            solids.Add(solid);

                            List <SilkwormMovement> solidMovements = addsolidBrep(Settings, solids);

                            unMovements.AddRange(solidMovements);

                            continue;
                        }
                        else if (Movement[u].Value is GH_Mesh)
                        {
                            Mesh mesh = null;
                            GH_Convert.ToMesh(Movement[u].Value, ref mesh, GH_Conversion.Both);

                            continue;
                        }

                        #endregion
                        #region Regions
                        //TODO
                        #endregion
                        #region Curves
                        else if (Movement[u].Value is GH_Curve)
                        {
                            Curve curve = null;
                            GH_Convert.ToCurve(Movement[u].Value, ref curve, GH_Conversion.Both);
                            SilkwormMovement movement = new SilkwormMovement(Settings, curve);
                            unMovements.Add(movement);
                            continue;
                        }

                        #endregion


                        #region SilkwormLine
                        else if (Movement[u].Value is SilkwormLine)
                        {
                            List <SilkwormLine> s_lines = new List <SilkwormLine>();
                            s_lines.Add((SilkwormLine)Movement[u].Value);

                            //Check if complete
                            if (isCompleteLine((SilkwormLine)Movement[u].Value))
                            {
                                unMovements.Add(new SilkwormMovement(s_lines, new Delimiter()));
                            }
                            else
                            {
                                List <Line> lines = new List <Line>();

                                SilkwormLine[] s_Movement = new SilkwormLine[s_lines.Count];


                                foreach (SilkwormLine line in s_lines)
                                {
                                    lines.Add(line.sLine);
                                }

                                List <SilkwormLine> sLines = new SilkwormMovement(Settings, lines).sMovement;

                                List <SilkwormLine> Movements = new List <SilkwormLine>();

                                //Complete Movements
                                for (int j = 0; j < sLines.Count; j++)
                                {
                                    if (s_Movement[j].Flow == -1)
                                    {
                                        s_Movement[j].Flow = sLines[j].Flow;
                                    }
                                    if (s_Movement[j].Speed == -1)
                                    {
                                        s_Movement[j].Speed = sLines[j].Speed;
                                    }
                                    Movements.Add(s_Movement[j]);
                                }

                                SilkwormMovement newMovement = new SilkwormMovement(Movements, new Delimiter());

                                //Add Configuration
                                newMovement.Configuration = Settings;

                                unMovements.Add(newMovement);
                            }
                            continue;
                        }

                        #endregion
                        #region Line

                        else if (Movement[u].Value is GH_Line)
                        {
                            Line line = new Line();
                            GH_Convert.ToLine(Movement[u].Value, ref line, GH_Conversion.Both);
                            List <Line> _lines = new List <Line>();
                            _lines.Add(line);
                            unMovements.Add(new SilkwormMovement(Settings, _lines));

                            continue;
                        }


                        #endregion
                        #region Point
                        else if (Movement[u].Value is GH_Point)
                        {
                            //TODO
                            continue;
                        }

                        #endregion

                        #region Not Supported
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Datatype Not Supported!");
                            continue;
                        }
                    }
                    #endregion
                }
                goto SortZ;
                #endregion
                break;

            case 3:
                #region Completely Sorted
                if (sorted == 3)
                {
                    //Initialise sMovements
                    sMovements    = new List <SilkwormMovement> [1];
                    sMovements[0] = new List <SilkwormMovement>();


                    for (int u = 0; u < Movement.Length; u++)
                    {
                        #region IfNull
                        if ((Movement[u].Value == null))
                        {
                            continue;
                        }
                        #endregion

                        #region SilkwormMovement

                        else if ((Movement[u].Value is Silkworm.Type.SilkwormMovement))
                        {
                            SilkwormMovement aMovement = (SilkwormMovement)Movement[u].Value;

                            if (aMovement.complete)
                            {
                                aMovement.Configuration = Settings;     //Make sure it has a config field
                                sMovements[0].Add(aMovement);
                                continue;
                            }
                            else
                            {
                                sMovements[0].Add(completeMovement(Settings, aMovement));

                                //sMovements[0].Add(new SilkwormMovement(Movements, new Delimiter()));
                                continue;
                            }
                        }
                        #endregion
                        #region Solids
                        else if (Movement[u].Value is GH_Brep)
                        {
                            Brep        solid  = null;
                            List <Brep> solids = new List <Brep>();

                            GH_Convert.ToBrep(Movement[u].Value, ref solid, GH_Conversion.Both);
                            solids.Add(solid);
                            List <SilkwormMovement> solidMovements = addsolidBrep(Settings, solids);

                            sMovements[0].AddRange(solidMovements);

                            continue;
                        }
                        else if (Movement[u].Value is GH_Mesh)
                        {
                            Mesh mesh = null;
                            GH_Convert.ToMesh(Movement[u].Value, ref mesh, GH_Conversion.Both);

                            continue;
                        }

                        #endregion
                        #region Regions
                        //TODO
                        #endregion
                        #region Curves
                        else if (Movement[u].Value is GH_Curve)
                        {
                            Curve curve = null;
                            GH_Convert.ToCurve(Movement[u].Value, ref curve, GH_Conversion.Both);
                            SilkwormMovement movement = new SilkwormMovement(Settings, curve);
                            sMovements[0].Add(movement);
                            continue;
                        }

                        #endregion


                        #region SilkwormLine
                        else if (Movement[u].Value is SilkwormLine)
                        {
                            List <SilkwormLine> s_lines = new List <SilkwormLine>();
                            s_lines.Add((SilkwormLine)Movement[u].Value);

                            //Check if complete
                            if (isCompleteLine((SilkwormLine)Movement[u].Value))
                            {
                                sMovements[0].Add(new SilkwormMovement(s_lines, new Delimiter()));
                            }
                            else
                            {
                                List <Line> lines = new List <Line>();

                                SilkwormLine[] s_Movement = new SilkwormLine[s_lines.Count];


                                foreach (SilkwormLine line in s_lines)
                                {
                                    lines.Add(line.sLine);
                                }

                                List <SilkwormLine> sLines = new SilkwormMovement(Settings, lines).sMovement;

                                List <SilkwormLine> Movements = new List <SilkwormLine>();

                                //Complete Movements
                                for (int j = 0; j < sLines.Count; j++)
                                {
                                    if (s_Movement[j].Flow == -1)
                                    {
                                        s_Movement[j].Flow = sLines[j].Flow;
                                    }
                                    if (s_Movement[j].Speed == -1)
                                    {
                                        s_Movement[j].Speed = sLines[j].Speed;
                                    }
                                    Movements.Add(s_Movement[j]);
                                }

                                SilkwormMovement newMovement = new SilkwormMovement(Movements, new Delimiter());

                                //Add Configuration
                                newMovement.Configuration = Settings;

                                sMovements[0].Add(newMovement);
                            }
                            continue;
                        }

                        #endregion
                        #region Line

                        else if (Movement[u].Value is GH_Line)
                        {
                            Line line = new Line();
                            GH_Convert.ToLine(Movement[u].Value, ref line, GH_Conversion.Both);
                            List <Line> _lines = new List <Line>();
                            _lines.Add(line);
                            sMovements[0].Add(new SilkwormMovement(Settings, _lines));

                            continue;
                        }

                        #endregion
                        #region Point
                        else if (Movement[u].Value is GH_Point)
                        {
                            //TODO
                            continue;
                        }

                        #endregion

                        #region Not Supported
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Datatype Not Supported!");
                            continue;
                        }
                    }
                    #endregion
                }
                goto Compiler;
                #endregion
                break;

            default:
                break;
            }

            #region ss
            ////Parse
            //#region Parse Input Type

            //List<Brep> solids = new List<Brep>();
            //List<Mesh> meshes = new List<Mesh>();

            ////Incomplete Silkworm Movements
            //List<SilkwormMovement> incmovements = new List<SilkwormMovement>();

            //List<Brep> shapes = new List<Brep>();
            //List<Curve> curves = new List<Curve>();
            //List<Polyline> plines = new List<Polyline>();
            //List<Line> lines = new List<Line>();



            //for (int i = 0; i < Movement.Length; i++)
            //{

            ////Sort Types into Container Lists
            //    #region IfNull
            //    if ((Movement[i].Value == null))
            //    { continue; }
            //    #endregion

            //#region SilkwormMovement

            //if ((Movement[i].Value is Silkworm.Type.SilkwormMovement))
            //{


            //    SilkwormMovement aMovement = (SilkwormMovement)Movement[i].Value;

            //    if(aMovement.complete)
            //    {
            //        unMovements.Add(aMovement);
            //        continue;
            //    }
            //    else
            //    {
            //        incmovements.Add(aMovement);
            //        continue;
            //    }

            //}
            //#endregion
            //#region Solids
            //if (Movement[i].Value is GH_Brep)
            //{
            //    Brep solid = null;
            //    GH_Convert.ToBrep(Movement[i].Value, ref solid, GH_Conversion.Both);
            //    solids.Add(solid);
            //    continue;
            //}
            //if (Movement[i].Value is GH_Mesh)
            //{
            //    Mesh mesh = null;
            //    GH_Convert.ToMesh(Movement[i].Value, ref mesh, GH_Conversion.Both);
            //    meshes.Add(mesh);
            //    continue;
            //}

            //#endregion
            //#region Regions
            ////TODO
            //#endregion
            //#region Curves
            //if (Movement[i].Value is GH_Curve)
            //{
            //    Curve curve = null;
            //    GH_Convert.ToCurve(Movement[i].Value, ref curve, GH_Conversion.Both);
            //    curves.Add(curve);
            //    continue;
            //}

            //#endregion


            //#region SilkwormLine
            //if (Movement[i].Value is SilkwormLine)
            //{
            //    List<SilkwormLine> slines = new List<SilkwormLine>();
            //    slines.Add((SilkwormLine)Movement[i].Value);

            //    //Check if complete
            //    if (isCompleteLine((SilkwormLine)Movement[i].Value))
            //    {
            //        unMovements.Add(new SilkwormMovement(slines, true));
            //    }
            //    else
            //    {
            //        incmovements.Add(new SilkwormMovement(slines, true));
            //    }
            //    continue;
            //}

            //#endregion
            //#region Line

            //    if (Movement[i].Value is GH_Line)
            //{

            //    Line line = new Line();
            //    GH_Convert.ToLine(Movement[i].Value, ref line, GH_Conversion.Both);
            //    lines.Add(line);

            //}

            //#endregion
            //#region Point
            //    if (Movement[i].Value is GH_Point)
            //{
            // //TODO
            //    continue;
            //}

            //#endregion

            //else
            //{
            //    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Datatype Not Supported!");
            //    continue;
            //}
            //#endregion

            //}
            ////Build Movements from Incomplete Parts
            //#region Build Movement

            //#region List<Brep>Add to unMovements

            //    //List<Brep> solidS = new List<Brep>();
            //    //solidS.Add((Brep)solid);

            //    List<Polyline>[] rPerimeter = new List<Polyline>[0];
            //    List<Polyline>[] rInfill = new List<Polyline>[0];

            //    //Slice, Skin and Fill Breps (TODO: Add Bridge Finder)
            //    SilkwormSkein skein = new SilkwormSkein(Settings, solids);

            //    if (skein.validPos)
            //    {
            //        rPerimeter = skein.plinePerimeter;
            //        rInfill = skein.plineInfill;
            //    }

            //    List<SilkwormMovement> solidMovements = new List<SilkwormMovement>();

            //    //Add to ORGANISED List of Movements (i.e. Model)
            //    for (int b = 0; b <= rPerimeter.GetUpperBound(0); b++)
            //    {
            //        foreach (Polyline pline in rPerimeter[b])
            //        {
            //            //List<SilkwormMovement> sList = new List<SilkwormMovement>();
            //            //sList.Add(new SilkwormMovement(Settings, pline, true));
            //            solidMovements.Add(new SilkwormMovement(Settings, pline, true));
            //        }
            //        foreach (Polyline pline in rInfill[b])
            //        {
            //            //List<SilkwormMovement> sList = new List<SilkwormMovement>();
            //            //sList.Add(new SilkwormMovement(Settings, pline, true));
            //            solidMovements.Add(new SilkwormMovement(Settings, pline, true));
            //        }
            //    }


            //    unMovements.AddRange(solidMovements);

            //#endregion

            //#region List<Mesh> Add to unMovements
            ////TODO
            //#endregion

            //#region List<Shapes> Add to unMovements
            ////TODO

            //#endregion

            //#region List<Curve> Add to unMovements
            //foreach (Curve curve in curves)
            //{
            //    SilkwormMovement movement = new SilkwormMovement(Settings, curve, true);
            //    unMovements.Add(movement);
            //}
            //#endregion

            //#region List<Line> Add to unMovements

            //foreach (Line line in lines)
            //{
            //    List<Line> _lines = new List<Line>();
            //    _lines.Add(line);
            //    unMovements.Add(new SilkwormMovement(Settings, _lines, true));

            //}
            //#endregion


            //#region List<IncompleteSilkwormMovement> Add to unMovements
            //foreach (SilkwormMovement movement in incmovements)
            //    {



            //            List<Line> lines = new List<Line>();

            //            SilkwormLine[] s_Movement = new SilkwormLine[movement.Count];


            //            foreach (SilkwormLine line in movement)

            //            {

            //                lines.Add(line.Curve);

            //            }

            //    List<SilkwormLine> sLines = new SilkwormMovement(Settings, lines,true).sMovement;

            //    List<SilkwormLine> Movements = new List<SilkwormLine>();

            //    //Complete Movements
            //    for (int j = 0; j < sLines.Count; j++)
            //    {
            //        if (s_Movement[j].Flow == -1)
            //        {
            //            s_Movement[j].Flow = sLines[j].Flow;
            //        }
            //        if (s_Movement[j].Speed == -1)
            //        {
            //            s_Movement[j].Speed = sLines[j].Speed;
            //        }
            //        Movements.Add(s_Movement[j]);
            //    }

            //    //Add Configuration
            //    movement.Configuration = Settings;

            //    unMovements.Add(new SilkwormMovement(Movements, true));
            //    continue;



            //}

            //#endregion

            //#endregion
            #endregion

            //Sort Unorganised Movements into Layered Model
SortZ:
            #region Build Model

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

            //Find Unique ZValues
            uniqueZ.AddRange(FindUniqueZValues(unMovements, layerHeightDP));


            //Sort List of Unique Z Levels
            uniqueZ.Sort();

            //Make Dictionary from List of Unique Z Levels
            Dictionary <double, int> ZLevel = new Dictionary <double, int>();
            for (int d = 0; d < uniqueZ.Count; d++)
            {
                ZLevel.Add(uniqueZ[d], d);
            }

            //Initialise Array of Lists
            sMovements = new List <SilkwormMovement> [uniqueZ.Count];
            for (int a = 0; a < sMovements.Length; a++)
            {
                sMovements[a] = new List <SilkwormMovement>();
            }
            //Sort Silkworm Movements into correct layers in Array of Lists
            foreach (SilkwormMovement movement in unMovements)
            {
                sMovements[ZLevel[Math.Round(movement.ZDomain.T0, layerHeightDP)]].Add(movement);
            }

            #endregion
            goto Compiler;

            //Compile Model to GCode
Compiler:
            #region GCode Compiler
            #region HEADER
            //Add Custom Commands at Start
            string header = Settings["start_gcode"];

            //Char[] splitChar = new Char[] {'\\','\n', 'n'};
            string[] splitChar = new string[] { "\\n" };
            string[] parts     = header.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);

            if (parts != null)
            {
                for (int i = 0; i < parts.Length; i++)
                {
                    sGCode.Add(new GH_String(parts[i]));
                }
            }
            else
            {
                sGCode.Add(new GH_String(header));
            }

            if (int.Parse(Settings["absolute_extrudersteps"]) == 1) //if true use absolute distances for extrusion, otherwise use relative
            {
                sGCode.Add(new GH_String("M82 ; use absolute distances for extrusion"));
            }

            sGCode.Add(new GH_String("G90 ; use absolute coordinates"));
            sGCode.Add(new GH_String("G21 ; set units to millimeters"));
            sGCode.Add(new GH_String("G92 E0 ; reset extrusion distance"));


            //Set Temperature
            double temp = double.Parse(Settings["temperature"]);
            sGCode.Add(new GH_String("M104 S" + temp + " ; set temperature"));
            sGCode.Add(new GH_String("M109 S" + temp + " ; wait for temperature to be reached"));

            //Extrude a bit of plastic before start
            sGCode.Add(new GH_String("G1 Z0.0 F360 E1"));
            #endregion

            for (int z = 0; z <= sMovements.GetUpperBound(0); z++)
            {
                foreach (SilkwormMovement movement in sMovements[z])
                {
                    sGCode.AddRange(movement.ToGCode());
                }
            }



            #region FOOTER

            sGCode.Add(new GH_String("G92 E0 ; reset extrusion distance"));

            //Add Custom Commands at End
            string footer = Settings["end_gcode"];

            string[] fparts = footer.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);

            if (fparts != null)
            {
                for (int i = 0; i < fparts.Length; i++)
                {
                    sGCode.Add(new GH_String(fparts[i]));
                }
            }
            else
            {
                sGCode.Add(new GH_String(footer));
            }

            #endregion

            ////Convert Array of Movements to List
            //List<SilkwormMovement> outMovements = new List<SilkwormMovement>();
            //for (int l = 0; l < sMovements.GetUpperBound(0); l++)
            //{
            //    outMovements.AddRange(sMovements[l]);
            //}
            #endregion

            #region Silkworm Model
            List <SilkwormMovement> s_Model = new List <SilkwormMovement>();
            for (int p = 0; p <= sMovements.GetUpperBound(0); p++)
            {
                for (int s = 0; s < sMovements[p].Count; s++)
                {
                    s_Model.Add(sMovements[p][s]);
                }
            }
            List <SilkwormModel> sModel = new List <SilkwormModel>();
            sModel.Add(new SilkwormModel(Settings, s_Model));
            #endregion

            //Output GCode and Model
            #region OUTPUTS

            DA.SetDataList(0, sGCode);
            DA.SetDataList(1, sModel);

            #endregion
        }
Beispiel #14
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)
        {
            List <Plane> camPlanes = new List <Plane>();

            DA.GetDataList <Plane>(0, camPlanes);

            string folder = string.Empty;

            DA.GetData <string>(1, ref folder);
            bool saveCubemaps = !string.IsNullOrEmpty(folder);

            if (saveCubemaps)
            {
                folder = Path.GetFullPath(folder);
                if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    folder += Path.DirectorySeparatorChar;
                }
            }

            string prefix = string.Empty;

            DA.GetData <string>(2, ref prefix);

            int imageWidth = 0;

            DA.GetData <int>(3, ref imageWidth);
            imageWidth = imageWidth / 4;
            Size size = new Size(imageWidth, imageWidth);

            string displayMode = string.Empty;

            DA.GetData <string>(4, ref displayMode);

            List <Color> colors = new List <Color>();

            DA.GetDataList <Color>(5, colors);
            bool filterColors = colors.Any();

            GH_Structure <GH_Mesh> ghObstacles = new GH_Structure <GH_Mesh>();

            DA.GetDataTree <GH_Mesh>(6, out ghObstacles);

            ///Flatten obstacle meshes and join them into one mesh
            ghObstacles.FlattenData();
            Mesh obstacles = new Mesh();
            bool showRays  = false;

            if (ghObstacles.DataCount > 0)
            {
                showRays = true;
                foreach (var obstacle in ghObstacles)
                {
                    Mesh temp = new Mesh();
                    GH_Convert.ToMesh(obstacle, ref temp, GH_Conversion.Primary);
                    obstacles.Append(temp);
                }
            }


            bool run = false;

            DA.GetData <bool>(7, ref run);

            int pad = camPlanes.Count.ToString().Length;

            List <string> cubemaps = new List <string>();

            GH_Structure <GH_Line>   rayTree   = new GH_Structure <GH_Line>();
            GH_Structure <GH_Colour> colorTree = new GH_Structure <GH_Colour>();

            ///Save the intial camera
            saveCam = camFromVP(Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);

            ///Set the display mode to be used for bitmaps
            ///TODO: Add menu item to use "Heron View Analysis" display mode
            DisplayModeDescription viewMode = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode;

            if (DisplayModeDescription.FindByName(displayMode) != null)
            {
                viewMode = DisplayModeDescription.FindByName(displayMode);
            }

            Message = viewMode.EnglishName;

            if (run)
            {
                for (int i = 0; i < camPlanes.Count; i++)
                {
                    ///TODO: setup ability to save cameras to the Rhino doc
                    ///Setup camera
                    Rhino.Display.RhinoView     view = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView;
                    Rhino.Display.RhinoViewport vp   = view.ActiveViewport;

                    ///Get the bounding box of all visible object in the doc for use in setting up the camera
                    ///target so that the far frustrum plane doesn't clip anything
                    double zoomDistance = Rhino.RhinoDoc.ActiveDoc.Objects.BoundingBoxVisible.Diagonal.Length;

                    Plane    camPlane = camPlanes[i];
                    Point3d  camPoint = camPlane.Origin;
                    Vector3d camDir   = camPlane.YAxis;
                    Point3d  tarPoint = Transform.Translation(camDir * zoomDistance / 2) * camPoint;


                    vp.ChangeToPerspectiveProjection(false, 12.0);
                    vp.Size        = size;
                    vp.DisplayMode = viewMode;
                    //view.Redraw();

                    ///Set up final bitmap
                    Bitmap cubemap = new Bitmap(imageWidth * 4, imageWidth * 3);

                    ///Place the images on cubemap bitmap
                    using (Graphics gr = Graphics.FromImage(cubemap))
                    {
                        ///Grab bitmap

                        ///Set up camera directions
                        Point3d        tarLeft    = Transform.Translation(-camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d        tarFront   = Transform.Translation(camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d        tarRight   = Transform.Translation(camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d        tarBack    = Transform.Translation(-camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d        tarUp      = Transform.Translation(camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        Point3d        tarDown    = Transform.Translation(-camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        List <Point3d> camTargets = new List <Point3d>()
                        {
                            tarLeft, tarFront, tarRight, tarBack, tarUp, tarDown
                        };

                        ///Loop through pano directions
                        int insertLoc = 0;
                        for (int d = 0; d < 4; d++)
                        {
                            ///Set camera direction
                            vp.SetCameraLocations(camTargets[d], camPoint);
                            //view.Redraw();

                            Bitmap bitmap = new Bitmap(view.CaptureToBitmap(size, viewMode));

                            if (saveCubemaps)
                            {
                                gr.DrawImage(bitmap, insertLoc, imageWidth);
                            }

                            if (showRays)
                            {
                                GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmap);
                                Color           col     = Color.Transparent;
                                for (int x = 0; x < bitmap.Width; x++)
                                {
                                    for (int y = 0; y < bitmap.Height; y++)
                                    {
                                        if (sampler.Sample(x, y, ref col))
                                        {
                                            if (colors.Contains(col))
                                            {
                                                GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                                Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                                Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                                double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                                Point3d rayIntersection = ray.PointAt(rayEnd);
                                                Line    ln = new Line(camPoint, rayIntersection);

                                                if (ln.IsValid & rayEnd > 0)
                                                {
                                                    rayTree.Append(new GH_Line(ln), path);
                                                    colorTree.Append(new GH_Colour(col), path);
                                                }
                                            }
                                            else if (!filterColors)
                                            {
                                                colors.Add(col);
                                                GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                                Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                                Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                                double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                                Point3d rayIntersection = ray.PointAt(rayEnd);
                                                Line    ln = new Line(camPoint, rayIntersection);

                                                if (ln.IsValid & rayEnd > 0)
                                                {
                                                    rayTree.Append(new GH_Line(ln), path);
                                                    colorTree.Append(new GH_Colour(col), path);
                                                }
                                            }
                                        }
                                    }
                                }
                                sampler.Release(false);
                            }

                            insertLoc = insertLoc + imageWidth;

                            bitmap.Dispose();
                        }


                        ///Get up and down views

                        ///Get up view
                        vp.SetCameraLocations(tarUp, camPoint);
                        view.Redraw();

                        Bitmap bitmapUp = new Bitmap(view.CaptureToBitmap(size, viewMode));

                        if (showRays)
                        {
                            GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmapUp);
                            Color           col     = Color.Transparent;
                            for (int x = 0; x < bitmapUp.Width; x++)
                            {
                                for (int y = 0; y < bitmapUp.Height; y++)
                                {
                                    if (sampler.Sample(x, y, ref col))
                                    {
                                        if (colors.Contains(col))
                                        {
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line    ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }
                                        }
                                        else if (!filterColors)
                                        {
                                            colors.Add(col);
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line    ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }
                                        }
                                    }
                                }
                            }
                            sampler.Release(false);
                        }

                        bitmapUp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        if (saveCubemaps)
                        {
                            gr.DrawImage(bitmapUp, imageWidth, 0);
                        }

                        bitmapUp.Dispose();


                        ///Get down view
                        vp.SetCameraLocations(tarDown, camPoint);
                        view.Redraw();

                        Bitmap bitmapDown = new Bitmap(view.CaptureToBitmap(size, viewMode));

                        if (saveCubemaps)
                        {
                            gr.DrawImage(bitmapDown, imageWidth, imageWidth * 2);
                        }

                        if (showRays)
                        {
                            GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmapDown);
                            Color           col     = Color.Transparent;
                            for (int x = 0; x < bitmapDown.Width; x++)
                            {
                                for (int y = 0; y < bitmapDown.Height; y++)
                                {
                                    if (sampler.Sample(x, y, ref col))
                                    {
                                        if (colors.Contains(col))
                                        {
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line    ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }
                                        }

                                        else if (!filterColors)
                                        {
                                            colors.Add(col);
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d   ray             = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double  rayEnd          = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line    ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }
                                        }
                                    }
                                }
                            }
                            sampler.Release(false);
                        }

                        bitmapDown.Dispose();
                    }
                    ///End pano directions loop

                    if (saveCubemaps)
                    {
                        ///Save cubemap bitmap
                        string s        = i.ToString().PadLeft(pad, '0');
                        string saveText = folder + prefix + "_" + s + ".png";
                        cubemap.Save(saveText, System.Drawing.Imaging.ImageFormat.Png);
                        cubemaps.Add(saveText);
                    }
                    cubemap.Dispose();
                }
            }

            ///Restore initial camera
            setCamera(saveCam, Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();

            DA.SetDataList(0, cubemaps);
            DA.SetDataTree(1, rayTree);
            DA.SetDataTree(2, colorTree);
        }
        /// <summary>
        /// Updates the geometry for an input chromosome
        /// </summary>
        /// <param name="chromo">The chromosome used to get geometry from the gh canvas</param>
        /// <returns></returns>
        public int GetGeometry(Chromosome chromo)
        {
            // Collect the object at the current instance
            List <object> localObjs = new List <object>();

            // Thank you Dimitrie :)
            foreach (IGH_Param param in Params.Input[1].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true)) // AllData flattens the tree
                {
                    localObjs.Add(myObj);
                }
            }

            // Gets lists of different geometry
            List <Mesh>          meshGeometry = new List <Mesh>();
            List <PolylineCurve> polyGeometry = new List <PolylineCurve>();

            // Get only mesh geometry from the object list
            for (int i = 0; i < localObjs.Count; i++)
            {
                // Need to replace with a Switch

                if (localObjs[i] is GH_Mesh)
                {
                    GH_Mesh myGHMesh = new GH_Mesh();
                    myGHMesh = (GH_Mesh)localObjs[i];
                    Mesh myLocalMesh = new Mesh();
                    GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                    myLocalMesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(myLocalMesh);

                    //Mesh joinedMesh = new Mesh();
                    //joinedMesh.Append(myLocalMesh);
                }

                if (localObjs[i] is GH_Brep)
                {
                    GH_Brep myBrep = new GH_Brep();
                    myBrep = (GH_Brep)localObjs[i];

                    Mesh[] meshes = Mesh.CreateFromBrep(myBrep.Value, MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Box)
                {
                    GH_Box myBox  = new GH_Box((GH_Box)localObjs[i]);
                    Mesh[] meshes = Mesh.CreateFromBrep(myBox.Brep(), MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Surface)
                {
                    GH_Surface mySurface = (GH_Surface)localObjs[i];

                    Mesh[] meshes = Mesh.CreateFromBrep(mySurface.Value, MeshingParameters.FastRenderMesh);

                    Mesh mesh = new Mesh();
                    mesh.Append(meshes);
                    mesh.Faces.ConvertQuadsToTriangles();

                    meshGeometry.Add(mesh);
                }

                if (localObjs[i] is GH_Curve)
                {
                    GH_Curve      myGHCurve = (GH_Curve)localObjs[i];
                    PolylineCurve myPoly    = myGHCurve.Value.ToPolyline(0, 0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, true);
                    polyGeometry.Add(myPoly);
                }

                if (localObjs[i] is GH_Arc)
                {
                    GH_Arc        myGHArc = (GH_Arc)localObjs[i];
                    PolylineCurve myPoly  = myGHArc.Value.ToNurbsCurve().ToPolyline(0, 0, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, true);
                    polyGeometry.Add(myPoly);
                }

                if (localObjs[i] is GH_Line)
                {
                    GH_Line        myGHLine = (GH_Line)localObjs[i];
                    List <Point3d> pts      = new List <Point3d> {
                        myGHLine.Value.From, myGHLine.Value.To
                    };
                    PolylineCurve myPoly = new PolylineCurve(pts);
                    polyGeometry.Add(myPoly);
                }
            }

            // Get performance data
            List <double> performas = new List <double>();
            List <string> criteria  = new List <string>();

            // Cap at eight criteria max.
            int pCount        = 0;
            int repeatCounter = 1;

            foreach (IGH_Param param in Params.Input[2].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true))
                {
                    if (myObj is GH_Number && pCount < 8)
                    {
                        GH_Number temp = (GH_Number)myObj;
                        performas.Add(temp.Value);

                        if (!criteria.Contains(param.NickName))
                        {
                            criteria.Add(param.NickName);
                        }

                        else
                        {
                            criteria.Add(param.NickName + " (" + repeatCounter + ")");
                            repeatCounter++;
                        }

                        pCount++;
                    }

                    else if (myObj is GH_Integer && pCount < 8)
                    {
                        GH_Integer temp = (GH_Integer)myObj;
                        performas.Add((double)temp.Value);

                        if (!criteria.Contains(param.NickName))
                        {
                            criteria.Add(param.NickName);
                        }

                        else
                        {
                            criteria.Add(param.NickName + " (" + repeatCounter + ")");
                            repeatCounter++;
                        }

                        pCount++;
                    }
                }
            }

            // Set the phenotype within the chromosome class
            chromo.SetPhenotype(meshGeometry, polyGeometry, performas, criteria);

            // Return the number of performance criteria
            return(performas.Count);
        }
Beispiel #16
0
        /// <summary>
        /// Grasshopper solve method
        /// </summary>
        /// <param name="DA"></param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // If we are currently static, then reset things and collect sliders
            if (!GO)
            {
                // Spring clean
                counter = 0;
                sliders.Clear();
                persGeo.Clear();
                sliderValues.Clear();

                DA.GetData("PopSize", ref popSize);

                // Collect the sliders up (just one at the moment)
                foreach (IGH_Param param in this.Params.Input[0].Sources)
                {
                    Grasshopper.Kernel.Special.GH_NumberSlider slider = param as Grasshopper.Kernel.Special.GH_NumberSlider;
                    if (slider != null)
                    {
                        sliders.Add(slider);
                    }
                }


                // Now set the value list
                // TODO: Replace with a tree, not just the first slider!
                // Thanks to Dimitrie A. Stefanescu for making Speckle open which has helped greatly here.


                for (int i = 0; i < sliders.Count; i++)
                {
                    double min = (double)sliders[i].Slider.Minimum;
                    double max = (double)sliders[i].Slider.Maximum;

                    // Note we use divisions-1 because we have inclusive slider bounds
                    double increment = (max - min) / ((double)popSize - 1);

                    for (int j = 0; j < popSize; j++)
                    {
                        sliderValues.Add(j * increment + min);
                    }
                }
            }

            // So if GO = true...
            else
            {
                // Get the slider values.
                // TODO: Include more than one slider.
                if (counter < popSize)
                {
                    //for (int i = 0; i < sliders.Count; i++)
                    sliders[0].Slider.Value = (decimal)sliderValues[counter];
                }


                // First things first...
                // We have to do the else stuff AFTER the slider has moved and the component is expired (tricky).
                if (counter == 0)
                {
                }
                else
                {
                    // Collect the object at the current instance
                    List <object> localObjs = new List <object>();
                    DA.GetDataList("Geometry", localObjs);

                    // Currently we only take meshes
                    Mesh joinedMesh = new Mesh();

                    for (int i = 0; i < localObjs.Count; i++)
                    {
                        if (localObjs[i] is GH_Mesh)
                        {
                            GH_Mesh myGHMesh = new GH_Mesh();
                            myGHMesh = (GH_Mesh)localObjs[i];
                            Mesh myLocalMesh = new Mesh();
                            GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                            myLocalMesh.Faces.ConvertQuadsToTriangles();
                            joinedMesh.Append(myLocalMesh);
                        }
                    }

                    persGeo.Add(joinedMesh);
                }


                // If we reach a limit, then stop and launch the window
                if (counter == sliderValues.Count)
                {
                    // Instantiate the window and export the geometry to WPF3D
                    myMainWindow = new DesignSpaceWindow(GetPersMeshList());
                    myMainWindow.Show();

                    GO = false;

                    // Expire this component
                    this.ExpireSolution(true);
                }

                // NOW iterate the master counter
                counter++;
            }

            // We need some interaction with the form before sending out the chosen phenotypes.
            DA.SetData(0, 444);
        }
        /// <summary>
        /// Updates the geometry for an input chromosome
        /// </summary>
        /// <param name="chromo">The chromosome used to get geometry from the gh canvas</param>
        /// <returns></returns>
        public int GetGeometry(Chromosome chromo)
        {
            // Collect the object at the current instance
            List <object> localObjs = new List <object>();

            // Thank you Dimitrie :)
            foreach (IGH_Param param in Params.Input[1].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true)) // AllData flattens the tree
                {
                    localObjs.Add(myObj);
                }
            }

            // TODO: The allGeometry should not be of type Mesh.
            List <Mesh> allGeometry = new List <Mesh>();

            // Get only mesh geometry from the object list
            for (int i = 0; i < localObjs.Count; i++)
            {
                if (localObjs[i] is GH_Mesh)
                {
                    GH_Mesh myGHMesh = new GH_Mesh();
                    myGHMesh = (GH_Mesh)localObjs[i];
                    Mesh myLocalMesh = new Mesh();
                    GH_Convert.ToMesh(myGHMesh, ref myLocalMesh, GH_Conversion.Primary);
                    myLocalMesh.Faces.ConvertQuadsToTriangles();
                    //Mesh joinedMesh = new Mesh(); yes this is commented out and no I am not a software engineer. Deal with it.
                    //joinedMesh.Append(myLocalMesh);
                    allGeometry.Add(myLocalMesh);
                }
            }

            // Get performance data
            List <double> performas = new List <double>();
            List <string> criteria  = new List <string>();

            // Cap at eight criteria max.
            int pCount = 0;

            foreach (IGH_Param param in Params.Input[2].Sources)
            {
                foreach (Object myObj in param.VolatileData.AllData(true))
                {
                    if (myObj is GH_Number && pCount < 8)
                    {
                        if (!criteria.Contains(param.NickName))
                        {
                            GH_Number temp = (GH_Number)myObj;
                            performas.Add(temp.Value);
                            criteria.Add(param.NickName);
                            pCount++;
                        }
                    }

                    else if (myObj is GH_Integer && pCount < 8)
                    {
                        if (!criteria.Contains(param.NickName))
                        {
                            GH_Integer temp = (GH_Integer)myObj;
                            performas.Add((double)temp.Value);
                            criteria.Add(param.NickName);
                            pCount++;
                        }
                    }
                }
            }

            // Set the phenotype within the chromosome class
            chromo.SetPhenotype(allGeometry, performas, criteria);

            // Return the number of performance criteria
            return(performas.Count);
        }
Beispiel #18
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)
        {
            if (!this.Hidden)
            {
                try
                {
                    m_display.Clear();
                }
                catch
                {
                    m_display = new CustomDisplay(true);
                }
                GH_Structure <IGH_GeometricGoo> geo = new GH_Structure <IGH_GeometricGoo>();
                List <Color> colors = new List <Color>();
                int          style  = 4;
                int          size   = 1;

                if (!DA.GetDataTree(0, out geo))
                {
                    return;
                }
                if (!DA.GetDataList(1, colors))
                {
                    return;
                }
                DA.GetData(2, ref style);
                DA.GetData(3, ref size);
                try
                {
                    geo.Simplify(GH_SimplificationMode.CollapseAllOverlaps);

                    if (geo.Branches.Count == colors.Count)
                    {
                        for (int i = 0; i < geo.Branches.Count; i++)
                        {
                            ConcurrentQueue <Point3d> points = new ConcurrentQueue <Point3d>();

                            // Testing first object
                            if (geo.Branches[i][0] is GH_Point)
                            {
                                Parallel.ForEach(geo.Branches[i], obj =>
                                {
                                    if (obj is GH_Point)
                                    {
                                        GH_Point p = new GH_Point();
                                        if (GH_Convert.ToGHPoint(obj, GH_Conversion.Both, ref p))
                                        {
                                            points.Enqueue(new Point3d(p.Value.X, p.Value.Y, p.Value.Z));
                                        }
                                    }
                                });
                            }
                            // Testing for mesh
                            else if (geo.Branches[i][0].TypeName == "Mesh")
                            {
                                Parallel.ForEach(geo.Branches[i], obj =>
                                {
                                    if (obj.TypeName == "Mesh")
                                    {
                                        Mesh m = new Mesh();
                                        if (GH_Convert.ToMesh(obj, ref m, GH_Conversion.Both))
                                        {
                                            points = new ConcurrentQueue <Point3d>(m.Vertices.ToPoint3dArray());
                                        }
                                    }
                                });
                            }

                            PointStyle pointStyle = (PointStyle)style;
                            m_display.AddPoints(points, colors[i], pointStyle, size);
                        }
                    }
                    else
                    {
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Data input incorrect!");
                    }
                }
                catch (Exception e)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                }
            }
        }