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)
        {
            // Declare a variable for the input

            List<Point3d> positions = new List<Point3d>();
            bool UX = false;
            bool UY = false;
            bool UZ = false;
            bool RX = false;
            bool RY = false;
            bool RZ = false;

            // Use the DA object to retrieve the data inside the first input parameter.
            // If the retieval fails (for example if there is no data) we need to abort.

            if (!DA.GetDataList<Point3d>(0, positions)) { return; }
            if (!DA.GetData(1, ref UX )) { return; }
            if (!DA.GetData(2, ref UY)) { return; }
            if (!DA.GetData(3, ref UZ)) { return; }
            if (!DA.GetData(4, ref RX)) { return; }
            if (!DA.GetData(5, ref RY)) { return; }
            if (!DA.GetData(6, ref RZ)) { return; }

            //Create node constrain
            GH_NodeSupport nodeSupport = new GH_NodeSupport(positions, UX, UY, UZ, RX, RY, RZ);

            //Return
            DA.SetData(0, nodeSupport);
        }
Exemplo n.º 3
0
    protected override bool GetInputs(IGH_DataAccess da)
    {
      agents = new List<IQuelea>();
      emitters = new List<AbstractEmitterType>();
      environment = new WorldEnvironmentType();
      // Then we need to access the input parameters individually. 
      // When data cannot be extracted from a parameter, we should abort this
      // method.
      if (!da.GetDataList(nextInputIndex++, agents)) return false;
      if (!da.GetDataList(nextInputIndex++, emitters)) return false;
      da.GetData(nextInputIndex++, ref environment);

      // We should now validate the data and warn the user if invalid data is 
      // supplied.
      if (agents.Count <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.agentsCountErrorMessage);
        return false;
      }
      if (emitters.Count <= 0)
      {
        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, RS.emittersCountErrorMessage);
        return false;
      }
      return true;
    }
Exemplo n.º 4
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;
            GH_String ip = null;

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

            var robotCellUR = program.Value.RobotSystem as RobotCellUR;
            if (DA.GetData(1, ref ip) && ip != null)
                robotCellUR.Remote.IP = ip.Value;

            bool connect = false, upload = false, play = false, pause = false;
            if (!DA.GetData("Connect", ref connect)) { return; }
            if (!DA.GetData("Upload", ref upload)) { return; }
            if (!DA.GetData("Play", ref play)) { return; }
            if (!DA.GetData("Pause", ref pause)) { return; }

            if (connect && !connected) { robotCellUR.Remote.Connect(); connected = true; }
            if (!connect && connected) { robotCellUR.Remote.Disconnect(); connected = false; }
            if (upload && connected) robotCellUR.Remote.UploadProgram(program.Value);
            if (play && connected) robotCellUR.Remote.Play();
            if (pause && connected) robotCellUR.Remote.Pause();

            DA.SetDataList(0, robotCellUR.Remote.Log);
        }
Exemplo n.º 5
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");
            }
        }
Exemplo n.º 6
0
 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;
 }
Exemplo n.º 7
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            //Process input
            double increment = 0;
            da.GetData(PInIncrement, ref increment);

            bool up = false;
            da.GetData(PInUp, ref up);
            if (up) FCounter += increment;

            bool down = false;
            da.GetData(PInDown, ref down);
            if (down) FCounter -= increment;

            double defaultValue = 0.0;
            da.GetData(PInDefault, ref defaultValue);

            bool reset = false;
            da.GetData(PInReset, ref reset);
            if (reset) FCounter = defaultValue;

            double min = 0.0;
            da.GetData(PInMinimum, ref min);
            if (FCounter < min) FCounter = min;

            double max = 0.0;
            da.GetData(PInMaximum, ref max);
            if (FCounter > max) FCounter = max;

            //Output
            da.SetData(POutOutput, FCounter);
        }
Exemplo n.º 8
0
    protected override void SetOutputs(IGH_DataAccess da)
    {
      outTree = new DataTree<Point3d>();
      GH_Path trunk = new GH_Path(0); // {0}
      GH_Path branch = new GH_Path(); // {}\
      GH_Path limb = new GH_Path();

      
      for (int i = 0; i < particles.Count; i++)
      {
        IQuelea particle = particles[i];
        branch = trunk.AppendElement(i);
        DataTree<Point3d> particlePositionHistoryTree = particle.Position3DHistory.ToTree();

        for (int j = 0; j < particlePositionHistoryTree.BranchCount; j++)
        {
          limb = branch.AppendElement(j);
          //for (int k = particlePositionHistoryTree.Branch(j).Count - 1; k >= 0; k--)
          //{
          //  outTree.Add(particlePositionHistoryTree.Branch(j)[k], limb);
          //}
          outTree.AddRange(particlePositionHistoryTree.Branch(j), limb);
          
        }
      }
      da.SetDataTree(nextOutputIndex++, outTree);
    }
Exemplo n.º 9
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   int n = vehicle.Wheels.Length;
   da.SetData(nextOutputIndex++, vehicle.Orientation);
   List<Point3d> wheelPositions = new List<Point3d>(n);
   List<Vector3d> wheelVelocities = new List<Vector3d>(n);
   List<double> wheelAngles = new List<double>(n);
   List<double> wheelRadii = new List<double>(n);
   List<double> wheelSpeeds = new List<double>(n);
   foreach (IWheel wheel in vehicle.Wheels)
   {
     wheelPositions.Add(wheel.Position);
     Vector3d wheelVelocity = vehicle.Velocity;
     wheelVelocity.Unitize();
     wheelVelocity = Vector3d.Multiply(wheelVelocity, wheel.TangentialVelocity);
     wheelVelocities.Add(wheelVelocity);
     wheelAngles.Add(wheel.Angle);
     wheelRadii.Add(wheel.Radius);
     wheelSpeeds.Add(wheel.AngularVelocity);
   }
   da.SetDataList(nextOutputIndex++, wheelPositions);
   da.SetDataList(nextOutputIndex++, wheelVelocities);
   da.SetDataList(nextOutputIndex++, wheelAngles);
   da.SetDataList(nextOutputIndex++, wheelRadii);
   da.SetDataList(nextOutputIndex++, wheelSpeeds);
 }
Exemplo n.º 10
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)
        {
            // 1. Declare placeholder variables
            var struts = new List<Curve>();
            double tol = 0.0;
            // 2. Attempt to retrieve input
            if (!DA.GetDataList(0, struts)) { return; }
            if (!DA.GetData(1, ref tol)) { return; }
            // 3. Validate input
            if (struts == null || struts.Count == 1) { return; }
            if (tol < 0) { return; }

            // 4. Call cleaning method
            var nodes = new Point3dList();
            var nodePairs = new List<IndexPair>();
            struts = FrameTools.CleanNetwork(struts, tol, out nodes, out nodePairs);

            // 5. Organize index lists
            var strutStart = new List<int>();
            var strutEnd = new List<int>();
            foreach (IndexPair nodePair in nodePairs)
            {
                strutStart.Add(nodePair.I);
                strutEnd.Add(nodePair.J);
            }

            // 6. Set output
            DA.SetDataList(0, struts);
            DA.SetDataList(1, nodes);
            DA.SetDataList(2, strutStart);
            DA.SetDataList(3, strutEnd);

        }
 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;
 }
        /// <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
            List<Line> bars = new List<Line>();
            if(!DA.GetDataList(0, bars)) { return; }

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

            List<double> displacements = new List<double>();
            if(!DA.GetDataList(2, displacements)) { return; }

            List<Color> gradientColours = new List<Color>();
            if(!DA.GetDataList(3, gradientColours)) { return; }


            //Calculate
            lines = new List<Line>();
            for(int i=0; i<bars.Count; i++)
            {
                lines.Add(bars[i]);
            }

            List<double> barDispl = calcBarDisplacements(bars, nodes, displacements);
            colours = mapDisplToColour(barDispl, gradientColours);

        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
#if DEBUG
            Rhino.RhinoApp.WriteLine("Designer " + this.Name + " is solving");
#endif
            
            // check if the controller is online
            SOGrasshopperController con = SOGrasshopperController.GetInstance(OnPingDocument());

            List<SODesigner_GHData> designerList = new List<SODesigner_GHData>();
            DA.GetDataList<SODesigner_GHData>(0, designerList);
            this.m_Designer.ClearDesigners();
            foreach (SODesigner_GHData data in designerList)
            {
                this.m_Designer.AddDesigner(data.Value);
            }
            
            if (this.m_Designer == null) { return; }
            try
            {
                this.m_Designer.RunDesigner();
            }
            catch (Exception)
            {
                return;
            }

            // return the designer data
            SODesigner_GHData data1 = new SODesigner_GHData(this.m_Designer);
            DA.SetData(0, data1);
#if DEBUG
            Rhino.RhinoApp.WriteLine("> Controller state: " + SOController.Instance.State.ToString());
#endif
        }
Exemplo n.º 14
0
    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;
    }
Exemplo n.º 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 bool GetInputs(IGH_DataAccess da)
 {
   if (!base.GetInputs(da)) return false;
   if (!da.GetData(nextInputIndex++, ref targetPt)) return false;
   targetPt = agent.Environment.MapTo2D(targetPt);
   return true;
 }
Exemplo n.º 16
0
    protected override bool GetInputs(IGH_DataAccess da)
    {
      if (!base.GetInputs(da)) return false;
      if (!da.GetData(nextInputIndex++, ref arrivalRadius)) return false;

      return true;
    }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (this.Analysis == null) { return; }

            base.SolveInstance(DA);
            DA.SetData(1, ((QTOAnalysis)this.Analysis).TextualOutput);
        }
Exemplo n.º 18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Point3d eye = new Point3d();
            Point3d target = new Point3d();
            string name = "";

            //get user inputs
            //user should be able to create a scene contianing only lines, or only meshes, or both.  All geo and material inputs will be optional, and we'll run some defense.
            if (!DA.GetData(0, ref eye)) return;
            if (!DA.GetData(1, ref target)) return;
            if (!DA.GetData(2, ref name)) return;

            try
            {
                //create json from lists of json:
                string outJSON = pointJSON(eye, target,name);
                outJSON = outJSON.Replace("OOO", "object");

                Element e = new Element(outJSON, va3cElementType.Camera);
                DA.SetData(0, e);
            }
            catch (Exception)
            {
                return;
            }
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var location = default(Plane);
            var text = default(string);
            var size = default(double);
            var bold = default(bool);
            var hAlign = default(int);
            var vAlign = default(int);

            if (!DA.GetData(0, ref location)) return;
            if (!DA.GetData(1, ref text)) return;
            if (!DA.GetData(2, ref size)) return;
            if (!DA.GetData(3, ref bold)) return;
            if (!DA.GetData(4, ref hAlign)) return;
            if (!DA.GetData(5, ref vAlign)) return;

            var typeWriter = bold ? Typewriter.Bold : Typewriter.Regular;

            var position = location.Origin;
            var unitX = location.XAxis * size;
            var unitZ = location.YAxis * size;

            var curves = typeWriter.Write(text, position, unitX, unitZ, hAlign, vAlign);

            DA.SetDataList(0, curves);

            //FontWriter.Save(@"C:\Users\Thomas\Desktop\Test.xml", new[] { Typewriter.Regular, Typewriter.Bold });
        }
Exemplo n.º 21
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<DHr> dhrs = new List<DHr>();
            string key = "";
            if ((DA.GetDataList(0, dhrs)) && (DA.GetData(1, ref key))) {
                float maxval = dhrs[0].val(key);
                float minval = dhrs[0].val(key);
                int max_day = 0;
                int min_day = 0;
                for (int n = 1; n < dhrs.Count; n++) {
                    float val = dhrs[n].val(key);
                    if (val > maxval) {
                        maxval = val;
                        max_day = dhrs[n].day_of_year;
                    }
                    if (val < minval) {
                        minval = val;
                        min_day = dhrs[n].day_of_year;
                    }
                }
                HourMask max_mask = new HourMask();
                max_mask.maskByDayOfYear(max_day, max_day);
                HourMask min_mask = new HourMask();
                min_mask.maskByDayOfYear(min_day, min_day);

                List<DHr> maxHrs = new List<DHr>();
                foreach (DHr hr in dhrs) if (max_mask.eval(hr)) maxHrs.Add(hr);
                List<DHr> minHrs = new List<DHr>();
                foreach (DHr hr in dhrs) if (min_mask.eval(hr)) minHrs.Add(hr);

                DA.SetDataList(0, maxHrs);
                DA.SetDataList(1, minHrs);
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Declare a variable for the input
            GH_Model model = null;

            // Use the DA object to retrieve the data inside the first input parameter.
            // If the retieval fails (for example if there is no data) we need to abort.
            if (!DA.GetData(0, ref model)) { return; }

            List<Vector3d> displacementVectors = new List<Vector3d>();
            List<Point3d> displacedPoints = new List<Point3d>();
            List<GeometryBase> displacedElements = new List<GeometryBase>();

            for (int i = 0; i < model.Nodes.Count; i++) {
                Vector3d vector = model.GetNodeDisplacement(i);
                Point3d point = model.GetDisplacedPoint(i);
                displacementVectors.Add(vector);
                displacedPoints.Add(point);
            }

            foreach (GH_Element element in model.Elements) {

                displacedElements.Add(element.GetDeformedGeometry(model));

            }

            DA.SetDataList(0, displacementVectors);
            DA.SetDataList(1, displacedPoints);
            DA.SetDataList(2, displacedElements);
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
 protected override void SolveInstance(IGH_DataAccess da)
 {
     if (!GetInputs(da)) return;
     connect = new List<Line>();
     weight = new List<double>();
     Random rand = new Random(DateTime.Now.Millisecond);
     float[,,] value = env.getTrails();
     float maxv = env.getMaxTrailValue();
     Point3d[,,] pos = env.getPosition();
     for (int i = 0; i < env.u; i++)
     {
         for (int j = 0; j < env.v; j++)
         {
             for (int k = 0; k < env.w; k++)
             {
                 if (rand.NextDouble() > (value[i, j, k]  / maxv) * possib)
                     continue;
                 Point3d thispt = pos[i,j,k];
                 List<Point3d> neighbor = env.getNeighbourTrailClosePos(i,j,k,radius, near_level);
                 foreach (Point3d pt in neighbor)
                 {
                     if (rand.NextDouble() < (value[i, j, k] / maxv)  * 0.5)
                     {
                         connect.Add(new Line(pt, thispt));
                         Point3d indexpos = env.getIndexByPosition(pt.X, pt.Y, pt.Z);
                         weight.Add(value[i, j, k] + value[(int)indexpos.X, (int)indexpos.Y, (int)indexpos.Z]);
                     }
                 }
             }
         }
     }
     SetOutputs(da);
 }
Exemplo n.º 26
0
 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;
 }
Exemplo n.º 27
0
 protected override void SolveInstance(IGH_DataAccess da)
 {
     if (!GetInputs(da)) return;
     if (reset == true)
     {
         trailTree = new DataTree<Point3d>();
         iter = 0;
         maxid = 0;
     }
     else
     {
         foreach (Amoeba amo in p.population)
         {
             GH_Path thispath = new GH_Path(amo.ID);
             if (amo.ID > maxid)
             {
                 trailTree.Add(amo.prev_loc, thispath);
                 maxid = amo.ID;
             }
             trailTree.Add(amo.Location, thispath);
             if (trailTree.Branch(thispath).Count > history)
             {
                 trailTree.Branch(thispath).RemoveAt(0);
             }
         }
         foreach (int id in p._todie_id)
         {
             GH_Path thispath = new GH_Path(id);
             trailTree.Branch(thispath).Clear();
         }
         iter++;
     }
     SetOutputs(da);
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            SpringMesh iSpringMesh = null;
            DA.GetData<SpringMesh>("Spring Mesh", ref iSpringMesh);

            DA.SetData("Rhino Mesh", iSpringMesh.ConvertToRhinoMesh());
        }
Exemplo n.º 29
0
        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);
        }
Exemplo n.º 30
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);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Sets inputs
            GH_Structure <GH_String>  names;
            GH_Structure <GH_Boolean> fineps;
            GH_Structure <GH_Number>  pzone_tcps;
            GH_Structure <GH_Number>  pzone_oris;
            GH_Structure <GH_Number>  pzone_eaxs;
            GH_Structure <GH_Number>  zone_oris;
            GH_Structure <GH_Number>  zone_leaxs;
            GH_Structure <GH_Number>  zone_reaxs;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Recognizes if Component is Deleted and removes it from Object Managers Zone Data and name list
            GH_Document doc = this.OnPingDocument();
            if (doc != null)
            {
                doc.ObjectsDeleted += DocumentObjectsDeleted;
            }
            #endregion
        }
Exemplo n.º 32
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 async void SolveInstance(IGH_DataAccess DA)
        {
            String pNumber = null;

            DA.GetData(0, ref pNumber);
            if (pNumber == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a valid project number");
            }

            String pName = null;

            DA.GetData(1, ref pName);
            if (pName == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a valid project name");
            }

            String epwFile = null;

            DA.GetData(2, ref epwFile);
            if (epwFile == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a valid EPW file");
            }

            if (!File.Exists(epwFile))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a valid, existing, EPW file");
            }

            List <String> idfFiles = new List <string>();

            DA.GetDataList(3, idfFiles);
            if (idfFiles.Count == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a valid list of IDF files");
            }

            if (!AllValidFiles(idfFiles))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Please provide a list of valid, existing, IDF files");
            }

            bool run = false;

            DA.GetData(4, ref run);

            if (pNumber == null || pName == null || epwFile == null || idfFiles.Count == 0 || !File.Exists(epwFile) || !AllValidFiles(idfFiles) || !run)
            {
                return;
            }

            //Everything is valid - let's run a simulation!
            AZEngine aEngine = new AZEngine(pNumber, pName);

            aEngine.CreateBlobStorage();

            aEngine.CreateBatchClients(idfFiles.Count);

            aEngine.InstallEnergyPlus();

            while (!aEngine.TrueWhenTasksComplete())
            {
                //Wait until the install is complete...
            }

            aEngine.UploadFile(epwFile);
            aEngine.UploadFiles(idfFiles);

            aEngine.RunEnergyPlus(idfFiles, epwFile);

            if (aEngine.TrueWhenTasksComplete())
            {
                DA.SetData(0, true);
            }
        }
Exemplo n.º 33
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 slot            = new Slot();
            var moduleNames     = new List <ModuleName>();
            var modulesProvided = false;

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

            if (slot == null || !slot.IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The slot is null or invalid.");
                return;
            }

            if (DA.GetDataList(1, moduleNames))
            {
                modulesProvided = true;
            }

            DA.SetDataList(0, new List <Point3d>()
            {
                slot.AbsoluteCenter
            });
            DA.SetDataList(1, new List <Plane>()
            {
                slot.BasePlane
            });
            DA.SetDataList(2, new List <Vector3d>()
            {
                slot.Diagonal
            });
            if (modulesProvided &&
                moduleNames != null &&
                slot.AllowsAnyModule &&
                slot.AllowedModuleNames.Count == 0)
            {
                DA.SetDataList(3, moduleNames);
            }
            else
            {
                DA.SetDataList(3, slot.AllowedModuleNames.Select(name => new ModuleName(name)));
            }
            if (modulesProvided &&
                moduleNames != null &&
                slot.AllowedModuleNames.Count >= moduleNames.Count &&
                moduleNames.All(name => slot.AllowedModuleNames.Contains(name.ToString())))
            {
                DA.SetDataList(5, new List <bool>()
                {
                    true
                });
            }
            else
            {
                DA.SetDataList(5, new List <bool>()
                {
                    slot.AllowsAnyModule
                });
            }
            DA.SetDataList(6, new List <bool>()
            {
                slot.IsContradictory
            });
            if (modulesProvided &&
                moduleNames != null &&
                (slot.AllowedModuleNames.Count > moduleNames.Count ||
                 !slot.AllowedModuleNames.All(name => moduleNames.Any(moduleName => moduleName.Name == name))
                ))
            {
                DA.SetDataList(7, new List <bool>()
                {
                    false
                });
            }
            else
            {
                DA.SetDataList(7, new List <bool>()
                {
                    slot.IsValid
                });
            }
            DA.SetDataList(4, new List <bool>()
            {
                slot.IsDeterministic
            });
        }
Exemplo n.º 34
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)
        {
            //// *********************************************************************************
            ////grasshopper current document
            //// *********************************************************************************
            //Component = this;
            //doc = Component.OnPingDocument();



            // *********************************************************************************
            // get info from grasshopper
            // *********************************************************************************
            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;
            }
            ;


            // time step
            double dt = 0.1;

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


            // wind speed
            double Vmet = 10;

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

            //terrain type
            int terrain = 0;

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


            bool run = false;

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



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

            DA.GetData(7, ref writeresults);


            DA.GetData(9, ref resetFFD);


            double nu = 1.511e-5;       // increase viscosity to impose turbulence. the higher velocity, the higher visc., 1e-3

            DA.GetData(10, ref nu);


            // *********************************************************************************
            //from Lukas
            // *********************************************************************************


            // Set initial velocity conditions
            double[, ,] u0 = new double[Nx + 1, Ny + 2, Nz + 2];
            double[, ,] v0 = new double[Nx + 2, Ny + 1, Nz + 2];
            double[, ,] w0 = new double[Nx + 2, Ny + 2, Nz + 1];

            // Create empty arrays for body forces
            double[, ,] f_x = new double[Nx + 1, Ny + 2, Nz + 2];
            double[, ,] f_y = new double[Nx + 2, Ny + 1, Nz + 2];
            double[, ,] f_z = new double[Nx + 2, Ny + 2, Nz + 1];

            // Create structure for solver parameters
            FluidSolver.solver_struct solver_prams = new FluidSolver.solver_struct();
            solver_prams.tol             = 1e-4;
            solver_prams.min_iter        = 1;
            solver_prams.max_iter        = 30;
            solver_prams.verbose         = false;
            solver_prams.backtrace_order = 2;
            solver_prams.mass_correction = false;
            solver_prams.mass_corr_alpha = 0.7;


            // Create FFD solver and domain
            if (ffd == null)
            {
                omega = new WindInflow(Nx + 2, Ny + 2, Nz + 2, xyzsize[0], xyzsize[1], xyzsize[2], Vmet, terrain);
                foreach (double[] geo in geom)
                {
                    omega.add_obstacle(geo[0], geo[1], geo[2], geo[3], geo[4], geo[5]);
                }

                ffd = new FluidSolver(omega, dt, nu, u0, v0, w0, solver_prams);
                de  = new DataExtractor(omega, ffd);
                t   = 0;
            }

            //reset FFD solver and domain
            if (resetFFD)
            {
                omega = new WindInflow(Nx + 2, Ny + 2, Nz + 2, xyzsize[0], xyzsize[1], xyzsize[2], Vmet, terrain);
                foreach (double[] geo in geom)
                {
                    omega.add_obstacle(geo[0], geo[1], geo[2], geo[3], geo[4], geo[5]);
                }

                ffd      = new FluidSolver(omega, dt, nu, u0, v0, w0, solver_prams);
                de       = new DataExtractor(omega, ffd);
                t        = 0;
                resetFFD = false;
            }



            //run solver. the solving-loop (new timestep) is executed in Grasshopper with a timer-component.
            if (run)
            {
                ffd.time_step(f_x, f_y, f_z);
            }



            // *******************************************************************************************
            // *******************************************************************************************
            // TO DO:   fix this loop with
            //   pp.export_data_vtk(String.Concat("lid_driven_cavity_", tstep, ".vtk"), Nx, Ny, Nz, tstep );
            //bool run2 = (bool)Component.Params.Input[5].Sources[0].VolatileData;
            //while (true)



            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // I could move all this away, an only output de data extractor

            // *******************************************************************************************
            // *********************************     Output Results       ********************************
            double[, ,] p  = new double[Nx, Ny, Nz];
            double[, ,] vu = new double[Nx, Ny, Nz];
            double[, ,] vv = new double[Nx, Ny, Nz];
            double[, ,] vw = new double[Nx, Ny, Nz];

            double[, ,] pstag  = new double[Nx + 1, Ny + 1, Nz + 1];
            double[, ,] vustag = new double[Nx + 1, Ny + 1, Nz + 1];
            double[, ,] vvstag = new double[Nx + 1, Ny + 1, Nz + 1];
            double[, ,] vwstag = new double[Nx + 1, Ny + 1, Nz + 1];

            for (int i = 0; i < Nx; i++)
            {
                for (int j = 0; j < Ny; j++)
                {
                    for (int k = 0; k < Nz; k++)
                    {
                        if (omega.obstacle_cells[i + 1, j + 1, k + 1] != 1)
                        {
                            p[i, j, k] = de.get_pressure(i * omega.hx + 0.5 * omega.hx, j * omega.hy + 0.5 * omega.hy, k * omega.hz + 0.5 * omega.hz);
                            double[] vel = de.get_velocity(i * omega.hx + 0.5 * omega.hx, j * omega.hy + 0.5 * omega.hy, k * omega.hz + 0.5 * omega.hz);
                            vu[i, j, k] = vel[0];
                            vv[i, j, k] = vel[1];
                            vw[i, j, k] = vel[2];

                            pstag[i, j, k] = de.get_pressure(i * omega.hx, j * omega.hy, k * omega.hz);
                            double[] velcen = de.get_velocity(i * omega.hx, j * omega.hy, k * omega.hz);
                            vustag[i, j, k] = velcen[0];
                            vvstag[i, j, k] = velcen[1];
                            vwstag[i, j, k] = velcen[2];
                        }
                        else
                        {
                            p[i, j, k]  = 0;
                            vu[i, j, k] = 0;
                            vv[i, j, k] = 0;
                            vw[i, j, k] = 0;

                            //pstag[i, j, k] = 0;
                            //vustag[i, j, k] = 0;
                            //vvstag[i, j, k] = 0;
                            //vwstag[i, k, k] = 0;

                            pstag[i, j, k] = de.get_pressure(i * omega.hx, j * omega.hy, k * omega.hz);
                            double[] velcen = de.get_velocity(i * omega.hx, j * omega.hy, k * omega.hz);
                            vustag[i, j, k] = velcen[0];
                            vvstag[i, j, k] = velcen[1];
                            vwstag[i, j, k] = velcen[2];
                        }
                    }
                }
            }

            //last x slice
            for (int j = 0; j < Ny + 1; j++)
            {
                for (int k = 0; k < Nz + 1; k++)
                {
                    pstag[Nx, j, k] = de.get_pressure((Nx) * omega.hx, j * omega.hy, k * omega.hz);
                    double[] vcen = de.get_velocity((Nx) * omega.hx, j * omega.hy, k * omega.hz);
                    vustag[Nx, j, k] = vcen[0];
                    vvstag[Nx, j, k] = vcen[1];
                    vwstag[Nx, j, k] = vcen[2];
                }
            }

            //last y slice
            for (int i = 0; i < Nx + 1; i++)
            {
                for (int k = 0; k < Nz + 1; k++)
                {
                    pstag[i, Ny, k] = de.get_pressure(i * omega.hx, (Ny) * omega.hy, k * omega.hz);
                    double[] vcen = de.get_velocity(i * omega.hx, (Ny) * omega.hy, k * omega.hz);
                    vustag[i, Ny, k] = vcen[0];
                    vvstag[i, Ny, k] = vcen[1];
                    vwstag[i, Ny, k] = vcen[2];
                }
            }

            //last z slice
            for (int i = 0; i < Nx + 1; i++)
            {
                for (int j = 0; j < Ny + 1; j++)
                {
                    pstag[i, j, Nz] = de.get_pressure(i * omega.hx, j * omega.hy, (Nz) * omega.hz);
                    double [] vcen = de.get_velocity(i * omega.hx, j * omega.hy, (Nz) * omega.hz);
                    vustag[i, j, Nz] = vcen[0];
                    vvstag[i, j, Nz] = vcen[1];
                    vwstag[i, j, Nz] = vcen[2];
                }
            }

            List <double[, , ]> veloutCen = new List <double[, , ]> {
            };

            veloutCen.Add(vu);
            veloutCen.Add(vv);
            veloutCen.Add(vw);

            List <double[, , ]> veloutStag = new List <double[, , ]> {
            };

            veloutStag.Add(vustag);
            veloutStag.Add(vvstag);
            veloutStag.Add(vwstag);


            DA.SetDataList(0, veloutCen);
            DA.SetData(1, p);
            DA.SetDataList(2, veloutStag);
            DA.SetData(3, pstag);



            // *******************************************************************************************
            // *******************************      Output Cp values on Surfaces   ***********************
            //if (mshCp.Count > 0)
            if (writeresults)
            {
                ////generate list of objects
                ////  each item contains:
                ////      - 2d matrix of Cp values for each node of the analysis mesh
                ////      - mesh itself
                //List<object[]> mshCpOUT = new List<object[]>();
                //foreach (Mesh msh in mshCp)
                //{
                //    object[] _mshCpout = new object[2] ;
                //    _mshCpout[0] = msh;
                //    //_mshCpout[1]
                //     double [] Cps = new double[msh.Vertices.Count];        //this will be the Cp values. size of array corresponds to mesh vertices
                //    for (int u = 0; u < msh.Vertices.Count; u++)
                //    {
                //        double pref = de.get_pressure(0, msh.Vertices[u].Y, msh.Vertices[u].Z);     //!!! adjust msh to origin and discretisationj
                //        double cp = de.get_pressure(msh.Vertices[u].X, msh.Vertices[u].Y, msh.Vertices[u].Z);
                //        Cps[u] = 1;
                //    }

                //}
                //DA.SetDataList(4, mshCp);


                DA.SetData(4, de);
            }



            // _____________________________________________________________________________________
            // // THIS SHOWS HOW TO ADD A FORM
            //if (f == null)
            //{
            //    f = new LEGACY_Form1();
            //    f.Show(Grasshopper.Instances.DocumentEditor);
            //    Grasshopper.Instances.DocumentEditor.FormShepard.RegisterForm(f);
            //    f.checkBox1.Text = "run the solver";
            //}



            // _____________________________________________________________________________________
            // // THIS SHOWS HOW TO DYNAMICALLY USE GRASSHOPPER SLIDER INPUTS
            //List<Grasshopper.Kernel.Special.GH_NumberSlider> sliders = new List<Grasshopper.Kernel.Special.GH_NumberSlider>();
            //foreach (IGH_Param param in Component.Params.Input)
            //{
            //    Grasshopper.Kernel.Special.GH_NumberSlider slider = param.Sources[0] as Grasshopper.Kernel.Special.GH_NumberSlider;
            //    if (slider != null)
            //    {
            //        sliders.Add(slider);
            //        x = (int)slider.CurrentValue;
            //    }
            //}

            //while (terminate != true)
            //{
            //    doc.NewSolution(false);

            //    fx = x * 10;
            //    maximize(x, fx);
            //    sliders[0].TickValue = xNew;
            //    x = xNew;
            //}
        }
Exemplo n.º 35
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Script to discretize a topography-mesh into cubes for the FFD solver
            //  2016-09-07  Christoph Waibel
            //



            //input:
            //  x,y,z grid size
            //  x,y,z cell numbers
            //  origin point (all calculations use this as reference)
            //  mesh geometry
            List <double> xyzsize = new List <double>();

            if (!DA.GetDataList(0, xyzsize))
            {
                return;
            }
            ;
            List <int> xyzcells = new List <int>();

            if (!DA.GetDataList(1, xyzcells))
            {
                return;
            }
            ;
            List <Mesh> meshs = new List <Mesh>();

            if (!DA.GetDataList(2, meshs))
            {
                return;
            }
            Point3d origin = Point3d.Unset;

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

            double tolerance = 0.01;

            //output:
            //  list of cubes (as double [6]{xmin, xmax, ymin, ymax, zmin, zmax})

            //1. create list of points on grid cells 0-point
            List <Point3d> pts       = new List <Point3d>();
            double         xcelldist = xyzsize[0] / xyzcells[0];
            double         ycelldist = xyzsize[1] / xyzcells[1];
            double         zcelldist = xyzsize[2] / xyzcells[2];

            for (int x = 0; x < xyzcells[0]; x++)
            {
                for (int y = 0; y < xyzcells[1]; y++)
                {
                    pts.Add(new Point3d((x + 0.5) * xcelldist + origin[0], (y + 0.5) * ycelldist + origin[1], origin[2]));
                }
            }

            Vector3d vec = new Vector3d(0, 0, 1);
            //foreach grid cell
            List <Box>      box   = new List <Box>();
            List <double[]> cubes = new List <double[]>();

            foreach (Point3d pt in pts)
            {
                foreach (Mesh mesh in meshs)
                {
                    //2. shoot rays straight up (from z-origin to zmax)
                    //Ray3d ray = new Ray3d(new Point3d(pt[0] + 0.5 * (double)xcelldist, pt[1] + 0.5 * (double)ycelldist, pt[2]), vec);
                    Ray3d ray = new Ray3d(new Point3d(pt[0], pt[1], pt[2]), vec);
                    //3. check for intersections with mesh
                    Point3d ptX1      = new Point3d(pt[0], pt[1], pt[2]);
                    bool    blninters = false;
                    double  inters1   = Rhino.Geometry.Intersect.Intersection.MeshRay(mesh, ray);


                    if (inters1 > 0)
                    {
                        Point3d ptat1 = ray.PointAt(inters1);
                        ray = new Ray3d(new Point3d(ptat1[0], ptat1[1], ptat1[2] + tolerance), vec);

                        //flatten point to the next/previous grid step
                        ptat1 = new Point3d(ptat1.X, ptat1.Y, Math.Round((ptat1[2] - origin[2]) / zcelldist, 0) * zcelldist + origin[2]);

                        double inters2 = Rhino.Geometry.Intersect.Intersection.MeshRay(mesh, ray);
                        if (inters2 > 0)
                        {
                            Point3d ptat2 = ray.PointAt(inters2);
                            blninters = true;
                            //repeat until there are no other intersections anymore
                            while (blninters == true)
                            {
                                //5. create cube with xmin xmax ymin ymax zmin (all already known), and zmax (calculated with mesh intersection)
                                //      rounding the intersection-z-value to match the grid-z-values
                                Point3d ptmax = new Point3d(ptat1[0] + 0.5 * xcelldist, ptat1[1] + 0.5 * ycelldist, Math.Round((ptat2[2] - origin[2]) / zcelldist, 0) * zcelldist + origin[2]);
                                box.Add(new Box(new BoundingBox(new Point3d(ptat1[0] - 0.5 * xcelldist, ptat1 [1] - 0.5 * ycelldist, ptat1[2]), ptmax)));
                                cubes.Add(new double[] { ptat1[0] - origin[0] - 0.5 * xcelldist, ptmax[0] - origin[0], ptat1[1] - origin[1] - 0.5 * ycelldist, ptmax[1] - origin[1], ptat1[2] - origin[2], ptmax[2] - origin[2] });

                                //check another intersection couple  */------/*
                                ptat1   = new Point3d(ptat2[0], ptat2[1], ptat2[2] + tolerance);
                                ray     = new Ray3d(ptat1, vec);
                                inters1 = Rhino.Geometry.Intersect.Intersection.MeshRay(mesh, ray);
                                if (inters1 > 0)
                                {
                                    ptat1   = ray.PointAt(inters1);
                                    ray     = new Ray3d(new Point3d(ptat1[0], ptat1[1], ptat1[2] + tolerance), vec);
                                    inters2 = Rhino.Geometry.Intersect.Intersection.MeshRay(mesh, ray);
                                    if (inters2 > 0)
                                    {
                                        ptat2 = ray.PointAt(inters2);
                                    }
                                    else
                                    {
                                        blninters = false;
                                    }
                                }
                                else
                                {
                                    blninters = false;
                                }
                            }
                        }
                    }
                }
            }



            DiscretizedGeometry myGeometry = new DiscretizedGeometry(cubes);



            DA.SetDataList(0, box);
            DA.SetDataList(1, cubes);
            DA.SetData(2, myGeometry);
        }
Exemplo n.º 36
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            counter++;
            DA.GetData(1, ref n);
            n = Math.Abs(n);

            Flex         flex   = null;
            List <Cloth> cloths = new List <Cloth>();

            if (!DA.GetData(0, ref flex))
            {
                return;
            }
            DA.GetDataList(2, cloths);

            if (flex == null)
            {
                throw new Exception("Invalid flex class");
            }

            List <FlexParticle> part = flex.Scene.GetClothParticles();

            if (n != 0 && counter % n == 0)
            {
                pts = new GH_Structure <GH_Point>();
                vel = new GH_Structure <GH_Vector>();

                foreach (FlexParticle fp in part)
                {
                    GH_Path p = new GH_Path(fp.GroupIndex);
                    pts.Append(new GH_Point(new Point3d(fp.PositionX, fp.PositionY, fp.PositionZ)), p);
                    vel.Append(new GH_Vector(new Vector3d(fp.VelocityX, fp.VelocityY, fp.VelocityZ)), p);
                }
            }

            if (cloths.Count > 0)
            {
                DA.GetData(3, ref mat);

                draw_msh = new GH_Structure <GH_Mesh>();
                foreach (Cloth c in cloths)
                {
                    List <FlexParticle> meshParts = new List <FlexParticle>();
                    foreach (FlexParticle fp in part)
                    {
                        if (fp.GroupIndex == c.GroupIndex)
                        {
                            meshParts.Add(fp);
                        }
                    }

                    GH_Path p = new GH_Path(c.GroupIndex);
                    for (int i = 0; i < c.Mesh.Vertices.Count; i++)
                    {
                        c.Mesh.Vertices[i] = new Point3f(meshParts[i + c.SpringOffset].PositionX, meshParts[i + c.SpringOffset].PositionY, meshParts[i + c.SpringOffset].PositionZ);
                    }
                    draw_msh.Append(new GH_Mesh(c.Mesh), p);
                }
            }


            if (n != 0 && counter % n == 0)
            {
                msh = draw_msh;
                DA.SetDataTree(0, pts);
                DA.SetDataTree(1, vel);
                DA.SetDataTree(2, msh);
            }
        }
Exemplo n.º 37
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)
 {
 }
Exemplo n.º 38
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Number> inSPDsPerDirPerHours = new GH_Structure <GH_Number>();

            DA.GetDataTree(0, out inSPDsPerDirPerHours);

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

            DA.GetDataList(1, inDirections);

            GH_Structure <GH_Number> inVrelSimVelocitiesPerDirPerPoint = new GH_Structure <GH_Number>();

            DA.GetDataTree(2, out inVrelSimVelocitiesPerDirPerPoint);


            double VmaxThreshold = 5.0;

            DA.GetData(3, ref VmaxThreshold);

            bool debug = false;

            DA.GetData(4, ref debug);

            bool run = false;

            DA.GetData(5, ref run);


            if (!run)
            {
                DA.SetDataList(0, outThresholdHoursPerPoint);
                //DA.SetDataTree(1, outThresholdHoursPerPointPerDirection);
                DA.SetDataList(2, accumulatedSpeedsPerPoint);
                return;
            }

            int noPoints         = inVrelSimVelocitiesPerDirPerPoint.get_Branch(0).Count;
            int noWindDirections = inVrelSimVelocitiesPerDirPerPoint.Branches.Count;


            accumulatedSpeedsPerPoint = new double[noPoints];



            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"stats 001");
            }



            // SPDS:
            //inSPDsPerDirPerHours.Branches[windDir][point].Value;

            // Vrels:
            //inVrelSimVelocitiesPerDirPerPoint.Branches[windDir][point].Value;

            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"stats 002.. Foreach inVelocitiesPerPointPerDir.PathCount {inVrelSimVelocitiesPerDirPerPoint.PathCount}");
            }



            // Checking if new weather data setup. Otherwise reuse the old.

            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"stats 003");
            }


            double newSumOfVelocities = 0;

            foreach (List <GH_Number> numbers in inVrelSimVelocitiesPerDirPerPoint.Branches)
            {
                foreach (GH_Number number in numbers)
                {
                    newSumOfVelocities += number.Value;
                }
            }

            if (oldSumOfVelocities != newSumOfVelocities)
            {
                if (debug)
                {
                    Rhino.RhinoApp.WriteLine($"redoing thresholds");
                }
                thresholdsForDirectionCheck = Utilities.GetThresholds(inDirections);
                oldSumOfVelocities          = newSumOfVelocities;
            }
            else
            {
                if (debug)
                {
                    Rhino.RhinoApp.WriteLine($"reusing thresholds");
                }
            }


            //if (debug) Rhino.RhinoApp.WriteLine($"stats 004");
            outThresholdHoursPerPointPerDirection = new GH_Structure <GH_Number>();
            outThresholdHoursPerPoint             = new List <double>(new double[noPoints].ToList());

            List <double> thresholds = Utilities.GetThresholds(inDirections);


            if (debug)
            {
                Rhino.RhinoApp.WriteLine($"foreach noPoints: {noPoints}");
            }
            for (int p = 0; p < noPoints; p++)
            {
                List <GH_Number> speedsInThisPointPerDir = new List <GH_Number>();

                if (debug && p < 5)
                {
                    Rhino.RhinoApp.WriteLine($"foreach noWindDirections: {noWindDirections}");
                }
                for (int d = 0; d < noWindDirections; d++)
                {
                    int hoursThisPointAndDirection = 0;

                    if (debug && d < 3 && p < 5)
                    {
                        Rhino.RhinoApp.WriteLine($"foreach SPDS: inSPDsPerDirPerHours[{d}].Count: {inSPDsPerDirPerHours[d].Count}");
                    }
                    for (int s = 0; s < inSPDsPerDirPerHours[d].Count; s++)
                    {
                        double result = inSPDsPerDirPerHours.Branches[d][s].Value * inVrelSimVelocitiesPerDirPerPoint.Branches[d][p].Value;

                        accumulatedSpeedsPerPoint[p] += result;

                        if (debug && s < 5 && p < 5 && d < 5)
                        {
                            Rhino.RhinoApp.WriteLine($"[{p}][{d}][{s}]  inSPDsPerDirPerHours.Branches[{d}][{s}].Value {inSPDsPerDirPerHours.Branches[d][s].Value:0.0} *  inVrelSimVelocitiesPerDirPerPoint.Branches[{d}][{p}].Value { inVrelSimVelocitiesPerDirPerPoint.Branches[d][p].Value:0.0} = {result:0.0}");
                        }
                        if (result >= VmaxThreshold)
                        {
                            hoursThisPointAndDirection++;
                            if (debug && s < 5 && p < 5 && d < 5)
                            {
                                Rhino.RhinoApp.WriteLine($"[{p}][{d}][{s}] adding");
                            }
                        }
                    }


                    speedsInThisPointPerDir.Add(new GH_Number(hoursThisPointAndDirection));
                }

                accumulatedSpeedsPerPoint[p] /= 8760.0; //should give average speed in this point over a year.

                outThresholdHoursPerPointPerDirection.AppendRange(speedsInThisPointPerDir, new GH_Path(p));
            }



            //now we got it per direction. Lets sum it up.

            List <double> hoursOutsideComfortPerPoint = new double[noPoints].ToList();

            for (int i = 0; i < outThresholdHoursPerPointPerDirection.Branches.Count; i++)
            {
                for (int j = 0; j < outThresholdHoursPerPointPerDirection.Branches[i].Count; j++)
                {
                    outThresholdHoursPerPoint[i] += outThresholdHoursPerPointPerDirection.Branches[i][j].Value / 8760.0 * 100.0; // to convert to pct per year
                }
            }
            //DA.SetDataList(0, hoursOutsideComfortPerPoint);

            //DA.SetData(1, outThresholdHoursPerPoint);

            //DA.SetDataList(2, accumulatedSpeedsPerPoint);
        }
Exemplo n.º 39
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string fileloc = "";

            DA.GetData <string>(2, ref fileloc);
            if (!fileloc.EndsWith(@"\"))
            {
                fileloc = fileloc + @"\";
            }

            string prefix = "";

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

            string URL = slippyURL;
            //DA.GetData<string>(4, ref URL);

            string userAgent = "";

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

            bool run = false;

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

            GH_Structure <GH_String>  mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_Curve>   imgFrame = new GH_Structure <GH_Curve>();
            GH_Structure <GH_Integer> tCount   = new GH_Structure <GH_Integer>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = fileloc + prefix + "_" + i + ".jpg";

                ///location of final image file
                mapList.Append(new GH_String(imgPath), path);

                ///create cache folder for images
                string        cacheLoc      = fileloc + @"HeronCache\";
                List <string> cacheFileLocs = new List <string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List <Point3d> boxPtList = new List <Point3d>();

                ///get the tile coordinates for all tiles within boundary
                List <List <int> > ranges = new List <List <int> >();
                ranges = Convert.GetTileRange(boundaryBox, zoom);

                List <List <int> > tileList = new List <List <int> >();
                List <int>         x_range  = ranges[0];
                List <int>         y_range  = ranges[1];

                ///cycle through tiles to get bounding box
                for (int y = y_range[0]; y <= y_range[1]; y++)
                {
                    for (int x = x_range[0]; x <= x_range[1]; x++)
                    {
                        ///add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cacheFileLocs.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + x + y + ".png");
                    }
                }

                ///bounding box of tile boundaries
                BoundingBox bboxPts = new BoundingBox(boxPtList);

                ///convert bounding box to polyline
                List <Point3d> imageCorners = bboxPts.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                imgFrame.Append(new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve()), path);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                                         + x_range[0].ToString()
                                         + y_range[0].ToString()
                                         + x_range[1].ToString()
                                         + y_range[1].ToString();

                ///check if the existing final image already covers the boundary.
                ///if so, no need to download more or reassemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFileLocs))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }
                        }
                    }
                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of assembling image
                ///setup final image container bitmap
                int    fImageW    = (x_range[1] - x_range[0] + 1) * 256;
                int    fImageH    = (y_range[1] - y_range[0] + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = y_range[0]; y <= y_range[1]; y++)
                        {
                            for (int x = x_range[0]; x <= x_range[1]; x++)
                            {
                                //create tileCache name
                                string tileCache    = slippySource.Replace(" ", "") + zoom + x + y + ".png";
                                string tileCahceLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List <int> {
                                        zoom, y, x
                                    });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                    System.Net.WebClient client = new System.Net.WebClient();

                                    ///insert header if required
                                    client.Headers.Add("user-agent", userAgent);

                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;
                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                        //save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Append(new GH_Integer(tileList.Count), path);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;
            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Slippy");
        }
        public override void SolveInstance(IGH_DataAccess DA, out string msg, out GH_RuntimeMessageLevel level)
        {
            msg   = "";
            level = GH_RuntimeMessageLevel.Blank;
            //    //var line = new LineCurve();
            //    Curve inCurve = null;
            //    var noIndex = 0;
            //    var comment = "";
            //    var rFMember = new RFMember();
            //    var inRFEM = new GH_RFEM();
            //    var mod = false;
            //    var del = false;
            //    var lineNo = 0;
            //    var memberType = 0;
            //    var taperType = 0;
            //    var rotAngle = 0.0;
            //    //var intPoints = 4;
            //    var sCS = 0;
            //    var eCS = 0;
            //    var sH = 0;
            //    var eH = 0;
            //    var ecc = 0;
            //    var div = 0;

            //    //int newNo = 0;

            //    if (DA.GetData(15, ref inRFEM))
            //    {
            //        rFMember = new RFMember((RFMember)inRFEM.Value);
            //        if (DA.GetData(1, ref sCS))
            //        {
            //            rFMember.StartCrossSectionNo = sCS;
            //        }
            //        if (DA.GetData(0, ref inCurve))
            //        {
            //            var myRFLine = new RFLine();
            //            Component_RFLine.SetGeometry(inCurve, ref myRFLine);
            //            rFMember.SetFrames();
            //        }
            //        if (DA.GetData(1, ref sCS))
            //        {
            //            rFMember.StartCrossSectionNo = sCS;
            //        }
            //    }
            //    else if (DA.GetData(0, ref inCurve) && DA.GetData(1, ref sCS))
            //    {
            //        var myRFLine = new RFLine();
            //        Component_RFLine.SetGeometry(inCurve, ref myRFLine);
            //        rFMember.BaseLine = myRFLine;
            //        rFMember.SetFrames();
            //        rFMember.StartCrossSectionNo = sCS;
            //    }
            //    else
            //    {
            //        msg = "Insufficient input parameters. Provide either Input Curve and Start Cross Section or existing RFMember Object. ";
            //        level = GH_RuntimeMessageLevel.Warning;
            //    return;
            //}
            //    if (DA.GetData(16, ref mod))
            //    {
            //        rFMember.ToModify = mod;
            //    }
            //    if (DA.GetData(17, ref del))
            //    {
            //        rFMember.ToDelete = del;
            //    }
            //    if (DA.GetData(2, ref noIndex))
            //    {
            //        rFMember.No = noIndex;
            //    }
            //    if (DA.GetData(3, ref comment))
            //    {
            //        rFMember.Comment = comment;
            //    }
            //    if (DA.GetData(4, ref lineNo))
            //    {
            //        rFMember.LineNo = lineNo;
            //    }
            //    if (DA.GetData(5, ref memberType))
            //    {
            //        rFMember.Type = (MemberType)memberType;
            //        if (rFMember.Type == MemberType.UnknownMemberType)
            //        {
            //            msg = "Member Type not supported. ";
            //            level = GH_RuntimeMessageLevel.Warning;
            //            return;
            //        }
            //    }
            //    if (DA.GetData(6, ref rotAngle))
            //    {
            //        rFMember.RotationType = RotationType.Angle;
            //        rFMember.RotationAngle = rotAngle;
            //    }
            //    if (DA.GetData(7, ref eCS))
            //    {
            //        rFMember.EndCrossSectionNo = eCS;
            //    }
            //    if (DA.GetData(8, ref sH))
            //    {
            //        rFMember.StartHingeNo = sH;
            //    }
            //    if (DA.GetData(9, ref eH))
            //    {
            //        rFMember.EndHingeNo = eH;
            //    }
            //    if (DA.GetData(10, ref ecc))
            //    {
            //        rFMember.EccentricityNo = ecc;
            //    }
            //    if (DA.GetData(11, ref div))
            //    {
            //        rFMember.DivisionNo = div;
            //    }
            //    if (DA.GetData(12, ref taperType))
            //    {
            //        rFMember.TaperShape = (TaperShapeType)taperType;
            //        if (rFMember.TaperShape == TaperShapeType.UnknownTaperShape)
            //        {
            //            msg = "Taper Shape Type not supported. ";
            //            level = GH_RuntimeMessageLevel.Warning;
            //            return;
            //        }
            //    }
            //    DA.SetData(0, rFMember);
        }
Exemplo n.º 41
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 folder     = null;
            string meshPath   = null;
            var    refresh    = false;
            var    _overrides = "";

            DA.GetData(0, ref folder);
            DA.GetData(1, ref meshPath);
            DA.GetData(2, ref _overrides);
            DA.GetData(3, ref refresh);

            var overrides = new ProbeResultOverrides().FromJson(_overrides) ?? new ProbeResultOverrides {
                Exclude = null, Include = null, Distance = 0.1, Outputs = null
            };

            AddOverrideOutputs(overrides);

            if (string.IsNullOrEmpty(folder))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Please provide a valid string to the Folder input.");
            }

            // Get Cache to see if we already did this
            var cacheKey     = folder + meshPath + _overrides;
            var cachedValues = StringCache.getCache(cacheKey);

            DA.DisableGapLogic();

            if (!string.IsNullOrEmpty(folder) && (cachedValues == null || refresh))
            {
                const string queueName = "probeResults";
                StringCache.setCache(InstanceGuid.ToString(), "");

                // Get queue lock
                var queueLock = StringCache.getCache(queueName);
                if (queueLock != "true")
                {
                    StringCache.setCache(queueName, "true");
                    StringCache.setCache(cacheKey + "progress", "Loading...");

                    QueueManager.addToQueue(queueName, () =>
                    {
                        try
                        {
                            var results = ProbeResult.ReadProbeResults(
                                folder,
                                overrides.Exclude,
                                overrides.Include
                                );
                            cachedValues = JsonConvert.SerializeObject(results);
                            StringCache.setCache(cacheKey, cachedValues);

                            var points = ProbeResult.ReadPointsFromResults(
                                folder,
                                overrides.Exclude,
                                overrides.Include
                                );
                            probePoints = ConvertPointsToDataTree(points);

                            if (!string.IsNullOrEmpty(meshPath))
                            {
                                loadedMeshes = Import.LoadMeshFromPath(meshPath, overrides.Exclude, overrides.Include);
                            }


                            if (loadedMeshes != null && loadedMeshes.Any())
                            {
                                if (points != null && points.Any())
                                {
                                    try
                                    {
                                        correctedMesh = CorrectMesh(loadedMeshes, points, overrides.Distance ?? 0.1);
                                    }
                                    catch (InvalidOperationException error)
                                    {
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                                          $"Could not construct new mesh. Got error: {error.Message}");
                                    }
                                }
                                else
                                {
                                    correctedMesh = CorrectMesh(loadedMeshes);
                                }
                            }

                            probeResults = new Dictionary <string, DataTree <object> >();
                            foreach (var key in results.Keys)
                            {
                                probeResults.Add(key, ConvertToDataTree(results[key]));
                            }

                            info       = UpdateInfo(results);
                            resultKeys = results.Keys.ToList();
                            StringCache.setCache(cacheKey + "progress", "Done");
                        }
                        catch (Exception e)
                        {
                            StringCache.setCache(InstanceGuid.ToString(), e.Message);
                            StringCache.setCache(cacheKey, "error");
                            StringCache.setCache(cacheKey + "progress", "");
                        }

                        ExpireSolutionThreadSafe(true);
                        Thread.Sleep(2000);
                        StringCache.setCache(queueName, "");
                    });
                    ExpireSolutionThreadSafe(true);
                }
            }


            HandleErrors();

            if (probePoints != null)
            {
                DA.SetDataTree(1, probePoints);
            }

            if (correctedMesh != null)
            {
                DA.SetDataTree(2, correctedMesh);
            }

            if (info != null)
            {
                DA.SetDataTree(0, info);
            }

            if (probeResults != null)
            {
                foreach (var key in probeResults.Keys)
                {
                    AddToOutput(DA, key, probeResults[key], overrides.Outputs);
                }
            }

            if (resultKeys != null && overrides.Outputs == null)
            {
                resultKeys.Add("Info");
                resultKeys.Add("Points");
                resultKeys.Add("Mesh");
                RemoveUnusedOutputs(resultKeys);
            }

            Message = StringCache.getCache(cacheKey + "progress");
        }
Exemplo n.º 42
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            bool run = false;

            if (!dataAccess.GetData(9, ref run))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                dataAccess.SetData(3, false);
                return;
            }
            if (!run)
            {
                return;
            }

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            List <Panel> panels = new List <Panel>();

            if (!dataAccess.GetDataList(0, panels))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            ConstructionLibrary constructionLibrary = null;

            dataAccess.GetData(1, ref constructionLibrary);
            if (constructionLibrary == null)
            {
                constructionLibrary = ActiveSetting.Setting.GetValue <ConstructionLibrary>(AnalyticalSettingParameter.DefaultConstructionLibrary);
            }

            ApertureConstructionLibrary apertureConstructionLibrary = null;

            dataAccess.GetData(2, ref apertureConstructionLibrary);
            if (apertureConstructionLibrary == null)
            {
                apertureConstructionLibrary = ActiveSetting.Setting.GetValue <ApertureConstructionLibrary>(AnalyticalSettingParameter.DefaultApertureConstructionLibrary);
            }

            string csvOrPath = null;

            if (!dataAccess.GetData(3, ref csvOrPath) || string.IsNullOrWhiteSpace(csvOrPath))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string sourceColumn = null;

            if (!dataAccess.GetData(4, ref sourceColumn) || string.IsNullOrWhiteSpace(sourceColumn))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string templateColumn = null;

            if (!dataAccess.GetData(5, ref templateColumn) || string.IsNullOrWhiteSpace(templateColumn))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string destinationColumn = null;

            if (!dataAccess.GetData(6, ref destinationColumn) || string.IsNullOrWhiteSpace(destinationColumn))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string typeColumn = null;

            if (!dataAccess.GetData(7, ref typeColumn) || string.IsNullOrWhiteSpace(typeColumn))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            string thicknessColumn = null;

            dataAccess.GetData(8, ref thicknessColumn);

            Core.DelimitedFileTable delimitedFileTable = null;
            if (Core.Query.ValidFilePath(csvOrPath))
            {
                delimitedFileTable = new Core.DelimitedFileTable(new Core.DelimitedFileReader(Core.DelimitedFileType.Csv, csvOrPath));
            }
            else
            {
                string[] lines = csvOrPath.Split('\n');
                delimitedFileTable = new Core.DelimitedFileTable(new Core.DelimitedFileReader(Core.DelimitedFileType.Csv, lines));
            }

            if (delimitedFileTable == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            int index_Source = delimitedFileTable.GetColumnIndex(sourceColumn);

            if (index_Source == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            int index_Template = delimitedFileTable.GetColumnIndex(templateColumn);

            if (index_Template == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            int index_Destination = delimitedFileTable.GetColumnIndex(destinationColumn);

            if (index_Destination == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            int index_Type = delimitedFileTable.GetColumnIndex(typeColumn);

            if (index_Type == -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            int index_Thickness = -1;

            if (!string.IsNullOrWhiteSpace(thicknessColumn))
            {
                index_Thickness = delimitedFileTable.GetColumnIndex(thicknessColumn);
            }

            Core.Revit.ConvertSettings convertSettings = null;

            if (convertSettings == null)
            {
                convertSettings = Core.Revit.Query.ConvertSettings();
            }

            ConstructionLibrary         constructionLibrary_Result         = new ConstructionLibrary(constructionLibrary.Name);
            ApertureConstructionLibrary apertureConstructionLibrary_Result = new ApertureConstructionLibrary(apertureConstructionLibrary.Name);

            List <Panel>       panels_Result          = new List <Panel>();
            List <Aperture>    apertures_Result       = new List <Aperture>();
            List <ElementType> elementTypes_Panels    = new List <ElementType>();
            List <ElementType> elementTypes_Apertures = new List <ElementType>();

            foreach (Panel panel in panels)
            {
                Construction construction = panel?.Construction;
                if (construction == null)
                {
                    continue;
                }

                string name = construction.Name;
                if (name == null)
                {
                    //result.Add(construction);
                    continue;
                }

                string    name_Destination = null;
                string    name_Template    = null;
                string    name_Source      = null;
                PanelType panelType        = PanelType.Undefined;
                double    thickness        = double.NaN;
                for (int i = 0; i < delimitedFileTable.RowCount; i++)
                {
                    string typeName = null;
                    if (delimitedFileTable.TryGetValue(i, index_Type, out typeName))
                    {
                        ApertureType apertureType = Analytical.Query.ApertureType(typeName);
                        if (apertureType != ApertureType.Undefined)
                        {
                            continue;
                        }

                        panelType = Analytical.Query.PanelType(typeName as object);
                    }

                    if (!delimitedFileTable.TryGetValue(i, index_Source, out name_Source))
                    {
                        continue;
                    }

                    if (!name.Equals(name_Source))
                    {
                        continue;
                    }

                    if (!delimitedFileTable.TryGetValue(i, index_Destination, out name_Destination))
                    {
                        name_Destination = null;
                        continue;
                    }

                    if (!delimitedFileTable.TryGetValue(i, index_Template, out name_Template))
                    {
                        name_Template = null;
                    }

                    if (index_Thickness != -1)
                    {
                        if (!delimitedFileTable.TryConvert(i, index_Thickness, out thickness))
                        {
                            thickness = double.NaN;
                        }
                    }

                    break;
                }

                if (string.IsNullOrWhiteSpace(name_Destination))
                {
                    name_Destination = name_Template;
                }

                if (string.IsNullOrWhiteSpace(name_Destination))
                {
                    continue;
                }

                if (panelType == PanelType.Undefined)
                {
                    panelType = panel.PanelType;
                }

                Construction construction_New = constructionLibrary_Result.GetConstructions(name_Destination)?.FirstOrDefault();
                if (construction_New == null)
                {
                    Construction construction_Temp = constructionLibrary.GetConstructions(name_Template)?.FirstOrDefault();
                    if (construction_Temp == null)
                    {
                        continue;
                    }

                    if (name_Destination.Equals(name_Template))
                    {
                        construction_New = construction_Temp;
                    }
                    else
                    {
                        construction_New = new Construction(construction_Temp, name_Destination);
                    }

                    construction_New.SetValue(ConstructionParameter.Description, construction.Name);
                    construction_New.RemoveValue(ConstructionParameter.DefaultPanelType);
                    //construction_New.SetValue(ConstructionParameter.DefaultPanelType, panelType.Text());

                    if (!double.IsNaN(thickness))
                    {
                        construction_New.SetValue(ConstructionParameter.DefaultThickness, thickness);
                    }

                    constructionLibrary_Result.Add(construction_New);
                }

                HostObjAttributes hostObjAttributes = Analytical.Revit.Convert.ToRevit(construction_New, document, panelType, panel.Normal, convertSettings);
                if (hostObjAttributes == null)
                {
                    if (string.IsNullOrWhiteSpace(name_Template))
                    {
                        Construction construction_Default = Analytical.Query.DefaultConstruction(panelType);
                        if (construction_Default != null)
                        {
                            name_Template = construction_Default.Name;
                        }
                    }

                    if (string.IsNullOrWhiteSpace(name_Template))
                    {
                        continue;
                    }

                    hostObjAttributes = Analytical.Revit.Modify.DuplicateByType(document, name_Template, panelType, construction_New) as HostObjAttributes;
                    if (hostObjAttributes == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, string.Format("Skipped - Could not duplicate construction for panel ({2}). Element Type Name for: {0}, could not be assinged from {1}", name, name_Template, panel.PanelType));
                        continue;
                    }
                }

                Panel panel_New = new Panel(panel, construction_New);
                if (panel_New.PanelType != panelType)
                {
                    panel_New = new Panel(panel_New, panelType);
                }

                List <Aperture> apertures = panel_New.Apertures;
                if (apertures != null && apertures.Count != 0)
                {
                    foreach (Aperture aperture in apertures)
                    {
                        panel_New.RemoveAperture(aperture.Guid);

                        ApertureConstruction apertureConstruction = aperture?.ApertureConstruction;
                        if (apertureConstruction == null)
                        {
                            continue;
                        }

                        name = apertureConstruction.Name;
                        if (name == null)
                        {
                            continue;
                        }

                        name_Destination = null;
                        name_Template    = null;
                        name_Source      = null;
                        ApertureType apertureType = ApertureType.Undefined;
                        for (int i = 0; i < delimitedFileTable.RowCount; i++)
                        {
                            string typeName = null;
                            if (!delimitedFileTable.TryGetValue(i, index_Type, out typeName))
                            {
                                continue;
                            }

                            apertureType = Analytical.Query.ApertureType(typeName);
                            if (apertureType == ApertureType.Undefined)
                            {
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Source, out name_Source))
                            {
                                continue;
                            }

                            if (!name.Equals(name_Source))
                            {
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Destination, out name_Destination))
                            {
                                name_Destination = null;
                                continue;
                            }

                            if (!delimitedFileTable.TryGetValue(i, index_Template, out name_Template))
                            {
                                name_Template = null;
                            }

                            break;
                        }


                        if (string.IsNullOrWhiteSpace(name_Destination))
                        {
                            name_Destination = name_Template;
                        }

                        if (string.IsNullOrWhiteSpace(name_Destination))
                        {
                            continue;
                        }

                        if (apertureType == ApertureType.Undefined)
                        {
                            continue;
                        }

                        ApertureConstruction apertureConstruction_New = apertureConstructionLibrary_Result.GetApertureConstructions(name_Destination, Core.TextComparisonType.Equals, true, apertureType)?.FirstOrDefault();
                        if (apertureConstruction_New == null)
                        {
                            ApertureConstruction apertureConstruction_Temp = apertureConstructionLibrary.GetApertureConstructions(name_Template, Core.TextComparisonType.Equals, true, apertureType)?.FirstOrDefault();
                            if (apertureConstruction_Temp == null)
                            {
                                continue;
                            }

                            if (name_Destination.Equals(name_Template))
                            {
                                apertureConstruction_New = apertureConstruction_Temp;
                            }
                            else
                            {
                                apertureConstruction_New = new ApertureConstruction(apertureConstruction_Temp, name_Destination);
                            }

                            apertureConstruction_New.SetValue(ApertureConstructionParameter.Description, apertureConstruction.Name);

                            apertureConstructionLibrary_Result.Add(apertureConstruction_New);
                        }

                        FamilySymbol familySymbol = Analytical.Revit.Convert.ToRevit(apertureConstruction_New, document, convertSettings);
                        if (familySymbol == null)
                        {
                            if (string.IsNullOrWhiteSpace(name_Template))
                            {
                                ApertureConstruction apertureConstruction_Default = Analytical.Query.DefaultApertureConstruction(panelType, apertureType);
                                if (apertureConstruction_Default != null)
                                {
                                    name_Template = apertureConstruction_Default.Name;
                                }
                            }

                            if (string.IsNullOrWhiteSpace(name_Template))
                            {
                                continue;
                            }

                            familySymbol = Analytical.Revit.Modify.DuplicateByType(document, name_Template, apertureConstruction_New) as FamilySymbol;
                            if (familySymbol == null)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, string.Format("Skipped - Could not duplicate construction for panel ({2}). Element Type Name for: {0}, could not be assinged from {1}", name, name_Template, panel.PanelType));
                                continue;
                            }
                        }

                        Aperture aperture_New = new Aperture(aperture, apertureConstruction_New);
                        if (panel_New.AddAperture(aperture_New))
                        {
                            elementTypes_Apertures.Add(familySymbol);
                            apertures_Result.Add(aperture_New);
                        }
                    }
                }

                elementTypes_Panels.Add(hostObjAttributes);
                panels_Result.Add(panel_New);
            }

            dataAccess.SetDataList(0, elementTypes_Panels);
            dataAccess.SetDataList(1, elementTypes_Apertures);
            dataAccess.SetDataList(2, panels_Result.ConvertAll(x => new GooPanel(x)));
            dataAccess.SetDataList(3, apertures_Result.ConvertAll(x => new GooAperture(x)));
            dataAccess.SetData(4, new GooConstructionLibrary(constructionLibrary_Result));
            dataAccess.SetData(5, new GooApertureConstructionLibrary(apertureConstructionLibrary_Result));
        }
        public override void SolveInstance(IGH_DataAccess DA, out string msg, out GH_RuntimeMessageLevel level)
        {
            msg   = "";
            level = GH_RuntimeMessageLevel.Warning;

            var myFilter = new RFFilter();

            myFilter.Type = "Filter (Surface Supports)";
            var supList     = new List <string>();
            var commentList = new List <string>();
            var x           = new List <Interval>();
            var y           = new List <Interval>();
            var z           = new List <Interval>();
            var tx          = new List <Interval>();
            var ty          = new List <Interval>();
            var tz          = new List <Interval>();
            var vxz         = new List <Interval>();
            var vyz         = new List <Interval>();
            var ntz         = new List <string>();
            var srfcList    = new List <string>();

            if (DA.GetDataList(0, supList))
            {
                var sfcListAll = new List <int>();
                foreach (var no in supList)
                {
                    sfcListAll.AddRange(no.ToInt());
                }
                myFilter.SupSList = sfcListAll;
            }
            if (DA.GetDataList(1, commentList))
            {
                myFilter.SupSComment = commentList;
            }
            if (DA.GetDataList(2, x))
            {
                myFilter.SupSX = x;
            }
            if (DA.GetDataList(3, y))
            {
                myFilter.SupSY = y;
            }
            if (DA.GetDataList(4, z))
            {
                myFilter.SupSZ = z;
            }
            if (DA.GetDataList(5, srfcList))
            {
                var sfcListAll = new List <int>();
                foreach (var no in srfcList)
                {
                    sfcListAll.AddRange(no.ToInt());
                }
                myFilter.SupSrfcList = sfcListAll;
            }
            if (DA.GetDataList(6, tx))
            {
                myFilter.SupSTx = tx;
            }
            if (DA.GetDataList(7, ty))
            {
                myFilter.SupSTy = ty;
            }
            if (DA.GetDataList(8, tz))
            {
                myFilter.SupSTz = tz;
            }
            if (DA.GetDataList(9, vxz))
            {
                myFilter.SupSVxz = vxz;
            }
            if (DA.GetDataList(10, vyz))
            {
                myFilter.SupSVyz = vyz;
            }
            if (DA.GetDataList(11, ntz))
            {
                myFilter.SupSNTz = ntz;
            }
            DA.SetData(0, myFilter);
        }
Exemplo n.º 44
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Collect inputs
            SharpSLO.Types.Molecular molecular = null;
            SharpSLO.Types.Molecular pcl = null;
            List <Vector3d>          fixities = new List <Vector3d>();
            List <Vector3d>          forces = new List <Vector3d>();
            double limitT, limitC, jCost;

            limitT = limitC = jCost = double.NaN;
            bool reset = true;

            if (!DA.GetData(0, ref molecular))
            {
                return;
            }
            DA.GetData(1, ref pcl); // Optional
            if (!DA.GetDataList <Vector3d>(2, fixities))
            {
                return;
            }
            if (!DA.GetDataList <Vector3d>(3, forces))
            {
                return;
            }
            if (!DA.GetData <double>(4, ref limitT))
            {
                return;
            }
            if (!DA.GetData <double>(5, ref limitC))
            {
                return;
            }
            if (!DA.GetData <double>(6, ref jCost))
            {
                return;
            }
            if (!DA.GetData <bool>(7, ref reset))
            {
                return;
            }

            if (reset || m_triggerReset) // Rebuild model from external source
            {
                var copy = molecular.Duplicate();

                // Add boundary conditions
                for (int i = 0; i < molecular.Nodes.Count; i++)
                {
                    copy.Nodes[i].Fixity = new SharpSLO.Geometry.Vector(fixities[i].X, fixities[i].Y, fixities[i].Z);
                    copy.Nodes[i].Force  = new SharpSLO.Geometry.Vector(forces[i].X, forces[i].Y, forces[i].Z);
                }

                if (pcl == null)
                {
                    m_optimiser = new SharpSLO.Optimiser(copy, m_solType);
                }
                else
                {
                    var potentials = pcl.Bars.Select(b => new Tuple <int, int>(b.Start, b.End)).ToArray();
                    m_optimiser = new SharpSLO.Optimiser(copy, potentials, m_solType);
                }

                m_optimiser.TensileStressLimit     = limitT;
                m_optimiser.CompressiveStressLimit = limitC;
                m_optimiser.JointCost = jCost;

                if (m_output.Count > 0)
                {
                    m_output.Clear();
                }
                m_runtime      = 0.0;
                m_triggerReset = false;
            }

            // solve
            int members_added = m_optimiser.SolveStep();

            if (members_added < 0)
            {
                return;
            }

            if (members_added == 0)
            {
                this.StopTimer();                     // Disable timer if solution converges
            }
            m_output.Add(string.Format("{0,3:D}: vol.: {1,9:F6} add. :{2,4:D} ({3,2:F3}s)",
                                       m_output.Count, m_optimiser.Volume, members_added, m_optimiser.Runtime));

            m_runtime += m_optimiser.Runtime;

            // set outputs
            DA.SetDataList(0, m_output);
            DA.SetData(1, m_optimiser.Volume);
            DA.SetData(2, m_optimiser.GroundStructure);
        }
Exemplo n.º 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)
        {
            // Input variables
            GH_Controller controllerGoo = null;
            bool          connect       = false;
            bool          upload        = false;
            bool          run           = false;
            bool          stop          = false;
            List <string> programCode   = new List <string>();
            List <string> systemCode    = new List <string>();

            // Catch input data
            if (!DA.GetData(0, ref controllerGoo))
            {
                return;
            }
            if (!DA.GetData(1, ref connect))
            {
                return;
            }
            if (!DA.GetData(2, ref upload))
            {
                return;
            }
            if (!DA.GetData(3, ref run))
            {
                return;
            }
            if (!DA.GetData(4, ref stop))
            {
                return;
            }
            if (!DA.GetDataList(5, programCode))
            {
                programCode = new List <string>()
                {
                };
            }
            if (!DA.GetDataList(6, systemCode))
            {
                systemCode = new List <string>()
                {
                };
            }
            base.DestroyIconCache();

            // Get controller value
            _controller = controllerGoo.Value;

            // Connect
            if (connect)
            {
                // Setup the connection
                Connect();

                // Run the program when toggled
                if (run)
                {
                    Run();
                }

                // Stop the program when toggled
                if (stop)
                {
                    Stop();
                }

                // Upload the code when toggled
                if (upload)
                {
                    // Reset program pointer warning
                    _programPointerWarning = false;

                    // First stop the current program
                    Stop();

                    // Get path for temporary saving of the module files on the local harddrive of the user
                    // NOTE: This is not a path on the controller, but on the pc of the user
                    string localDirectory = Path.Combine(DocumentsFolderPath(), "RobotComponents", "temp");

                    // Check if the directory already exists
                    if (Directory.Exists(localDirectory))
                    {
                        // Delete if it already exists
                        Directory.Delete(localDirectory, true);
                    }

                    // Create new directory
                    Directory.CreateDirectory(localDirectory);

                    // Save the RAPID code to the created directory / local folder
                    SaveModulesToFile(localDirectory, programCode, systemCode);

                    // Directory to save the modules on the controller
                    string controllerDirectory = Path.Combine(_controller.FileSystem.RemoteDirectory, "RAPID");

                    // Module file paths
                    string filePathProgram;
                    string filePathSystem;
                    string directory;

                    // Upload to the real physical controller
                    if (_controller.IsVirtual == false)
                    {
                        _controller.AuthenticationSystem.DemandGrant(Grant.WriteFtp);
                        _controller.FileSystem.PutDirectory(localDirectory, "RAPID", true);
                        directory = controllerDirectory;
                    }
                    // Upload to a virtual controller
                    else
                    {
                        directory = localDirectory;
                    }

                    // The real upload
                    using (Mastership master = Mastership.Request(_controller))
                    {
                        // Get task
                        Task[] tasks = _controller.Rapid.GetTasks();
                        Task   task  = tasks[0];

                        // TODO: Make a pick task form? As for pick controller?
                        // TODO: This can be a solution for multi move with multiple tasks
                        // Task task = controller.Rapid.GetTask(tasks[0].Name) // Get task with specified name

                        // Grant acces
                        _controller.AuthenticationSystem.DemandGrant(Grant.LoadRapidProgram);

                        // Load the new program from the created file
                        for (int i = 0; i < systemCode.Count; i++)
                        {
                            filePathSystem = Path.Combine(directory, "SystemModule_" + i.ToString() + ".sys");
                            task.LoadModuleFromFile(filePathSystem, RapidLoadMode.Replace);
                        }
                        for (int i = 0; i < programCode.Count; i++)
                        {
                            filePathProgram = Path.Combine(directory, "ProgramModule_" + i.ToString() + ".mod");
                            task.LoadModuleFromFile(filePathProgram, RapidLoadMode.Replace);
                        }

                        // Resets the program pointer of this task to the main entry point.
                        if (_controller.OperatingMode == ControllerOperatingMode.Auto)
                        {
                            _controller.AuthenticationSystem.DemandGrant(Grant.ExecuteRapid);

                            try
                            {
                                task.ResetProgramPointer(); // Requires auto mode and execute rapid
                                _programPointerWarning = false;
                            }
                            catch
                            {
                                _programPointerWarning = true;
                            }
                        }

                        // Update action status message
                        if (programCode != null || systemCode != null)
                        {
                            _uStatus = "The RAPID code is succesfully uploaded.";
                        }
                        else
                        {
                            _uStatus = "The RAPID is not uploaded since there is no code defined.";
                        }

                        // Give back the mastership
                        master.Release();
                    }

                    // Delete the temporary files
                    if (Directory.Exists(localDirectory))
                    {
                        Directory.Delete(localDirectory, true);
                    }
                }
            }

            // Disconnect
            else
            {
                // Disconnect
                Disconnect();

                // Update the satus message when a command wants to be executed without having a connection.
                if (run || stop || upload)
                {
                    _uStatus = "Please connect first.";
                }
            }

            // Output message
            _msg = $"The remote connection status:\n\nController: {_cStatus}\nActions: {_uStatus}";

            if (_programPointerWarning == true)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The program pointer could not be reset. Check the program modules that are defined" +
                                  " in your controller. Probably you defined two main functions or there are other errors in your RAPID code.");
            }

            // Output
            DA.SetData(0, _msg);
        }
Exemplo n.º 46
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            int Res = -1;

            DA.GetData <int>("Resolution", ref Res);

            string folderPath = string.Empty;

            DA.GetData <string>("File Location", ref folderPath);
            if (!folderPath.EndsWith(@"\"))
            {
                folderPath = folderPath + @"\";
            }

            string prefix = "";

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

            string URL = "";

            DA.GetData <string>("REST URL", ref URL);

            bool run = false;

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

            string userSRStext = "";

            DA.GetData <string>("User Spatial Reference System", ref userSRStext);

            string imageType = "";

            DA.GetData <string>("Image Type", ref imageType);

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();

            ///TODO: implement SetCRS here.
            ///Option to set CRS here to user-defined.  Needs a SetCRS global variable.
            //string userSRStext = "EPSG:4326";

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput(userSRStext);
            int userSRSInt = Int16.Parse(userSRS.GetAuthorityCode(null));

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);


            GH_Structure <GH_String>    mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    mapquery = new GH_Structure <GH_String>();
            GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>();

            FileInfo file = new FileInfo(folderPath);

            file.Directory.Create();

            string size = "";

            if (Res != 0)
            {
                size = "&size=" + Res + "%2C" + Res;
            }

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                ///Get image frame for given boundary
                BoundingBox imageBox = boundary[i].GetBoundingBox(false);
                imageBox.Transform(modelToUserSRSTransform);

                ///Make sure to have a rect for output
                Rectangle3d rect = BBoxToRect(imageBox);

                ///Query the REST service
                string restquery = URL +
                                   ///legacy method for creating bounding box string
                                   "bbox=" + imageBox.Min.X + "%2C" + imageBox.Min.Y + "%2C" + imageBox.Max.X + "%2C" + imageBox.Max.Y +
                                   "&bboxSR=" + userSRSInt +
                                   size +                     //"&layers=&layerdefs=" +
                                   "&imageSR=" + userSRSInt + //"&transparent=false&dpi=&time=&layerTimeOptions=" +
                                   "&format=" + imageType +
                                   "&f=json";

                mapquery.Append(new GH_String(restquery), path);

                string result = "";

                if (run)
                {
                    ///get extent of image from arcgis rest service as JSON
                    result = Heron.Convert.HttpToJson(restquery);
                    JObject jObj   = JsonConvert.DeserializeObject <JObject>(result);
                    Point3d extMin = new Point3d((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0);
                    Point3d extMax = new Point3d((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0);
                    rect = new Rectangle3d(Plane.WorldXY, extMin, extMax);
                    rect.Transform(userSRSToModelTransform);

                    ///download image from source
                    string imageQuery = jObj["href"].ToString();
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.DownloadFile(imageQuery, folderPath + prefix + "_" + i + "." + imageType);
                    webClient.Dispose();
                }
                var bitmapPath = folderPath + prefix + "_" + i + "." + imageType;
                mapList.Append(new GH_String(bitmapPath), path);

                imgFrame.Append(new GH_Rectangle(rect), path);
                AddPreviewItem(bitmapPath, rect);
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, mapquery);
        }
Exemplo n.º 47
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 = -1;

            bool run = false;

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

            GH_ObjectWrapper objectWrapper = null;


            index = Params.IndexOfInputParam("revitLinkInstance_");
            if (index != -1)
            {
                dataAccess.GetData(index, ref objectWrapper);
            }

            Transform tranform = null;
            Document  document = null;

            if (objectWrapper != null && Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out RevitLinkInstance revitLinkInstance) && revitLinkInstance != null)
            {
                document = revitLinkInstance.GetLinkDocument();
                tranform = revitLinkInstance.GetTotalTransform();
            }
            else if (objectWrapper?.Value is RhinoInside.Revit.GH.Types.ProjectDocument)
            {
                document = ((RhinoInside.Revit.GH.Types.ProjectDocument)objectWrapper.Value).Value;
            }

            if (document == null)
            {
                document = RhinoInside.Revit.Revit.ActiveDBDocument;
            }

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            if (tranform == null)
            {
                tranform = Transform.Identity;
            }

            index = Params.IndexOfInputParam("_view");
            if (index == -1 || !dataAccess.GetData(index, ref objectWrapper) || objectWrapper.Value == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            IEnumerable <ElementId> elementIds = null;

            if (Core.Grasshopper.Revit.Query.TryGetElement(objectWrapper, out ViewPlan viewPlan))
            {
                Outline outline = Core.Revit.Query.Outline(viewPlan, tranform);
                if (outline != null)
                {
                    //LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new BoundingBoxIsInsideFilter(outline), new BoundingBoxIntersectsFilter(outline));
                    //elementIds = new FilteredElementCollector(document_Linked).WherePasses(logicalOrFilter)?.ToElementIds();

                    BoundingBoxIsInsideFilter boundingBoxIsInsideFilter = new BoundingBoxIsInsideFilter(outline, Core.Tolerance.MacroDistance);
                    elementIds = new FilteredElementCollector(document).WherePasses(boundingBoxIsInsideFilter).ToElementIds();
                }
            }

            if (elementIds == null || elementIds.Count() == 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            ConvertSettings convertSettings          = new ConvertSettings(true, true, true);
            IEnumerable <Core.ISAMObject> sAMObjects = null;

            List <Panel> panels = Analytical.Revit.Convert.ToSAM_Panels(document, elementIds, convertSettings);

            if (panels != null)
            {
                sAMObjects = panels.Cast <Core.ISAMObject>();
            }

            dataAccess.SetDataList(0, sAMObjects);
        }
Exemplo n.º 48
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Structure <GH_Point>   ptsTree  = new GH_Structure <GH_Point>();
            GH_Structure <GH_Vector>  velTree  = new GH_Structure <GH_Vector>();
            GH_Structure <GH_Number>  massTree = new GH_Structure <GH_Number>();
            GH_Structure <GH_Boolean> scTree   = new GH_Structure <GH_Boolean>();
            GH_Structure <GH_Boolean> ifTree   = new GH_Structure <GH_Boolean>();
            GH_Structure <GH_Integer> giTree   = new GH_Structure <GH_Integer>();

            DA.GetDataTree(0, out ptsTree);
            DA.GetDataTree(1, out velTree);
            DA.GetDataTree(2, out massTree);
            DA.GetDataTree(3, out scTree);
            DA.GetDataTree(4, out ifTree);
            DA.GetDataTree(5, out giTree);

            #region clean up etc
            if (!ptsTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }
            if (!velTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }
            if (!massTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }
            if (!scTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }
            if (!ifTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }
            if (!giTree.IsEmpty)
            {
                ptsTree.Simplify(GH_SimplificationMode.CollapseAllOverlaps);
            }

            if (ptsTree.Branches.Count == 1)
            {
                GH_Structure <GH_Point> pT = new GH_Structure <GH_Point>();
                pT.AppendRange(ptsTree.Branches[0], new GH_Path(0));
                ptsTree = pT;
            }
            if (velTree.Branches.Count == 1)
            {
                GH_Structure <GH_Vector> pT = new GH_Structure <GH_Vector>();
                pT.AppendRange(velTree.Branches[0], new GH_Path(0));
                velTree = pT;
            }
            if (massTree.Branches.Count == 1)
            {
                GH_Structure <GH_Number> mT = new GH_Structure <GH_Number>();
                mT.AppendRange(massTree.Branches[0], new GH_Path(0));
                massTree = mT;
            }
            if (scTree.Branches.Count == 1)
            {
                GH_Structure <GH_Boolean> mT = new GH_Structure <GH_Boolean>();
                mT.AppendRange(scTree.Branches[0], new GH_Path(0));
                scTree = mT;
            }
            if (ifTree.Branches.Count == 1)
            {
                GH_Structure <GH_Boolean> mT = new GH_Structure <GH_Boolean>();
                mT.AppendRange(ifTree.Branches[0], new GH_Path(0));
                ifTree = mT;
            }
            if (giTree.Branches.Count == 1)
            {
                GH_Structure <GH_Integer> mT = new GH_Structure <GH_Integer>();
                mT.AppendRange(giTree.Branches[0], new GH_Path(0));
                giTree = mT;
            }
            #endregion

            List <FlexParticle> parts = new List <FlexParticle>();

            for (int i = 0; i < ptsTree.PathCount; i++)
            {
                GH_Path path = new GH_Path(i);

                for (int j = 0; j < ptsTree.get_Branch(path).Count; j++)
                {
                    float[] pos = new float[3] {
                        (float)ptsTree.get_DataItem(path, j).Value.X, (float)ptsTree.get_DataItem(path, j).Value.Y, (float)ptsTree.get_DataItem(path, j).Value.Z
                    };

                    float[] vel = new float[3] {
                        0.0f, 0.0f, 0.0f
                    };
                    if (velTree.PathExists(path))
                    {
                        if (velTree.get_Branch(path).Count > j)
                        {
                            vel = new float[3] {
                                (float)velTree.get_DataItem(path, j).Value.X, (float)velTree.get_DataItem(path, j).Value.Y, (float)velTree.get_DataItem(path, j).Value.Z
                            }
                        }
                        ;
                        else
                        {
                            vel = new float[3] {
                                (float)velTree.get_DataItem(path, 0).Value.X, (float)velTree.get_DataItem(path, 0).Value.Y, (float)velTree.get_DataItem(path, 0).Value.Z
                            }
                        };
                    }

                    float iM = 1.0f;
                    if (massTree.PathExists(path))
                    {
                        if (massTree.get_Branch(path).Count > j)
                        {
                            iM = 1.0f / (float)massTree.get_DataItem(path, j).Value;
                        }
                        else
                        {
                            iM = 1.0f / (float)massTree.get_DataItem(path, 0).Value;
                        }
                    }

                    bool sc = false;
                    if (scTree.PathExists(path))
                    {
                        if (scTree.get_Branch(path).Count > j)
                        {
                            sc = scTree.get_DataItem(path, j).Value;
                        }
                        else
                        {
                            sc = scTree.get_DataItem(path, 0).Value;
                        }
                    }

                    bool isf = false;
                    if (ifTree.PathExists(path))
                    {
                        if (ifTree.get_Branch(path).Count > j)
                        {
                            isf = ifTree.get_DataItem(path, j).Value;
                        }
                        else
                        {
                            isf = ifTree.get_DataItem(path, 0).Value;
                        }
                    }

                    int gi = i;
                    if (giTree.PathExists(path))
                    {
                        if (giTree.get_Branch(path).Count > j)
                        {
                            gi = giTree.get_DataItem(path, j).Value;
                        }
                        else
                        {
                            gi = giTree.get_DataItem(path, 0).Value;
                        }
                    }

                    parts.Add(new FlexParticle(pos, vel, iM, sc, isf, gi, true));
                }
            }

            DA.SetDataList(0, parts);
        }
Exemplo n.º 49
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///////////////////////////////////////////////// INPUT ////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            List <Point3d> controlPoints = new List <Point3d>();
            List <double>  knotsCsi      = new List <double>();
            int            p             = 0;
            int            i             = 1;
            double         csi           = 0;
            List <double>  knotsEta      = new List <double>();
            int            q             = 0;
            int            j             = 1;
            double         eta           = 0;

            if (!DA.GetDataList(0, controlPoints))
            {
                return;
            }
            if (!DA.GetDataList(1, knotsCsi))
            {
                return;
            }
            if (!DA.GetData(2, ref p))
            {
                return;
            }
            if (!DA.GetData(3, ref i))
            {
                return;
            }
            if (!DA.GetData(4, ref csi))
            {
                return;
            }
            if (!DA.GetDataList(5, knotsEta))
            {
                return;
            }
            if (!DA.GetData(6, ref q))
            {
                return;
            }
            if (!DA.GetData(7, ref j))
            {
                return;
            }
            if (!DA.GetData(8, ref eta))
            {
                return;
            }

            int n = knotsCsi.Count - p - 1;
            int m = knotsEta.Count - q - 1;

            if (i > n)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Index 1 can not be greater than or equal to the number of knots minus the degree");
                return;
            }
            if (j > m)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Index 2 can not be greater than or equal to the number of knots minus the degree");
                return;
            }
            if (n * m != controlPoints.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Number of control points does not match the number of basis function for the given degrees");
                return;
            }

            /////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            List <List <Point3d> > B = CreateControlPointList(controlPoints, n, m);
            Point3d        point     = CreatePoint(n, m, p, q, B, knotsCsi, knotsEta, csi, eta);
            List <Point3d> dPoint    = CreateDerivativePoint(n, m, p, q, B, knotsCsi, knotsEta, csi, eta);
            double         N         = BasisFunction(knotsCsi, i - 1, p, csi);
            double         dN_dCsi   = DerivativeBasisFunction(knotsCsi, i - 1, p, csi);
            double         M         = BasisFunction(knotsEta, j - 1, q, eta);
            double         dM_dEta   = DerivativeBasisFunction(knotsEta, j - 1, q, eta);

            //////////////////////////////////////////////// OUTPUT ////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////////////

            DA.SetData(0, point);
            DA.SetData(1, dPoint[0]);
            DA.SetData(2, dPoint[1]);
            DA.SetData(3, N);
            DA.SetData(4, dN_dCsi);
            DA.SetData(5, M);
            DA.SetData(6, dM_dEta);
        }
        //protected override void ExpireDownStreamObjects()
        //{
        //    if (_updateOutputs)
        //    {
        //        for (int i = 0; i < Params.Output.Count; i++)
        //        {
        //            Params.Output[i].ExpireSolution(false);
        //        }
        //    }
        //}

        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // This stops the component from assigning nulls
            // if we don't assign anything to an output.
            DA.DisableGapLogic();

            string msg = null;

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

            // Some sanity: users sometimes connect the Bridge from `Connect` to this input,
            // rather than the message coming out of `Listen`. Display alert.
            if (msg.Equals("MachinaGrasshopper.Utils.MachinaBridgeSocket"))
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component requires a \"Msg\" from the \"Listen\" component as input");
                return;
            }



            // TEMPORARILY DEACTIVATED GATED OUTPUT, wasn't working well

            //// Output the values precomputed in the last solution.
            //DA.SetData(0, _instruction);
            //DA.SetData(1, _tcp);
            //DA.SetDataList(2, _axes);
            //DA.SetDataList(3, _externalAxes);

            //// If on second solution, stop checking.
            //if (_updateOutputs)
            //{
            //    _updateOutputs = false;
            //    return;
            //}

            //// Otherwise, search for updated values (only if new messages have been received
            //// by the Listener), and schedule a new solution if they are new.
            //bool rescheduleRightAway = ReceivedNewMessage(msg);

            //// If new data came in, schedule a new solution immediately and flag outputs to expire.
            //if (rescheduleRightAway)
            //{
            //    _updateOutputs = true;

            //    this.OnPingDocument().ScheduleSolution(5, doc =>
            //    {
            //        this.ExpireSolution(false);
            //    });
            //}

            // NO GATED UPDATES
            // Parse message
            bool valid = ReceivedNewMessage(msg);

            // Output the parsed values.
            if (valid)
            {
                DA.SetData(0, _instruction);
                DA.SetData(1, _tcp);
                DA.SetDataList(2, _axes);
                DA.SetDataList(3, _externalAxes);
            }
        }
Exemplo n.º 51
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            bool               go    = false;
            List <WR_Node3d>   nodes = new List <WR_Node3d>();
            List <WR_IElemRcp> beams = new List <WR_IElemRcp>();

            if (!DA.GetDataList(0, nodes))
            {
                return;
            }
            if (!DA.GetDataList(1, beams))
            {
                return;
            }
            if (!DA.GetData(2, ref go))
            {
                return;
            }

            if (go)
            {
                resElems = new List <ResultElement>();

                log.Clear();
                log.Add("Structure invokation started");

                // Create structure wrapper
                WR_Structure structure = new WR_Structure();

                // Add restraint nodes
                foreach (WR_Node3d n in nodes)
                {
                    structure.AddNode(n);
                }
                log.Add("" + nodes.Count + " nodes added to structure");

                // Add elements
                foreach (WR_Elem3dRcp e in beams)
                {
                    structure.AddElementRcp(e);
                }
                log.Add("" + beams.Count + " elements added to structure");

                // Add forces

                // Solve
                WR_LinearSolver solver = new WR_LinearSolver(structure, true);
                solver.Solve();

                // 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);
                    }
                }

                //Extract Points
                pts = new List <Rhino.Geometry.Point3d>();
                List <WR_XYZ> xyzs = structure.GetAllPoints();

                for (int i = 0; i < xyzs.Count; i++)
                {
                    pts.Add(new Rhino.Geometry.Point3d(xyzs[i].X, xyzs[i].Y, xyzs[i].Z));
                }
            }

            DA.SetData(0, log);
            DA.SetDataList(1, resElems);
            DA.SetDataList(2, pts);
        }
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Get inputs.
            Connection connect = null;

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

            // Expire Solution.
            if (connect.status)
            {
                GH_Document document = this.OnPingDocument();
                if (document != null)
                {
                    document.ScheduleSolution(UIReceiver.expireDelay, ScheduleCallback);
                }
            }
        }
Exemplo n.º 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)
        {
            List <Curve>   interiorPartitions = new List <Curve>();
            List <Point3d> exitPts            = new List <Point3d>();
            Plane          plane = Plane.Unset;

            try
            {
                if (InPreSolve)
                {
                    rectangles         = new List <Rectangle3d>();
                    interiorPartitions = new List <Curve>();

                    DA.GetData(IN_AutoColor, ref autoColor);
                    DA.GetData(IN_plane, ref plane);
                    if (!DA.GetDataList(IN_rects, rectangles))
                    {
                        return;
                    }
                    DA.GetDataList(IN_partitions, interiorPartitions);
                    if (!DA.GetDataList(IN_exitPts, exitPts))
                    {
                        return;
                    }

                    if (interiorPartitions.Count == 0 || interiorPartitions == null)
                    {
                        _plan = new SmartPlan(rectangles, exitPts, plane);
                    }
                    else
                    {
                        _plan = new SmartPlan(rectangles, interiorPartitions, exitPts, plane);
                    }

                    if (rectangles.Count * exitPts.Count > 10000)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Try either increasing the voxel resoultion or reducing the amount of exit points.. Currently" +
                                          "the computation is too large.");
                        return;
                    }



                    Task <SolveResults> task = Task.Run(() => ComputeExit(_plan), CancelToken);
                    TaskList.Add(task);
                    return;
                }

                if (!GetSolveResults(DA, out SolveResults result))
                {
                    rectangles         = new List <Rectangle3d>();
                    interiorPartitions = new List <Curve>();

                    DA.GetData(IN_AutoColor, ref autoColor);
                    DA.GetData(IN_plane, ref plane);
                    DA.GetDataList(IN_rects, rectangles);
                    DA.GetDataList(IN_partitions, interiorPartitions);
                    DA.GetDataList(IN_exitPts, exitPts);

                    if (interiorPartitions.Count == 0 || interiorPartitions == null)
                    {
                        _plan = new SmartPlan(rectangles, exitPts, plane);
                    }
                    else
                    {
                        _plan = new SmartPlan(rectangles, interiorPartitions, exitPts, plane);
                    }

                    if (rectangles.Count * exitPts.Count > 10000)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Try either increasing the voxel resoultion or reducing the amount of exit points.. Currently" +
                                          "the computation is too large.");
                        return;
                    }

                    result = ComputeExit(_plan);
                    _plan  = result.Value;
                }

                if (result != null)
                {
                    _exitMetric = _plan.getExitMetric();
                    DA.SetDataList(OUT_pathMetric, _exitMetric);
                    DA.SetDataTree(OUT_paths, _plan.pathCurves);
                }
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.ToString());
            }
        }
Exemplo n.º 54
0
        protected override void SetOutputs(IGH_DataAccess da)
        {
            AbstractFoodType food = new PointFoodType(pts);

            da.SetData(nextOutputIndex++, food);
        }
Exemplo n.º 55
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            int Res = -1;

            DA.GetData <int>("Resolution", ref Res);

            string fileloc = "";

            DA.GetData <string>("File Location", ref fileloc);
            if (!fileloc.EndsWith(@"\"))
            {
                fileloc = fileloc + @"\";
            }

            string prefix = "";

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

            string URL = "";

            DA.GetData <string>("REST URL", ref URL);

            bool run = false;

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

            string userSRStext = "";

            DA.GetData <string>("User Spatial Reference System", ref userSRStext);

            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();

            ///TODO: implement SetCRS here.
            ///Option to set CRS here to user-defined.  Needs a SetCRS global variable.
            //string userSRStext = "EPSG:4326";

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput(userSRStext);
            int userSRSInt = Int16.Parse(userSRS.GetAuthorityCode(null));

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);

            OSGeo.OSR.CoordinateTransformation coordTransformRhinoToUser = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS);
            OSGeo.OSR.CoordinateTransformation coordTransformUserToRhino = new OSGeo.OSR.CoordinateTransformation(userSRS, rhinoSRS);


            GH_Structure <GH_String>    mapList  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    mapquery = new GH_Structure <GH_String>();
            GH_Structure <GH_Rectangle> imgFrame = new GH_Structure <GH_Rectangle>();

            FileInfo file = new FileInfo(fileloc);

            file.Directory.Create();

            string size = "";

            if (Res != 0)
            {
                size = "&size=" + Res + "%2C" + Res;
            }

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                //Get image frame for given boundary
                BoundingBox imageBox = boundary[i].GetBoundingBox(false);

                Point3d     min  = Heron.Convert.XYZToWGS(imageBox.Min);
                Point3d     max  = Heron.Convert.XYZToWGS(imageBox.Max);
                Rectangle3d rect = BBoxToRect(imageBox);

                ///ogr method
                OSGeo.OGR.Geometry minOgr = Heron.Convert.Point3dToOgrPoint(min);
                minOgr.Transform(coordTransformRhinoToUser);

                OSGeo.OGR.Geometry maxOgr = Heron.Convert.Point3dToOgrPoint(max);
                maxOgr.Transform(coordTransformRhinoToUser);

                //Query the REST service
                string restquery = URL +
                                   ///legacy method for creating bounding box string
                                   //"bbox=" + Heron.Convert.ConvertLat(min.X, 3857) + "%2C" + Heron.Convert.ConvertLon(min.Y, 3857) + "%2C" + Heron.Convert.ConvertLat(max.X, 3857) + "%2C" + Heron.Convert.ConvertLon(max.Y, 3857) +

                                   ///ogr method for creating bounding box string
                                   "bbox=" + minOgr.GetX(0) + "%2C" + minOgr.GetY(0) + "%2C" + maxOgr.GetX(0) + "%2C" + maxOgr.GetY(0) +

                                   "&bboxSR=" + userSRSInt +
                                   size +                     //"&layers=&layerdefs=" +
                                   "&imageSR=" + userSRSInt + //"&transparent=false&dpi=&time=&layerTimeOptions=" +
                                   "&format=jpg&f=json";

                mapquery.Append(new GH_String(restquery), path);

                string result = "";

                if (run)
                {
                    ///get extent of image from arcgis rest service as JSON
                    result = Heron.Convert.HttpToJson(restquery);
                    JObject jObj   = JsonConvert.DeserializeObject <JObject>(result);
                    Point3d extMin = new Point3d((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0);
                    Point3d extMax = new Point3d((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0);

                    ///convert and transform extents to points
                    OSGeo.OGR.Geometry extOgrMin = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPointZM);
                    extOgrMin.AddPoint((double)jObj["extent"]["xmin"], (double)jObj["extent"]["ymin"], 0.0);
                    extOgrMin.Transform(coordTransformUserToRhino);
                    Point3d ogrPtMin = Heron.Convert.OgrPointToPoint3d(extOgrMin);

                    OSGeo.OGR.Geometry extOgrMax = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPointZM);
                    extOgrMax.AddPoint((double)jObj["extent"]["xmax"], (double)jObj["extent"]["ymax"], 0.0);
                    extOgrMax.Transform(coordTransformUserToRhino);
                    Point3d ogrPtMax = Heron.Convert.OgrPointToPoint3d(extOgrMax);

                    ///if SRS is geographic (ie WGS84) use Rhino's internal projection
                    ///this is still buggy as it doesn't work with other geographic systems like NAD27
                    if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
                    {
                        rect = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(extMin), Heron.Convert.WGSToXYZ(extMax));
                    }
                    else
                    {
                        //rect = new Rectangle3d(Plane.WorldXY, Heron.Convert.UserSRSToXYZ(extMin, userSRSToModel), Heron.Convert.UserSRSToXYZ(extMax, userSRSToModel));
                        rect = new Rectangle3d(Plane.WorldXY, userSRSToModelTransform * extMin, userSRSToModelTransform * extMax);
                    }


                    ///download image from source
                    string imageQuery = jObj["href"].ToString();
                    System.Net.WebClient webClient = new System.Net.WebClient();
                    webClient.DownloadFile(imageQuery, fileloc + prefix + "_" + i + ".jpg");
                    webClient.Dispose();
                }
                var bitmapPath = fileloc + prefix + "_" + i + ".jpg";
                mapList.Append(new GH_String(bitmapPath), path);

                imgFrame.Append(new GH_Rectangle(rect), path);
                AddPreviewItem(bitmapPath, rect);
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, mapquery);
        }
Exemplo n.º 56
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Rhino.Geometry.Mesh> meshes = new List <Rhino.Geometry.Mesh>();
            List <string>   names             = new List <string>();
            MaterialWrapper material          = null;

            if (!DA.GetDataList(0, meshes))
            {
                return;
            }
            if (!DA.GetDataList(1, names))
            {
                return;
            }
            DA.GetData(2, ref material);

            List <dynamic> bufferGeometries = new List <dynamic>();
            List <dynamic> children         = new List <dynamic>();

            int counter = 0;

            foreach (Rhino.Geometry.Mesh mesh in meshes)
            {
                dynamic attributes = new ExpandoObject();
                dynamic position   = new ExpandoObject();
                dynamic normal     = new ExpandoObject();
                dynamic uv         = new ExpandoObject();
                dynamic index      = new ExpandoObject();

                Guid guid = Guid.NewGuid();

                List <double> vertices = new List <double>();
                for (int i = 0; i < mesh.Vertices.Count; i++)
                {
                    vertices.Add(Math.Round(mesh.Vertices[i].X, 3) * -1);
                    vertices.Add(Math.Round(mesh.Vertices[i].Z, 3));
                    vertices.Add(Math.Round(mesh.Vertices[i].Y, 3));
                }

                List <double> normals = new List <double>();
                for (int i = 0; i < mesh.Normals.Count; i++)
                {
                    normals.Add(Math.Round(mesh.Normals[i].X, 3) * -1);
                    normals.Add(Math.Round(mesh.Normals[i].Z, 3));
                    normals.Add(Math.Round(mesh.Normals[i].Y, 3));
                }

                List <double> uvs = new List <double>();
                for (int i = 0; i < mesh.TextureCoordinates.Count; i++)
                {
                    uvs.Add(Math.Round(mesh.TextureCoordinates[i].X, 3));
                    uvs.Add(Math.Round(mesh.TextureCoordinates[i].Y, 3));
                }

                position.itemSize   = 3;
                position.type       = "Float32Array";
                position.array      = vertices;
                position.normalized = false;

                normal.itemSize   = 3;
                normal.type       = "Float32Array";
                normal.array      = normals;
                normal.normalized = false;

                uv.itemSize   = 2;
                uv.type       = "Float32Array";
                uv.array      = uvs;
                uv.normalized = false;

                attributes.position = position;
                attributes.normal   = normal;
                attributes.uv       = uv;

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

                for (int i = 0; i < mesh.Faces.Count; i++)
                {
                    faces.Add(mesh.Faces.GetFace(i).A);
                    faces.Add(mesh.Faces.GetFace(i).B);
                    faces.Add(mesh.Faces.GetFace(i).C);
                }

                index.type  = "Uint32Array";
                index.array = faces;

                dynamic data = new ExpandoObject();
                data.attributes = attributes;
                data.index      = index;

                /// Add the bufferGeometry
                dynamic bufferGeometry = new ExpandoObject();
                bufferGeometry.uuid = guid;
                bufferGeometry.type = "BufferGeometry";
                bufferGeometry.data = data;

                bufferGeometries.Add(bufferGeometry);

                /// Add the child
                dynamic child = new ExpandoObject();
                child.uuid = Guid.NewGuid();

                if (names.Count == 0)
                {
                    child.name = "";
                }
                else if (names.Count == 1)
                {
                    child.name = names[0];
                }
                else
                {
                    child.name = names[counter];
                }

                child.type     = "Mesh";
                child.geometry = guid;
                child.material = material.Material.uuid;
                child.matrix   = new List <double> {
                    1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1
                };
                child.castShadow    = true;
                child.receiveShadow = true;

                children.Add(child);

                counter += 1;
            }

            List <dynamic> materials = new List <dynamic>();

            materials.Add(material.Material);

            /// Wrap the bufferGeometries and children to the wrapper
            MeshWrapper wrapper = new MeshWrapper(bufferGeometries, children, material.Material);

            string JSON = JsonConvert.SerializeObject(wrapper);

            DA.SetData(0, JSON);
            DA.SetData(1, wrapper);
        }
Exemplo n.º 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)
        {
            List <Plane>  TarPls    = new List <Plane>();
            List <double> RobotData = new List <double>();
            Point3d       tool      = Point3d.Origin;


            if (!DA.GetDataList(0, TarPls))
            {
                return;
            }
            if (!DA.GetDataList(1, RobotData))
            {
                return;
            }
            if (!DA.GetData(2, ref tool))
            {
                return;
            }

            double a2z = RobotData[0];
            double a2x = RobotData[1];
            double d23 = RobotData[2];
            double d34 = RobotData[3];
            double d45 = RobotData[4];
            double d56 = RobotData[5];

            double d35 = Math.Pow(d34 * d34 + d45 * d45, 0.5);
            double da  = 180 * Math.Atan(d34 / d45) / Math.PI;

            double Tx = tool.X;
            double Ty = 0;
            double Tz = tool.Z;

            double Axis1 = 0;
            double Axis2 = 0;
            double Axis3 = 0;
            double Axis4 = 0;
            double Axis5 = 0;
            double Axis6 = 0;

            List <double[]> AllAxises    = new List <double[]>();
            List <double>   AllAxiesFlat = new List <double>();


            for (int i = 0; i < TarPls.Count; i++)
            {
                Plane    pl    = TarPls[i];
                Point3d  pltar = pl.Origin;
                Vector3d plf   = pl.Normal;
                plf.Unitize();
                Vector3d toolf      = new Vector3d(-plf.X * Tx, -plf.Y * Tx, -plf.Z * Tx);
                Point3d  toolOrigin = Point3d.Add(pltar, toolf);

                double px = toolOrigin.X;
                double py = toolOrigin.Y;
                double pz = toolOrigin.Z;

                Axis1 = (180 * Math.Atan(py / px) / Math.PI);

                Plane   armpl   = new Plane(py, -px, 0, 0);
                Point3d proTool = armpl.ClosestPoint(pltar);
                double  refDis  = armpl.DistanceTo(pltar);
                Axis6 = -180 * Math.Asin(refDis / Tx) / Math.PI;


                Plane    Falan   = new Plane(pltar, proTool, toolOrigin);
                Vector3d a5a6vec = Falan.Normal;
                a5a6vec.Unitize();
                Vector3d a5tool = Vector3d.Multiply(d56 + Tz, a5a6vec);
                if (Axis6 < 0)
                {
                    a5tool.Reverse();
                }
                double a5World = 180 * Vector3d.VectorAngle(a5tool, Vector3d.ZAxis) / Math.PI;
                if (a5tool.X > 0)
                {
                    a5World = -a5World;
                }



                Point3d a5Real = Point3d.Add(toolOrigin, a5tool);


                double CalHorizontalLength = Math.Pow((a5Real.X * a5Real.X) + (a5Real.Y * a5Real.Y), 0.5) - a2x;
                double CalVerticalLength   = a5Real.Z - a2z;
                double SumLength           = Math.Pow((CalHorizontalLength * CalHorizontalLength + CalVerticalLength * CalVerticalLength), 0.5);

                double cosA2i = (d23 * d23 + SumLength * SumLength - d35 * d35) / (2 * d23 * SumLength);
                double A2i    = Math.Acos(cosA2i);
                double cosA2j = CalHorizontalLength / SumLength;
                double A2j    = Math.Acos(cosA2j);
                if (CalVerticalLength < 0)
                {
                    A2j = -A2j;
                }

                Axis2 = 180 * -(A2i + A2j) / Math.PI;

                double cosA3i = (d23 * d23 + d35 * d35 - SumLength * SumLength) / (2 * d23 * d35);
                double A3i    = Math.Acos(cosA3i);

                Axis3 = 180 * (Math.PI - A3i) / Math.PI;

                Axis4 = 0;

                Axis3 = Axis3 + da;
                Axis5 = (0 - Axis3 - Axis2) + (90 - a5World);

                Axis1 = -Math.Round(Axis1, 3);
                Axis2 = Math.Round(Axis2, 3);
                Axis3 = Math.Round(Axis3, 3);
                Axis4 = -Math.Round(Axis4, 3);
                Axis5 = Math.Round(Axis5, 3);
                Axis6 = -Math.Round(Axis6, 3);

                double[] Axises = new double[6];
                Axises[0] = Axis1;
                Axises[1] = Axis2;
                Axises[2] = Axis3;
                Axises[3] = Axis4;
                Axises[4] = Axis5;
                Axises[5] = Axis6;
                AllAxises.Add(Axises);
                for (int k = 0; k < 6; k++)
                {
                    AllAxiesFlat.Add(Axises[k]);
                }
            }


            DA.SetDataList(0, AllAxiesFlat);
        }
Exemplo n.º 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)
        {
            List <string> layer = new List <string>(); string name_mat = "mat"; string name_sec = "sec"; string name_angle = "angle"; string name_joint = "joint"; string name_lby = "lby"; string name_lbz = "lbz"; string name_bar = "bar"; string name_ele_wx = "ele_wx"; string name_ele_wy = "ele_wy"; string name_ele_wz = "ele_wz"; List <string> on_off = new List <string>(); string name_x = "wickX"; string name_y = "wickY"; List <string> on_off2 = new List <string>();

            DA.GetDataList("layer(all)", layer); DA.GetData("name mat", ref name_mat); DA.GetData("name sec", ref name_sec); DA.GetData("name angle", ref name_angle); DA.GetData("name joint", ref name_joint); DA.GetData("name lby", ref name_lby); DA.GetData("name lbz", ref name_lbz); DA.GetData("name bar", ref name_bar); DA.GetData("name ele_wx", ref name_ele_wx); DA.GetData("name ele_wy", ref name_ele_wy); DA.GetData("name ele_wz", ref name_ele_wz);
            DA.GetData("name wick1", ref name_x); DA.GetData("name wick2", ref name_y); DA.GetDataList("on_off", on_off); DA.GetDataList("on_off(wick)", on_off2);
            List <Curve>  lines = new List <Curve>(); List <int> mat = new List <int>(); List <int> sec = new List <int>(); List <double> angle = new List <double>();
            List <double> lby = new List <double>(); List <double> lbz = new List <double>(); List <double> bar = new List <double>(); GH_Structure <GH_Number> joint = new GH_Structure <GH_Number>(); GH_Structure <GH_Number> e_load = new GH_Structure <GH_Number>(); List <int> index = new List <int>();
            var           names = new GH_Structure <GH_String>();
            var           doc = RhinoDoc.ActiveDoc; int e = 0; int k = 0; int kk = 0;
            var           rigid = 1e+12; var pin = 0.001;//joint stiffness

            if (on_off[0] == "")
            {
                on_off = layer;
            }
            for (int i = 0; i < layer.Count; i++)
            {
                var line = doc.Objects.FindByLayer(layer[i]);
                for (int j = 0; j < line.Length; j++)
                {
                    var obj = line[j];
                    var l = (new ObjRef(obj)).Curve(); lines.Add(l);  var length = l.GetLength();
                    var text = obj.Attributes.GetUserString(name_mat);//材料情報
                    if (text == null)
                    {
                        mat.Add(0);
                    }
                    else
                    {
                        mat.Add(int.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_sec);//断面情報
                    if (text == null)
                    {
                        sec.Add(0);
                    }
                    else
                    {
                        sec.Add(int.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_angle);//コードアングル情報
                    if (text == null)
                    {
                        angle.Add(0.0);
                    }
                    else
                    {
                        angle.Add(float.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_lby);//部材y軸方向座屈長さ情報
                    if (text == null)
                    {
                        lby.Add(length);
                    }
                    else
                    {
                        lby.Add(float.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_lbz);//部材z軸方向座屈長さ情報
                    if (text == null)
                    {
                        lbz.Add(length);
                    }
                    else
                    {
                        lbz.Add(float.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_bar);//配筋情報
                    if (text == null)
                    {
                        bar.Add(0);
                    }
                    else
                    {
                        bar.Add(int.Parse(text));
                    }
                    text = obj.Attributes.GetUserString(name_joint);//材端ピン情報
                    if (text != null)
                    {
                        List <GH_Number> jlist = new List <GH_Number>();
                        jlist.Add(new GH_Number(e)); jlist.Add(new GH_Number(int.Parse(text)));
                        jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(rigid));
                        jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(pin)); jlist.Add(new GH_Number(pin));
                        jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(rigid));
                        jlist.Add(new GH_Number(rigid)); jlist.Add(new GH_Number(pin)); jlist.Add(new GH_Number(pin));
                        joint.AppendRange(jlist, new GH_Path(k));
                        k += 1;
                    }
                    var t1 = obj.Attributes.GetUserString(name_ele_wx); var t2 = obj.Attributes.GetUserString(name_ele_wy); var t3 = obj.Attributes.GetUserString(name_ele_wz);//分布荷重
                    if (t1 != null || t2 != null || t3 != null)
                    {
                        var wx = 0.0; var wy = 0.0; var wz = 0.0;
                        if (t1 != null)
                        {
                            wx = float.Parse(t1);
                        }
                        if (t2 != null)
                        {
                            wy = float.Parse(t2);
                        }
                        if (t3 != null)
                        {
                            wz = float.Parse(t3);
                        }
                        List <GH_Number> flist = new List <GH_Number>();
                        flist.Add(new GH_Number(e)); flist.Add(new GH_Number(wx)); flist.Add(new GH_Number(wy)); flist.Add(new GH_Number(wz));
                        e_load.AppendRange(flist, new GH_Path(kk));
                        kk += 1;
                    }
                    string text1 = obj.Attributes.GetUserString(name_x); string text2 = obj.Attributes.GetUserString(name_y);//軸ラベル
                    if (on_off.Contains(layer[i]) == true)
                    {
                        if (on_off2[0] != "")
                        {
                            if (on_off2.Contains(text1) == true || on_off2.Contains(text2) == true)
                            {
                                index.Add(e);//指定軸が含まれていればindexを格納
                            }
                        }
                        else
                        {
                            index.Add(e);
                        }
                    }
                    var namelist = new List <GH_String>(); namelist.Add(new GH_String(layer[i]));
                    if (text1 != null)
                    {
                        namelist.Add(new GH_String(text1));
                    }
                    if (text2 != null)
                    {
                        namelist.Add(new GH_String(text2));
                    }
                    names.AppendRange(namelist, new GH_Path(e));
                    e += 1;
                }
            }
            if (on_off[0] == "" && on_off2[0] == "")
            {
                index.Add(-9999);
            }
            else if (index.Count == 0)
            {
                index.Add(9999);
            }
            DA.SetDataList("beam", lines);
            DA.SetDataList("mat", mat);
            DA.SetDataList("sec", sec);
            DA.SetDataList("angle", angle);
            DA.SetDataTree(4, joint);
            DA.SetDataList("Lby", lby);
            DA.SetDataList("Lbz", lbz);
            DA.SetDataList("bar", bar);
            DA.SetDataTree(8, e_load);
            DA.SetDataList("index", index);
            DA.SetDataTree(10, names);
        }
Exemplo n.º 59
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 (Controller != null)
            {
                List <bool>   buttons         = new List <bool>();
                List <double> thumbsttriggers = new List <double>();
                Vector3d      lt = new Vector3d(Controller.ThumbLeftX, Controller.ThumbLeftY, 0);
                Vector3d      rt = new Vector3d(Controller.ThumbRightX, Controller.ThumbRightY, 0);

                int    refreshInt = 0;
                double leftVib    = 0.0;
                double rightVib   = 0.0;
                double sdzCent    = 10.0;
                double sdzThr     = 10.0;
                double ltThr      = 10.0;
                double rtThr      = 10.0;

                if (!(DA.GetData(0, ref refreshInt)))
                {
                    return;
                }
                if (!(DA.GetData(1, ref leftVib)))
                {
                    return;
                }
                if (!(DA.GetData(2, ref rightVib)))
                {
                    return;
                }
                if (!(DA.GetData(3, ref sdzCent)))
                {
                    return;
                }
                if (!(DA.GetData(4, ref sdzThr)))
                {
                    return;
                }
                if (!(DA.GetData(5, ref ltThr)))
                {
                    return;
                }
                if (!(DA.GetData(6, ref rtThr)))
                {
                    return;
                }

                Controller.RefreshIntervalMilliseconds = refreshInt;
                Controller.SetLeftMotorVibrationSpeed(leftVib);
                Controller.SetRightMotorVibrationSpeed(rightVib);
                Controller.SnapDeadZoneCenter         = sdzCent;
                Controller.SnapDeadZoneTolerance      = sdzThr;
                Controller.TriggerLeftPressThreshold  = ltThr;
                Controller.TriggerRightPressThreshold = rtThr;

                DA.SetData(0, Controller.ButtonAPressed);
                buttons.Add(Controller.ButtonAPressed);
                DA.SetData(1, Controller.ButtonBPressed);
                buttons.Add(Controller.ButtonBPressed);
                DA.SetData(2, Controller.ButtonXPressed);
                buttons.Add(Controller.ButtonXPressed);
                DA.SetData(3, Controller.ButtonYPressed);
                buttons.Add(Controller.ButtonXPressed);
                DA.SetData(4, Controller.ButtonShoulderLeftPressed);
                buttons.Add(Controller.ButtonShoulderLeftPressed);
                DA.SetData(5, Controller.ButtonShoulderRightPressed);
                buttons.Add(Controller.ButtonShoulderRightPressed);
                DA.SetData(6, Controller.ButtonUpPressed);
                buttons.Add(Controller.ButtonUpPressed);
                DA.SetData(7, Controller.ButtonDownPressed);
                buttons.Add(Controller.ButtonDownPressed);
                DA.SetData(8, Controller.ButtonLeftPressed);
                buttons.Add(Controller.ButtonLeftPressed);
                DA.SetData(9, Controller.ButtonRightPressed);
                buttons.Add(Controller.ButtonRightPressed);
                DA.SetData(10, Controller.ButtonStartPressed);
                buttons.Add(Controller.ButtonStartPressed);
                DA.SetData(11, Controller.ButtonBackPressed);
                buttons.Add(Controller.ButtonBackPressed);
                DA.SetData(12, Controller.TriggerLeftPressed);
                buttons.Add(Controller.TriggerLeftPressed);
                DA.SetData(13, Controller.TriggerRightPressed);
                buttons.Add(Controller.TriggerRightPressed);
                DA.SetData(14, Controller.ThumbpadLeftPressed);
                buttons.Add(Controller.ThumbpadLeftPressed);
                DA.SetData(15, Controller.ThumbpadRightPressed);
                buttons.Add(Controller.ThumbpadRightPressed);
                DA.SetData(16, Controller.ThumbLeftX);
                thumbsttriggers.Add(Controller.ThumbLeftX);
                DA.SetData(17, Controller.ThumbLeftY);
                thumbsttriggers.Add(Controller.ThumbLeftY);
                DA.SetData(18, Controller.ThumbRightX);
                thumbsttriggers.Add(Controller.ThumbRightX);
                DA.SetData(19, Controller.ThumbRightY);
                thumbsttriggers.Add(Controller.ThumbRightY);
                DA.SetData(20, Controller.TriggerLeftPosition);
                thumbsttriggers.Add(Controller.TriggerLeftPosition);
                DA.SetData(21, Controller.TriggerRightPosition);
                thumbsttriggers.Add(Controller.TriggerRightPosition);
                DA.SetDataList(22, buttons);
                DA.SetDataList(23, thumbsttriggers);
                DA.SetData(24, lt);
                DA.SetData(25, rt);
                DA.SetData(26, Controller.PlayerIndex);

                this.Message = ("Connected: " + Controller.IsConnected + Environment.NewLine + "Refresh Interval: " + Controller.RefreshIntervalMilliseconds);
            }
            else
            {
                this.Message = "No Controller Connected";
            }
        }
Exemplo n.º 60
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Manipulator manipulator = null;

            if (!DA.GetData(0, ref manipulator))
            {
                manipulator = Manipulator.Default;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No robot system defined, using default");
            }   // Set Robot.
            if (!DA.GetData(1, ref c_Target))
            {
                return;                               // Get the target.
            }
            c_Robot  = (Manipulator)manipulator.Duplicate();
            c_Target = (Target)c_Target.Duplicate();
            if (c_Target.Tool != null)
            {
                c_Tool = c_Target.Tool;                        // Get the tool from the target.
            }
            Manipulator.ManipulatorPose pose = new Manipulator.ManipulatorPose(c_Robot, c_Target);

            // Handle errors
            List <string> log = new List <string>();

            if (pose.OverHeadSig)
            {
                log.Add("Close to overhead singularity.");
            }
            if (pose.WristSing)
            {
                log.Add("Close to wrist singularity.");
            }
            if (pose.OutOfReach)
            {
                log.Add("Target out of range.");
            }
            if (pose.OutOfRoation)
            {
                log.Add("Joint out of range.");
            }

            if (c_Pose != null)
            {
                c_Robot.SetPose(c_Pose, checkValidity: true);
            }
            c_Robot.SetPose(pose, checkValidity: true);
            if (c_Robot.CurrentPose.IsValid)
            {
                c_Pose = c_Robot.CurrentPose;
            }

            Plane flange = (c_Robot.CurrentPose.IsValid)? c_Robot.CurrentPose.Flange: Plane.Unset;

            double[] selectedAngles = c_Robot.CurrentPose.Angles;

            // Set output
            DA.SetData("Flange", flange);
            DA.SetDataList("Angles", selectedAngles);
            DA.SetDataList("Log", log);
            if (c_PoseOut)
            {
                DA.SetData("Robot Pose", c_Robot.CurrentPose);
            }


            // Update and display data
            c_Robot.UpdatePose();
            c_Robot.GetBoundingBox(Transform.Identity);

            c_Tool.UpdatePose(c_Robot);
            c_Tool.GetBoundingBox(Transform.Identity);
        }