protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = String.Empty;
            bool gravityOn = false;
            Vector3d gravField = Vector3d.Unset;
            List<PointLoadCarrier> ptLds = new List<PointLoadCarrier>();

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref gravityOn)) { return; }
            if (!DA.GetData(2, ref gravField)) { return; }

            if(!DA.GetDataList(3, ptLds))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No pointloads provided");
            }

            WR_LoadCombination loadComb;

            if(gravityOn)
            {
                loadComb = new WR_LoadCombination(name, new WR_Vector(gravField.X, gravField.Y, gravField.Z));
            }
            else
            {
                loadComb = new WR_LoadCombination(name, gravityOn);
            }

            foreach (PointLoadCarrier plc in ptLds)
            {
                loadComb.AddPointLoad(plc.CIForce, plc.CIMoment, plc.CIPos);
            }

            DA.SetData(0, loadComb);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            WR_Structure structure = null;
            bool go = false;
            List<int> modes = new List<int>();
            double sFac = 0;

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            if (!DA.GetData(0, ref structure)) { return; }
            if (!DA.GetData(1, ref go)) { return; }
            if (!DA.GetDataList(2, modes)) { return; }
            if (!DA.GetData(3, ref sFac)) { return; }

            if (go)
            {
                _resElems = new List<ResultElement>();
                _log.Clear();
                watch.Restart();

                // Solve
                WR_ModeShapeOptimizer optimizer = new WR_ModeShapeOptimizer(structure);

                watch.Stop();

                _log.Add(String.Format("Initialising: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();

                //Run
                optimizer.Run(modes, sFac);

                watch.Stop();

                _log.Add(String.Format("Run mode shape optimization: {0}ms", watch.ElapsedMilliseconds));

                watch.Restart();

                // Extract results
                List<WR_IElement> elems = structure.GetAllElements();
                for (int i = 0; i < elems.Count; i++)
                {

                    if (elems[i] is WR_Element3d)
                    {
                        WR_Element3d el3d = (WR_Element3d)elems[i];
                        ResultElement re = new ResultElement(el3d);
                        _resElems.Add(re);
                    }
                }

                watch.Stop();

                _log.Add(String.Format("Extract results: {0}ms", watch.ElapsedMilliseconds));

            }
            DA.SetDataList(0, _log);
            DA.SetDataList(1, _resElems);
        }
Example #3
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input String
            string filename = null;
            bool activate = false;
            // 1. Declare placeholder variables and assign initial invalid data.
            //    This way, if the input parameters fail to supply valid data, we know when to abort.

            // 2. Retrieve input data.
            if (!DA.GetData(0, ref filename)) { return; }
            if (!DA.GetData(1, ref activate)) { return; }

            // If the retrieved data is Nothing, we need to abort.
            if (filename == null) { return; }
            if (!File.Exists(filename)) { return; }

            if (activate)
            {
                GH_Cluster cluster = new GH_Cluster();
                cluster.CreateFromFilePath(filename);

                GH_Document doc = OnPingDocument();
                doc.AddObject(cluster, false);
             }
        }
        /// <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)
        {
            var parameters = new List<RhinoNestKernel.Nesting.RhinoNestObject>();

            //Declaration.
            var Object = new List<Guid>();
            var orientation = new OrientationGoo();
            var criterion = new CriterionGoo();
            var copies = 0;
            var priority = 0;
            //clear value and get the objects.
            if (!da.GetDataList(0, Object)) return;
            da.GetData(1, ref copies);
            da.GetData(2, ref priority);
            da.GetData(3, ref orientation);
            da.GetData(4, ref criterion);

            var organizer = new RhinoNestKernel.Curves.OrganizeObjects(Object);
            var res = organizer.Sort();

            foreach (var rhinoNestObject in organizer.Result)
            {
                rhinoNestObject.Parameters.Priority = priority;
                rhinoNestObject.Parameters.Copies = copies;
                rhinoNestObject.Parameters.Criterion = criterion.Value.Constraint;
                rhinoNestObject.Parameters.Orientation = orientation.Value.Constraint;
                parameters.Add(rhinoNestObject);
            }
            //Put the list to Output.
            da.SetDataList(0, parameters);
        }
Example #5
0
    protected override bool GetInputs(IGH_DataAccess da)
    {
      if (!base.GetInputs(da)) return false;
      if (!da.GetData(nextInputIndex++, ref mass)) return false;
      if (!da.GetData(nextInputIndex++, ref lowerLimit)) return false;
      if (!da.GetData(nextInputIndex++, ref upperLimit)) return false;

      if (mass <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.massErrorMessage);
        return false;
      }

      if (lowerLimit <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Lower limit must be greater than 0.");
        return false;
      }
      if (upperLimit <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Upper limit must be greater than 0.");
        return false;
      }
      if (upperLimit < lowerLimit)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Upper limit must be greater than lower limit.");
        return false;
      }

      return true;
    }
        /// <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)
        {
            String uri = "";

            // Default values
            String password = BIMPlusServer.Password;
            String username = BIMPlusServer.Username;
            //String serializer = BimPlusApi.Ifc2XSersializer;

            DA.GetData<String>(0, ref uri);
            DA.GetData(1, ref username);
            DA.GetData(2, ref password);
            //DA.GetData(3, ref serializer);

            BIMPlusServer bimPlusServer = new BIMPlusServer();

            try
            {
                bimPlusServer.authorize();
            }
            catch (System.IO.FileNotFoundException e)
            {
                Console.WriteLine(e.FileName);
            }


        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // string crossSection = "";
            WR_IXSec xSec= null;
            WR_ReleaseBeam3d stREl = null;
            WR_ReleaseBeam3d enREl = null;
            WR_Material mat = null;
            WR_Element3dOptProp optProp = null;

            if (!DA.GetData(0, ref xSec)) { return; }
            if (!DA.GetData(1, ref stREl)) { return; }
            if (!DA.GetData(2, ref enREl)) { return; }
            if (!DA.GetData(3, ref mat)) { return; }

            // Check releases
            if (!CheckReleases(stREl, enREl))
                return;

            BeamProperties beamProp;

            if (!DA.GetData(4, ref optProp))
                beamProp = new BeamProperties(mat, xSec, stREl, enREl);
            else
                beamProp = new BeamProperties(mat, xSec, stREl, enREl, optProp);

            DA.SetData(0, beamProp);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            BeamProperties prop = null;
            Line ln = Line.Unset;
            Vector3d norm = Vector3d.Unset;

            if (!DA.GetData(0, ref ln)) { return; }
            if (!DA.GetData(1, ref prop)) { return; }
            if (!DA.GetData(2, ref norm)) { return; }

            norm.Unitize();

            //Check if angle between tangent and normal is less than 1 degree
            if(Vector3d.VectorAngle(norm, ln.UnitTangent) < 0.0174 || Vector3d.VectorAngle(-norm, ln.UnitTangent) < 0.0174)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The given normal is within 1 degree of the tangent of the centre line. Please adjust normal");
                return;
            }

            double factor = Utilities.GetScalingFactorFromRhino();

            WR_Vector wrNorm = new WR_Vector(norm.X, norm.Y, norm.Z);
            WR_XYZ st = new WR_XYZ(ln.FromX* factor, ln.FromY* factor, ln.FromZ* factor);
            WR_XYZ en = new WR_XYZ(ln.ToX* factor, ln.ToY* factor, ln.ToZ* factor);

            WR_Elem3dRcp beam = new WR_Elem3dRcp(st, en, prop.StartRelease, prop.EndRelease, prop.CrossSection, prop.Material, wrNorm, prop.OptimizationProperties);

            DA.SetData(0, beam);
        }
Example #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = null; 
            GH_RobotSystem robotSystem = null;
            var initCommandsGH = new List<GH_Command>();
            var targetsA = new List<GH_Target>();
            var targetsB = new List<GH_Target>();
            var multiFileIndices = new List<int>();
            double stepSize = 1;

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref robotSystem)) { return; }
            if (!DA.GetDataList(2, targetsA)) { return; }
            DA.GetDataList(3, targetsB);
            DA.GetDataList(4, initCommandsGH);
            DA.GetDataList(5, multiFileIndices);
            if (!DA.GetData(6, ref stepSize)) { return; }

            var initCommands = initCommandsGH.Count > 0 ? new Robots.Commands.Group(initCommandsGH.Select(x => x.Value)) : null;

            var targets = new List<IEnumerable<Target>>();
            targets.Add(targetsA.Select(x => x.Value));
            if (targetsB.Count > 0) targets.Add(targetsB.Select(x => x.Value));

            var program = new Program(name, robotSystem.Value, targets, initCommands, multiFileIndices, stepSize);

            DA.SetData(0, new GH_Program(program));


            if (program.Code != null)
            {
                var path = DA.ParameterTargetPath(2);
                var structure = new GH_Structure<GH_String>();

                for (int i = 0; i < program.Code.Count; i++)
                {
                    var tempPath = path.AppendElement(i);
                    for (int j = 0; j < program.Code[i].Count; j++)
                    {
                        structure.AppendRange(program.Code[i][j].Select(x => new GH_String(x)), tempPath.AppendElement(j));
                    }
                }

                DA.SetDataTree(1, structure);
            }

            DA.SetData(2, program.Duration);

            if (program.Warnings.Count > 0)
            {
                DA.SetDataList(3, program.Warnings);
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Warnings in program");
            }

            if (program.Errors.Count > 0)
            {
                DA.SetDataList(4, program.Errors);
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Errors in program");
            }
        }
Example #10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // 1. Get Input Data
            Curve path=null;
            DA.GetData(0, ref path);

            Plane pathPlane=new Plane();
            DA.GetData(1, ref pathPlane);

            Curve section=null;
            DA.GetData(2, ref section);

            Plane sectionPlane=new Plane();
            DA.GetData(3, ref sectionPlane);

            // 2. Orientate section profile to path
            Point3d origin = path.PointAtStart;
            Vector3d xDir = pathPlane.Normal;
            Vector3d yDir = path.TangentAt(path.Domain.T0);
            yDir.Rotate(Rhino.RhinoMath.ToRadians(90.0), xDir);

            Plane targetPlane = new Plane(origin,xDir,yDir);
            section.Transform(Transform.PlaneToPlane(sectionPlane, targetPlane));

            // 3. Generate Member
            SweepOneRail sweep = new SweepOneRail();
            Brep[] beam = sweep.PerformSweep(path, section);
            DA.SetDataList(0, beam);
        }
 protected override bool GetInputs(IGH_DataAccess da)
 {
     if (!da.GetData(0, ref p)) return false;
     if (!da.GetData(1, ref history)) return false;
     if (!da.GetData(2, ref reset)) return false;
     return true;
 }
Example #12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string name = null;
            GH_Plane tcp = null;
            double weight = 0;
            GH_Mesh mesh = null;
            GH_Point centroid = null;
            List<GH_Plane> planes = new List<GH_Plane>();

            if (!DA.GetData(0, ref name)) { return; }
            if (!DA.GetData(1, ref tcp)) { return; }
            DA.GetDataList(2, planes);
            if (!DA.GetData(3, ref weight)) { return; }
            DA.GetData(4, ref centroid);
            DA.GetData(5, ref mesh);

            var tool = new Tool(tcp.Value, name, weight, centroid?.Value, mesh?.Value);

            if (planes.Count > 0)
            {
                if (planes.Count != 4)
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, " Calibration input must be 4 planes");
                else
                    tool.FourPointCalibration(planes[0].Value, planes[1].Value, planes[2].Value, planes[3].Value);
            }

            DA.SetData(0, new GH_Tool(tool));
            DA.SetData(1, tool.Tcp);
        }
Example #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)
        {
            //Input
            Point3d supportPt = new Point3d();
            DA.GetData(0, ref supportPt);

            bool isXFixed = true;
            DA.GetData(1, ref isXFixed);

            bool isYFixed = true;
            DA.GetData(2, ref isYFixed);

            bool isZFixed = true;
            DA.GetData(3, ref isZFixed);

            double weight = 1.0;
            DA.GetData(4, ref weight);

            //Warning if no direction is fixed
            if (!isXFixed && !isYFixed && !isZFixed)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The specified point is free to move!");
            }


            //Create simple support goal
            GoalObject support = new SupportGoal(supportPt, isXFixed, isYFixed, isZFixed, weight);


            //Output
            DA.SetData(0, support);
        }
 protected override bool GetInputs(IGH_DataAccess da)
 {
   if (!base.GetInputs(da)) return false;
   if (!da.GetData(nextInputIndex++, ref minTimeToCollision)) return false;
   if (!da.GetData(nextInputIndex++, ref potentialCollisionDistance)) return false;
   return true;
 }
Example #15
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)
        {
            //Input
            Line line = new Line();
            DA.GetData(0, ref line);

            double eModulus = 0.0;
            DA.GetData(1, ref eModulus);

            double area = 0.0;
            DA.GetData(2, ref area);

            double preStress = 0.0;
            if (this.Params.Input[3].SourceCount != 0)
            {
                DA.GetData(3, ref preStress);
            }


            //Create instance of bar
            GoalObject cableElement = new CableGoal(line, eModulus, area, preStress);


            //Output
            DA.SetData(0, cableElement);
        }
    protected override bool GetInputs(IGH_DataAccess da)
    {
      if(!base.GetInputs(da)) return false;
      // First, we need to retrieve all data from the input parameters.

      // Then we need to access the input parameters individually. 
      // When data cannot be extracted from a parameter, we should abort this method.
      if (!da.GetData(nextInputIndex++, ref vehicle)) return false;
      if (!da.GetData(nextInputIndex++, ref visionRadiusMultiplier)) return false;
      if (!da.GetData(nextInputIndex++, ref visionAngleMultiplier)) return false;
      if (!da.GetData(nextInputIndex++, ref crossed)) return false;
      if (!(0.0 <= visionRadiusMultiplier && visionRadiusMultiplier <= 1.0))
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.visionRadiusMultiplierErrorMessage);
        return false;
      }
      if (!(0.0 <= visionAngleMultiplier && visionAngleMultiplier <= 1.0))
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.visionAngleMultiplierErrorMessage);
        return false;
      }
      sensorLeftPos = vehicle.GetSensorPosition(visionRadiusMultiplier, visionAngleMultiplier);
      sensorRightPos = vehicle.GetSensorPosition(visionRadiusMultiplier, -visionAngleMultiplier);
      return true;
    }
 protected override bool GetInputs(IGH_DataAccess da)
 {
     if (!da.GetData(0, ref sensor_angle)) return false;
     if (!da.GetData(1, ref rotate_angle)) return false;
     if (!da.GetData(2, ref sensor_offset)) return false;
     return true;
 }
Example #18
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     String name = null;
     Object value = null;
     DA.GetData(0, ref name);
     DA.GetData(1, ref value);
     DA.SetData(0, new HashType(name, value));
 }
    protected override bool GetInputs(IGH_DataAccess da)
    {
      if (!base.GetInputs(da)) return false;
      if (!da.GetData(nextInputIndex++, ref environment)) return false;
      if (!da.GetData(nextInputIndex++, ref visionRadiusMultiplier)) return false;

      return true;
    }
 protected override bool GetInputs(IGH_DataAccess da)
 {
   if(!base.GetInputs(da)) return false;
   if (!da.GetData(nextInputIndex++, ref environment)) return false;
   if (!da.GetData(nextInputIndex++, ref stepDistance)) return false;
   if (!da.GetData(nextInputIndex++, ref angle)) return false;
   return true;
 }
 protected override bool GetInputs(IGH_DataAccess da)
 {
   if(!base.GetInputs(da)) return false;
   if (!da.GetData(nextInputIndex++, ref path)) return false;
   if (!da.GetData(nextInputIndex++, ref radius)) return false;
   if (!da.GetData(nextInputIndex++, ref predictionDistance)) predictionDistance = agent.VisionRadius/5;
   if (!da.GetData(nextInputIndex++, ref pathTargetDistance)) pathTargetDistance = agent.VisionRadius/5;
   return true;
 }
Example #22
0
 protected override bool GetInputs(IGH_DataAccess da)
 {
     if(! da.GetData(0, ref env)) return false;
     if (!da.GetData(1, ref emit)) return false;
     if (!da.GetData(2, ref food)) return false;
     da.GetDataList(3, setList);
     if (!da.GetData(4, ref rst)) return false;
     return true;
 }
 protected override bool GetInputs(IGH_DataAccess da)
 {
     if (!da.GetData(0, ref env)) return false;
     if (!da.GetData(1, ref z)) return false;
     if (z < env.getWMin())
         z = env.getWMin();
     else if (z > env.getWMax())
         z = env.getWMax();
     return true;
 }
 /// <summary>
 /// Gets the unique ID for this component. Do not change this ID after release.
 /// </summary>
 protected override bool GetInputs(IGH_DataAccess da)
 {
     obs = new List<Brep>();
     if (!da.GetData(nextInputIndex++, ref x_count)) return false;
     if (!da.GetData(nextInputIndex++, ref y_count)) return false;
     if (!da.GetData(nextInputIndex++, ref z_count)) return false;
     if (!da.GetData(nextInputIndex++, ref box)) return false;
     da.GetDataList(nextInputIndex++, obs);
     return true;
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<ResultElement> res = new List<ResultElement>();
            double sFac = double.NaN;
            string name = null;

            if (!DA.GetDataList(0, res)) { return; }
            if (!DA.GetData(1, ref sFac)) { return; }
            if(!DA.GetData(2, ref name))
            {
                if(res.Count>0)
                {
                    name = res[0].N1.First().Key;
                }
            }

            _dispCrvs.Clear();

            Point3d stPos, enPos;
            Vector3d norm, tan, yDir;

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

            foreach (ResultElement re in res)
            {
                stPos = re.sPos;
                enPos = re.ePos;
                norm = re.elNormal;

                norm.Unitize();

                tan = enPos - stPos;
                tan.Unitize();

                yDir = Vector3d.CrossProduct(norm, tan);
                yDir.Unitize();

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

                int nbEval = re.pos.Count;

                for (int i = 0; i < nbEval; i++)
                {
                    Point3d curvePt = stPos + tan * (re.pos[i]+re.u[name][i]* sFac) +norm*re.w[name][i]* sFac + yDir*re.v[name][i]* sFac;
                    curvePts.Add(curvePt);
                    allPts.Add(curvePt);
                }

                _dispCrvs.Add(Rhino.Geometry.Curve.CreateInterpolatedCurve(curvePts, 3));
            }

            _bb = new BoundingBox(allPts);

            DA.SetDataList(0, _dispCrvs);
        }
Example #26
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_RobotSystem robotSystem = null;
            var targets = new List<GH_Target>();
            var prevJointsText = new List<GH_String>();
            bool drawMeshes = false;

            if (!DA.GetData(0, ref robotSystem)) { return; }
            if (!DA.GetDataList(1, targets)) { return; }
            DA.GetDataList(2, prevJointsText);
            if (!DA.GetData(3, ref drawMeshes)) { return; }

            List<double[]> prevJoints = null;

            if (prevJointsText.Count > 0)
            {
                prevJoints = new List<double[]>();

                foreach (var text in prevJointsText)
                {
                    if (text != null)
                    {
                        string[] jointsText = text.Value.Split(',');
                        var prevJoint = new double[jointsText.Length];

                        for (int i = 0; i < jointsText.Length; i++)
                            if (!GH_Convert.ToDouble_Secondary(jointsText[i], ref prevJoint[i])) throw new Exception(" Previous joints not formatted correctly.");

                        prevJoints.Add(prevJoint);
                    }
                }
            }

            var kinematics = robotSystem.Value.Kinematics(targets.Select(x => x.Value), prevJoints, drawMeshes);

            var errors = kinematics.SelectMany(x => x.Errors);
            if (errors.Count() > 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Errors in solution");
            }

            var strings = kinematics.SelectMany(x => x.Joints).Select(x => new GH_Number(x).ToString());
            var joints = string.Join(",", strings);

            var planes = kinematics.SelectMany(x => x.Planes);
            if (drawMeshes)
            {
                var meshes = kinematics.SelectMany(x => x.Meshes);
                DA.SetDataList(0, meshes.Select(x => new GH_Mesh(x)));
            }

            DA.SetData(1, joints);
            DA.SetDataList(2, planes.Select(x => new GH_Plane(x)));
            DA.SetDataList(3, errors);
        }
 protected override bool GetInputs(IGH_DataAccess da)
 {
     obs = new List<Brep>();
     cont = new List<Brep>();
     if (!da.GetData(0, ref u_count)) return false;
     if (!da.GetData(1, ref v_count)) return false;
     if (!da.GetData(2, ref srf)) return false;
     da.GetDataList(3, cont);
     da.GetDataList(4, obs);
     return true;
 }
Example #28
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //container for errors/messages passed by controller, partition, etc.
            List<String> errorContainer = new List<String>();

            GH_PreviewUtil preview = new GH_PreviewUtil(true);

            //declare placeholder variables and assign initial empty mesh
            Mesh baseMesh = new Rhino.Geometry.Mesh();
            int errorMetricIdentifer = -1;
            int numPanels = -1;

            //Retrieve input data
            if (!DA.GetData(0, ref baseMesh)) { return; }
            if (!DA.GetData(1, ref errorMetricIdentifer)) { return; }
            if (!DA.GetData(2, ref numPanels)) { return; }

            if (baseMesh.DisjointMeshCount > 1)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Problem with mesh input - disjoint mesh");
            }
            else
            {
                //compute and unify normal
                baseMesh.Normals.ComputeNormals();
                baseMesh.UnifyNormals();

                //create wingedmesh from rhinomesh
                WingedMesh myMesh = new WingedMesh(errorContainer, baseMesh);

                PlanarMesher controller = new PlanarMesher(errorContainer, myMesh, baseMesh, numPanels, errorMetricIdentifer, preview);

                controller.createFirstCluster();

                for (int i = 0; i < 40; i++)
                {
                    controller.iterateCluster();
                    //controller.currentPartition.drawProxies(preview);
                }

                controller.createConnectivityMesh();

                //creating voronoi
                WingedMesh voronoiMesh = new WingedMesh(errorContainer, controller.currentPartition.proxyToMesh.convertWingedMeshToPolylines());

                //set all the output data
                DA.SetDataList(0, voronoiMesh.convertWingedMeshToPolylines());
            }

            foreach (var item in errorContainer)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, item);
            }
        }
Example #29
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            AWorld refwrld = new AWorld();
            if (!DA.GetData(0, ref refwrld) || !refwrld.IsValid) return;
            AWorld wrld = new AWorld(refwrld);

            int g = 0;
            if (!DA.GetData(1, ref g)) return;
            if (g > wrld.GenCount - 1) g = wrld.GenCount - 1;
            DA.SetDataList(0, wrld.gens[g]);
        }
 protected override bool GetInputs(IGH_DataAccess da)
 {
   if (!base.GetInputs(da)) return false;
   if (!da.GetData(nextInputIndex++, ref sourcePt)) return false;
   if (!da.GetData(nextInputIndex++, ref radius)) return false;
   if (radius < 0)
   {
     AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Radius must be positive.");
     return false;
   }
   return true;
 }
        /// <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)
        {
            Grasshopper.Kernel.Data.GH_Structure <IGH_Goo> elementsToAdd = new Grasshopper.Kernel.Data.GH_Structure <IGH_Goo>();
            double        width          = 0;
            double        height         = 0;
            List <string> rowDefinitions = new List <string>();
            List <string> colDefinitions = new List <string>();
            List <int>    memberships    = new List <int>();


            if (!DA.GetDataTree <IGH_Goo>(0, out elementsToAdd))
            {
                return;
            }
            bool hasMemberships = DA.GetDataList <int>("Grid Membership", memberships);
            bool hasWidth       = DA.GetData <double>("Width", ref width);
            bool hasHeight      = DA.GetData <double>("Height", ref height);

            bool hasRowDefs = DA.GetDataList <string>("Row Definitions", rowDefinitions);
            bool hasColDefs = DA.GetDataList <string>("Column Definitions", colDefinitions);

            if (hasMemberships)
            {
                if (memberships.Count != elementsToAdd.Branches.Count)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Grid Membership list length must equal the number of Elements branches.");
                    return;
                }
            }
            else
            {
                // Create a default list of a single branch grouping to apply to all trees
                memberships = new List <int>()
                {
                    0
                };
            }

            int[] defaultMembership = { 0 };

            // Create an array of the membership values
            int[] membershipArray = hasMemberships ? memberships.ToArray() : defaultMembership;

            // Create empty list of branch metadata and populate with values
            List <BranchMetadata> branchMetaData = new List <BranchMetadata>();

            for (int i = 0; i < elementsToAdd.Branches.Count(); i++)
            {
                int myMembership = hasMemberships ? membershipArray[i] : 0;

                BranchMetadata bm = new BranchMetadata(i, myMembership);
                branchMetaData.Add(bm);
            }

            // Sort and group the metadata
            var branchGroupings = branchMetaData
                                  .OrderBy(b => b.membershipIndex)
                                  .GroupBy(b => b.membershipIndex);


            // create an empty List of grids and populate

            List <Grid> grids = new List <Grid>();

            foreach (var group in branchGroupings)
            {
                //initialize a grid
                Grid grid = new Grid();
                grid.HorizontalAlignment = HorizontalAlignment.Left;
                grid.VerticalAlignment   = VerticalAlignment.Top;
                grid.Name = "GH_Grid";
                if (hasWidth)
                {
                    grid.Width = width;
                }
                else
                {
                    grid.HorizontalAlignment = HorizontalAlignment.Stretch;
                }
                if (hasHeight)
                {
                    grid.Height = height;
                }
                else
                {
                    grid.VerticalAlignment = VerticalAlignment.Stretch;
                }

                // Add grid to List
                grids.Add(grid);
            }

            // Populate the Grids (should this be done before adding the grids to the List?)

            foreach (var group in branchGroupings)
            {
                // Count the number of branches in this array
                int currentBranchCount = group.Count();

                //set up a "GridLengthConverter" to handle parsing our strings.
                GridLengthConverter gridLengthConverter = new GridLengthConverter();

                //set up rows and columns if present
                if (hasColDefs)
                {
                    for (int i = 0; i < currentBranchCount; i++)
                    {
                        ColumnDefinition cd = new ColumnDefinition();
                        cd.Width = (GridLength)gridLengthConverter.ConvertFromString(colDefinitions[i % colDefinitions.Count]);  // use repeating pattern of supplied list
                        // Note: group.Key is the index of the group/grid
                        grids[group.Key].ColumnDefinitions.Add(cd);
                    }
                }

                if (hasRowDefs)
                {
                    int maxCount = 0;

                    // Find the count of the longest list
                    foreach (BranchMetadata md in group)
                    {
                        // get the count of data from the branch
                        var myCount = elementsToAdd.get_Branch(elementsToAdd.get_Path(md.branchIndex)).Count;

                        if (myCount > maxCount)
                        {
                            maxCount = myCount;
                        }
                    }

                    // Build up the row heights based on a repeating pattern
                    for (int i = 0; i < maxCount; i++)
                    {
                        RowDefinition rd = new RowDefinition();
                        rd.Height = (GridLength)gridLengthConverter.ConvertFromString(rowDefinitions[i % rowDefinitions.Count]);  // use repeating pattern of supplied list
                        // Note: group.Key is the index of the group/grid
                        grids[group.Key].RowDefinitions.Add(rd);
                    }
                }

                // Set up a counter for iterating through the appropriate number of columns
                int currentColumn = 0;

                // Populate the Grids with Elements
                foreach (BranchMetadata md in group)
                {
                    // Get each branch referenced in the metadata
                    var branch = elementsToAdd.get_Branch(elementsToAdd.get_Path(md.branchIndex));


                    //for all the elements in each branch
                    for (int j = 0; j < branch.Count; j++)
                    {
                        UIElement_Goo u = branch[j] as UIElement_Goo;
                        //make sure it doesn't already have a parent
                        HUI_Util.removeParent(u.element);
                        FrameworkElement fe = u.element as FrameworkElement;
                        if (fe != null)
                        {
                            //set its alignment to be relative to upper left - this makes margin-based positioning easy
                            fe.HorizontalAlignment = HorizontalAlignment.Left;
                            fe.VerticalAlignment   = VerticalAlignment.Top;

                            //set up row and column positioning
                            Grid.SetColumn(fe, currentColumn);
                            Grid.SetRow(fe, j);
                        }

                        //add it to the grid
                        grids[group.Key].Children.Add(u.element);
                    }

                    // Increment the column index
                    currentColumn++;
                }
            }

            // Create the list of Elements and add each grid
            List <UIElement_Goo> output = new List <UIElement_Goo>();

            foreach (Grid g in grids)
            {
                output.Add(new UIElement_Goo(g, "Simple Grid", InstanceGuid, DA.Iteration));
            }

            //pass the grids out
            DA.SetDataList("Simple Grid", output);
        }
Example #32
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)
        {
// ===============================================================================================
// Read input parameters
// ===============================================================================================
            var    mesh            = new Mesh();
            var    attractorPoints = new List <Point3d>();
            var    interval        = 0;
            double threshold       = 0;
            double distance        = 0;
            var    run             = true;
            var    reset           = true;

            //get values from grasshopper
            DA.GetData("Input Mesh", ref mesh);
            DA.GetDataList("Attractor Points", attractorPoints);
            DA.GetData("Interval", ref interval);
            DA.GetData("Threshold", ref threshold);
            DA.GetData("Distance", ref distance);
            DA.GetData("Run", ref run);
            DA.GetData("Reset", ref reset);
// ===============================================================================================
// Applying Values to Class
// ===============================================================================================
            _pts        = attractorPoints;
            _iThreshold = threshold;
            _iInterval  = interval;

            if (run)
            {
                _count++;
            }
            else
            {
                _count = 0;
            }
            //Recursion Loop
            mesh.Weld(0.01);
            if (_tempMesh2 == null)
            {
                _tempMesh = mesh;
            }
            else
            {
                _tempMesh = _tempMesh2;
            }

            var points    = _tempMesh.Vertices;
            var faces     = _tempMesh.Faces;
            var pointList = points.ToPoint3dArray().ToList();

            for (int i = 0; i < _count; i++)
            {
                foreach (Point3d pt in _pts)
                {
                    int index;
                    PointOperations.ClosestPointWithIndex(pt, pointList, out index);

                    if (pt.DistanceTo(pointList[index]) <= _iThreshold)
                    {
                        //Move Point
                        Vector3d moveVector = (pointList[index] - pt) / pt.DistanceTo(pointList[index]);
                        moveVector = moveVector * distance;
                        Transform move       = Transform.Translation(moveVector);
                        var       movedPoint = pointList[index];
                        movedPoint.Transform(move);

                        pointList[index] = movedPoint;
                    }
                }
                //Build constructedMesh
                Mesh constructedMesh = new Mesh();
                constructedMesh.Vertices.AddVertices(pointList);
                constructedMesh.Faces.AddFaces(faces);
                constructedMesh.FaceNormals.ComputeFaceNormals();
                constructedMesh.Normals.ComputeNormals();
                constructedMesh.Compact();

                _tempMesh2 = constructedMesh;
            }
            if (reset)
            {
                _tempMesh2 = mesh;
                _count     = 0;
            }
// ===============================================================================================
// Exporting Data to Grasshopper
// ===============================================================================================
            var a = _tempMesh2;

            DA.SetData("Carved Mesh", a);
        }
Example #33
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)
        {
            Point3d origin = Point3d.Unset;

            if (!DA.GetData(0, ref origin))
            {
                origin = new Point3d(0, 0, 0);
            }

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

            if (!DA.GetDataList(1, mshCp))
            {
                return;
            }

            DataExtractor de = null;

            if (!DA.GetData(2, ref de))
            {
                return;
            }

            double roh = 1.2041;

            DA.GetData(3, ref roh);

            double min = -1;
            double max = 1;

            DA.GetData(4, ref min);
            DA.GetData(5, ref max);

            int colourSheme = 1;

            DA.GetData(6, ref colourSheme);

            double fontsize = 0.5;

            DA.GetData(7, ref fontsize);

            Point3d zrefp = new Point3d();

            if (!DA.GetData(8, ref zrefp))
            {
                return;
            }

            string face    = "Baskerville";
            bool   bold    = false;
            bool   italics = true;


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

            Grasshopper.DataTree <double> cptree = new Grasshopper.DataTree <double>();
            int branch = 0;

            //vref and pdyn should be measured at the building height...
            double[] vref  = de.get_velocity(zrefp[0] - origin[0], zrefp[1] - origin[1], zrefp[2] - origin[2]);
            Vector3d vrefv = new Vector3d(vref[0], vref[1], vref[2]);
            double   vrefl = vrefv.Length;
            double   pref  = de.get_pressure(0, zrefp[1] - origin[1], zrefp[2] - origin[2]);
            double   pdyn  = 0.5 * roh * Math.Pow(vrefl, 2);

            foreach (Mesh msh in mshCp)
            {
                double[]     Cp     = new double[msh.Vertices.Count];
                Color[]      Cols   = new Color[msh.Vertices.Count];
                Mesh         mshcol = new Mesh();
                List <Curve> lst    = new List <Curve>();

                for (int u = 0; u < msh.Vertices.Count; u++)
                {
                    //double[] vref = de.get_velocity(0 - origin[0], msh.Vertices[u].Y - origin[1], msh.Vertices[u].Z - origin[2]);
                    //Vector3d vrefv = new Vector3d(vref[0], vref[1], vref[2]);
                    //double vrefl = vrefv.Length;
                    //double pref = de.get_pressure(0 - origin[0], msh.Vertices[u].Y - origin[1], msh.Vertices[u].Z - origin[2]);
                    //double pdyn = 0.5 * roh * Math.Pow(vrefl, 2);
                    double px = de.get_pressure(msh.Vertices[u].X - origin[0], msh.Vertices[u].Y - origin[1], msh.Vertices[u].Z - origin[2]);


                    Cp[u] = (px - pref) / pdyn;
                    cptree.Add(Cp[u], new Grasshopper.Kernel.Data.GH_Path(branch));
                    Cols[u] = Utilities.GetRGB(colourSheme, Cp[u], max, min);
                    mshcol.Vertices.Add(msh.Vertices[u]);
                    mshcol.VertexColors.SetColor(u, Cols[u]);

                    string   strval = Math.Round(Cp[u], 2).ToString();
                    Point3d  plp    = new Point3d(msh.Vertices[u].X, msh.Vertices[u].Y, msh.Vertices[u].Z);
                    Vector3d vec    = new Vector3d(-1, 0, 0);
                    Plane    pl     = new Plane(plp, vec);

                    var te = Rhino.RhinoDoc.ActiveDoc.Objects.AddText(strval, pl, fontsize, face, bold, italics);
                    Rhino.DocObjects.TextObject txt = Rhino.RhinoDoc.ActiveDoc.Objects.Find(te) as Rhino.DocObjects.TextObject;

                    if (txt != null)
                    {
                        var     tt = txt.Geometry as Rhino.Geometry.TextEntity;
                        Curve[] A  = tt.Explode();

                        foreach (Curve crv in A)
                        {
                            lst.Add(crv);
                        }
                    }

                    Rhino.RhinoDoc.ActiveDoc.Objects.Delete(te, true);
                }
                branch++;

                for (int j = 0; j < msh.Faces.Count; j++)
                {
                    mshcol.Faces.AddFace(msh.Faces[j].A, msh.Faces[j].B, msh.Faces[j].C, msh.Faces[j].D);
                }


                // output Cp numbers as text into rhino viewport
                DA.SetDataList(1, lst);

                // output coloured meshes
                mshCpOUT.Add(mshcol);
            }

            DA.SetDataTree(2, cptree);
            DA.SetDataList(0, mshCpOUT);



            //THIS IS FROM GIULIO PIACENTINO's page... txtlines component
            //            private void RunScript(string face, bool bold, bool italics, double size, string content, Plane pl, ref object A)
            //{

            //  if(size == 0)
            //    size = 1;

            //  if(!string.IsNullOrEmpty(face) && size > 0 && !string.IsNullOrEmpty(content) &&
            //    pl.IsValid)

            //    var te = RhinoDoc.ActiveDoc.Objects.AddText(content, pl, size, face, bold, italics);
            //    Rhino.DocObjects.TextObject txt = RhinoDoc.ActiveDoc.Objects.Find(te) as Rhino.DocObjects.TextObject;

            //    if(txt != null)
            //    {
            //      var tt = txt.Geometry as Rhino.Geometry.TextEntity;
            //      A = tt.Explode();
            //    }

            //    RhinoDoc.ActiveDoc.Objects.Delete(txt, true);
            //    RhinoDoc.ActiveDoc.Objects.Delete(te, true);
            //  }

            //}
        }
Example #34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // get input
            Curve curve = null;

            if (!DA.GetData(0, ref curve))
            {
                return;
            }

            double stiffness = 1E7;
            double ae        = stiffness;

            if (!DA.GetData(1, ref ae))
            {
                // pass
            }

            double itg = stiffness;

            if (!DA.GetData(2, ref itg))
            {
                // pass
            }

            double i1e = stiffness;

            if (!DA.GetData(3, ref i1e))
            {
                // pass
            }

            double i2e = stiffness;

            if (!DA.GetData(4, ref i2e))
            {
                // pass
            }

            Bars.Connectivity        startConnectivity = Bars.Connectivity.GetDefault();
            Bars.Connectivity        endConnectivity   = Bars.Connectivity.GetDefault();
            List <Bars.Connectivity> connectivity      = new List <Bars.Connectivity>();

            if (!DA.GetDataList(5, connectivity))
            {
                // pass
            }
            else
            {
                if (connectivity.Count == 1)
                {
                    startConnectivity = connectivity[0];
                    endConnectivity   = connectivity[0];
                }
                else if (connectivity.Count == 2)
                {
                    startConnectivity = connectivity[0];
                    endConnectivity   = connectivity[1];
                }
                else
                {
                    throw new System.ArgumentException($"Connectivity must contain 1 or 2 items. Number of items is {connectivity.Count}");
                }
            }

            Vector3d v = Vector3d.Zero;

            if (!DA.GetData(6, ref v))
            {
                // pass
            }

            bool orientLCS = true;

            if (!DA.GetData(7, ref orientLCS))
            {
                // pass
            }

            string name = "BF";

            if (!DA.GetData(8, ref name))
            {
                // pass
            }

            if (curve == null || startConnectivity == null || endConnectivity == null || v == null || name == null)
            {
                return;
            }

            // convert geometry
            Geometry.Edge edge = curve.FromRhinoLineOrArc2();

            // create virtual bar
            ModellingTools.FictitiousBar bar = new ModellingTools.FictitiousBar(edge, edge.CoordinateSystem.LocalY, startConnectivity, endConnectivity, name, ae, itg, i1e, i2e);

            // set local y-axis
            if (!v.Equals(Vector3d.Zero))
            {
                bar.LocalY = v.FromRhino();
            }

            // else orient coordinate system to GCS
            else
            {
                if (orientLCS)
                {
                    bar.OrientCoordinateSystemToGCS();
                }
            }

            // output
            DA.SetData(0, bar);
        }
Example #35
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)
        {
            //retrive inputs
            string filePath = "";

            if (!DA.GetData(0, ref filePath))
            {
                return;
            }

            bool readFile = false;

            if (!DA.GetData(1, ref readFile))
            {
                return;
            }

            //JObject geoJsonData = null;
            JArray jsonObj = null;

            if (readFile)
            {
                //file = "filePath
                Harlow.ShapeFileReader harlowShpReader = new Harlow.ShapeFileReader(filePath);
                harlowShpReader.LoadFile();
                string shpJsonString = harlowShpReader.FeaturesAsJson();
                //string shpjsonString = harlowShpReader.FeatureAsJson()


                //System.IO.File.ReadAllText(filePath,)
                //geoJsonData = JObject.Parse(shpJsonString);
                jsonObj = JArray.Parse(shpJsonString);
                JObject geoJsonData = new JObject();
                geoJsonData.Add("features", jsonObj);

                //var json = Newtonsoft.Json.JsonConvert.SerializeObject(geoJsonData, Newtonsoft.Json.Formatting.Indented);
                //DA.SetData(0, json);


                //read features
                JArray features = (JArray)geoJsonData["features"];
                GH_Structure <GH_String> attributes      = new GH_Structure <GH_String>();
                GH_Structure <GH_Point>  featureGeometry = new GH_Structure <GH_Point>();
                int featureIndex = 0;
                foreach (JObject feature in features)
                {
                    GH_Path currentPath = new GH_Path(featureIndex);
                    foreach (var attr in (JObject)feature["properties"])
                    {
                        JToken    attributeToken  = attr.Value;
                        string    thisAttribute   = (string)attributeToken;
                        GH_String thisGhAttribute = new GH_String(thisAttribute);
                        attributes.Append(thisGhAttribute, currentPath);
                    }
                    int pathIndex = 0;


                    foreach (JArray pathsArray in (JArray)feature["coordinates"])
                    {
                        List <GH_Point> thisPathPoints = new List <GH_Point>();
                        foreach (var path in pathsArray)
                        {
                            Point3d  thisPoint   = new Point3d((double)path[0], (double)path[1], 0);
                            GH_Point thisGhPoint = new GH_Point(thisPoint);
                            thisPathPoints.Add(thisGhPoint);
                        }
                        GH_Path thisPath = new GH_Path(featureIndex, pathIndex);
                        featureGeometry.AppendRange(thisPathPoints, thisPath);
                        pathIndex++;
                    }

                    featureIndex++;
                }//end polyline
                DA.SetDataTree(1, attributes);
                DA.SetDataTree(2, featureGeometry);

                ///
                ///set attributes

                List <string> featureFields = new List <string>();
                JToken        fieldObjs     = geoJsonData["features"][0]["properties"];
                foreach (JProperty prop in fieldObjs)
                {
                    string thisField = (string)prop.Name;
                    featureFields.Add(thisField);
                }
                DA.SetDataList(0, featureFields);
            }//end if read file
        }
Example #36
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)
        {
            string label = "";

            DA.GetData <string>("Label", ref label);

            if (DA.Iteration == 0)
            {
                Iterator = 0;
            }
            List <GH_ValueList> GHValLists = new List <GH_ValueList>();


            List <object> listItems     = new List <object>();
            int           selectedIndex = 0;

            if (!DA.GetDataList <object>("List Items", listItems))
            {
                return;
            }
            bool selectedIndexSupplied = DA.GetData <int>("Selected Index", ref selectedIndex);

            //try to retrieve any attached GHValueLists
            GHValLists.AddRange(Params.Input[1].Sources.Where(s => s is GH_ValueList).Cast <GH_ValueList>());

            //if GHValLists is empty, either user has supplied direct text or direct value list objects, e.g. from metahopper output

            if (GHValLists.Count == 0)
            { // see if we got any vallists as objects directly
                foreach (object o in listItems)
                {
                    GH_ObjectWrapper wrapper = o as GH_ObjectWrapper;
                    if (wrapper != null)
                    {
                        GHValLists.Add(wrapper.Value as GH_ValueList);
                    }
                }
            }

            //if GHValLists is STILL empty, we just process straight up text, once. otherwise, we iterate over all the lists

            if (GHValLists.Count == 0)
            {
                //initialize combobox
                ComboBox pd = new ComboBox();
                //for each string add a textbox object to the combobox
                foreach (object item in listItems)
                {
                    TextBlock textbox = new TextBlock();
                    textbox.Text = item.ToString();
                    pd.Items.Add(textbox);
                }
                pd.Margin        = new Thickness(4);
                pd.SelectedIndex = selectedIndex;

                DockPanel sp = new DockPanel();
                //  sp.Orientation = Orientation.Horizontal;

                //set up the button
                sp.Margin = new Thickness(4);
                Label l = new Label();
                l.Content = label;

                //add the label to the stackpanel if showLabel is true
                if (!string.IsNullOrWhiteSpace(label) & showLabel)
                {
                    sp.Name = "GH_PullDown_Label";
                    sp.Children.Add(l);
                }
                else
                {
                    sp.Name = "GH_PullDown_NoLabel";
                }

                //List<UIElement_Goo> combobox = new List<UIElement_Goo>() { new UIElement_Goo(pd, "Pulldown", InstanceGuid, Iterator) };

                sp.Children.Add(pd);

                //pass out the stackpanel
                DA.SetData("Pulldown", new UIElement_Goo(sp, String.Format("Pulldown: {0}", label), InstanceGuid, DA.Iteration));

                ////pass out the combobox
                //DA.SetDataList("Pulldown", new List<UIElement_Goo>() { new UIElement_Goo(pd, "Pulldown", InstanceGuid, Iterator) });
                //Iterator++;
            }
            else
            {
                List <UIElement_Goo> goosOut = new List <UIElement_Goo>();
                foreach (GH_ValueList valList in GHValLists)
                {
                    //initialize combobox
                    ComboBox pd = new ComboBox();
                    //for each string add a textbox object to the combobox

                    List <string> values = valList.ListItems.Select(li => li.Name).ToList();

                    foreach (string value in values)
                    {
                        TextBlock textbox = new TextBlock();
                        textbox.Text = value;
                        pd.Items.Add(textbox);
                    }
                    pd.Margin = new Thickness(4);
                    if (selectedIndexSupplied)
                    {
                        pd.SelectedIndex = selectedIndex;
                    }
                    else
                    {
                        pd.SelectedIndex = valList.ListItems.IndexOf(valList.FirstSelectedItem);
                    }

                    DockPanel sp = new DockPanel();
                    //  sp.Orientation = Orientation.Horizontal;

                    //set up the button
                    sp.Margin = new Thickness(4);
                    Label l = new Label();
                    l.Content = label;

                    //add the label to the stackpanel if showLabel is true
                    if (!string.IsNullOrWhiteSpace(label) & showLabel)
                    {
                        sp.Name = "GH_PullDown_Label";
                        sp.Children.Add(l);
                    }
                    else
                    {
                        sp.Name = "GH_PullDown_NoLabel";
                    }

                    sp.Children.Add(pd);

                    //pass out the stackpanel
                    DA.SetData("Pulldown", new UIElement_Goo(sp, String.Format("Pulldown: {0}", label), InstanceGuid, DA.Iteration));

                    ////pass out the combobox
                    //goosOut.Add(new UIElement_Goo(pd, "Pulldown", InstanceGuid, Iterator));
                    //Iterator++;
                }
                //DA.SetDataList("Pulldown", goosOut);
            }
        }
Example #37
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Retrive data from component
            List <double>          A         = new List <double>();
            List <double>          E         = new List <double>();
            List <Line>            lines     = new List <Line>();
            List <ContstraintNode> rNodes    = new List <ContstraintNode>();
            List <LoadNode>        loadNodes = new List <LoadNode>();
            double scaleFactor = 1.0;

            DA.GetDataList("Line", lines);
            DA.GetDataList("Area", A);
            DA.GetDataList("Youngs Modulus", E);
            DA.GetDataList("Restraint Nodes", rNodes);
            DA.GetDataList("Load Nodes", loadNodes);
            DA.GetData("Scale Factor", ref scaleFactor);

            // The length of A and E must be the same as lines
            if ((A.Count != E.Count) | (E.Count != lines.Count))
            {
                throw new ArgumentException("Length of A and E must equal length of Line");
            }

            // Create one list to store the nodes and one list to store the bars
            List <Node> trussNodes = new List <Node>();
            List <Bar>  trussBars  = new List <Bar>();

            // Topology matrix to keep track of element dofs
            List <List <int> > eDof = new List <List <int> >();

            // Loop trough each line and create nodes at end points
            for (int i = 0; i < lines.Count; i++)
            {
                Node node1 = new Node(lines[i].From);
                Node node2 = new Node(lines[i].To);

                // To keep track if the node is unique
                bool unique1 = true;
                bool unique2 = true;


                // Check if node is unique, if so give it an ID and degress of freedom
                foreach (Node existingNode in trussNodes)
                {
                    // If not unique use an already identified node
                    if (node1 == existingNode)
                    {
                        node1   = existingNode;
                        unique1 = false;
                    }

                    if (node2 == existingNode)
                    {
                        node2   = existingNode;
                        unique2 = false;
                    }
                }

                // If unique give it an ID
                if (unique1)
                {
                    int id_node_1 = trussNodes.Count;
                    node1.ID   = id_node_1;
                    node1.Dofs = System.Linq.Enumerable.Range(id_node_1 * 3, 3).ToList();

                    // Check if any boundary node or load node exist at current node
                    foreach (ContstraintNode rNode in rNodes)
                    {
                        if (rNode == node1)
                        {
                            // Add restraint data
                            node1.ConstraintX = rNode.ConstraintX;
                            node1.ConstraintY = rNode.ConstraintY;
                            node1.ConstraintZ = rNode.ConstraintZ;
                        }
                    }

                    foreach (LoadNode loadNode in loadNodes)
                    {
                        if (loadNode == node1)
                        {
                            // Add force data
                            node1.ForceX = loadNode.ForceX;
                            node1.ForceY = loadNode.ForceY;
                            node1.ForceZ = loadNode.ForceZ;
                        }
                    }


                    // Finally add the node
                    trussNodes.Add(node1);
                }

                if (unique2)
                {
                    int id_node_2 = trussNodes.Count;
                    node2.ID   = id_node_2;
                    node2.Dofs = System.Linq.Enumerable.Range(id_node_2 * 3, 3).ToList();

                    // Check if any boundary node or load node exist at current node
                    foreach (ContstraintNode rNode in rNodes)
                    {
                        if (rNode == node2)
                        {
                            // Add constraint data
                            node2.ConstraintX = rNode.ConstraintX;
                            node2.ConstraintY = rNode.ConstraintY;
                            node2.ConstraintZ = rNode.ConstraintZ;
                        }
                    }


                    foreach (LoadNode loadNode in loadNodes)
                    {
                        if (loadNode == node2)
                        {
                            // Add force data
                            node2.ForceX = loadNode.ForceX;
                            node2.ForceY = loadNode.ForceY;
                            node2.ForceZ = loadNode.ForceZ;
                        }
                    }

                    // Finally add the node
                    trussNodes.Add(node2);
                }


                // Create a bar object between the nodes
                Bar bar = new Bar(node1, node2, A[i], E[i]);
                trussBars.Add(bar);

                // Topology matrix
                List <int> dofs1 = bar.Nodes[0].Dofs;
                List <int> dofs2 = bar.Nodes[1].Dofs;

                List <int> eDofRow = new List <int>();
                eDofRow.AddRange(dofs1);
                eDofRow.AddRange(dofs2);
                eDof.Add(eDofRow);
            }

            int nDof  = trussNodes.Count * 3;
            int nElem = eDof.Count;


            // Loop trough each node and construct a load vector and boundary vector
            LinearAlgebra.Vector <double> forceVector = LinearAlgebra.Vector <double> .Build.Dense(nDof);

            List <int>     boundaryDofs        = new List <int>();
            List <double?> boundaryConstraints = new List <double?>();

            for (int i = 0; i < trussNodes.Count; i++)
            {
                // Load vector
                forceVector[i * 3]     = trussNodes[i].ForceX;
                forceVector[i * 3 + 1] = trussNodes[i].ForceY;
                forceVector[i * 3 + 2] = trussNodes[i].ForceZ;

                // Boundary vector
                for (int j = 0; j < 3; j++)
                {
                    if (j == 0 && trussNodes[i].ConstraintX != null)
                    {
                        boundaryDofs.Add(trussNodes[i].Dofs[j]);
                        boundaryConstraints.Add(trussNodes[i].ConstraintX);
                    }
                    else if (j == 1 && trussNodes[i].ConstraintY != null)
                    {
                        boundaryDofs.Add(trussNodes[i].Dofs[j]);
                        boundaryConstraints.Add(trussNodes[i].ConstraintY);
                    }

                    else if (j == 2 && trussNodes[i].ConstraintZ != null)
                    {
                        boundaryDofs.Add(trussNodes[i].Dofs[j]);
                        boundaryConstraints.Add(trussNodes[i].ConstraintZ);
                    }
                }
            }

            // Loop trough each element, compute local stiffness matrix and assemble into global stiffness matrix
            LinearAlgebra.Matrix <double> K = LinearAlgebra.Matrix <double> .Build.Dense(nDof, nDof);

            for (int i = 0; i < trussBars.Count; i++)
            {
                LinearAlgebra.Matrix <double> KElem = trussBars[i].ComputeStiffnessMatrix();

                // Assemble
                for (int k = 0; k < 6; k++)
                {
                    for (int l = 0; l < 6; l++)
                    {
                        K[eDof[i][k], eDof[i][l]] = K[eDof[i][k], eDof[i][l]] + KElem[k, l];
                    }
                }
            }

            // Calculate the displacements
            Solver solver = new Solver();

            LinearAlgebra.Vector <double> displacements = solver.solveEquations(K, forceVector, boundaryDofs, boundaryConstraints.Cast <double>().ToList());

            // Save the displacement for each node and calculate the stress in each bar
            List <double> elemStress = new List <double> {
            };

            for (int i = 0; i < nElem; i++)
            {
                double disp1 = displacements[eDof[i][0]];
                double disp2 = displacements[eDof[i][1]];
                double disp3 = displacements[eDof[i][2]];
                double disp4 = displacements[eDof[i][3]];
                double disp5 = displacements[eDof[i][4]];
                double disp6 = displacements[eDof[i][5]];

                Point3d newPoint1 = new Point3d(disp1 * scaleFactor, disp2 * scaleFactor, disp3 * scaleFactor);
                Point3d newPoint2 = new Point3d(disp4 * scaleFactor, disp5 * scaleFactor, disp6 * scaleFactor);

                // Translate original points
                trussBars[i].Nodes[0].Point = trussBars[i].Nodes[0].Point + newPoint1;
                trussBars[i].Nodes[1].Point = trussBars[i].Nodes[1].Point + newPoint2;

                // Calculate element stress
                elemStress.Add(trussBars[i].ComputeStress(new List <double> {
                    disp1, disp2, disp3, disp4, disp5, disp6
                }));
            }

            // Return the deformed lines
            List <Line> deformedLines = new List <Line>();

            foreach (Bar bar in trussBars)
            {
                deformedLines.Add(new Line(bar.Nodes[0].Point, bar.Nodes[1].Point));
            }
            DA.SetDataList("Deformed Truss", deformedLines);
            DA.SetDataList("Element Stress", elemStress);
        }
        // This is the method that actually does the work.
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Some variables
            string output = "";                        // The file output
            string status = "Starting component...\n"; // The debug output

            // Several arrays where the data is stored
            List <Material>     materials     = new List <Material>();
            List <CrossSection> crossSections = new List <CrossSection>();
            List <Node>         nodes         = new List <Node>();
            List <Beam>         beams         = new List <Beam>();
            List <Load>         loads         = new List <Load>();

            // We need to reset some variables because the objects are not freed until Grasshopper is unloaded
            Parser.id_count = 1;

            try {
                // Load the data from Karamba

                // Retrieve and clone the input model
                GH_Model in_gh_model = null;
                if (!DA.GetData <GH_Model>(0, ref in_gh_model))
                {
                    return;
                }
                Model model = in_gh_model.Value;
                model = (Karamba.Models.Model)model.Clone();  // If the model is not cloned a modification to this variable will imply modification of the input model, thus modifying behavior in other components.

                if (model == null)
                {
                    status += "ERROR: The input model is null.";
                    output  = "Nothing to convert";
                }
                else
                {
                    string path = null;
                    if (!DA.GetData <string>(1, ref path))
                    {
                        path = "";
                    }
                    if (path == "")
                    {
                        status += "No file path specified. Will not save data to a .dat file.\n";
                    }



                    // Retrieve and store the data

                    // Materials
                    foreach (Karamba.Materials.FemMaterial material in model.materials)
                    {
                        // The first material seems to be wong but I don't know why it exists
                        if (model.materials.IndexOf(material) != 0)
                        {
                            materials.Add(new Material(material));
                        }
                    }

                    /*Disabled for forward compatibility
                     * // Check for material duplicates
                     * // This is necessary because karamba uses a preset material that is added every time that a model is assembled
                     * // As a consequence a model can get a great amount of redundant materials that will flood the output
                     *
                     * // Furthermore karamba seems to create a buggy material at index 0 during the cloning operation
                     * materials.RemoveAt(0);
                     * // Using a for loop because a collection used in foreach is immutable
                     * for (int i = 0; i < materials.Count; i++) {
                     *  materials.RemoveAll(delegate(Material test_material) {
                     *      return test_material.id != materials[i].id && materials[i].duplicate(test_material);
                     *  });
                     * }
                     */
                    status += materials.Count + " materials loaded...\n";



                    // Cross sections
                    foreach (Karamba.CrossSections.CroSec crosec in model.crosecs)
                    {
                        crossSections.Add(new CrossSection(crosec));
                    }

                    /*Disabled for forward compatibility
                     * // The same happens with Cross Sections
                     * crossSections.RemoveAt(0);
                     * for (int i = 0; i < crossSections.Count; i++) {
                     *  crossSections.RemoveAll(delegate(CrossSection test_crosec) {
                     *      return test_crosec.id != crossSections[i].id && crossSections[i].duplicate(test_crosec);
                     *  });
                     * }
                     * status += crossSections.Count + " cross sections loaded...\n";
                     */


                    // Nodes
                    foreach (Karamba.Nodes.Node node in model.nodes)
                    {
                        nodes.Add(new Node(node));
                    }
                    status += nodes.Count + " nodes loaded...\n";

                    foreach (Karamba.Supports.Support support in model.supports)
                    {
                        nodes[support.node_ind].addConstraint(support);
                    }
                    status += "Support constraints added to " + model.supports.Count + " nodes.\n";



                    // Beams
                    foreach (Karamba.Elements.ModelElement beam in model.elems)
                    {
                        Beam curBeam = new Beam(beam);

                        // Adding the start and end nodes
                        curBeam.start = nodes[curBeam.ids[0]];
                        curBeam.end   = nodes[curBeam.ids[1]];
                        beams.Add(curBeam);
                    }
                    status += beams.Count + " beams loaded...\n";



                    // Loads
                    foreach (KeyValuePair <int, Karamba.Loads.GravityLoad> load in model.gravities)
                    {
                        loads.Add(new Load(load));
                    }
                    status += model.gravities.Count + " gravity loads added.\n";

                    foreach (Karamba.Loads.PointLoad load in model.ploads)
                    {
                        Load current = new Load(load);
                        current.node = nodes[load.node_ind];
                        loads.Add(current);
                    }
                    status += model.ploads.Count + " point loads added.\n";

                    foreach (Karamba.Loads.ElementLoad load in model.eloads)
                    {
                        // Create a load variable base on the load type
                        Load current = new Load();

                        Karamba.Loads.UniformlyDistLoad line = load as Karamba.Loads.UniformlyDistLoad;
                        Karamba.Loads.PreTensionLoad    pret = load as Karamba.Loads.PreTensionLoad;
                        Karamba.Loads.TemperatureLoad   temp = load as Karamba.Loads.TemperatureLoad;

                        if (line != null)
                        {
                            current = new Load(line);
                        }
                        // Very important to check Temperature BEFORE Pretension becaus Temperature derivates from Pretension
                        else if (temp != null)
                        {
                            current = new Load(temp);
                        }
                        else if (pret != null)
                        {
                            current = new Load(pret);
                        }


                        // If there is not target element, apply the load to the whole structure
                        if (load.beamId == "")
                        {
                            current.beam_id = "";
                            loads.Add(current);
                        }
                        else
                        {
                            // We search the element
                            current.beam = beams.Find(delegate(Beam beam) {
                                return(beam.user_id == load.beamId);
                            });
                            loads.Add(current);
                        }
                    }

                    status += model.eloads.Count + " line loads added.\n";

                    // ID matching
                    // Karamba and Sofistik use different ID systems
                    // Karamba's materials and cross sections are pointing to an element ID
                    // Sofistik's elements need a cross section ID which needs a material ID

                    foreach (Material material in materials)
                    {
                        // If the IDs list is empty, it means that we want to apply the material to the whole structure (whichi is the default behavior: the default material is set by the constructors of all elements)
                        bool test = false;
                        foreach (string id in material.ids)
                        {
                            if (id != "")
                            {
                                test = true;
                            }
                        }
                        if (test)
                        {
                            foreach (CrossSection crosec in crossSections)
                            {
                                if (material.ids.Contains((crosec.id - 1).ToString()))
                                {
                                    crosec.material = material;
                                }
                            }
                        }
                    }
                    status += "Matching with material IDs...\n";

                    foreach (CrossSection crosec in crossSections)
                    {
                        // If the IDs list is empty, it means that we want to apply the cross section to the whole structure (which is the default behavior: the default cross section is set by the constructors of all elements)
                        bool test = false;
                        foreach (string id in crosec.ids)
                        {
                            if (id != "")
                            {
                                test = true;
                            }
                        }
                        if (test)
                        {
                            foreach (Beam beam in beams)
                            {
                                if (crosec.ids.Contains((beam.id - 1).ToString()))
                                {
                                    beam.sec = crosec;
                                }
                            }
                        }
                    }
                    status += "Matching with cross section IDs...\n";

                    // Write the data into a .dat file format
                    Parser parser = new Parser(materials, crossSections, nodes, beams, loads);
                    output = parser.file;

                    if (path != "")
                    {
                        status += "Saving file to " + path + "\n";
                        System.IO.File.WriteAllText(@path, output);
                        status += "File saved!\n";
                    }
                }
            }
            catch (Exception e) {
                status += "\nERROR!\n" + e.ToString() + "\n" + e.Data;
            }

            // Return data
            DA.SetData(0, output);
            DA.SetData(1, status);
        }
Example #39
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Autodesk.Revit.DB.Family family = null;
            if (!DA.GetData("Family", ref family))
            {
                return;
            }

            var filePath = string.Empty;

            DA.GetData("Path", ref filePath);

            var overrideFile = false;

            if (!DA.GetData("OverrideFile", ref overrideFile))
            {
                return;
            }

            var compact = false;

            if (!DA.GetData("Compact", ref compact))
            {
                return;
            }

            var backups = -1;

            if (!DA.GetData("Backups", ref backups))
            {
                return;
            }

            if (Revit.ActiveDBDocument.EditFamily(family) is Document familyDoc)
            {
                using (familyDoc)
                {
                    try
                    {
                        var options = new SaveAsOptions()
                        {
                            OverwriteExistingFile = overrideFile, Compact = compact
                        };
                        if (backups > -1)
                        {
                            options.MaximumBackups = backups;
                        }

                        if (string.IsNullOrEmpty(filePath))
                        {
                            filePath = familyDoc.PathName;
                        }

                        if (string.IsNullOrEmpty(filePath))
                        {
                            filePath = familyDoc.Title;
                        }

                        if (Directory.Exists(filePath))
                        {
                            filePath = Path.Combine(filePath, filePath);
                        }

                        if (!Path.HasExtension(filePath))
                        {
                            filePath += ".rfa";
                        }

                        if (Path.IsPathRooted(filePath))
                        {
                            familyDoc.SaveAs(filePath, options);
                            DA.SetData("Family", family);
                        }
                        else
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Path should be absolute.");
                        }
                    }
                    catch (Autodesk.Revit.Exceptions.InvalidOperationException e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); }
                    finally { familyDoc.Close(false); }
                }
            }
            else
            {
                DA.SetData("Family", null);
            }
        }
Example #40
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var doc         = Revit.ActiveDBDocument;
            var scaleFactor = 1.0 / Revit.ModelUnits;

            var overrideFamily = false;

            if (!DA.GetData("OverrideFamily", ref overrideFamily))
            {
                return;
            }

            var overrideParameters = false;

            if (!DA.GetData("OverrideParameters", ref overrideParameters))
            {
                return;
            }

            var name = string.Empty;

            if (!DA.GetData("Name", ref name))
            {
                return;
            }

            var categoryId = ElementId.InvalidElementId;

            DA.GetData("Category", ref categoryId);
            var updateCategory = categoryId != ElementId.InvalidElementId;

            var geometry       = new List <IGH_GeometricGoo>();
            var updateGeometry = !(!DA.GetDataList("Geometry", geometry) && Params.Input[Params.IndexOfInputParam("Geometry")].SourceCount == 0);

            var family = default(Family);

            using (var collector = new FilteredElementCollector(doc).OfClass(typeof(Family)))
                family = collector.ToElements().Cast <Family>().Where(x => x.Name == name).FirstOrDefault();

            bool familyIsNew = family is null;

            var templatePath = string.Empty;

            if (familyIsNew)
            {
                if (!DA.GetData("Template", ref templatePath))
                {
                    templatePath = GetFamilyTemplateFilePath(categoryId, doc.Application);
                }

                if (!Path.HasExtension(templatePath))
                {
                    templatePath += ".rft";
                }

                if (!Path.IsPathRooted(templatePath))
                {
                    templatePath = Path.Combine(doc.Application.FamilyTemplatePath, templatePath);
                }
            }
            else
            {
                updateCategory &= family.FamilyCategory.Id != categoryId;
            }

            if (familyIsNew || (overrideFamily && (updateCategory || updateGeometry)))
            {
                try
                {
                    if
                    (
                        (
                            familyIsNew ?
                            doc.Application.NewFamilyDocument(templatePath) :
                            doc.EditFamily(family)
                        )
                        is var familyDoc
                    )
                    {
                        try
                        {
                            using (var transaction = new Transaction(familyDoc))
                            {
                                transaction.Start(Name);

                                if (updateCategory && familyDoc.OwnerFamily.FamilyCategoryId != categoryId)
                                {
                                    try { familyDoc.OwnerFamily.FamilyCategoryId = categoryId; }
                                    catch (Autodesk.Revit.Exceptions.ArgumentException e)
                                    {
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                        return;
                                    }
                                }

                                if (updateGeometry)
                                {
                                    using (var collector = new FilteredElementCollector(familyDoc).OfClass(typeof(GenericForm)))
                                        familyDoc.Delete(collector.ToElementIds());

                                    using (var collector = new FilteredElementCollector(familyDoc).OfClass(typeof(CurveElement)))
                                        familyDoc.Delete(collector.ToElementIds());

                                    bool hasVoids          = false;
                                    var  planesSet         = new List <KeyValuePair <double[], SketchPlane> >();
                                    var  planesSetComparer = new PlaneComparer();

                                    foreach (var geo in geometry.Select(x => AsGeometryBase(x).ChangeUnits(scaleFactor)))
                                    {
                                        try
                                        {
                                            switch (geo)
                                            {
                                            case Rhino.Geometry.Brep brep: hasVoids |= Add(doc, familyDoc, brep); break;

                                            case Rhino.Geometry.Curve curve: Add(doc, familyDoc, curve, planesSet); break;

                                            default: AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"{geo.GetType().Name} is not supported and will be ignored"); break;
                                            }
                                        }
                                        catch (Autodesk.Revit.Exceptions.InvalidOperationException e)
                                        {
                                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                        }
                                    }

                                    familyDoc.OwnerFamily.get_Parameter(BuiltInParameter.FAMILY_ALLOW_CUT_WITH_VOIDS).Set(hasVoids ? 1 : 0);
                                }

                                transaction.Commit();
                            }

                            family = familyDoc.LoadFamily(doc, new FamilyLoadOptions(overrideFamily, overrideParameters));
                        }
                        finally
                        {
                            familyDoc.Close(false);
                        }

                        if (familyIsNew)
                        {
                            using (var transaction = new Transaction(doc))
                            {
                                transaction.Start(Name);
                                try { family.Name = name; }
                                catch (Autodesk.Revit.Exceptions.ArgumentException e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message); }

                                if (doc.GetElement(family.GetFamilySymbolIds().First()) is FamilySymbol symbol)
                                {
                                    symbol.Name = name;
                                }

                                transaction.Commit();
                            }
                        }
                    }
                }
                catch (Autodesk.Revit.Exceptions.ArgumentException e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                }
            }
            else if (!overrideFamily)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Family '{name}' already loaded!");
            }

            DA.SetData("Family", family);
        }
Example #41
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var viewSpecific = false; if (!DA.GetData("ViewSpecific", ref viewSpecific))
            {
                return;
            }

            var planRCPCut = false;   if (!DA.GetData("PlanRCPCut", ref planRCPCut))
            {
                return;
            }
            var topBottom = false;    if (!DA.GetData("TopBottom", ref topBottom))
            {
                return;
            }
            var frontBack = false;    if (!DA.GetData("FrontBack", ref frontBack))
            {
                return;
            }
            var leftRight = false;    if (!DA.GetData("LeftRight", ref leftRight))
            {
                return;
            }
            var onlyWhenCut = false;  if (!DA.GetData("OnlyWhenCut", ref onlyWhenCut))
            {
                return;
            }

            var coarse = false;       if (!DA.GetData("Coarse", ref coarse))
            {
                return;
            }
            var medium = false;       if (!DA.GetData("Medium", ref medium))
            {
                return;
            }
            var fine = false;         if (!DA.GetData("Fine", ref fine))
            {
                return;
            }

            int value = 0;

            if (viewSpecific)
            {
                value |= 1 << 1;
            }

            if (planRCPCut)
            {
                value |= 1 << 2;
            }
            if (topBottom)
            {
                value |= 1 << 3;
            }
            if (frontBack)
            {
                value |= 1 << 4;
            }
            if (leftRight)
            {
                value |= 1 << 5;
            }
            if (onlyWhenCut)
            {
                value |= 1 << 6;
            }

            if (coarse)
            {
                value |= 1 << 13;
            }
            if (medium)
            {
                value |= 1 << 14;
            }
            if (fine)
            {
                value |= 1 << 15;
            }

            DA.SetData("Visibility", value);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // get input
            Brep surface = null;

            if (!DA.GetData(0, ref surface))
            {
                return;
            }

            List <FemDesign.Shells.Thickness> thickness = new List <FemDesign.Shells.Thickness>();

            if (!DA.GetDataList(1, thickness))
            {
                return;
            }

            FemDesign.Materials.Material material = null;
            if (!DA.GetData(2, ref material))
            {
                return;
            }

            FemDesign.Shells.ShellEccentricity eccentricity = FemDesign.Shells.ShellEccentricity.GetDefault();
            if (!DA.GetData(3, ref eccentricity))
            {
                // pass
            }

            FemDesign.Shells.ShellOrthotropy orthotropy = FemDesign.Shells.ShellOrthotropy.GetDefault();
            if (!DA.GetData(4, ref orthotropy))
            {
                // pass
            }

            FemDesign.Shells.EdgeConnection edgeConnection = FemDesign.Shells.EdgeConnection.GetRigid();
            if (!DA.GetData(5, ref edgeConnection))
            {
                // pass
            }

            Rhino.Geometry.Vector3d x = Vector3d.Zero;
            if (!DA.GetData(6, ref x))
            {
                // pass
            }

            Rhino.Geometry.Vector3d z = Vector3d.Zero;
            if (!DA.GetData(7, ref z))
            {
                // pass
            }

            string identifier = "P";

            if (!DA.GetData(8, ref identifier))
            {
                // pass
            }
            if (surface == null || thickness == null || material == null || eccentricity == null || orthotropy == null || edgeConnection == null)
            {
                return;
            }
            if (thickness.Count != 3)
            {
                throw new System.ArgumentException("Thickness must contain exactly 3 items.");
            }

            //
            FemDesign.Geometry.Region region = surface.FromRhino();

            //
            FemDesign.Shells.Slab obj = FemDesign.Shells.Slab.Plate(identifier, material, region, edgeConnection, eccentricity, orthotropy, thickness);

            // set local x-axis
            if (!x.Equals(Vector3d.Zero))
            {
                obj.SlabPart.LocalX = x.FromRhino();
            }

            // set local z-axis
            if (!z.Equals(Vector3d.Zero))
            {
                obj.SlabPart.LocalZ = z.FromRhino();
            }

            // return
            DA.SetData(0, obj);
        }
Example #43
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="dataAccess">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            int index_successful = Params.IndexOfOutputParam("successful");

            if (index_successful != -1)
            {
                dataAccess.SetData(index_successful, false);
            }

            int index;

            bool run = false;

            index = Params.IndexOfInputParam("_run");
            if (index == -1 || !dataAccess.GetData(index, ref run))
            {
                run = false;
            }

            if (!run)
            {
                return;
            }

            string path = null;

            index = Params.IndexOfInputParam("_path_TBD");
            if (index == -1 || !dataAccess.GetData(index, ref path) || string.IsNullOrWhiteSpace(path))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            AnalyticalModel analyticalModel = null;

            index = Params.IndexOfInputParam("_analyticalModel");
            if (index == -1 || !dataAccess.GetData(index, ref analyticalModel) || string.IsNullOrWhiteSpace(path))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            WeatherData weatherData = null;

            index = Params.IndexOfInputParam("weatherData_");
            if (index != -1)
            {
                if (!dataAccess.GetData(index, ref weatherData))
                {
                    weatherData = null;
                }
            }

            List <DesignDay> heatingDesignDays = new List <DesignDay>();

            index = Params.IndexOfInputParam("heatingDesignDays_");
            if (index == -1 || !dataAccess.GetDataList(index, heatingDesignDays) || heatingDesignDays == null || heatingDesignDays.Count == 0)
            {
                heatingDesignDays = null;
            }

            List <DesignDay> coolingDesignDays = new List <DesignDay>();

            index = Params.IndexOfInputParam("coolingDesignDays_");
            if (index == -1 || !dataAccess.GetDataList(index, coolingDesignDays) || coolingDesignDays == null || coolingDesignDays.Count == 0)
            {
                coolingDesignDays = null;
            }

            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            using (SAMTBDDocument sAMTBDDocument = new SAMTBDDocument(path))
            {
                TBD.TBDDocument tBDDocument = sAMTBDDocument.TBDDocument;

                if (weatherData != null)
                {
                    Weather.Tas.Modify.UpdateWeatherData(tBDDocument, weatherData);
                }

                TBD.Calendar calendar = tBDDocument.Building.GetCalendar();

                List <TBD.dayType> dayTypes = Grashopper.Tas.Query.DayTypes(calendar);
                if (dayTypes.Find(x => x.name == "HDD") == null)
                {
                    TBD.dayType dayType = calendar.AddDayType();
                    dayType.name = "HDD";
                }

                if (dayTypes.Find(x => x.name == "CDD") == null)
                {
                    TBD.dayType dayType = calendar.AddDayType();
                    dayType.name = "CDD";
                }

                Analytical.Tas.Convert.ToTBD(analyticalModel, tBDDocument);
                Analytical.Tas.Modify.UpdateZones(tBDDocument.Building, analyticalModel, true);

                if (coolingDesignDays != null || heatingDesignDays != null)
                {
                    Analytical.Tas.Modify.AddDesignDays(tBDDocument, coolingDesignDays, heatingDesignDays, 30);
                }

                sAMTBDDocument.Save();
            }

            index = Params.IndexOfOutputParam("analyticalModel");
            if (index != -1)
            {
                dataAccess.SetData(index, analyticalModel);
            }

            if (index_successful != -1)
            {
                dataAccess.SetData(index_successful, true);
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var res   = new List <string>();
            var @base = new Base();

            for (int i = 0; i < Params.Input.Count; i++)
            {
                var param      = Params.Input[i] as GenericAccessParam;
                var type       = param.Access.ToString();
                var detachable = param.Detachable;

                var key = detachable ? "@" + param.NickName : param.NickName;

                object result = null;

                switch (param.Access)
                {
                case GH_ParamAccess.item:
                    object value = null;
                    DA.GetData(i, ref value);

                    if (value == null)
                    {
                        break;
                    }

                    result = Utilities.TryConvertItemToSpeckle(value, Converter);

                    if (result == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Data of type {value.GetType().Name} in {param.NickName} could not be converted.");
                    }
                    break;

                case GH_ParamAccess.list:
                    var myList = new List <object>();
                    var values = new List <object>();
                    var j      = 0;
                    DA.GetDataList(i, values);

                    if (values == null)
                    {
                        break;
                    }

                    foreach (var item in values)
                    {
                        var conv = Utilities.TryConvertItemToSpeckle(item, Converter);
                        myList.Add(conv);
                        if (conv == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Data of type {item.GetType().Name} in {param.NickName} at index {j} could not be converted.");
                        }
                        j++;
                    }

                    result = myList;
                    break;
                }

                res.Add($"{key} ({type}, detach {detachable}) {result?.ToString()} \n");

                if (result != null)
                {
                    @base[key] = result;
                }
            }

            DA.SetData(0, new GH_SpeckleBase()
            {
                Value = @base
            });
        }
Example #45
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)
        {
            IGH_Goo goo = null;
            Bitmap  top = new Bitmap(100, 100);

            if (!DA.GetData(0, ref goo))
            {
                return;
            }
            if (!goo.TryGetBitmap(ref top))
            {
                return;
            }

            Mp.Layer topLayer = new Mp.Layer(top);

            IGH_Goo gooT   = null;
            Bitmap  bottom = new Bitmap(100, 100);

            if (!DA.GetData(1, ref gooT))
            {
                return;
            }
            if (!gooT.TryGetBitmap(ref bottom))
            {
                return;
            }

            Mp.Layer bottomLayer = new Mp.Layer(bottom);

            IGH_Goo gooM    = null;
            Image   img     = new Image();
            bool    hasMask = false;
            Bitmap  mask    = new Bitmap(100, 100);

            if (DA.GetData(2, ref gooM))
            {
                if (gooM.TryGetImage(ref img))
                {
                    hasMask = true;
                    img.SwapChannel(Image.Channels.Luminance, Image.Channels.Alpha);
                    mask = img.Bitmap;
                }
            }

            int blendMode = 0;

            DA.GetData(3, ref blendMode);

            double opacity = 1.0;

            DA.GetData(4, ref opacity);

            topLayer.BlendMode = (Mp.Layer.BlendModes)blendMode;
            topLayer.Opacity   = 100 * opacity;
            if (hasMask)
            {
                topLayer.Mask = mask;
            }

            Mp.Composition composition = new Mp.Composition();
            composition.Layers.Add(bottomLayer);
            composition.Layers.Add(topLayer);

            DA.SetData(0, new Image(composition.GetBitmap()));
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA, EvaluationUnit unit)
        {
            //OnComponentLoaded();

            // Input counter
            //modelDataCount1 = 1 + modelDataCount2;

            // RFEM variables
            var        modelName = "";
            IModel     model     = null;
            IModelData data      = null;
            ILoads     loads     = null;

            // Output message
            var msg = new List <string>();

            // Assign GH Input
            bool run   = false;
            var  scale = 0.0;

            DA.GetData(0, ref run);
            DA.GetData(1, ref scale);

            // Do stuff
            if (run)
            {
                if (!DA.GetData(3, ref modelName))
                {
                    Component_GetData.ConnectRFEM(ref model, ref data);
                }
                else
                {
                    Component_GetData.ConnectRFEM(modelName, ref model, ref data);
                }
                _saveddata = data;
                try
                {
                    // Get deformtions
                    _resetLC = true;
                    // Get loads
                    Component_GetData.GetLoadsFromRFEM(model, ref loads);
                    // Get calculation results
                    _results = model.GetCalculation();
                    var errors = _results.CalculateAll();
                    if (errors != null)
                    {
                        msg.AddRange(errors.Select(x => x.Description));
                    }
                    // Update load cases and combos to display in dropdown menu
                    loads.GetLoadCasesAndCombos(ref _lCasesAndCombos, ref _countCases, ref _countCombos, ref _countRcombos);
                    updateDropDownMenu(_lCasesAndCombos);
                    // Get Fe Meshes from RFEM
                    _rfemMesh = _results.GetFeMesh();
                    _feMeshes = CreateFEMeshes(ref msg);
                    // _controlPoints = CreateControlPoints(ref msg); -> Obtained with displacements
                }
                catch (Exception ex)
                {
                    // Clear output!!!
                    _saveddata = null;
                    _rfemMesh  = null;
                    _results   = null;
                    _lcresults = null;
                    _feMeshes.Clear();
                    _meshdisplacements.Clear();
                    _deformedMeshes.Clear();
                    _controlPoints.Clear();
                    _memberdisplacements.Clear();
                    _deformedMembers.Clear();
                    throw ex;
                }
                Component_GetData.DisconnectRFEM(ref model, ref data);
            }
            // Get results to display
            if (_loadDrop.Items.Count > 0 && _resetLC && msg.Count == 0)
            {
                int no = Int16.Parse(_loadDrop.Items[_loadDrop.Value].name.Split(' ')[1]);
                if (_loadDrop.Value < _countCases)
                {
                    _lcresults = _results.GetResultsInFeNodes(LoadingType.LoadCaseType, no);
                }
                else if (_loadDrop.Value < _countCases + _countCombos)
                {
                    _lcresults = _results.GetResultsInFeNodes(LoadingType.LoadCombinationType, no);
                }
                else if (_loadDrop.Value < _countCases + _countCombos + _countRcombos)
                {
                    _lcresults = _results.GetResultsInFeNodes(LoadingType.ResultCombinationType, no);
                }
                else
                {
                    msg.Add("Load case or combo not found");
                }
                // Get deformations
                _meshdisplacements   = GetMeshDisplacements(ref msg);
                _memberdisplacements = GetMemberDisplacements(ref msg);
                // Set _resetLC to false again
                _resetLC = false;
            }

            // Get output
            _deformedMeshes  = GetDeformedMeshes(scale, ref msg);
            _deformedMembers = GetDeformedMembers(scale, ref msg);

            // Assign GH Output
            DA.SetDataTree(0, _deformedMembers);
            DA.SetDataTree(1, _deformedMeshes);

            if (msg.Count != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, String.Join(System.Environment.NewLine, msg.ToArray()));
            }
        }
Example #47
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 first time put the panel geo to memory only once
            Boolean start = false;

            if (!DA.GetData(3, ref start))
            {
                return;
            }

            if (!ready && start && PathMaker.analysisPoint3d.Count > 0)
            {
                Vector3d moveTemp = new Vector3d(0, 0, 0);
                if (!DA.GetData(4, ref moveTemp))
                {
                    return;
                }
                List <Brep> panelTemp = new List <Brep>();
                Brep        baseTemp  = null;
                if (!DA.GetData(1, ref panelTemp))
                {
                    return;
                }
                if (!DA.GetData(0, ref baseTemp))
                {
                    return;
                }
                for (int i = 0; i < PathMaker.analysisPoint3d.Count; i++)
                {
                    List <Brep> panelTemp2 = new List <Brep>(panelTemp);
                    Brep        baseTemp2  = baseTemp.DuplicateBrep();
                    Vector3d    totVec     = new Vector3d(0, 0, 0);
                    totVec += new Rhino.Geometry.Vector3d(PathMaker.analysisPoint3d[i]);
                    totVec += moveTemp;
                    baseTemp.Translate(totVec);
                    baseGeo.Add(baseTemp);

                    for (int j = 0; j < panelTemp2.Count; j++)
                    {
                        Brep panelTempBrep = panelTemp2[i];
                        panelTempBrep.Translate(totVec);
                        panelGeo.Add(panelTempBrep);
                    }
                }
                if (!DA.GetData(2, ref robo))
                {
                    return;
                }

                ready = true;
            }

            foreach (Double d in analysisResults)
            {
                colors.Clear();
                if (d < 15)
                {
                    colors.Add(System.Drawing.Color.FromArgb(0, 255, 0));
                }
                else
                {
                    int r = 0 + Map((int)d - 15, 0, 85, 0, 255);
                    int g = 255 - Map((int)d - 15, 0, 85, 0, 255);
                    colors.Add(System.Drawing.Color.FromArgb(r, g, 0));
                }
            }

            if (PathMaker.actionCount > roboLoc)
            {
                Vector3d vecMove  = new Vector3d(0, 0, 0);
                Vector3d vecTemp1 = new Vector3d(PathMaker.inputPoints[roboLoc]);
                Vector3d vecTemp2 = new Vector3d(PathMaker.inputPoints[PathMaker.actionCount]);
                vecMove += vecTemp2 - vecTemp1;

                robo.Translate(vecMove);
                roboLoc = PathMaker.actionCount;
            }
        }
Example #48
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            string ctrl = da.GetData <string>(1);
            double tolg = da.GetData <double>(2);
            bool   mesh = da.GetData <bool>(3);
            double hmin = da.GetData <double>(4);
            string text = da.GetData <string>(5);

            var structural_elements = new List <IGS_StructuralElement>();

            foreach (var it in da.GetDataList <IGH_Goo>(0))
            {
                if (it is IGS_StructuralElement)
                {
                    structural_elements.Add(it as IGS_StructuralElement);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Data conversion failed from " + it.TypeName + " to IGS_StructuralElement.");
                }
            }

            var sb = new StringBuilder();

            sb.AppendLine("+PROG SOFIMSHC");
            sb.AppendLine("HEAD");
            sb.AppendLine("PAGE UNII 0"); // export always in SOFiSTiK database units
            sb.AppendLine("SYST 3D GDIR NEGZ GDIV -1000");
            sb.AppendFormat("CTRL TOLG {0:F6}\n", tolg);
            if (mesh)
            {
                sb.AppendLine("CTRL MESH 1");
                sb.AppendFormat("CTRL HMIN {0:F3}\n", hmin);
            }

            // add control string
            if (!string.IsNullOrEmpty(ctrl))
            {
                sb.Append(ctrl);
            }
            sb.AppendLine();

            // write structural lines
            foreach (var se in structural_elements)
            {
                if (se is GS_StructuralPoint)
                {
                    var     spt = se as GS_StructuralPoint;
                    Point3d p   = spt.Value.Location;

                    string id_string = spt.Id > 0 ? spt.Id.ToString() : "-";

                    sb.AppendFormat("SPT {0} X {1:F8} {2:F8} {3:F8}", id_string, p.X, p.Y, p.Z);

                    if (spt.DirectionLocalX.Length > 0.0)
                    {
                        sb.AppendFormat(" SX {0:F6} {1:F6} {2:F6}", spt.DirectionLocalX.X, spt.DirectionLocalX.Y, spt.DirectionLocalX.Z);
                    }

                    if (spt.DirectionLocalZ.Length > 0.0)
                    {
                        sb.AppendFormat(" NX {0:F6} {1:F6} {2:F6}", spt.DirectionLocalZ.X, spt.DirectionLocalZ.Y, spt.DirectionLocalZ.Z);
                    }

                    if (string.IsNullOrWhiteSpace(spt.FixLiteral) == false)
                    {
                        sb.AppendFormat(" FIX {0}", spt.FixLiteral);
                    }

                    sb.AppendLine();
                }
                // write structural lines
                else if (se is GS_StructuralLine)
                {
                    var sln = se as GS_StructuralLine;

                    string id_string  = sln.Id > 0 ? sln.Id.ToString() : "-";
                    string id_group   = sln.GroupId > 0 ? sln.GroupId.ToString() : "-";
                    string id_section = sln.SectionId > 0 ? sln.SectionId.ToString() : "-";

                    sb.AppendFormat("SLN {0} GRP {1} SNO {2}", id_string, id_group, id_section);

                    if (sln.DirectionLocalZ.Length > 0.0)
                    {
                        sb.AppendFormat(" DRX {0:F6} {1:F6} {2:F6}", sln.DirectionLocalZ.X, sln.DirectionLocalZ.Y, sln.DirectionLocalZ.Z);
                    }

                    if (string.IsNullOrWhiteSpace(sln.FixLiteral) == false)
                    {
                        sb.AppendFormat(" FIX {0}", sln.FixLiteral);
                    }

                    sb.AppendLine();

                    AppendCurveGeometry(sb, sln.Value);
                }
                // write structural areas
                else if (se is GS_StructuralArea)
                {
                    var sar  = se as GS_StructuralArea;
                    var brep = sar.Value;

                    string id_string  = sar.Id > 0 ? sar.Id.ToString() : "-";
                    string grp_string = sar.GroupId > 0 ? sar.GroupId.ToString() : "-";
                    string thk_string = sar.Thickness.ToString("F6");

                    // some preparations
                    brep.CullUnusedSurfaces();
                    brep.CullUnusedFaces();
                    brep.CullUnusedEdges();

                    // loop over all faces within the brep
                    foreach (var fc in brep.Faces)
                    {
                        // checks and preparations
                        fc.ShrinkFace(BrepFace.ShrinkDisableSide.ShrinkAllSides);

                        if (fc.IsClosed(0) || fc.IsClosed(1))
                        {
                            this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "A given Surface is closed in one direction.\nSuch surfaces cannot be handled by SOFiMSHC and need to be split.");
                        }

                        // write SAR header
                        sb.AppendLine();
                        sb.AppendFormat("SAR {0} GRP {1} T {2}", id_string, grp_string, thk_string);
                        id_string = string.Empty; // set only the 1st time

                        if (sar.MaterialId > 0)
                        {
                            sb.AppendFormat(" MNO {0}", sar.MaterialId.ToString());
                        }
                        if (sar.ReinforcementId > 0)
                        {
                            sb.AppendFormat(" MRF {0}", sar.ReinforcementId.ToString());
                        }
                        if (sar.DirectionLocalX.Length > 1.0E-8)
                        {
                            sb.AppendFormat(" DRX {0:F6} {1:F6} {2:F6}", sar.DirectionLocalX.X, sar.DirectionLocalX.Y, sar.DirectionLocalX.Z);
                        }

                        sb.AppendLine();

                        // outer boundary
                        AppendSurfaceBoundary(sb, fc);

                        // write geometry
                        if (fc.IsPlanar() == false)
                        {
                            AppendSurfaceGeometry(sb, fc.ToNurbsSurface());
                        }
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unsupported type encountered: " + se.TypeName);
                }
            }
            sb.AppendLine();

            // add control string
            if (!string.IsNullOrEmpty(text))
            {
                sb.Append(text);
            }
            sb.AppendLine();
            sb.AppendLine("END");

            da.SetData(0, sb.ToString());
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GsaGridLineLoad gridlineload = new GsaGridLineLoad();

            // 0 Load case
            int        lc    = 1;
            GH_Integer gh_lc = new GH_Integer();

            if (DA.GetData(0, ref gh_lc))
            {
                GH_Convert.ToInt32(gh_lc, out lc, GH_Conversion.Both);
            }
            gridlineload.GridLineLoad.Case = lc;

            // Do plane input first as to see if we need to project polyline onto grid plane
            // 2 Plane
            Plane pln      = Plane.WorldXY;
            bool  planeSet = false;
            GsaGridPlaneSurface grdplnsrf = new GsaGridPlaneSurface();
            GH_ObjectWrapper    gh_typ    = new GH_ObjectWrapper();

            if (DA.GetData(2, ref gh_typ))
            {
                if (gh_typ.Value is GsaGridPlaneSurfaceGoo)
                {
                    GsaGridPlaneSurface temppln = new GsaGridPlaneSurface();
                    gh_typ.CastTo(ref temppln);
                    grdplnsrf = temppln.Duplicate();
                    pln       = grdplnsrf.Plane;
                    planeSet  = true;
                }
                else if (gh_typ.Value is Plane)
                {
                    gh_typ.CastTo(ref pln);
                    grdplnsrf = new GsaGridPlaneSurface(pln);
                    planeSet  = true;
                }
                else
                {
                    int id = 0;
                    if (GH_Convert.ToInt32(gh_typ.Value, out id, GH_Conversion.Both))
                    {
                        gridlineload.GridLineLoad.GridSurface = id;
                        gridlineload.GridPlaneSurface         = null;
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Error in GPS input. Accepted inputs are Grid Plane Surface or Plane. " +
                                          System.Environment.NewLine + "If no input here then the line's best-fit plane will be used");
                        return;
                    }
                }
            }

            // we wait setting the gridplanesurface until we have run the polyline input

            // 1 Polyline
            Polyline ln     = new Polyline();
            GH_Curve gh_crv = new GH_Curve();

            if (DA.GetData(1, ref gh_crv))
            {
                Curve crv = null;
                GH_Convert.ToCurve(gh_crv, ref crv, GH_Conversion.Both);

                //convert to polyline
                if (crv.TryGetPolyline(out ln))
                {
                    // get control points
                    List <Point3d> ctrl_pts = ln.ToList();

                    // plane
                    if (!planeSet)
                    {
                        // create best-fit plane from pts
                        pln = Util.GH.Convert.CreateBestFitUnitisedPlaneFromPts(ctrl_pts);

                        // create grid plane surface from best fit plane
                        grdplnsrf = new GsaGridPlaneSurface(pln, true);
                    }
                    else
                    {
                        // project original curve onto grid plane
                        crv = Curve.ProjectToPlane(crv, pln);

                        // convert to polyline again
                        crv.TryGetPolyline(out ln);

                        //get control points again
                        ctrl_pts = ln.ToList();
                    }

                    // string to write polyline description to
                    string desc = "";

                    // loop through all points
                    for (int i = 0; i < ctrl_pts.Count; i++)
                    {
                        if (i > 0)
                        {
                            desc += " ";
                        }

                        // get control points in local plane coordinates
                        Point3d temppt = new Point3d();
                        pln.RemapToPlaneSpace(ctrl_pts[i], out temppt);

                        // write point to string
                        // format accepted by GSA: (0,0) (0,1) (1,2) (3,4) (4,0)(m)
                        desc += "(" + temppt.X + "," + temppt.Y + ")";
                    }
                    // add units to the end
                    desc += "(" + Units.LengthLarge + ")";

                    // set polyline in grid line load
                    gridlineload.GridLineLoad.Type = GridLineLoad.PolyLineType.EXPLICIT_POLYLINE;
                    gridlineload.GridLineLoad.PolyLineDefinition = desc;
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not convert Curve to Polyline");
                }
            }

            // now we can set the gridplanesurface:
            if (gridlineload.GridPlaneSurface != null)
            {
                if (gridlineload.GridPlaneSurface.GridSurfaceID == 0)
                {
                    gridlineload.GridPlaneSurface = grdplnsrf;
                }
            }

            // 3 direction
            string    dir   = "Z";
            Direction direc = Direction.Z;

            GH_String gh_dir = new GH_String();

            if (DA.GetData(3, ref gh_dir))
            {
                GH_Convert.ToString(gh_dir, out dir, GH_Conversion.Both);
            }
            dir = dir.ToUpper();
            if (dir == "X")
            {
                direc = Direction.X;
            }
            if (dir == "Y")
            {
                direc = Direction.Y;
            }

            gridlineload.GridLineLoad.Direction = direc;

            // 4 Axis
            int axis = 0;

            gridlineload.GridLineLoad.AxisProperty = 0;
            GH_Integer gh_ax = new GH_Integer();

            if (DA.GetData(4, ref gh_ax))
            {
                GH_Convert.ToInt32(gh_ax, out axis, GH_Conversion.Both);
                if (axis == 0 || axis == -1)
                {
                    gridlineload.GridLineLoad.AxisProperty = axis;
                }
            }

            // 5 Projected
            bool       proj    = false;
            GH_Boolean gh_proj = new GH_Boolean();

            if (DA.GetData(5, ref gh_proj))
            {
                if (GH_Convert.ToBoolean(gh_proj, out proj, GH_Conversion.Both))
                {
                    gridlineload.GridLineLoad.IsProjected = proj;
                }
            }

            // 6 Name
            string    name    = "";
            GH_String gh_name = new GH_String();

            if (DA.GetData(6, ref gh_name))
            {
                if (GH_Convert.ToString(gh_name, out name, GH_Conversion.Both))
                {
                    gridlineload.GridLineLoad.Name = name;
                }
            }

            // 7 load value
            double load1 = 0;

            if (DA.GetData(7, ref load1))
            {
                load1 *= -1000; //convert to kN
            }
            gridlineload.GridLineLoad.ValueAtStart = load1;

            // 8 load value
            double load2 = load1;

            if (DA.GetData(8, ref load2))
            {
                load2 *= -1000; //convert to kN
            }
            gridlineload.GridLineLoad.ValueAtEnd = load2;

            // convert to goo
            GsaLoad gsaLoad = new GsaLoad(gridlineload);

            DA.SetData(0, new GsaLoadGoo(gsaLoad));
        }
        /// <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)
        {
            InputChecker inputChecker = new InputChecker(this);

            #region AssignInput
            Curve inCrv     = null;
            bool  canGetCrv = DA.GetData(0, ref inCrv);
            inputChecker.StopIfConversionIsFailed(canGetCrv);
            inCrv.Domain = new Interval(0, 1);

            List <double> inData     = new List <double>();
            bool          canGetData = DA.GetDataList(1, inData);
            inputChecker.StopIfConversionIsFailed(canGetData);

            List <double> inDataOptional     = new List <double>();
            bool          canGetDataOptional = DA.GetDataList(2, inDataOptional);
            inputChecker.StopIfConversionIsFailed(canGetDataOptional);
            if (inDataOptional.Count == 0)
            {
                EqualCurveSubD(inData, inDataOptional);
            }
            ValuesAllocator.MatchLists(inData, inDataOptional);

            Color inFirstColor = new Color();
            if (!DA.GetData(3, ref inFirstColor))
            {
                return;
            }

            Color inSecondColor = new Color();
            if (!DA.GetData(4, ref inSecondColor))
            {
                return;
            }

            List <double> inRotationAngles = new List <double>();
            DA.GetDataList(5, inRotationAngles);
            ValuesAllocator.MatchLists(inData, inRotationAngles);

            #endregion

            int           lastValueIndex = inData.Count - 1;
            List <double> sortedData     = new List <double>(inData);
            sortedData.Sort();
            double refStartDomain = sortedData[0];
            double refEndDomain   = sortedData[lastValueIndex];

            List <Line>  histogramLines  = new List <Line>();
            List <Color> histogramColors = new List <Color>();

            for (int i = 0; i < inData.Count; i++)
            {
                Plane  pFrame;
                double tValue = inDataOptional[i];
                inCrv.PerpendicularFrameAt(tValue, out pFrame);

                double angle_rad = inRotationAngles[i];
                if (_useDegrees)
                {
                    angle_rad = RhinoMath.ToRadians(angle_rad);
                }
                pFrame.Rotate(angle_rad, pFrame.ZAxis);

                double dataVal = inData[i];
                Line   line    = new Line(pFrame.Origin, pFrame.YAxis, dataVal);
                histogramLines.Add(line);

                Color color = ColorRemapper.RemappedColor(ref inFirstColor, ref inSecondColor, refEndDomain, refStartDomain, dataVal);
                histogramColors.Add(color);
            }

            #region SetOutput
            DA.SetDataList(0, histogramLines);
            DA.SetDataList(1, histogramColors);
            #endregion
        }
Example #51
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)
        {
            double span = 0;
            List <VariableSection> vSect = new List <VariableSection>();

            if (!DA.GetData(0, ref span))
            {
                return;
            }
            if (!DA.GetDataList(1, vSect))
            {
                return;
            }

            int N = vSect.Count;

            if (N < 2)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "VSect needs at least 2 inputs");
                return;
            }

            Transform mirrorYZ = Transform.Mirror(Plane.WorldYZ);
            Transform mirrorXZ = Transform.Mirror(Plane.WorldZX);

            Point3d spPtA    = new Point3d(-span * 0.5, 0, 0);
            Curve   spCrv    = new Line(spPtA, Plane.WorldXY.XAxis, span).ToNurbsCurve();
            Curve   spCrvHlf = new Line(spPtA, Plane.WorldXY.XAxis, span * 0.5).ToNurbsCurve();

            //if (N < 2) { N = 3; }
            double[] spCrvDiv = spCrv.DivideByCount(N - 1, true);
            Plane[]  spCrvPln = spCrv.GetPerpendicularFrames(spCrvDiv);
            for (int i = 0; i < spCrvPln.Length; i++) //reorient planes to align with z-axis
            {
                Plane pl = spCrvPln[i];
                pl.Rotate(-Math.PI * 0.5, Plane.WorldXY.XAxis);
                spCrvPln[i] = pl;
            }

            List <Point3d> allPts = new List <Point3d>();
            List <Curve>   crvs   = new List <Curve>();

            int ptCnt = vSect[0].sctPts.Count;

            Point3d[,] crvPts = new Point3d[ptCnt, vSect.Count];
            //for(int i = 0; i < vSect.Count; i++) { Point3d[] crvPt = new Point3d[vSect.Count]; }


            for (int i = 0; i < vSect.Count; i++) //moves and reorients points from input i indicates number section, j number curve/point in section
            {
                List <Point3d> sctPts = vSect[i].sctPts;
                Plane          sctPln = vSect[i].sctPln;

                if (sctPts.Count != ptCnt)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Each section needs the same number of points"); return;
                }

                Transform reorient = Transform.PlaneToPlane(sctPln, spCrvPln[i]);
                //foreach (Point3d pt in sctPts) { pt.Transform(reorient); allPts.Add(pt); } //remove when workaround is figured out

                for (int j = 0; j < sctPts.Count; j++) //separate points to each "row" in a list of arrays
                {
                    Point3d pt = sctPts[j];
                    pt.Transform(reorient);
                    crvPts[j, i] = pt;
                }
            }

            int degree = 3;

            for (int i = 0; i < crvPts.GetLength(0); i++) //creates curves through points
            {
                Point3d[] aCrvPts = new Point3d[vSect.Count];
                for (int j = 0; j < crvPts.GetLength(1); j++)
                {
                    aCrvPts[j] = crvPts[i, j];
                }
                Curve crv = Curve.CreateInterpolatedCurve(aCrvPts, degree);
                crvs.Add(crv);
            }

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

            Brep[] loftFace = Brep.CreateFromLoft(crvs, Point3d.Unset, Point3d.Unset, LoftType.Straight, false);
            //Brep face1 = new Brep();
            //foreach(Brep face in loftFace) { face1 = face.DuplicateBrep(); }
            Brep face1 = loftFace[0].DuplicateBrep();
            Brep face2 = face1.DuplicateBrep(); face2.Transform(mirrorXZ);

            faces.Add(face1); faces.Add(face2);

            Curve[] naked1 = face1.DuplicateNakedEdgeCurves(true, false); Curve[] naked2 = face2.DuplicateNakedEdgeCurves(true, false);
            Curve[] loftCrv1 = new Curve[] { naked1[1], naked2[1] }; Curve[] loftCrv2 = new Curve[] { naked1[3], naked2[3] };
            Brep[]  face3 = Brep.CreateFromLoft(loftCrv1, Point3d.Unset, Point3d.Unset, LoftType.Straight, false);
            Brep[]  face4 = Brep.CreateFromLoft(loftCrv2, Point3d.Unset, Point3d.Unset, LoftType.Straight, false);
            faces.Add(face3[0]); faces.Add(face4[0]);

            Brep[] beamBreps = Brep.JoinBreps(faces, DocumentTolerance());
            Brep   beam      = beamBreps[0].CapPlanarHoles(DocumentTolerance());

            int intersects = 0;
            int a          = crvs.Count;

            for (int i = 0; i < (a - 1); i++)
            {
                for (int j = (i + 1); j < a; j++)
                {
                    Rhino.Geometry.Intersect.CurveIntersections crvCheck = Rhino.Geometry.Intersect.Intersection.CurveCurve(
                        crvs[i], crvs[j], DocumentTolerance(), 0.0);

                    intersects += crvCheck.Count;
                }
            }

            if (intersects > 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Beam volume is invalid.");
                return;
            }

            DA.SetDataList(0, spCrvPln);
            DA.SetDataList(1, crvPts);
            DA.SetDataList(2, crvs);
            DA.SetData(3, beam);
            DA.SetData(4, spCrv);
        }
Example #52
0
        /// <summary>
        /// Wrap input geometry into module cages.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from
        ///     input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var geometryRaw = new List <IGH_GeometricGoo>();
            var basePlane   = new Plane();
            var diagonal    = new Vector3d();
            var method      = 2;
            var precision   = 0.5;

            if (!DA.GetDataList(0, geometryRaw))
            {
                return;
            }

            if (!DA.GetData(1, ref basePlane))
            {
                return;
            }

            if (!DA.GetData(2, ref diagonal))
            {
                return;
            }

            if (!DA.GetData(3, ref method))
            {
                return;
            }

            if (!DA.GetData(4, ref precision))
            {
                return;
            }


            if (diagonal.X <= 0 || diagonal.Y <= 0 || diagonal.Z <= 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "One or more slot dimensions are not larger than 0.");
                return;
            }

            if (method < 0 || method > 3)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Unknown Fill Method (F).");
                return;
            }

            var geometryClean = geometryRaw
                                .Where(goo => goo != null)
                                .Select(goo => {
                var geo      = goo.Duplicate();
                var geometry = GH_Convert.ToGeometryBase(geo);
                // Transformation of BReps sometimes does not work as expected
                // For example non uniform scaling of a sphere results in a sphere
                // Mesh scaling is safe and populating is fast(er)
                if (geometry.HasBrepForm)
                {
                    var meshingParameters = MeshingParameters.FastRenderMesh;
                    var brep   = Brep.TryConvertBrep(geometry);
                    var meshes = Mesh.CreateFromBrep(brep, meshingParameters);
                    var mesh   = new Mesh();
                    foreach (var meshFace in meshes)
                    {
                        mesh.Append(meshFace);
                    }
                    mesh.Weld(Math.PI / 8);
                    return(mesh);
                }
                else
                {
                    return(geometry);
                }
            }
                                        );

            if (!geometryClean.Any())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Failed to collect any valid geometry.");
                return;
            }

            // Scale down to unit size
            var normalizationTransform = Transform.Scale(basePlane,
                                                         1 / diagonal.X,
                                                         1 / diagonal.Y,
                                                         1 / diagonal.Z);

            // Orient to the world coordinate system
            var worldAlignmentTransform = Transform.PlaneToPlane(basePlane, Plane.WorldXY);

            var centersNormalized = new List <Point3i>();
            var ambiguityWarning  = false;

            foreach (var goo in geometryClean)
            {
                var geometry = goo.Duplicate();
                if (geometry.Transform(normalizationTransform) &&
                    geometry.Transform(worldAlignmentTransform))
                {
                    var objectType = goo.ObjectType;
                    var isMesh     = objectType == ObjectType.Mesh;
                    if ((method == 0 || method == 2 || method == 3) && objectType == ObjectType.Point)
                    {
                        var p = ((Point)geometry).Location;
                        if (!IsOnEdgeUnitized(p))
                        {
                            centersNormalized.Add(new Point3i(p));
                        }
                        else
                        {
                            ambiguityWarning = true;
                        }
                    }
                    if ((method == 0 || method == 2 || method == 3) && objectType == ObjectType.Curve)
                    {
                        centersNormalized.AddRange(PopulateCurve(precision, (Curve)geometry)
                                                   .Where(p => !IsOnEdgeUnitized(p))
                                                   .Select(p => new Point3i(p))
                                                   .Distinct());
                        ambiguityWarning = true;
                    }
                    if (objectType == ObjectType.Mesh &&
                        (method == 0 ||
                         ((method == 2 || method == 3) &&
                          !((Mesh)geometry).IsClosed)))
                    {
                        centersNormalized.AddRange(PopulateMeshSurface(precision, (Mesh)geometry)
                                                   .Where(p => !IsOnEdgeUnitized(p))
                                                   .Select(p => new Point3i(p))
                                                   .Distinct());
                        ambiguityWarning = true;
                    }
                    if (method == 1 && objectType == ObjectType.Mesh && ((Mesh)geometry).IsClosed)
                    {
                        centersNormalized.AddRange(CentersFromMeshVolume((Mesh)geometry));
                    }
                    if (method == 2 && objectType == ObjectType.Mesh && ((Mesh)geometry).IsClosed)
                    {
                        centersNormalized.AddRange(CentersFromMeshVolumeAndSurface((Mesh)geometry));
                    }
                    if (method == 3 && objectType == ObjectType.Mesh && ((Mesh)geometry).IsClosed)
                    {
                        centersNormalized.AddRange(CentersFromMeshSurface((Mesh)geometry));
                    }
                }
            }

            if (ambiguityWarning)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
                                  "Test points matching the Slot grid may have been skipped " +
                                  "due to ambiguity.");
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
                                  "Slightly move, scale or remodel the geometry where Slot " +
                                  "centers are missing.");
            }

            if (!centersNormalized.Any())
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "Failed to collect any Slot centers from the given geometry.");
                return;
            }

            var centers = centersNormalized
                          .Distinct()
                          .Select(centerNormalized => centerNormalized.ToCartesian(basePlane, diagonal));

            DA.SetDataList(0, centers);
        }
Example #53
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)
        {
            string ID   = this.Attributes.InstanceGuid.ToString();
            string name = new GUIDtoAlpha(Convert.ToString(ID + Convert.ToString(this.RunCount)), false).Text;
            int    C    = this.RunCount;

            wObject  WindObject = new wObject();
            pElement Element    = new pElement();
            bool     Active     = Elements.ContainsKey(C);

            var pCtrl = new pScrollValue(name);

            if (Elements.ContainsKey(C))
            {
                Active = true;
            }

            //Check if control already exists
            if (Active)
            {
                if (Elements[C] != null)
                {
                    WindObject = Elements[C];
                    Element    = (pElement)WindObject.Element;
                    pCtrl      = (pScrollValue)Element.ParrotControl;
                }
            }
            else
            {
                Elements.Add(C, WindObject);
            }

            //Set Unique Control Properties

            List <string> V = new List <string>();
            int           I = 0;
            bool          E = true;

            if (!DA.GetDataList(0, V))
            {
                return;
            }
            if (!DA.GetData(1, ref I))
            {
                return;
            }
            if (!DA.GetData(2, ref E))
            {
                return;
            }

            pCtrl.SetProperties(V, I, E);

            //Set Parrot Element and Wind Object properties
            if (!Active)
            {
                Element = new pElement(pCtrl.Element, pCtrl, pCtrl.Type);
            }
            WindObject          = new wObject(Element, "Parrot", Element.Type);
            WindObject.GUID     = this.InstanceGuid;
            WindObject.Instance = C;

            Elements[this.RunCount] = WindObject;

            DA.SetData(0, WindObject);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Init local variables
            GH_SpeckleBase ghBase = null;
            var            keys   = new List <string>();

            // Grab data from input
            if (!DA.GetData(0, ref ghBase))
            {
                return;
            }
            if (!DA.GetDataList(1, keys))
            {
                return;
            }
            if (!DA.GetDataTree(2, out GH_Structure <IGH_Goo> valueTree))
            {
                return;
            }

            // TODO: Handle data validation
            var b = ghBase.Value.ShallowCopy();

            CleanDeletedKeys(b, keys);
            // Search for the path coinciding with the current iteration.
            var path = new GH_Path(DA.Iteration);

            if (valueTree.PathExists(path))
            {
                var values = valueTree.get_Branch(path) as List <IGH_Goo>;
                // Input is a list of values. Assign them directly
                if (keys.Count != values?.Count)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    return;
                }
                AssignToObject(b, keys, values);
            }
            else if (valueTree.Branches.Count == 1)
            {
                var values = valueTree.Branches[0];
                if (keys.Count != values.Count)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    return;
                }
                // Input is just one list, so use it.
                AssignToObject(b, keys, values);
            }
            else
            {
                // Input is a tree, meaning it's values are either lists or trees.
                var subTree = Utilities.GetSubTree(valueTree, path);
                int index   = 0;
                keys.ForEach(key =>
                {
                    var subPath = new GH_Path(index);
                    if (subTree.PathExists(subPath))
                    {
                        // Value is a list, convert and assign.
                        var list = subTree.get_Branch(subPath) as List <IGH_Goo>;
                        if (list?.Count > 0)
                        {
                            var converted = list.Select(goo => Utilities.TryConvertItemToSpeckle(goo, Converter)).ToList();
                            b[key]        = converted;
                        }
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot handle trees yet");
                    }
                    index++;
                });
            }

            lastSolutionKeys = keys;
            DA.SetData(0, new GH_SpeckleBase {
                Value = b
            });
        }
Example #55
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)
        {
            ///define i/o parameters
            PointCloud Rhino_Cloud = new PointCloud();
            double     Samples     = new double();
            double     Resolution  = new double();

            /// read inputs
            if (!DA.GetData("Point_Cloud", ref Rhino_Cloud))
            {
                return;
            }
            if (!DA.GetData("Samples", ref Samples))
            {
                return;
            }

            /// interal parameters
            var           Rhino_xyz = Rhino_Cloud.GetPoints();
            List <double> xyz       = new List <double>();
            List <double> x         = new List <double>();

            //if (x.Count != 0)
            //{
            //    var temp = x.Max();
            //    if (temp != 0)
            //    {
            //        var result = x.Select(k => k / temp).ToList(); ;
            //    }
            //    else
            //    {
            //        var result = x;
            //    }

            //    A = result;
            //}

            for (int i = 0; i < Rhino_Cloud.Count; i++)
            {
                xyz.Add(Rhino_xyz[i].X);
                xyz.Add(Rhino_xyz[i].Y);
                xyz.Add(Rhino_xyz[i].Z);
            }

            ///2.
            var Matlab_samples = new MWNumericArray(Samples);
            var Matlab_xyz     = new MWNumericArray(Rhino_Cloud.Count, 3, xyz.ToArray());


            /// 3.
            Segmentation.segment segment_mesh = new Segmentation.segment();

            MWArray cluster = new MWNumericArray();

            cluster = segment_mesh.G_Resolution_PCD(Matlab_xyz, Matlab_samples);

            /// 4.
            MWNumericArray na = (MWNumericArray)cluster;

            double[] dc = (double[])na.ToVector(0);

            /// 5.%£%/:
            Resolution = dc[0];

            /// 6.
            DA.SetData(0, Resolution);
        }
Example #56
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string sourceFileLocation = string.Empty;

            DA.GetData <string>(1, ref sourceFileLocation);

            string clippedLocation = string.Empty;

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

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            ///Read in the raster data
            Dataset datasource = Gdal.Open(sourceFileLocation, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();

            string srcInfo = string.Empty;

            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The raster datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);

            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is missing.  SRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            ///Get info about image
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);
            Band band = datasource.GetRasterBand(1);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84.
            ///TODO: Allow for UserSRS
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            ///Get bounding box for entire raster data
            Rectangle3d datasourceBBox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));


            ///https://gis.stackexchange.com/questions/312440/gdal-translate-bilinear-interpolation
            ///set output to georeferenced tiff as a catch-all
            string clippedRasterFile = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_clipped.tif";
            string previewPNG        = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_preview.png";

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Original Resolution: " + datasource.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

            if (boundary != null)
            {
                Point3d clipperMin = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(true, false, true));
                Point3d clipperMax = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(false, true, true));

                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                ///GDALTranslate should also be its own component with full control over options
                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    //"-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedRasterFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, clippedDataset, null, null, null);

                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipped Resolution: " + clippedDataset.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

                    ///clean up
                    clippedDataset.FlushCache();
                    clippedDataset.Dispose();
                    previewDataset.FlushCache();
                    previewDataset.Dispose();

                    AddPreviewItem(previewPNG, BBoxToRect(boundary.GetBoundingBox(true)));
                }
            }

            else
            {
                Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, datasource, null, null, null);

                ///clean up
                previewDataset.FlushCache();
                previewDataset.Dispose();

                AddPreviewItem(previewPNG, datasourceBBox);
            }

            ///clean up
            datasource.FlushCache();
            datasource.Dispose();

            DA.SetData(0, srcInfo);
            DA.SetData(1, datasourceBBox);
            DA.SetData(2, clippedRasterFile);
        }
Example #57
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)
        {
            var valueX = new List <double>(); var valueY = new List <double>(); int step = 0; DA.GetData("step", ref step);

            if (!DA.GetDataList("value X", valueX))
            {
                return;
            }
            if (!DA.GetDataList("value Y", valueY))
            {
                return;
            }
            var X = 0.0; DA.GetData("x width", ref X); var Y = 0.0; DA.GetData("y width", ref Y); var cp = new List <double> {
                0, 0, 0
            }; var p = new Point3d(); DA.GetData("origin", ref p); cp[0] = p[0]; cp[1] = p[1]; cp[2] = p[2];
            var    xmax = valueX.Max(); var xmin = valueX.Min(); var ymax = valueY.Max(); var ymin = valueY.Min();
            var    XminXmax = new List <double>(); var YminYmax = new List <double>(); var wavecolor = Color.Red; DA.GetData("color", ref wavecolor); _wavecolor.Add(wavecolor);

            if (!DA.GetDataList("XminXmax", XminXmax))
            {
            }
            ; if (!DA.GetDataList("YminYmax", YminYmax))
            {
            }
            ;
            if (XminXmax.Count == 0)
            {
                XminXmax = new List <double> {
                    xmin, xmax
                };
            }
            if (YminYmax.Count == 0)
            {
                YminYmax = new List <double> {
                    ymin, ymax
                };
            }
            var xlabel = ""; var ylabel = ""; DA.GetData("label x", ref xlabel); DA.GetData("label y", ref ylabel); var title = ""; DA.GetData("title", ref title);

            cp[1] -= Y;
            var xrange = XminXmax[1] - XminXmax[0]; var yrange = YminYmax[1] - YminYmax[0];
            var dx = X / xrange; var dy = Y / yrange;
            var dX = xrange / 5.0; var dY = yrange / 5.0;

            if (!DA.GetData("pitch x", ref dX))
            {
            }
            ; if (!DA.GetData("pitch y", ref dY))
            {
            }
            ;
            var x = 0.0;

            while (x < XminXmax[1])//グリッド線描画
            {
                _scale.Add(new Line(cp[0] + dx * x, cp[1] + dy * YminYmax[0], cp[2], cp[0] + dx * x, cp[1] + dy * YminYmax[1], cp[2]));
                _xp.Add(new Point3d(cp[0] + dx * x, cp[1] + dy * YminYmax[0], cp[2])); _xtext.Add(x.ToString().Substring(0, Math.Min(5, (x.ToString()).Length)));
                x += dX;
            }
            _frame.Add(new Line(cp[0] + dx * XminXmax[1], cp[1] + dy * YminYmax[0], cp[2], cp[0] + dx * XminXmax[1], cp[1] + dy * YminYmax[1], cp[2])); //外枠の描画(右側の縦線)
            x = -dX;
            while (x > XminXmax[0])                                                                                                                     //グリッド線描画
            {
                _scale.Add(new Line(cp[0] + dx * x, cp[1] + dy * YminYmax[0], cp[2], cp[0] + dx * x, cp[1] + dy * YminYmax[1], cp[2]));
                _xp.Add(new Point3d(cp[0] + dx * x, cp[1] + dy * YminYmax[0], cp[2])); _xtext.Add(x.ToString().Substring(0, Math.Min(6, (x.ToString()).Length)));
                x -= dX;
            }
            _frame.Add(new Line(cp[0] + dx * XminXmax[0], cp[1] + dy * YminYmax[0], cp[2], cp[0] + dx * XminXmax[0], cp[1] + dy * YminYmax[1], cp[2])); //外枠の描画(左側の縦線)
            _xp.Add(new Point3d(cp[0] + dx * (XminXmax[0] + xrange / 2.0), cp[1] + dy * YminYmax[0], cp[2])); _xtext.Add("\n" + xlabel);                //xラベル
            _tp.Add(new Point3d(cp[0] + dx * (XminXmax[0] + xrange / 2.0), cp[1] + dy * YminYmax[1], cp[2])); _ttext.Add(title);                        //タイトル
            var y = 0.0;

            while (y < YminYmax[1])
            {
                _scale.Add(new Line(cp[0] + dx * XminXmax[0], cp[1] + dy * y, cp[2], cp[0] + dx * XminXmax[1], cp[1] + dy * y, cp[2]));
                _yp.Add(new Point3d(cp[0] + dx * XminXmax[0], cp[1] + dy * y, cp[2])); _ytext.Add(y.ToString().Substring(0, Math.Min(5, (y.ToString()).Length)));
                y += dY;
            }
            _frame.Add(new Line(cp[0] + dx * XminXmax[0], cp[1] + dy * YminYmax[1], cp[2], cp[0] + dx * XminXmax[1], cp[1] + dy * YminYmax[1], cp[2]));//外枠の描画(上側の横線)
            y = -dY;
            while (y > YminYmax[0])
            {
                _scale.Add(new Line(cp[0] + dx * XminXmax[0], cp[1] + dy * y, cp[2], cp[0] + dx * XminXmax[1], cp[1] + dy * y, cp[2]));
                _yp.Add(new Point3d(cp[0] + dx * XminXmax[0], cp[1] + dy * y, cp[2])); _ytext.Add(y.ToString().Substring(0, Math.Min(6, (y.ToString()).Length)));
                y -= dY;
            }
            _frame.Add(new Line(cp[0] + dx * XminXmax[0], cp[1] + dy * YminYmax[0], cp[2], cp[0] + dx * XminXmax[1], cp[1] + dy * YminYmax[0], cp[2])); //外枠の描画(下側の横線)
            _yp.Add(new Point3d(cp[0] + dx * XminXmax[0], cp[1] + dy * (YminYmax[0] + yrange / 2.0), cp[2])); _ytext.Add(ylabel + "       ");           //yラベル
            if (step > 0)
            {
                for (int i = 0; i < step; i++)
                {
                    _wave.Add(new Line(cp[0] + valueX[i] * dx, cp[1] + (valueY[i]) * dy, cp[2], cp[0] + valueX[i + 1] * dx, cp[1] + (valueY[i + 1]) * dy, cp[2]));
                }
                _p.Add(_wave[step - 1].To);
            }
            _p.Add(new Point3d(cp[0], cp[1], cp[2]));
            DA.SetData("xmin", valueX.Min()); DA.SetData("xmax", valueX.Max()); DA.SetData("ymin", valueY.Min()); DA.SetData("ymax", valueY.Max());
        }
Example #58
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)
        {
            string filepath;

            //Domain omega;
            //FluidSolver ffd;
            //DataExtractor de;

            //double t;
            bool resetFFD = false;


            // current filepath
            filepath = Path.GetDirectoryName(this.OnPingDocument().FilePath);
            string residualstxt = filepath + @"\\residual.txt";


            // *********************************************************************************
            // Inputs
            // *********************************************************************************
            List <double> xyzsize = new List <double>();

            if (!DA.GetDataList(0, xyzsize))
            {
                return;
            }
            ;

            List <int> Nxyz = new List <int>();

            if (!DA.GetDataList(1, Nxyz))
            {
                return;
            }
            ;
            int Nx = Nxyz[0];
            int Ny = Nxyz[1];
            int Nz = Nxyz[2];


            List <double[]> geom = new List <double[]>();

            if (!DA.GetDataList(2, geom))
            {
                return;
            }
            ;

            for (int i = 0; i < geom.Count; i++)
            {
                double[] geo = geom[i];
                Rhino.RhinoApp.WriteLine($"[{i}] {geo[0]}, {geo[1]}, {geo[2]}, {geo[3]}, {geo[4]}, {geo[5]}");
                if (i == 10)
                {
                    break;
                }
            }



            // time step
            double dt = 0.1;

            if (!DA.GetData(3, ref dt))
            {
                return;
            }

            // horizon
            double t_end = 1;

            if (!DA.GetData(4, ref t_end))
            {
                return;
            }

            // wind speed
            double Vmet = 10;

            if (!DA.GetData(5, ref Vmet))
            {
                return;
            }

            //terrain type
            int terrain = 0;

            if (!DA.GetData(6, ref terrain))
            {
                return;
            }


            bool run = false;

            if (!DA.GetData(7, ref run))
            {
                return;
            }



            //List<Mesh> mshCp = new List<Mesh>();
            //DA.GetDataList(10, mshCp);
            bool writeresults = false;

            DA.GetData(8, ref writeresults);

            bool writeVTK = false;

            DA.GetData(9, ref writeVTK);


            DA.GetData(10, ref resetFFD);


            bool calcres = false;

            DA.GetData(12, ref calcres);

            int m = 10;

            DA.GetData(13, ref m);

            string strparam = null;

            DA.GetData(11, ref strparam);

            string[] str_params = null;
            if (strparam != null)
            {
                str_params = strparam.Split(';');
            }


            bool addResiduals = true;

            DA.GetData(12, ref addResiduals);

            int meanDt = 10;

            DA.GetData(13, ref meanDt);

            bool stop = false;

            DA.GetData(14, ref stop);

            bool update = false;

            DA.GetData(15, ref update);


            if (stop)
            {
                ffdSolver.StopRun();
                //running[0] = false;
                //Rhino.RhinoApp.WriteLine("stoprun()");

                //computingTask.Dispose();
                //Rhino.RhinoApp.WriteLine("dispose()");
            }


            if ((skipSolution && run == false) || update)
            {
                skipSolution = false;
                DA.IncrementIteration();

                //DA.SetDataList(0, veloutCen);
                //DA.SetData(1, p);
                //DA.SetDataList(2, veloutStag);
                //DA.SetData(3, pstag);
                //DA.SetData(3, pstagResults);
                //DA.SetData(4, de);
                //DA.SetData(5, obstacle_cells);
                DA.SetData(6, ffdSolver);
                DA.SetData(7, ffdSolver.omega);
                DA.SetData(8, ffdSolver.ffd);
                //Rhino.RhinoApp.WriteLine("trying to update outputs");
                Grasshopper.Instances.RedrawAll();
            }
            else if (!componentBusy)
            {
                DA.DisableGapLogic();

                //if (resetFFD)
                //{
                //    ffdSolver.run = false;
                //    ffdSolver = new FFDSolver(
                //        this.OnPingDocument().FilePath,
                //        Nxyz,
                //        xyzsize,
                //        geom,
                //        t_end,
                //        Vmet,
                //        terrain,
                //        strparam
                //        );

                //}
                bool returnSomething()
                {
                    return(true);
                }

                Task <bool> computingTask = new Task <bool>(() => returnSomething());

                if (resetFFD)
                {
                    ffdSolver = new FFDSolver(
                        this.OnPingDocument().FilePath,
                        Nxyz,
                        xyzsize,
                        geom,
                        t_end,
                        dt,
                        meanDt,
                        Vmet,
                        terrain,
                        strparam
                        );
                }

                if (run)
                {
                    ffdSolver.run = false;
                    if (ffdSolver.dt == 0.0) //we know it's empty.
                    {
                        ffdSolver = new FFDSolver(
                            this.OnPingDocument().FilePath,
                            Nxyz,
                            xyzsize,
                            geom,
                            t_end,
                            dt,
                            meanDt,
                            Vmet,
                            terrain,
                            strparam
                            );
                    }


                    computingTask = new Task <bool>(() => ffdSolver.Run());
                }



                computingTask.ContinueWith(r =>
                {
                    if (r.Status == TaskStatus.RanToCompletion)
                    {
                        bool result = computingTask.Result;
                        if (result == true)
                        {
                            //Rhino.RhinoApp.WriteLine("outputting");
                            NickName     = "Task Finished!";
                            skipSolution = true;

                            //pstagResults = ffdSolver.pstag;



                            //p = ffdSolver.p;
                            //veloutCen = ffdSolver.veloutCen;
                            //veloutStag = ffdSolver.veloutStag;
                            //pstag = ffdSolver.pstag;
                            de             = ffdSolver.de;
                            obstacle_cells = ffdSolver.obstacle_cells;



                            ExpireSolution(false);
                            Grasshopper.Instances.ActiveCanvas.Document.NewSolution(false);
                        }
                        else
                        {
                            Rhino.RhinoApp.WriteLine("failed");
                            NickName = "Task Failed.";
                            Grasshopper.Instances.RedrawAll();
                        }
                        componentBusy = false;
                    }
                    else if (r.Status == TaskStatus.Faulted)
                    {
                        NickName = "Task Faulted.";
                        Grasshopper.Instances.RedrawAll();
                        componentBusy = false;
                    }
                },
                                           TaskScheduler.FromCurrentSynchronizationContext()


                                           );


                computingTask.Start();
                if (run)
                {
                    NickName = "Processing...";
                }
                Grasshopper.Instances.RedrawAll();
                componentBusy = true;

                //if (stop)
                //{
                //    ffdSolver.StopRun();

                //    Rhino.RhinoApp.WriteLine("stoprun()");

                //    computingTask.Dispose();
                //    Rhino.RhinoApp.WriteLine("dispose()");
                //}
            }
        }
Example #59
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            // get input
            DB.MullionType mullionType = default;
            if (!DA.GetData("Mullion Type", ref mullionType))
            {
                return;
            }

            // determine the mullion type by looking at parameters
            // this chart shows param availability on various mullion types
            // almost all types have unique param types except for L and V mullions
            // L and V mullions are differentiated by testing the FamilyName of the mullion
            // L and V mullion FamilyName always start with "L " or "V " in any language
            //
            //                  | Circ | Rect | Quad | Trapiz | L | V
            // --------------------------------------------------------
            // Radius           |  X   |  -   |  -   |  -     | - | -
            // Leg 1            |  -   |  -   |  -   |  -     | X | X
            // Leg 2            |  -   |  -   |  -   |  -     | X | X
            // Thickness        |  -   |  X   |  -   |  -     | X | X
            // Is Corner        |  0   |  0   |  1   |  1     | 1 | 1
            // Depth 1          |  -   |  -   |  X   |  -     | - | -
            // Depth 2          |  -   |  -   |  X   |  -     | - | -
            // Width Side 1     |  -   |  X   |  -   |  -     | - | -
            // Width Side 2     |  -   |  X   |  -   |  -     | - | -
            // Profile          |  X   |  X   |  -   |  -     | - | -
            // Depth            |  -   |  -   |  -   |  X     | - | -
            // Center Width     |  -   |  -   |  -   |  X     | - | -
            //
            // Mullion System Families (Values are defined here not in the API)
            //    Rectangular      = 0
            //    Circular         = 1
            //    L Corner         = 2
            //    Trapezoid Corner = 3
            //    Quad Corner      = 4
            //    V Corner         = 5
            var hasRadius         = mullionType.get_Parameter(DB.BuiltInParameter.CIRC_MULLION_RADIUS) != null;
            var hasRectWidthside1 = mullionType.get_Parameter(DB.BuiltInParameter.RECT_MULLION_WIDTH1) != null;
            var hasCustWidthside1 = mullionType.get_Parameter(DB.BuiltInParameter.CUST_MULLION_WIDTH1) != null;
            var hasDepth1         = mullionType.get_Parameter(DB.BuiltInParameter.MULLION_DEPTH1) != null;
            var hasCenterWidth    = mullionType.get_Parameter(DB.BuiltInParameter.TRAP_MULL_WIDTH) != null;
            var hasLeg1           = mullionType.get_Parameter(DB.BuiltInParameter.LV_MULLION_LEG1) != null;

            var mullionSystemFamily = DBX.CurtainMullionSystemFamily.Unknown;

            // rectangular
            if (hasRectWidthside1 || hasCustWidthside1)
            {
                mullionSystemFamily = DBX.CurtainMullionSystemFamily.Rectangular;
            }
            // cicular
            else if (hasRadius)
            {
                mullionSystemFamily = DBX.CurtainMullionSystemFamily.Circular;
            }
            // quad
            else if (hasDepth1)
            {
                mullionSystemFamily = DBX.CurtainMullionSystemFamily.QuadCorner;
            }
            // trapezoid
            else if (hasCenterWidth)
            {
                mullionSystemFamily = DBX.CurtainMullionSystemFamily.TrapezoidCorner;
            }
            // corner L or V
            else if (hasLeg1)
            {
                // confirmed that the corner mullion system family name in other languages also starts with L or V
                if (mullionType.FamilyName.StartsWith("L "))
                {
                    mullionSystemFamily = DBX.CurtainMullionSystemFamily.LCorner;
                }
                else if (mullionType.FamilyName.StartsWith("V "))
                {
                    mullionSystemFamily = DBX.CurtainMullionSystemFamily.VCorner;
                }
            }

            DA.SetData("Mullion System Family", mullionSystemFamily);

            PipeHostParameter(DA, mullionType, DB.BuiltInParameter.MULLION_ANGLE, "Angle");
            PipeHostParameter(DA, mullionType, DB.BuiltInParameter.MULLION_OFFSET, "Offset");

            var profile = new Types.MullionProfile(mullionType.Document, mullionType.get_Parameter(DB.BuiltInParameter.MULLION_PROFILE).AsElementId());

            DA.SetData("Profile", profile);

            var position = new Types.MullionPosition(mullionType.Document, mullionType.get_Parameter(DB.BuiltInParameter.MULLION_POSITION).AsElementId());

            DA.SetData("Position", position);

            PipeHostParameter(DA, mullionType, DB.BuiltInParameter.MULLION_CORNER_TYPE, "Corner Mullion");

            // output params are reused for various mullion types
            //
            //                  | Circ | Rect | Quad | Trapiz | L  | V
            // ----------------------------------------------------------
            // Radius           |  R   |  -   |  -   |  -     | -  | -
            // Leg 1            |  -   |  -   |  -   |  -     | D1 | D1
            // Leg 2            |  -   |  -   |  -   |  -     | D2 | D2
            // Thickness        |  -   |  T   |  -   |  -     | T  | T
            // Depth 1          |  -   |  -   |  D1  |  -     | -  | -
            // Depth 2          |  -   |  -   |  D2  |  -     | -  | -
            // Width Side 1     |  -   |  D1  |  -   |  -     | -  | -
            // Width Side 2     |  -   |  D2  |  -   |  -     | -  | -
            // Depth            |  -   |  -   |  -   |  D1    | -  | -
            // Center Width     |  -   |  -   |  -   |  T     | -  | -
            // Diameter         |  T   <= custom calculated for circular mullions
            var thicknessParam =
                mullionType.get_Parameter(DB.BuiltInParameter.RECT_MULLION_THICK) ??
                mullionType.get_Parameter(DB.BuiltInParameter.CUST_MULLION_THICK) ??
                mullionType.get_Parameter(DB.BuiltInParameter.TRAP_MULL_WIDTH);

            DA.SetData("Thickness", thicknessParam.AsGoo());

            var depth1Param =
                mullionType.get_Parameter(DB.BuiltInParameter.RECT_MULLION_WIDTH1) ??
                mullionType.get_Parameter(DB.BuiltInParameter.CUST_MULLION_WIDTH1) ??
                mullionType.get_Parameter(DB.BuiltInParameter.LV_MULLION_LEG1) ??
                mullionType.get_Parameter(DB.BuiltInParameter.MULLION_DEPTH1) ??
                mullionType.get_Parameter(DB.BuiltInParameter.MULLION_DEPTH);

            DA.SetData("Depth 1", depth1Param.AsGoo());

            var depth2Param =
                mullionType.get_Parameter(DB.BuiltInParameter.RECT_MULLION_WIDTH2) ??
                mullionType.get_Parameter(DB.BuiltInParameter.CUST_MULLION_WIDTH2) ??
                mullionType.get_Parameter(DB.BuiltInParameter.LV_MULLION_LEG2) ??
                mullionType.get_Parameter(DB.BuiltInParameter.MULLION_DEPTH2);

            DA.SetData("Depth 2", depth2Param.AsGoo());

            var radiusParam = mullionType.get_Parameter(DB.BuiltInParameter.CIRC_MULLION_RADIUS);

            if (radiusParam != null)
            {
                DA.SetData("Radius", radiusParam.AsGoo());
                DA.SetData("Thickness", radiusParam.AsDoubleInRhinoUnits() * 2);
            }
        }
Example #60
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Initialize Input Variables, Persistent in ComponentChange.
            List <Point3d> CenterList = new List <Point3d>();
            List <double>  RadiusList = new List <double>();
            Boolean        InsideBool = true;

            if (!DA.GetDataList("Center", CenterList))
            {
                return;
            }
            if (!DA.GetDataList("Radius", RadiusList))
            {
                return;
            }
            if (!DA.GetData("Leave", ref InsideBool))
            {
                return;
            }

            //Prepare Input for Instruction
            //and write ErrorMessages
            ///Loop through Input Centers and Radiuses
            ///and test for equal count or single count.

            if (CenterList.Count > 1 & RadiusList.Count == 1)
            {
                for (int i = 1; i < CenterList.Count; i++)
                {
                    RadiusList.Add(RadiusList[0]);
                }
            }
            if (RadiusList.Count > 1 & CenterList.Count == 1)
            {
                for (int i = 1; i < RadiusList.Count; i++)
                {
                    CenterList.Add(CenterList[0]);
                }
            }
            else if (CenterList.Count != RadiusList.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Need equal amount of CenterPoints and Radius'. Or single of one of them.");
                return;
            }

            //Excute Instruction
            ///If Component is set as Instruction.
            if (isInstruction)
            {
                DA.SetData("Instr", new Instruction.Instr_SphereCrop(CenterList, RadiusList, InsideBool));
            }
            else
            ///If Component is set to StandAlone.
            {
                ///Initialize PointCloud Input Variable.
                GH_Cloud pointCloud = null;
                if (!DA.GetData("Cloud", ref pointCloud))
                {
                    return;
                }
                ///Duplicate GH Cloud.
                GH_Cloud   newGHCloud = pointCloud.DuplicateCloud();
                PointCloud newCloud   = newGHCloud.Value;
                ///Execute Instruction.
                Instruction.Instr_SphereCrop inst = new Instruction.Instr_SphereCrop(CenterList, RadiusList, InsideBool);
                Boolean Result = inst.Execute(ref newCloud);

                ///Set New Output Cloud
                newGHCloud.Value = newCloud;
                DA.SetData("Cloud", newGHCloud);

                //Add RuntimeMessage: ComponentChange.
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "'Right Click' to Switch between StandAlone and Instruction Component.");
            }
        }