Ejemplo n.º 1
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   desiredVelocity = CalculateDesiredVelocity();
   Vector3d appliedForce = ApplyDesiredVelocity();
   da.SetData(nextOutputIndex++, appliedForce);
   da.SetData(nextOutputIndex++, desiredVelocity);
 }
Ejemplo n.º 2
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   da.SetData(nextOutputIndex++, agent.MaxSpeed);
   da.SetData(nextOutputIndex++, agent.MaxForce);
   da.SetData(nextOutputIndex++, agent.VisionRadius);
   da.SetData(nextOutputIndex++, agent.VisionAngle);
 }
Ejemplo n.º 3
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);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Indata
            WR_Utilisation util = null;
            if (!DA.GetData(0, ref util)) { return; }

            DA.SetData(0, util.GetUtilisationDegree());
            DA.SetData(1, util.ToString());
        }
Ejemplo n.º 5
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   //da.SetDataList(nextOutputIndex++, particle.velocity3DHistory.ToList());
   da.SetData(nextOutputIndex++, particle.Velocity3D);
   if (particle.Environment.GetType() == typeof (SurfaceEnvironmentType))
   {
     da.SetData(nextOutputIndex++, particle.Velocity);
   }
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ResultElement res = null;

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

            DA.SetData(0, new Line(res.sPos, res.ePos));
            DA.SetData(1, CrossSectionCasts.GetRhinoString(res.SectionPropertyString));
            DA.SetData(2, res.elNormal);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            WR_Structure struc = null;

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

            DA.SetData(0, struc.GetWeight());
            DA.SetData(1, struc.NodeCount);
            DA.SetData(2, struc.ElementCount);
        }
Ejemplo n.º 8
0
    protected override void SetOutputs(IGH_DataAccess da)
    {
      if (!apply)
      {
        da.SetData(nextOutputIndex++, false);
        return;
      }

      bool behaviorApplied = Run();
      da.SetData(nextOutputIndex++, behaviorApplied);
    }
Ejemplo n.º 9
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     DHr dhr = new DHr();
     if (DA.GetData(0, ref dhr))
     {
         DA.SetData(0, dhr.hr);
         DA.SetDataList(1, dhr.keys);
         DA.SetDataList(2, dhr.values);
         DA.SetData(3, dhr.color);
         DA.SetData(4, dhr.pos);
     }
 }
Ejemplo n.º 10
0
        protected override void SolveInstance(IGH_DataAccess da)
        {
            bool set = false;
            da.GetData(PInSet, ref set);
            bool reset = false;
            da.GetData(PInReset, ref reset);

            if (set) FOutput = true;
            else if (reset) FOutput = false;

            da.SetData(POutOutput, FOutput);
            da.SetData(POutInverseOutput, !FOutput);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Input
            Object[] output = new Object[2];
            DA.GetData(0, ref output);

            //Casting
            Point3d pt = (Point3d) output[0];
            Vector3d force = (Vector3d) output[1];

            //Output
            DA.SetData(0, pt);
            DA.SetData(1, force);
        }
Ejemplo n.º 12
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");
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            SpringMesh iSpringMesh = null;
            DA.GetData<SpringMesh>("Spring Mesh", ref iSpringMesh);

            DA.SetData("Rhino Mesh", iSpringMesh.ConvertToRhinoMesh());
        }
Ejemplo n.º 14
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Input
            Point3d supportPt = new Point3d();
            DA.GetData(0, ref supportPt);

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

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

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

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

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


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


            //Output
            DA.SetData(0, support);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (this.Analysis == null) { return; }

            base.SolveInstance(DA);
            DA.SetData(1, ((QTOAnalysis)this.Analysis).TextualOutput);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Input
            Line line = new Line();
            DA.GetData(0, ref line);

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

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

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


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


            //Output
            DA.SetData(0, cableElement);
        }
        protected override 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
        }
Ejemplo n.º 18
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);
 }
Ejemplo n.º 19
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)
        {
            PlanktonMesh P = new PlanktonMesh();
            List<Point3d> Points = new List<Point3d>();
            if ((!DA.GetData<PlanktonMesh>(0, ref P)) || (!DA.GetDataList(1, Points))) return;
            PlanktonMesh pMesh = P.ReplaceVertices(Points);           
            DA.SetData(0, pMesh);
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Point3d M = Point3d.Origin;
            Point3d A = Point3d.Origin;
            Point3d B = Point3d.Origin;

            DA.GetData<Point3d>(0, ref M);
            DA.GetData<Point3d>(1, ref A);
            DA.GetData<Point3d>(2, ref B);

            LineCurve AB = new LineCurve(A, B);
            double t;
            AB.ClosestPoint(M, out t);

            DA.SetData(0, Utils.ClosestPointOnLine(M, A, B));
            DA.SetData(1, AB.PointAt(t));
        }
Ejemplo n.º 21
0
 protected override void SolveInstance(IGH_DataAccess DA)
 {
     String name = null;
     Object value = null;
     DA.GetData(0, ref name);
     DA.GetData(1, ref value);
     DA.SetData(0, new HashType(name, value));
 }
Ejemplo n.º 22
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
     BoxEnvironmentType environment = new BoxEnvironmentType(box.BoundingBox, x_count, y_count, z_count);
     environment.setContainer();
     if (obs != null)
         environment.setObstacles(obs);
     //environment.setContainer(null);
     da.SetData(nextOutputIndex++, environment);
 }
Ejemplo n.º 23
0
    protected override void SetOutputs(IGH_DataAccess da)
    {
      // We're set to create the output now. To keep the size of the SolveInstance() method small, 
      // The actual functionality will be in a different method:
      IVehicle vehicle = new VehicleType(agent, wheelRadius);

      // Finally assign the spiral to the output parameter.
      da.SetData(nextOutputIndex++, vehicle);
    }
Ejemplo n.º 24
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //Input
            Object[] output = new Object[3];
            DA.GetData(0, ref output);

            //Casting
            int PIndex = (int)output[0];
            Plane pl = (Plane)output[1];
            double moment = (double)output[2];
            double stress = (double)output[3];

            //Output
            DA.SetData(0, PIndex);
            DA.SetData(1, pl);
            DA.SetData(2, Math.Round(moment, 3));
            DA.SetData(3, Math.Round(stress, 1));
        }
Ejemplo n.º 25
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)
        {
            Mesh M = new Mesh();          
            if (!DA.GetData(0, ref M)) return;

            PlanktonMesh pMesh = M.ToPlanktonMesh();

            DA.SetData(0, pMesh);
        }
Ejemplo n.º 26
0
 protected override void SetOutputs(IGH_DataAccess da)
 {
   if (!filepath.Equals(previousFilepath) || reload)
   {
     bitmap = new Bitmap(filepath);
   }
   previousFilepath = filepath;
   da.SetData(nextOutputIndex++, bitmap);
 }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int i = 0;

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

            string lc = "Mode " + i;

            DA.SetData(0, lc);
        }
Ejemplo n.º 28
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string m = null;
            if (DA.GetData(0, ref m))
            {
                var t = Persistance.ReadText(m);

                DA.SetData(0, t);
            }
        }
Ejemplo n.º 29
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ITurtleMesh m = null;
            if (DA.GetData(0, ref m))
            {
                var r = Persistance.WritableText(m);

                DA.SetData(0, r);
            }
        }
Ejemplo n.º 30
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)
    {
      // First, we need to retrieve all data from the input parameters.
      // We'll start by declaring variables and assigning them starting values.
      AgentType agent = new AgentType();

      // 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(0, ref agent)) return;

      // We should now validate the data and warn the user if invalid data is supplied.

      // We're set to create the output now. To keep the size of the SolveInstance() method small, 
      // The actual functionality will be in a different method:

      // Finally assign the spiral to the output parameter.
      DA.SetData(0, agent.Position);
      DA.SetData(1, agent.Velocity);
      DA.SetData(2, agent.Acceleration);
      DA.SetData(3, agent.Lifespan);
    }
Ejemplo n.º 31
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            bool hasTarget   = Params.Input.Any(x => x.Name == "Target");
            bool hasJoints   = Params.Input.Any(x => x.Name == "Joints");
            bool hasPlane    = Params.Input.Any(x => x.Name == "Plane");
            bool hasConfig   = Params.Input.Any(x => x.Name == "RobConf");
            bool hasMotion   = Params.Input.Any(x => x.Name == "Motion");
            bool hasTool     = Params.Input.Any(x => x.Name == "Tool");
            bool hasSpeed    = Params.Input.Any(x => x.Name == "Speed");
            bool hasZone     = Params.Input.Any(x => x.Name == "Zone");
            bool hasCommand  = Params.Input.Any(x => x.Name == "Command");
            bool hasFrame    = Params.Input.Any(x => x.Name == "Frame");
            bool hasExternal = Params.Input.Any(x => x.Name == "External");

            GH_Target sourceTarget = null;

            if (hasTarget)
            {
                if (!DA.GetData("Target", ref sourceTarget))
                {
                    return;
                }
            }

            double[] joints = null;
            var      plane  = new Plane();

            Target.RobotConfigurations?configuration = null;
            Target.Motions             motion        = Target.Motions.Joint;
            Tool    tool    = null;
            Speed   speed   = null;
            Zone    zone    = null;
            Command command = null;
            Frame   frame   = null;

            double[] external = null;

            if (hasJoints)
            {
                GH_String jointsGH = null;
                if (!DA.GetData("Joints", ref jointsGH))
                {
                    return;
                }

                string[] jointsText = jointsGH.Value.Split(',');
                if (jointsText.Length != 6)
                {
                    return;
                }

                joints = new double[6];

                for (int i = 0; i < 6; i++)
                {
                    if (!GH_Convert.ToDouble_Secondary(jointsText[i], ref joints[i]))
                    {
                        return;
                    }
                }
            }
            else if (sourceTarget != null)
            {
                if (sourceTarget.Value is JointTarget)
                {
                    joints = (sourceTarget.Value as JointTarget).Joints;
                }
            }

            if (hasPlane)
            {
                GH_Plane planeGH = null;
                if (hasPlane)
                {
                    if (!DA.GetData("Plane", ref planeGH))
                    {
                        return;
                    }
                }
                plane = planeGH.Value;
            }
            else if (sourceTarget != null)
            {
                if (sourceTarget.Value is CartesianTarget)
                {
                    plane = (sourceTarget.Value as CartesianTarget).Plane;
                }
            }

            if (hasConfig)
            {
                GH_Integer configGH = null;
                if (hasConfig)
                {
                    DA.GetData("RobConf", ref configGH);
                }
                configuration = (configGH == null) ? null : (Target.RobotConfigurations?)configGH.Value;
            }
            else if (sourceTarget != null)
            {
                if (sourceTarget.Value is CartesianTarget)
                {
                    configuration = (sourceTarget.Value as CartesianTarget).Configuration;
                }
            }

            if (hasMotion)
            {
                GH_String motionGH = null;
                DA.GetData("Motion", ref motionGH);
                motion = (motionGH == null) ? Target.Motions.Joint : (Target.Motions)Enum.Parse(typeof(Target.Motions), motionGH.Value);
            }
            else if (sourceTarget != null)
            {
                if (sourceTarget.Value is CartesianTarget)
                {
                    motion = (sourceTarget.Value as CartesianTarget).Motion;
                }
            }

            if (hasTool)
            {
                GH_Tool toolGH = null;
                DA.GetData("Tool", ref toolGH);
                tool = toolGH?.Value;
            }
            else if (sourceTarget != null)
            {
                tool = sourceTarget.Value.Tool;
            }

            if (hasSpeed)
            {
                GH_Speed speedGH = null;
                DA.GetData("Speed", ref speedGH);
                speed = speedGH?.Value;
            }
            else if (sourceTarget != null)
            {
                speed = sourceTarget.Value.Speed;
            }

            if (hasZone)
            {
                GH_Zone zoneGH = null;
                DA.GetData("Zone", ref zoneGH);
                zone = zoneGH?.Value;
            }
            else if (sourceTarget != null)
            {
                zone = sourceTarget.Value.Zone;
            }

            if (hasCommand)
            {
                GH_Command commandGH = null;
                DA.GetData("Command", ref commandGH);
                command = commandGH?.Value;
            }
            else if (sourceTarget != null)
            {
                command = sourceTarget.Value.Command;
            }

            if (hasFrame)
            {
                GH_Frame frameGH = null;
                DA.GetData("Frame", ref frameGH);
                frame = frameGH?.Value;
            }
            else if (sourceTarget != null)
            {
                frame = sourceTarget.Value.Frame;
            }

            if (hasExternal)
            {
                GH_String externalGH = null;
                if (!DA.GetData("External", ref externalGH))
                {
                    external = new double[0];
                }
                else
                {
                    string[] externalText = externalGH.Value.Split(',');
                    int      length       = externalText.Length;
                    external = new double[length];
                    for (int i = 0; i < length; i++)
                    {
                        if (!GH_Convert.ToDouble_Secondary(externalText[i], ref external[i]))
                        {
                            return;
                        }
                    }
                }
            }
            else if (sourceTarget != null)
            {
                external = sourceTarget.Value.External;
            }

            Target target;

            bool localCartesian = isCartesian;

            if (hasTarget && !hasPlane && !hasJoints)
            {
                localCartesian = sourceTarget.Value is CartesianTarget;
            }

            if (localCartesian)
            {
                target = new CartesianTarget(plane, configuration, motion, tool, speed, zone, command, frame, external);
            }
            else
            {
                target = new JointTarget(joints, tool, speed, zone, command, frame, external);
            }

            DA.SetData(0, new GH_Target(target));
        }
Ejemplo n.º 32
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (readFailed)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This component has changed or cannot be found, please create a new one");
                return;
            }

            if (SelectedConstructor is null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No schema has been selected.");
                return;
            }

            var units = Units.GetUnitsFromString(Rhino.RhinoDoc.ActiveDoc.GetUnitSystemName(true, false, false, false));

            List <object> cParamsValues = new List <object>();
            var           cParams       = SelectedConstructor.GetParameters();
            object        mainSchemaObj = null;

            for (var i = 0; i < cParams.Length; i++)
            {
                var    cParam     = cParams[i];
                var    param      = Params.Input[i];
                object objectProp = null;
                if (param.Access == GH_ParamAccess.list)
                {
                    var inputValues = new List <object>();
                    DA.GetDataList(i, inputValues);
                    if (!inputValues.Any() && !param.Optional)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input list `" + param.Name + "` is empty.");
                        return;
                    }

                    try
                    {
                        inputValues = inputValues.Select(x => ExtractRealInputValue(x)).ToList();
                        objectProp  = GetObjectListProp(param, inputValues, cParam.ParameterType);
                    }
                    catch (Exception e)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                        return;
                    }
                }
                else if (param.Access == GH_ParamAccess.item)
                {
                    object inputValue = null;
                    DA.GetData(i, ref inputValue);
                    var extractRealInputValue = ExtractRealInputValue(inputValue);
                    objectProp = GetObjectProp(param, extractRealInputValue, cParam.ParameterType);
                }
                cParamsValues.Add(objectProp);
                if (CustomAttributeData.GetCustomAttributes(cParam)?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0)
                {
                    mainSchemaObj = objectProp;
                }
            }


            object schemaObject = null;

            try
            {
                schemaObject = SelectedConstructor.Invoke(cParamsValues.ToArray());
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                return;
            }

            var @base = ((Base)schemaObject);

            @base.applicationId = $"{Seed}-{SelectedConstructor.DeclaringType.FullName}-{DA.Iteration}";
            @base.units         = units;

            // create commit obj from main geometry param and try to attach schema obj. use schema obj if no main geom param was found.
            Base commitObj = (Base)schemaObject;

            try
            {
                if (mainSchemaObj != null)
                {
                    commitObj = (Base)mainSchemaObj;
                    commitObj["@SpeckleSchema"] = schemaObject;
                    commitObj.units             = units;
                }
            }
            catch { }

            // Finally, add any custom props created by the user.
            for (var j = cParams.Length; j < Params.Input.Count; j++)
            {
                // Additional props added to the object
                var ghParam = Params.Input[j];
                if (ghParam.Access == GH_ParamAccess.item)
                {
                    object input = null;
                    DA.GetData(j, ref input);

                    commitObj[ghParam.Name] = Utilities.TryConvertItemToSpeckle(input, Converter);
                }
                else if (ghParam.Access == GH_ParamAccess.list)
                {
                    List <object> input = new List <object>();
                    DA.GetDataList(j, input);
                    commitObj[ghParam.Name] = input.Select(i => Utilities.TryConvertItemToSpeckle(i, Converter)).ToList();
                }
            }
            DA.SetData(0, new GH_SpeckleBase()
            {
                Value = commitObj
            });
        }
Ejemplo n.º 33
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            sSystemSetting sysSetting = null;
            List <object>  sElement   = new List <object>();

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


            sRhinoConverter rhcon       = new sRhinoConverter();
            string          currentUnit = Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem.ToString();

            if (sysSetting == null)
            {
                sysSetting = new sSystemSetting();
                sysSetting.systemOriUnit = currentUnit;

                sysSetting.systemName       = "DefaultSetting";
                sysSetting.currentCase      = "DEAD";
                sysSetting.currentCheckType = eSystemCheckType.StrengthCheck;

                sysSetting.currentStressThreshold_pascal = 25 * 6894757.28;
                sysSetting.currentDeflectionThreshold_mm = 100;

                sysSetting.mergeTolerance_m = 0.005;
                sysSetting.meshDensity_m    = 0.5;
            }

            if (currentUnit == "Meters" || currentUnit == "Feet")
            {
                ISystem jsys = InitiateISystem(sElement);

                jsys.systemSettings = sysSetting;
                List <IsObject> sObjs = new List <IsObject>();

                jsys.loadPatterns.Add("DEAD");

                int supCount = 0;
                int nodeID   = 0;

                try
                {
                    foreach (object so in sElement)
                    {
                        GH_ObjectWrapper wap = new GH_ObjectWrapper(so);

                        IFrameSet bs = wap.Value as IFrameSet;
                        if (bs != null)
                        {
                            //jsys.beamSets.Add(bs);
                            jsys.AddsBeamSet(bs);
                            //??
                            sObjs.Add(bs);
                            if (bs.lineLoads != null)
                            {
                                foreach (sLineLoad ll in bs.lineLoads)
                                {
                                    jsys.AwarePatternNames(ll.loadPatternName);
                                }
                            }
                        }

                        sPointLoad pl = wap.Value as sPointLoad;
                        if (pl != null)
                        {
                            if (jsys.UpdateNodeFromPointElement(pl, nodeID))
                            {
                                nodeID++;
                                jsys.AwarePatternNames(pl.loadPatternName);
                            }
                        }

                        sLoadCombination com = wap.Value as sLoadCombination;
                        if (com != null)
                        {
                            jsys.SetLoadCombination(com);
                        }
                    }

                    foreach (object so in sElement)
                    {
                        GH_ObjectWrapper wap  = new GH_ObjectWrapper(so);
                        sPointSupport    psup = wap.Value as sPointSupport;
                        if (psup != null)
                        {
                            if (jsys.UpdateNodeFromPointElement(psup, nodeID))
                            {
                                nodeID++;
                            }
                            supCount++;
                        }
                    }

                    foreach (sMesh am in jsys.meshes)
                    {
                        //  sObjs.Add(am);
                    }

                    if (supCount > 0)
                    {
                        this.Message = "System : " + sysSetting.systemName + "\nis instantiated";
                        jsys.systemSettings.systemBoundingBox = rhcon.TosBoundingBox(sObjs);

                        //jsys.SystemName = sysSetting.systemName;
                        DA.SetData(0, jsys);
                    }
                    else
                    {
                        this.Message = "System : " + sysSetting.systemName + "\nneeds supports";
                        //jsys.SystemName = sysSetting.systemName;
                        this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, this.Message);
                        DA.SetData(0, null);
                    }
                }
                catch (Exception e)
                {
                    this.Message = "System : " + sysSetting.systemName + "\ninstantiation failed";
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                    DA.SetData(0, null);
                }
            }
            else
            {
                this.Message = "ASKSGH.Bridgify only works in\n Meters or Feet";
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, this.Message);
                DA.SetData(0, null);
            }
        }
Ejemplo n.º 34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //______________________________________________________________________________________________
            ////////////////////////////////        I N P U T S          ///////////////////////////////////
            Mesh            msh    = new Mesh();
            CObstacleObject mshobj = null;

            if (!DA.GetData(0, ref mshobj))
            {
                return;
            }
            msh = mshobj.mesh;

            //should containt analysis surface itself
            List <CObstacleObject> objObst = new List <CObstacleObject>();

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

            List <CPermObject> treeObst = new List <CPermObject>();

            DA.GetDataList(2, treeObst);

            double latitude = 0.0;

            if (!DA.GetData(4, ref latitude))
            {
                return;
            }
            double longitude = 0.0;

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

            int year = 0;

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

            double snow_threshold = 1.0;

            if (!DA.GetData(7, ref snow_threshold))
            {
                snow_threshold = 1.0;
            }
            double tilt_threshold = 60.0;

            if (!DA.GetData(8, ref tilt_threshold))
            {
                tilt_threshold = 60.0;
            }


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

            if (!DA.GetDataList(10, DNI))
            {
                return;
            }
            List <double> DHI = new List <double>();

            if (!DA.GetDataList(11, DHI))
            {
                return;
            }
            List <double> SNOW = new List <double>();

            if (!DA.GetDataList(12, SNOW))
            {
                for (int t = 0; t < 8760; t++)
                {
                    SNOW.Add(0.0);
                }
            }
            List <double> groundalbedo = new List <double>();

            if (!DA.GetDataList(13, groundalbedo))
            {
                for (int t = 0; t < 8760; t++)
                {
                    groundalbedo.Add(0.2);
                }
            }
            List <double> solarAzimuth = new List <double>();

            DA.GetDataList(14, solarAzimuth);
            List <double> solarAltitude = new List <double>();

            DA.GetDataList(15, solarAltitude);

            int MainSkyRes = 0;

            if (!DA.GetData(17, ref MainSkyRes))
            {
                MainSkyRes = 1;
            }
            int MainInterpMode = 0;

            if (!DA.GetData(18, ref MainInterpMode))
            {
                MainInterpMode = 0;
            }

            int SpecBounces = 1;

            if (!DA.GetData(20, ref SpecBounces))
            {
                SpecBounces = 1;
            }
            SpecBounces = (SpecBounces < 0) ? 0 : SpecBounces;
            int SpecInterpMode = 0;

            if (!DA.GetData(21, ref SpecInterpMode))
            {
                SpecInterpMode = 0;
            }

            int DiffIReflSkyRes = 0;

            if (!DA.GetData(23, ref DiffIReflSkyRes))
            {
                DiffIReflSkyRes = 0;
            }
            int DiffIReflSkyRes2nd = 0;

            if (!DA.GetData(24, ref DiffIReflSkyRes2nd))
            {
                DiffIReflSkyRes2nd = 0;
            }
            int DiffIReflMode = 1;

            if (!DA.GetData(25, ref DiffIReflMode))
            {
                DiffIReflMode = 1;
            }

            CResultsInterreflections ResultsIreflIn = null;

            DA.GetData(27, ref ResultsIreflIn);

            bool mt = false;

            if (!DA.GetData(29, ref mt))
            {
                mt = false;
            }

            int timezone = 0;

            DA.GetData(30, ref timezone);

            ////////////////////////////////////////////////////////////////////////////////////////////////
            //______________________________________________________________________________________________


            //______________________________________________________________________________________________
            ////////////////////////////////        S I M U L A T E      ///////////////////////////////////
            CCalculateSolarMesh calc = new CCalculateSolarMesh(
                mshobj, objObst, treeObst, latitude, longitude, DNI, DHI, SNOW, groundalbedo, snow_threshold,
                tilt_threshold, year, null, mt, solarAzimuth, solarAltitude, timezone);

            calc.RunAnnualSimulation_MT(
                mshobj.tolerance, MainSkyRes, MainInterpMode, SpecBounces, SpecInterpMode, DiffIReflSkyRes, DiffIReflSkyRes2nd, DiffIReflMode);

            CResults results = calc.getResults();

            //cResultsInterreflections resultsIreflOut = calc.getResultsInterreflections();
            ////////////////////////////////////////////////////////////////////////////////////////////////
            //______________________________________________________________________________________________


            //______________________________________________________________________________________________
            ////////////////////////////////          O U T P U T        ///////////////////////////////////
            DA.SetData(0, results);

            ////////////////////////////////////////////////////////////////////////////////////////////////
            //______________________________________________________________________________________________


            Rhino.RhinoApp.WriteLine("SOLAR MODEL... Done");
        }
Ejemplo n.º 35
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            var elementType = default(DB.ElementType);

            if (!DA.GetData("Type", ref elementType))
            {
                return;
            }

            var folder = default(string);

            DA.GetData("Folder", ref folder);

            if (string.IsNullOrEmpty(folder))
            {
                folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), elementType.Document.Title);
            }

            Directory.CreateDirectory(folder);

            var overrideFile = default(bool);

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

            var fileType = default(DB.ImageFileType);

            if (!DA.GetData("File Type", ref fileType))
            {
                return;
            }

            var resolution = default(DB.ImageResolution);

            if (!DA.GetData("Resolution", ref resolution))
            {
                return;
            }

            var pixelSizeX = default(int);

            if (!DA.GetData("Pixel Size X", ref pixelSizeX))
            {
                return;
            }

            var pixelSizeY = default(int);

            if (!DA.GetData("Pixel Size Y", ref pixelSizeY))
            {
                return;
            }

            var size = new System.Drawing.Size(pixelSizeX, pixelSizeY);

            var elementTypeName = $"{elementType.Category?.Name} - {elementType.FamilyName} - {elementType.Name}";

            var filePath = Path.Combine(folder, elementTypeName);

            if (!overrideFile && File.Exists(filePath))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"File '{filePath}' already exists.");
            }
            else
            {
                var bitmap = elementType.GetPreviewImage(size);

                switch (resolution)
                {
                case DB.ImageResolution.DPI_72:  bitmap.SetResolution(72, 72); break;

                case DB.ImageResolution.DPI_150: bitmap.SetResolution(150, 150); break;

                case DB.ImageResolution.DPI_300: bitmap.SetResolution(300, 300); break;

                case DB.ImageResolution.DPI_600: bitmap.SetResolution(600, 600); break;
                }

                switch (fileType)
                {
                case DB.ImageFileType.BMP:
                    filePath += ".bmp";
                    bitmap.Save(filePath, ImageFormat.Bmp);
                    break;

                case DB.ImageFileType.JPEGLossless:
                {
                    filePath += ".jpg";
                    var codec = ImageCodecInfo.GetImageDecoders().Where(x => x.FormatID == ImageFormat.Jpeg.Guid).FirstOrDefault();
                    using (var parameters = new EncoderParameters(1))
                    {
                        parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100);
                        bitmap.Save(filePath, codec, parameters);
                    }
                }
                break;

                case DB.ImageFileType.JPEGMedium:
                {
                    filePath += ".jpg";
                    var codec = ImageCodecInfo.GetImageDecoders().Where(x => x.FormatID == ImageFormat.Jpeg.Guid).FirstOrDefault();
                    using (var parameters = new EncoderParameters(1))
                    {
                        parameters.Param[0] = new EncoderParameter(Encoder.Quality, 50);
                        bitmap.Save(filePath, codec, parameters);
                    }
                }
                break;

                case DB.ImageFileType.JPEGSmallest:
                {
                    filePath += ".jpg";
                    var codec = ImageCodecInfo.GetImageDecoders().Where(x => x.FormatID == ImageFormat.Jpeg.Guid).FirstOrDefault();
                    using (var parameters = new EncoderParameters(1))
                    {
                        parameters.Param[0] = new EncoderParameter(Encoder.Quality, 1);
                        bitmap.Save(filePath, codec, parameters);
                    }
                }
                break;

                case DB.ImageFileType.PNG:
                    filePath += ".png";
                    bitmap.Save(filePath, ImageFormat.Png);
                    break;

                case DB.ImageFileType.TARGA:
                    filePath += ".tga";
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Unsuported file format.");
                    filePath = string.Empty;
                    break;

                case DB.ImageFileType.TIFF:
                    filePath += ".tif";
                    bitmap.Save(filePath, ImageFormat.Tiff);
                    break;
                }
            }

            DA.SetData("Image File", filePath);
        }
Ejemplo n.º 36
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GsaGridAreaLoad gridareaload = new GsaGridAreaLoad();

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

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

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

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

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

            // 1 Polyline
            Brep brep = new Brep();


            GH_Brep gh_brep = new GH_Brep();

            if (DA.GetData(1, ref gh_brep))
            {
                GH_Convert.ToBrep(gh_brep, ref brep, GH_Conversion.Both);

                // get edge curves
                Curve[] edgeSegments = brep.DuplicateEdgeCurves();
                Curve[] edges        = Curve.JoinCurves(edgeSegments);
                Curve   crv          = edges[0];

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

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

                        // create grid plane surface from best fit plane
                        grdplnsrf = new GsaGridPlaneSurface(pln, true);
                    }

                    // project original curve onto grid plane
                    crv = Curve.ProjectToPlane(crv, pln);

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

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

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

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

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

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

                    // set polyline in grid line load
                    gridareaload.GridAreaLoad.Type = GridAreaPolyLineType.POLYGON;
                    gridareaload.GridAreaLoad.PolyLineDefinition = desc;
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not convert Brep edge to Polyline");
                }
            }

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

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

            GH_String gh_dir = new GH_String();

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

            gridareaload.GridAreaLoad.Direction = direc;

            // 4 Axis
            int axis = 0;

            gridareaload.GridAreaLoad.AxisProperty = 0;
            GH_Integer gh_ax = new GH_Integer();

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

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

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

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

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

            // 7 load value
            double load1 = 0;

            if (DA.GetData(7, ref load1))
            {
                load1 *= -1000; //convert to kN
            }
            gridareaload.GridAreaLoad.Value = load1;

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

            DA.SetData(0, new GsaLoadGoo(gsaLoad));
        }
Ejemplo 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)
        {
            string ID   = this.Attributes.InstanceGuid.ToString();
            string name = new GUIDtoAlpha(Convert.ToString(ID + Convert.ToString(this.RunCount)), false).Text;
            int    C    = this.RunCount;

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

            var pCtrl = new pColorPicker(name);

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

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

            //Set Unique Control Properties

            Color        D = Color.Transparent;
            List <Color> S = new List <Color>();
            List <Color> K = new List <Color>();
            int          M = 1;

            if (!DA.GetData(0, ref D))
            {
                return;
            }
            if (!DA.GetData(1, ref M))
            {
                return;
            }
            if (!DA.GetDataList(2, K))
            {
                return;
            }
            if (!DA.GetDataList(3, S))
            {
                return;
            }

            pColorSets ClrSets = new pColorSets();

            if (S.Count < 1)
            {
                S = ClrSets.Standard;
            }
            if (K.Count < 1)
            {
                K = ClrSets.Standard;
            }

            pCtrl.SetProperties(D, S, K, M);

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

            Elements[this.RunCount] = WindObject;

            DA.SetData(0, WindObject);
        }
Ejemplo n.º 38
0
        protected override void SolveInstance(IGH_DataAccess access)
        {
            // If the input parameter has persistent data, or is connected to sources,
            // then assign the RetainedData from the input.
            // Otherwise use the retained data.
            bool   toggle = false;
            string key    = "0";
            GH_Structure <IGH_Goo> data;
            bool   clear    = false;
            bool   write    = false;
            bool   read     = false;
            string filePath = "";
            var    input    = Params.Input[2] as Param_GenericObject;

            access.GetData(0, ref toggle);
            access.GetData(1, ref key);
            access.GetData(3, ref clear);
            access.GetData(4, ref write);
            access.GetData(5, ref read);
            access.GetData(6, ref filePath);



            if (input is null)
            {
                throw new InvalidCastException("Input was supposed to be a Param_GenericObject.");
            }

            if (clear)
            {
                storage.Clear();
            }

            if (input.SourceCount > 0 || !input.PersistentData.IsEmpty)
            {
                access.GetDataTree(2, out data);
                if (toggle)
                {
                    if (storage.ContainsKey(key))
                    {
                        storage[key] = data.ShallowDuplicate();
                    }
                    else
                    {
                        storage.Add(key, data.ShallowDuplicate());
                    }
                }
            }

            //json write
            if (write)
            {
                this.JsonStringWrite = JsonSerializer.Serialize <Dictionary <string, GH_Structure <IGH_Goo> > >(storage, this.jso);
                this.WriteJson(filePath);
            }
            //json read
            IsRead = read;
            if (read && File.Exists(filePath))
            {
                this.ReadJson(filePath);
            }

            if (storage.ContainsKey(key))
            {
                data = storage[key];
                access.SetDataTree(0, data);
            }
            else
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The given key is not present.");
            }

            access.SetData(1, this.JsonStringWrite);
        }
Ejemplo n.º 39
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <IGH_GeometricGoo> geometry = new List <IGH_GeometricGoo>();
            double cellSize = 1.0;
            bool   z0       = false;
            bool   centerXY = true;
            double xyScale  = 1.2;
            double xyOffset = 10;
            double zScale   = 2.0;
            bool   square   = true;

            if (!DA.GetDataList(0, geometry))
            {
                return;
            }
            if (!DA.GetData(1, ref cellSize))
            {
                return;
            }
            if (!DA.GetData(2, ref z0))
            {
                return;
            }
            if (!DA.GetData(3, ref centerXY))
            {
                return;
            }
            if (!DA.GetData(4, ref square))
            {
                return;
            }
            if (!DA.GetData(5, ref xyScale))
            {
                return;
            }
            if (!DA.GetData(6, ref xyOffset))
            {
                return;
            }
            if (!DA.GetData(7, ref zScale))
            {
                return;
            }

            // Create Bounding Box
            List <BoundingBox> bbs = new List <BoundingBox>();

            foreach (IGH_GeometricGoo o in geometry)
            {
                bbs.Add(o.Boundingbox);
            }
            BoundingBox bb = Domain.getMultiBoundingBox(bbs, cellSize, z0, centerXY, xyScale, xyOffset, zScale, square);

            // Construct Surface Dict

            List <Dictionary <string, object> > surfaces = new List <Dictionary <string, object> >();

            foreach (IGH_GeometricGoo mesh in geometry)
            {
                surfaces.Add(new Dictionary <string, object>
                {
                    { Geometry.getUserString(mesh, "ComputeName"), new Dictionary <string, object>
                      {
                          { "level", new Dictionary <string, string> {
                            { "min", Geometry.getUserString(mesh, "ComputeMeshMinLevel") },
                            { "max", Geometry.getUserString(mesh, "ComputeMeshMaxLevel") },
                        } }
                      } }
                });
            }

            var outputs = new Inputs {
                Mesh = new CFDMesh {
                    BaseMesh = new BaseMesh
                    {
                        Type        = "simpleBox",
                        CellSize    = cellSize,
                        BoundingBox = new Dictionary <string, object> {
                            { "min", new List <double> {
                                  bb.Min.X, bb.Min.Y, bb.Min.Z
                              } },
                            { "max", new List <double> {
                                  bb.Max.X, bb.Max.Y, bb.Max.Z
                              } }
                        },
                        Parameters = new Dictionary <string, string>
                        {
                            { "square", Convert.ToString(square) },
                            { "z0", Convert.ToString(z0) }
                        }
                    },
                    SnappyHexMesh = new SnappyHexMesh
                    {
                        Surfaces = surfaces
                    }
                }
            };

            /*
             * var outputs = new CFDMesh().ToJson(new Dictionary<string, object> {
             *  {"bounding_box", new Dictionary<string, object> {
             *      {"min", new List<double>{
             *          bb.Min.X, bb.Min.Y, bb.Min.Z
             *      } },
             *      {"max", new List<double>{
             *          bb.Max.X, bb.Max.Y, bb.Max.Z
             *      } }
             *  }
             *  },
             *  {"cell_size", cellSize },
             *  {"surfaces", surfaces }
             * });
             * /*
             * {
             * bbox: {
             *  min: x,y,z
             *  max: x,y,z
             * },
             * cellSize: 2
             * surfaces: [
             *  {names, level}
             * ]
             * }
             */

            // Get the required info from the coreDict

            /*foamDictionary coreDict = new foamDictionary(inText);
             * string caseDir = coreDict.GetPath("system.caseDir");
             *
             * List<BoundingBox> bbs = new List<BoundingBox>();
             * foreach (IGH_GeometricGoo o in _geo) { bbs.Add(o.Boundingbox); }
             * BoundingBox bb = domainCalcs.getMultiBoundingBox(bbs, cellSize, z0, centerXY, xyScale, xyOffset, zScale, square);
             *
             * int[] divs = new int[3];
             * divs[0] = (int)(Math.Abs(bb.Max.X - bb.Min.X) / cellSize);
             * divs[1] = (int)(Math.Abs(bb.Max.Y - bb.Min.Y) / cellSize);
             * divs[2] = (int)(Math.Abs(bb.Max.Z - bb.Min.Z) / cellSize);
             * blockMesh blockMeshDict = new blockMesh(caseDir, bb, divs);
             *
             * double r = (4 + (new Random().NextDouble() - 1)) / 16.0;
             * string keepPointOverride = string.Format(
             *  "castellatedMeshControls {{ locationInMesh ({0} {1} {2}); }}",
             *  (bb.Center.X + Math.Abs(bb.Max.X - bb.Min.X) * r).ToString(),
             *  (bb.Center.Y + Math.Abs(bb.Max.Y - bb.Min.Y) * r).ToString(),
             *  (bb.Center.Z + Math.Abs(bb.Max.Z - bb.Min.Z) * r).ToString()
             *  );
             *
             * // Add the output to the coreDict
             * foamDictionary domainDict = new foamDictionary();
             * domainDict["blockMeshDict"] = blockMeshDict.fields;
             * domainDict["keepPointOverride"] = new foamDictionary(keepPointOverride);
             * domainDict["vwtDims"] = new foamDictionary($"length {Math.Abs(bb.Max.X - bb.Min.X)}; height {Math.Abs(bb.Max.Z - bb.Min.Z)}; divsXY {divs[0]}; divsZ {divs[2]}; isCircular false; radiusFactor 1.5; widthFactor 1.7; radialDivision 10;");
             * coreDict.AddOrUpdate("domain", domainDict);*/

            DA.SetData(0, outputs.ToJson());
            DA.SetData(1, bb);
            DA.SetDataList(2, geometry);
        }
        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 (Materials)";
            var matList     = new List <string>();
            var matListAll  = new List <int>();
            var commentList = new List <string>();
            var E           = new List <Interval>();
            var Mu          = new List <Interval>();
            var G           = new List <Interval>();
            var W           = new List <Interval>();
            var Alpha       = new List <Interval>();
            var Gamma       = new List <Interval>();
            var description = new List <string>();
            var modelType   = new List <string>();
            var userDefined = new List <bool>();


            if (DA.GetDataList(0, matList))
            {
                foreach (var no in matList)
                {
                    matListAll.AddRange(no.ToInt());
                }
                myFilter.MatList = matListAll;
            }
            if (DA.GetDataList(1, commentList))
            {
                myFilter.MatComment = commentList;
            }
            if (DA.GetDataList(2, description))
            {
                myFilter.MatDes = description;
            }
            if (DA.GetDataList(3, E))
            {
                myFilter.MatE = E;
            }
            if (DA.GetDataList(4, Mu))
            {
                myFilter.MatMu = Mu;
            }
            if (DA.GetDataList(5, G))
            {
                myFilter.MatG = G;
            }
            if (DA.GetDataList(6, W))
            {
                myFilter.MatW = W;
            }
            if (DA.GetDataList(7, Alpha))
            {
                myFilter.MatAlpha = Alpha;
            }
            if (DA.GetDataList(8, Gamma))
            {
                myFilter.MatGamma = Gamma;
            }
            if (DA.GetDataList(9, modelType))
            {
                myFilter.MatModelType = modelType;
            }
            if (DA.GetDataList(10, userDefined))
            {
                myFilter.MatUserDefined = userDefined;
            }

            DA.SetData(0, myFilter);
        }
Ejemplo 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)
        {
            var inputAlgorithmA = new Boa_Algorithm();
            var inputAlgorithmB = new Boa_Algorithm();

            //baseAlgorithmA = new Boa_Algorithm();
            //baseAlgorithmB = new Boa_Algorithm();

            if (!DA.GetData(0, ref inputAlgorithmA))
            {
                return;
            }
            if (!DA.GetData(1, ref inputAlgorithmB))
            {
                return;
            }

            var parallelAlgorithm = GenerateParallelAlgorithm(inputAlgorithmA, inputAlgorithmB);

            var algorithm = new Boa_Algorithm();

            if (!parallelAlgorithm.GenerateAlgorithm(ref algorithm))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Algorithms outputs are of different sizes and cannot be combined.");
                return;
            }

            Algorithm = algorithm;
            //baseAlgorithmA = inputAlgorithmA.GetBaseAlgorithm();
            //baseAlgorithmB = inputAlgorithmB.GetBaseAlgorithm();

            //inputSizeA = baseAlgorithmA.InputDimension;
            //inputSizeB = baseAlgorithmB.InputDimension;

            //int newInputSize, newOutputSize = 0;
            //SolveAlgorithm parallelAlgorithmSolution;

            //if (inputAlgorithmA.OutputIsFixedSize && inputAlgorithmB.OutputIsFixedSize)
            //    if (!parallelAlgorithm.CalculateFixedAlgorithmOutputSize(inputAlgorithmA.OutputDimension, inputAlgorithmB.OutputDimension, ref newOutputSize)) return;

            //if (baseAlgorithmA.Equals(baseAlgorithmB))
            //{
            //    newInputSize = baseAlgorithmA.InputDimension;
            //    parallelAlgorithmSolution = SolveParallelAlgorithmWithSameBase;
            //    hasSameBase = true;
            //}
            //else
            //{
            //    //if either algorithms have non-fixed, inputs, then this algorithm will have non-fixed inputs (size 0);
            //    if (!baseAlgorithmA.InputIsFixedSize || !baseAlgorithmB.InputIsFixedSize)
            //    {
            //        newInputSize = 0;

            //        if (baseAlgorithmA.InputIsFixedSize)
            //            parallelAlgorithmSolution = SolveFixedAParallelAlgorithm;
            //        else if (baseAlgorithmB.InputIsFixedSize)
            //            parallelAlgorithmSolution = SolveFixedBParallelAlgorithm;
            //        else
            //            parallelAlgorithmSolution = SolveUnFixedParallelAlgorithm;
            //    }
            //    else
            //    {
            //        newInputSize = baseAlgorithmA.InputDimension + baseAlgorithmB.InputDimension;
            //        parallelAlgorithmSolution = SolveFixedParallelAlgorithm;
            //    }
            //    hasSameBase = false;
            //}

            //Algorithm = new Boa_Algorithm(parallelAlgorithmSolution, newInputSize, newOutputSize);

            //if (hasSameBase)
            //    Algorithm.AddDisjointedBase(baseAlgorithmA);

            DA.SetData(AlgorithmOutputIndex, Algorithm);
        }
Ejemplo n.º 42
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)
        {
            Mesh m = null;
            List <GH_GeometricGooWrapper> obj = new List <GH_GeometricGooWrapper>();
            double iso = 0d;
            double res = 0d;

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


            if (!DA.GetData(0, ref m))
            {
                return;
            }
            if (!DA.GetDataList <GH_GeometricGooWrapper>(1, obj))
            {
                return;
            }
            if (!DA.GetData(2, ref iso))
            {
                return;
            }
            if (!DA.GetData(3, ref res))
            {
                return;
            }

            var hem   = m.ToHeMesh();
            var field = MeshField3d.Double.Create(hem);

            //cast objects to geometry types
            foreach (GH_GeometricGooWrapper g in obj)
            {
                if (g.TypeName == "{Point}")
                {
                    Point3d p = new Point3d();
                    g.CastTo <Point3d>(ref p);
                    pts.Add(p);
                }
                else if (g.TypeName == "{Curve}")
                {
                    Curve c = null;
                    g.CastTo <Curve>(ref c);
                    crvs.Add(c);
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input must be points or curves.");
                    return;
                }
            }

            //if curves are inputted, convert them into points
            Utility.ConvertCrvsToPts(crvs, ref pts, res);

            //get vector of each field pt to the closest point.
            List <double> val = Utility.GetDistanceField(m, pts);

            Interval interval = Utility.GetInterval(val);

            //

            for (int i = 0; i < val.Count; i++)
            {
                val[i] = (SpatialSlur.SlurCore.SlurMath.Remap(val[i], interval.T0, interval.T1, -1, 1)) - iso;
            }


            field.Set(val);
            DA.SetData(0, FuncField3d.Create(i => field.ValueAt(i)));
        }
Ejemplo n.º 43
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)
        {
            //// *********************************************************************************
            ////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;

            DA.GetData(4, ref Vmet);

            //terrain type
            int terrain = 0;

            DA.GetData(5, ref terrain);


            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 WindInflowAytac(Nx + 2, Ny + 2, Nz + 2, xyzsize[0], xyzsize[1], xyzsize[2]);
                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 WindInflowAytac(Nx + 2, Ny + 2, Nz + 2, xyzsize[0], xyzsize[1], xyzsize[2]);
                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 shit 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, k, 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, k, 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)
            {
                DA.SetData(4, de);
            }
        }
    private int runCount;                              //Legacy field.

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

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

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

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

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

        int xCount = default(int);

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

        double xElimination = default(double);

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

        double y = default(double);

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

        int yCount = default(int);

        if (inputs[4] != null)
        {
            yCount = (int)(inputs[4]);
        }

        double yElimination = default(double);

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

        double z = default(double);

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

        int zCount = default(int);

        if (inputs[7] != null)
        {
            zCount = (int)(inputs[7]);
        }

        double zElimination = default(double);

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

        object void0 = default(object);

        if (inputs[9] != null)
        {
            void0 = (object)(inputs[9]);
        }

        int rollTheBones = default(int);

        if (inputs[10] != null)
        {
            rollTheBones = (int)(inputs[10]);
        }

        int result = default(int);

        if (inputs[11] != null)
        {
            result = (int)(inputs[11]);
        }



        //3. Declare output parameters
        object Elapsed    = null;
        object resultTree = null;


        //4. Invoke RunScript
        RunScript(x, xCount, xElimination, y, yCount, yElimination, z, zCount, zElimination, void0, rollTheBones, result, ref Elapsed, ref resultTree);

        try
        {
            //5. Assign output parameters to component...
            if (Elapsed != null)
            {
                if (GH_Format.TreatAsCollection(Elapsed))
                {
                    IEnumerable __enum_Elapsed = (IEnumerable)(Elapsed);
                    DA.SetDataList(1, __enum_Elapsed);
                }
                else
                {
                    if (Elapsed is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(Elapsed));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, Elapsed);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
            if (resultTree != null)
            {
                if (GH_Format.TreatAsCollection(resultTree))
                {
                    IEnumerable __enum_resultTree = (IEnumerable)(resultTree);
                    DA.SetDataList(2, __enum_resultTree);
                }
                else
                {
                    if (resultTree is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(2, (Grasshopper.Kernel.Data.IGH_DataTree)(resultTree));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(2, resultTree);
                    }
                }
            }
            else
            {
                DA.SetData(2, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
Ejemplo n.º 45
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_Goo X = null;
            int     D = 0;
            string  F = "G";
            string  T = "";

            if (!DA.GetData(0, ref X))
            {
                return;
            }
            if (!DA.GetData(1, ref D))
            {
                return;
            }
            if (!DA.GetData(2, ref F))
            {
                return;
            }
            if (!DA.GetData(3, ref T))
            {
                return;
            }

            DataPt DataObj = new DataPt();

            object obj = new object();

            X.CastTo(out obj);
            DataObj.Value = obj;

            DataObj.Type = D;
            DataObj.Tag  = T;

            DataObj.Label.Format   = F;
            DataObj.ToolTip.Format = F;

            DataObj.Graphics.Width = 1;

            string L = "";

            switch (D)
            {
            case 1:
                double num = new double();
                X.CastTo(out num);

                L = string.Format("{0:" + F + "}", num);

                DataObj.Integer = (int)num;
                DataObj.Number  = num;
                DataObj.Text    = num.ToString();
                DataObj.Domain  = new Tuple <double, double>(0, num);

                break;

            case 2:
                int intg = new int();
                X.CastTo(out intg);

                L = string.Format("{0:" + F + "}", intg);

                DataObj.Text    = intg.ToString();
                DataObj.Integer = intg;
                DataObj.Number  = (double)intg;
                DataObj.Domain  = new Tuple <double, double>(0, intg);
                break;

            case 3:
                Interval domain = new Interval();
                X.CastTo(out domain);

                L = string.Format("{0:" + F + "}" + " to " + "{1:" + F + "}", domain.T0, domain.T1);

                DataObj.Text           = domain.ToString();
                DataObj.Domain         = new Tuple <double, double>(domain.T0, domain.T1);
                DataObj.Point          = new wPoint(domain.T0, domain.T1, 0);
                DataObj.Graphics.Width = 10;
                break;

            case 4:
                Point3d point = new Point3d();
                X.CastTo(out point);

                L = string.Format("{0:" + F + "}", point.Z);

                DataObj.Text  = point.ToString();
                DataObj.Point = new wPoint(point.X, point.Y, point.Z);

                DataObj.Marker.Mode = wMarker.MarkerType.Circle;
                break;

            default:
                string text = "";
                X.CastTo(out text);
                L            = text;
                DataObj.Text = text;
                break;
            }

            switch (LabelStatus)
            {
            default:
                DataObj.Label.Content   = "";
                DataObj.ToolTip.Content = "";
                break;

            case 1:
                DataObj.Label.Enabled   = true;
                DataObj.Label.Content   = T;
                DataObj.ToolTip.Enabled = true;
                DataObj.ToolTip.Content = T;
                break;

            case 2:
                DataObj.Label.Enabled   = true;
                DataObj.Label.Content   = L;
                DataObj.ToolTip.Enabled = true;
                DataObj.ToolTip.Content = L;
                break;
            }

            DataObj.Graphics.FontObject.FontColor = wColors.Gray;
            DataObj.Graphics.Background           = wColors.VeryLightGray;
            DataObj.Graphics.StrokeColor          = wColors.OffWhite;
            DataObj.Graphics.SetUniformStrokeWeight(1);
            DataObj.Graphics.SetUniformPadding(2);

            DataObj.ToolTip.Graphics.Background           = new wColor(150, 250, 250, 250);
            DataObj.ToolTip.Graphics.FontObject.Size      = 10;
            DataObj.ToolTip.Graphics.FontObject.FontColor = wColors.Gray;

            wObject WindObject = new wObject(DataObj, "Pollen", "DataPoint");

            WindObject.Graphics = DataObj.Graphics;

            DA.SetData(0, WindObject);
        }
Ejemplo n.º 46
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)
        {
            dataAccess.SetData(0, false);

            bool run = false;

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


            string path_T3D = null;

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

            string path_gbXML = null;

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

            bool @override = false;

            if (!dataAccess.GetData(2, ref @override))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            bool fixNormals = true;

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

            bool zonesFromSpaces = true;

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

            bool useWidths = true;

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


            bool result = Core.Tas.Convert.ToT3D(path_T3D, path_gbXML, @override, fixNormals, zonesFromSpaces, useWidths);


            //SAM.Core.Tas.Import.ToT3D(path_T3D, path_gbXML, @override, fixNormals, zonesFromSpaces);

            //IGeometry geometry = objectWrapper.Value as IGeometry;

            dataAccess.SetData(0, result);
        }
Ejemplo n.º 47
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Brep   basebrep = new Brep();
            double height   = 0;
            bool   revers   = true;

            DA.GetData(0, ref basebrep);
            DA.GetData(1, ref height);
            DA.GetData(2, ref revers);

            List <Point3d>  ps      = new List <Point3d>();
            List <BrepEdge> be_list = new List <BrepEdge>();

            foreach (BrepTrim btr in basebrep.Loops[0].Trims)
            {
                be_list.Add(btr.Edge);
            }

            AddFirstEdge(be_list[0], be_list[1]);

            for (int i = 1; i < be_list.Count - 1; i++)
            {
                AddEdge(be_list[i]);
            }

            if (revers)
            {
                ps.Reverse();
            }

            Vector3d nv = Tools.GetFaceNormal(ps)[0];

            nv = new Vector3d(nv.X * height, nv.Y * height, nv.Z * height);

            List <FD_Vertex> basepolyline = new List <FD_Vertex>();

            foreach (Point3d pt in ps)
            {
                basepolyline.Add(new FD_Vertex(pt.X, pt.Y, pt.Z));
            }

            ps.Add(ps[0]);

            PolylineCurve pc = new PolylineCurve(ps);

            Surface extrusion = Surface.CreateExtrusion(pc, nv);

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

            bl.Add(basebrep);
            bl.Add(extrusion.ToBrep());

            Brep step1 = Brep.JoinBreps(bl, 0.1)[0];

            basebrep.Translate(nv);

            bl = new List <Brep>();
            bl.Add(basebrep);
            bl.Add(step1);

            Brep step2 = Brep.JoinBreps(bl, 0.1)[0];

            FD_Cube cube = new FD_Cube(basepolyline, height);

            DA.SetData(0, cube);
            DA.SetData(1, step2);

            bool SamePoint(Point3d p1, Point3d p2)
            {
                double dx = Math.Abs(p1.X - p2.X);
                double dy = Math.Abs(p1.Y - p2.Y);
                double dz = Math.Abs(p1.Z - p2.Z);

                if (dx < 0.001 && dy < 0.001 && dz < 0.001)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            void AddEdge(BrepEdge be)
            {
                if (SamePoint(ps[ps.Count - 1], be.PointAtStart))
                {
                    ps.Add(be.PointAtEnd);
                }
                else
                {
                    ps.Add(be.PointAtStart);
                }
            }

            void AddFirstEdge(BrepEdge be0, BrepEdge be1)
            {
                ps.Clear();

                if (SamePoint(be0.PointAtEnd, be1.PointAtEnd) || SamePoint(be0.PointAtEnd, be1.PointAtStart))
                {
                    ps.Add(be0.PointAtStart);
                    ps.Add(be0.PointAtEnd);
                }
                else
                {
                    ps.Add(be0.PointAtEnd);
                    ps.Add(be0.PointAtStart);
                }
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            IGH_Goo goo   = null;
            Image   image = new Image();

            if (!DA.GetData(0, ref goo))
            {
                return;
            }
            if (!goo.TryGetImage(ref image))
            {
                return;
            }

            int mode = 0;

            DA.GetData(1, ref mode);

            Interval valA = new Interval(0, 1);

            DA.GetData(2, ref valA);
            Interval valB = new Interval(0, 1);

            DA.GetData(3, ref valB);
            Interval valC = new Interval(0, 1);

            DA.GetData(4, ref valC);

            bool flip = true;

            DA.GetData(5, ref flip);

            Color color = Color.Black;

            DA.GetData(6, ref color);

            Filter filter = new Filter();

            switch ((FilterModes)mode)
            {
            case FilterModes.Channel:
                SetParameter(2, "R", "Red", "[0-1] Unitized adjustment value");
                SetParameter(3, "G", "Green", "[0-1] Unitized adjustment value");
                SetParameter(4, "B", "Blue", "[0-1] Unitized adjustment value");
                SetParameter(5, "F", "Outside", "Flip between inside and outside range");
                filter = new Channel(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip);
                image.Filters.Add(new Channel(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip));
                break;

            case FilterModes.HSL:
                SetParameter(2, "H", "Hue", "[0-1] Unitized adjustment value");
                SetParameter(3, "S", "Saturation", "[0-1] Unitized adjustment value");
                SetParameter(4, "L", "Luminance", "[0-1] Unitized adjustment value");
                SetParameter(5, "F", "Outside", "Flip between inside and outside range");
                SetParameter(6, "C", "Color", "Replacement Color");
                filter = new ColorFilter(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color);
                image.Filters.Add(new ColorFilter(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color));
                break;

            case FilterModes.RGB:
                SetParameter(2, "R", "Red", "[0-1] Unitized adjustment value");
                SetParameter(3, "G", "Green", "[0-1] Unitized adjustment value");
                SetParameter(4, "B", "Blue", "[0-1] Unitized adjustment value");
                SetParameter(5, "F", "Outside", "Flip between inside and outside range");
                SetParameter(6, "C", "Color", "Replacement Color");
                filter = new HSL(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color);
                image.Filters.Add(new HSL(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color));
                break;

            case FilterModes.YCbCr:
                SetParameter(2, "Y", "Y", "[0-1] Unitized adjustment value");
                SetParameter(3, "Cb", "Cb", "[0-1] Unitized adjustment value");
                SetParameter(4, "Cr", "Cr", "[0-1] Unitized adjustment value");
                SetParameter(5, "F", "Outside", "Flip between inside and outside range");
                SetParameter(6, "C", "Color", "Replacement Color");
                filter = new YCbCr(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color);
                image.Filters.Add(new YCbCr(valA.ToDomain(), valB.ToDomain(), valC.ToDomain(), flip, color));
                break;
            }

            message = ((FilterModes)mode).ToString();
            UpdateMessage();

            DA.SetData(0, image);
            DA.SetData(1, filter);
        }
Ejemplo n.º 49
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Point3d> pProjected = new List <Point3d>();

            string view = "";

            DA.GetData <string>(0, ref view);
            viewportName = view;
            ///Get viewport boundary
            Rhino.Display.RhinoView[] rvList = Rhino.RhinoDoc.ActiveDoc.Views.GetViewList(true, false);
            Rhino.Display.RhinoView   rv     = Rhino.RhinoDoc.ActiveDoc.Views.Find(view, true);

            if (!rvList.Contains(rv))
            {
                rv = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Viewport name is not valid. Using active viewport " + rv.ActiveViewport.Name);
            }


            Rhino.Display.RhinoViewport vp = rv.MainViewport;
            Point3d[] pNear = rv.MainViewport.GetNearRect();
            Point3d[] pFar  = rv.MainViewport.GetFarRect();

            ///Project viewport boundary to a plane
            for (int i = 0; i < pNear.Length; i++)
            {
                Vector3d  tVec  = pFar[i] - pNear[i];
                Transform trans = Transform.ProjectAlong(Plane.WorldXY, tVec);
                pNear[i].Transform(trans);
                pProjected.Add(pNear[i]);
            }

            ///Create polyline from project viewport boundary
            Polyline pL = new Polyline();

            pL.Add(pProjected[2]);
            pL.Add(pProjected[3]);
            pL.Add(pProjected[1]);
            pL.Add(pProjected[0]);
            pL.Add(pProjected[2]);


            ///Calculate recommended zoom level from viewport size
            BoundingBox bb     = pL.BoundingBox;
            Vector3d    dia    = bb.Diagonal;
            Double      maxDim = Math.Max(dia.X, dia.Y) * Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);
            Double      maxPix = Math.Max(vp.Size.Height, vp.Size.Width);


            ///https://gis.stackexchange.com/questions/19632/how-to-calculate-the-optimal-zoom-level-to-display-two-or-more-points-on-a-map
            ///diameter of earth at equator is approx 40,000km
            ///resolution = (512px*distance)/40,075,000 meters * 2^zoom
            ///2^zoom = (resolution * 40,000,000) / (512px * distance)
            Double a = (maxPix * 40075000) / (512 * maxDim * 1.2);

            ///Solve for zoom
            ///https://stackoverflow.com/questions/4016213/whats-the-opposite-of-javascripts-math-pow
            Double z = Math.Log(a) / Math.Log(2);


            ///make sure zoom doesn't get too ridiculous levels
            DA.SetData(0, pL);
            DA.SetData(1, Math.Min(z, 21));
        }
Ejemplo n.º 50
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {// the input curve
            Curve  tc       = null;
            Curve  tc2      = null;
            int    vertical = 0;
            int    around   = 0;
            int    degree   = 0;
            double angle    = 0;
            bool   flip     = false;

            DA.GetData(0, ref tc);
            DA.GetData(1, ref tc2);
            DA.GetData(2, ref vertical);
            DA.GetData(3, ref around);
            DA.GetData(4, ref degree);
            DA.GetData(5, ref angle);
            DA.GetData(6, ref flip);

            if (tc == null || !tc.IsValid || !tc.IsClosed)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "First input curve is either unvalid or not closed!"); return;
            }
            if (tc2 == null || !tc2.IsValid || !tc2.IsClosed)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Second input curve is either unvalid or not closed!"); return;
            }

            Curve _targetCurve  = tc;
            Curve _targetCurve2 = tc2;

            // number of control points, tells about the complexity of the curve
            int nrCont = _targetCurve.ToNurbsCurve().Points.Count;
            int crDeg  = _targetCurve.Degree;

            int idealDegree = nrCont * crDeg;
            int _degree     = Math.Min(Math.Max(10, idealDegree), 50);

            //  number of boundary subdivisions
            int _n      = 23 * _degree;
            int nrCont2 = _targetCurve2.ToNurbsCurve().Points.Count;
            int crDeg2  = _targetCurve2.Degree;

            int idealDegree2 = nrCont2 * crDeg2;
            int _degree2     = Math.Min(Math.Max(10, idealDegree2), 50);
            int _n2          = 23 * _degree2;

            int deg;

            if (degree == 0)
            {
                deg = Math.Max(_degree, _degree2);
            }
            else
            {
                deg = degree;
            }

            double[] t             = _targetCurve.DivideByCount(_n, true);
            var      _targetPoints = Enumerable.Range(0, _n).Select(i => _targetCurve.PointAt(flip ? 1 - t[i] : t[i])).ToList();

            double[] t2             = _targetCurve2.DivideByCount(_n2, true);
            var      _targetPoints2 = Enumerable.Range(0, _n2).Select(i => _targetCurve2.PointAt(t2[(i + (int)((double)_n2 * (angle / 2 * Math.PI))) % _n2])).ToList();

            double R1 = 0.5;
            double R2 = 1.5;

            // now, do the actual work and compute the three complex polynomials
            // ok, let's get the coefficients
            List <double> xs1 = _targetPoints.Select(o => o.X).ToList();  // 1 ms
            List <double> xs2 = _targetPoints2.Select(o => o.X).ToList(); // 1 ms
                                                                          //        LaplaceData kx = new LaplaceData(xs1, deg); <-- if it's just one curve
            AnnularLaplaceData akx = new AnnularLaplaceData(xs1, R1, xs2, R2, deg);

            List <double> ys1 = _targetPoints.Select(o => o.Y).ToList();  // 1 ms
            List <double> ys2 = _targetPoints2.Select(o => o.Y).ToList(); // 1 ms
                                                                          //       LaplaceData ky = new LaplaceData(ys1, deg);
            AnnularLaplaceData aky = new AnnularLaplaceData(ys1, R1, ys2, R2, deg);

            List <double> zs1 = _targetPoints.Select(o => o.Z).ToList();  // 1 ms
            List <double> zs2 = _targetPoints2.Select(o => o.Z).ToList(); // 1 ms
                                                                          //       LaplaceData kkz = new LaplaceData(zs1, deg);
            AnnularLaplaceData akkz = new AnnularLaplaceData(zs1, R1, zs2, R2, deg);

            var MM = UncappedCylinder(around, vertical);

            var Cyl = MM.DuplicateMesh();



            // bottleneck
            // can't be done with MM.Vertices.GetEnumerator() I guess

            for (int ii = 0; ii < MM.Vertices.Count; ii++)
            {
                var x = MM.Vertices[ii].X;
                var y = MM.Vertices[ii].Y;
                var z = MM.Vertices[ii].Z;
                var f = (R1 + z * (R2 - R1)) / Math.Sqrt(x * x + y * y);
                var p = new Point2d(f * x, f * y);
                MM.Vertices.SetVertex(ii, akx.eval(p), aky.eval(p), akkz.eval(p));
            }

            DA.SetData(0, MM);

            DA.SetData(1, Enumerable.Range(0, Cyl.Vertices.Count).Average(
                           ii =>
            {
                var x = Cyl.Vertices[ii].X;
                var y = Cyl.Vertices[ii].Y;
                var z = Cyl.Vertices[ii].Z;
                var f = (R1 + z * (R2 - R1)) / Math.Sqrt(x * x + y * y);
                var p = new Point2d(f * x, f * y);

                var gg = Math.Pow(
                    akx.drtimesdtheta(p) + aky.drtimesdtheta(p) + akkz.drtimesdtheta(p), 2);
                return(gg);
            }
                           )
                       );
        }
Ejemplo n.º 51
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Target target = null;

            if (!DA.GetData("Target", ref target))
            {
                return;
            }

            bool isCartesian = target.Value is CartesianTarget;
            // if (isTargetCartesian != isCartesian) SwitchCartesian();

            bool hasJoints   = Params.Output.Any(x => x.Name == "Joints");
            bool hasPlane    = Params.Output.Any(x => x.Name == "Plane");
            bool hasConfig   = Params.Output.Any(x => x.Name == "RobConf");
            bool hasMotion   = Params.Output.Any(x => x.Name == "Motion");
            bool hasTool     = Params.Output.Any(x => x.Name == "Tool");
            bool hasSpeed    = Params.Output.Any(x => x.Name == "Speed");
            bool hasZone     = Params.Output.Any(x => x.Name == "Zone");
            bool hasCommand  = Params.Output.Any(x => x.Name == "Command");
            bool hasFrame    = Params.Output.Any(x => x.Name == "Frame");
            bool hasExternal = Params.Output.Any(x => x.Name == "External");

            if (hasJoints)
            {
                DA.SetData("Joints", isCartesian ? null : new GH_String(string.Join(",", (target.Value as JointTarget).Joints.Select(x => $"{x:0.000}"))));
            }
            if (hasPlane)
            {
                DA.SetData("Plane", isCartesian ? new GH_Plane((target.Value as CartesianTarget).Plane) : null);
            }
            if (hasConfig)
            {
                DA.SetData("RobConf", isCartesian ? (target.Value as CartesianTarget).Configuration == null ? null : new GH_Integer((int)(target.Value as CartesianTarget).Configuration) : null);
            }
            if (hasMotion)
            {
                DA.SetData("Motion", isCartesian ? new GH_String((target.Value as CartesianTarget).Motion.ToString()) : null);
            }
            if (hasTool && (target.Value.Tool != null))
            {
                DA.SetData("Tool", new GH_Tool(target.Value.Tool));
            }
            if (hasSpeed && (target.Value.Speed != null))
            {
                DA.SetData("Speed", new GH_Speed(target.Value.Speed));
            }
            if (hasZone && (target.Value.Zone != null))
            {
                DA.SetData("Zone", new GH_Zone(target.Value.Zone));
            }
            if (hasCommand)
            {
                DA.SetData("Command", new GH_Command(target.Value.Command));
            }
            if (hasFrame)
            {
                DA.SetData("Frame", new GH_Frame(target.Value.Frame));
            }
            if (hasExternal)
            {
                DA.SetData("External", new GH_String(string.Join(",", target.Value.External.Select(x => $"{x:0.000}"))));
            }
        }
Ejemplo n.º 52
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");
            }
        }
Ejemplo n.º 53
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)
        {
            bool run = false;

            if (!dataAccess.GetData(1, ref run) || !run)
            {
                return;
            }

            GH_ObjectWrapper objectWrapper = null;

            if (!dataAccess.GetData(0, ref objectWrapper) || objectWrapper.Value == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

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

            dynamic obj = objectWrapper.Value;

            if (obj is RhinoInside.Revit.GH.Types.ProjectDocument)
            {
                Document     document = ((RhinoInside.Revit.GH.Types.ProjectDocument)obj).Value;
                List <Panel> panels   = Analytical.Revit.Convert.ToSAM_Panels(document, convertSettings);
                if (panels != null)
                {
                    sAMObjects = panels.Cast <Core.ISAMObject>();
                }

                if (sAMObjects == null || sAMObjects.Count() == 0)
                {
                    message = string.Format("Cannot convert Document.");
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                    dataAccess.SetData(1, message);

                    return;
                }

                dataAccess.SetDataList(0, sAMObjects);

                message = string.Format("Document converted");
                dataAccess.SetData(1, message);

                return;
            }

            ElementId aId = obj.Id as ElementId;

            Element element = (obj.Document as Document).GetElement(aId);

            if (element == null)
            {
                message = "Invalid Element";
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                dataAccess.SetData(1, message);

                return;
            }

            if (element is FamilyInstance && ((FamilyInstance)element).Symbol.Family.IsInPlace)
            {
                message = string.Format("Cannot convert In-Place family. ElementId: {0} ", element.Id.IntegerValue);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                dataAccess.SetData(1, message);

                return;
            }


            if (element is RevitLinkInstance)
            {
                List <Panel> panels = Analytical.Revit.Convert.ToSAM_Panels((RevitLinkInstance)element, convertSettings);
                if (panels != null)
                {
                    sAMObjects = panels.Cast <Core.ISAMObject>();
                }
            }
            else
            {
                try
                {
                    sAMObjects = Analytical.Revit.Convert.ToSAM(element, convertSettings);
                }
                catch (Exception exception)
                {
                    message = string.Format("Cannot convert Element. ElementId: {0} Category: {1} Exception: {2}", element.Id.IntegerValue, element.Category.Name, exception.Message);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                    dataAccess.SetData(1, message);
                }
            }

            if (sAMObjects == null || sAMObjects.Count() == 0)
            {
                message = string.Format("Cannot convert Element. ElementId: {0} Category: {1}", element.Id.IntegerValue, element.Category.Name);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, message);
                dataAccess.SetData(1, message);

                return;
            }

            dataAccess.SetDataList(0, sAMObjects);

            message = string.Format("Element converted. ElementId: {0} Category: {1}", element.Id.IntegerValue, element.Category.Name);
            dataAccess.SetData(1, message);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string ID   = this.Attributes.InstanceGuid.ToString();
            string name = new GUIDtoAlpha(Convert.ToString(ID + Convert.ToString(this.RunCount)), false).Text;
            int    C    = this.RunCount;

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

            var pCtrl = new pListBox(name);

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

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

            //Set Unique Control Properties

            List <string> V = new List <string>();
            int           I = -1;

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

            pCtrl.SetProperties(V, I);


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

            Elements[this.RunCount] = WindObject;

            DA.SetData(0, WindObject);
        }
Ejemplo n.º 55
0
    private int runCount;                              //Legacy field.

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

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

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

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

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

        double y = default(double);

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

        double z = default(double);

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



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


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

        try
        {
            //5. Assign output parameters to component...
            if (A != null)
            {
                if (GH_Format.TreatAsCollection(A))
                {
                    IEnumerable __enum_A = (IEnumerable)(A);
                    DA.SetDataList(1, __enum_A);
                }
                else
                {
                    if (A is Grasshopper.Kernel.Data.IGH_DataTree)
                    {
                        //merge tree
                        DA.SetDataTree(1, (Grasshopper.Kernel.Data.IGH_DataTree)(A));
                    }
                    else
                    {
                        //assign direct
                        DA.SetData(1, A);
                    }
                }
            }
            else
            {
                DA.SetData(1, null);
            }
        }
        catch (Exception ex)
        {
            this.__err.Add(string.Format("Script exception: {0}", ex.Message));
        }
        finally
        {
            //Add errors and messages...
            if (owner.Params.Output.Count > 0)
            {
                if (owner.Params.Output[0] is Grasshopper.Kernel.Parameters.Param_String)
                {
                    List <string> __errors_plus_messages = new List <string>();
                    if (this.__err != null)
                    {
                        __errors_plus_messages.AddRange(this.__err);
                    }
                    if (this.__out != null)
                    {
                        __errors_plus_messages.AddRange(this.__out);
                    }
                    if (__errors_plus_messages.Count > 0)
                    {
                        DA.SetDataList(0, __errors_plus_messages);
                    }
                }
            }
        }
    }
Ejemplo n.º 56
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            Types.GraphicalElement element = default;
            if (!DA.GetData("Element", ref element))
            {
                return;
            }

            bool?facing = default;
            {
                var _Facing_ = Params.IndexOfInputParam("Facing");
                if (_Facing_ >= 0 && Params.Input[_Facing_].DataType != GH_ParamData.@void)
                {
                    bool flipped = false;
                    if (DA.GetData(_Facing_, ref flipped))
                    {
                        facing = flipped;
                    }
                }
                if (facing.HasValue && !element.CanFlipFacing)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Facing can not be flipped for this element. {{{element.Id.IntegerValue}}}");
                    return;
                }
            }

            bool?hand = default;
            {
                var _Hand_ = Params.IndexOfInputParam("Hand");
                if (_Hand_ >= 0 && Params.Input[_Hand_].DataType != GH_ParamData.@void)
                {
                    bool flipped = false;
                    if (DA.GetData(_Hand_, ref flipped))
                    {
                        hand = flipped;
                    }
                }
                if (hand.HasValue && !element.CanFlipFacing)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Hand can not be flipped for this element. {{{element.Id.IntegerValue}}}");
                    return;
                }
            }

            bool?workplane = default;

            {
                var _WorkPlane_ = Params.IndexOfInputParam("Work Plane");
                if (_WorkPlane_ >= 0 && Params.Input[_WorkPlane_].DataType != GH_ParamData.@void)
                {
                    bool flipped = false;
                    if (DA.GetData(_WorkPlane_, ref flipped))
                    {
                        workplane = flipped;
                    }
                }
                if (workplane.HasValue && !element.CanFlipWorkPlane)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Work Plane can not be flipped for this element. {{{element.Id.IntegerValue}}}");
                    return;
                }
            }

            if (facing.HasValue || hand.HasValue || workplane.HasValue)
            {
                StartTransaction(element.Document);
                {
                    element.FacingFlipped    = facing;
                    element.HandFlipped      = hand;
                    element.WorkPlaneFlipped = workplane;

                    if (element is IGH_PreviewMeshData preview)
                    {
                        preview.DestroyPreviewMeshes();
                    }
                }
            }

            DA.SetData("Element", element);
            DA.SetData("Facing", element.FacingFlipped);
            DA.SetData("Hand", element.HandFlipped);
            DA.SetData("Work Plane", element.WorkPlaneFlipped);
        }
        //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);
            //DA.SetData(4, _pendingRelease);

            //// 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);
                DA.SetData(4, _pendingRelease);
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            iPoints = new List <Point3d>();
            DA.GetDataList <Point3d>("Points", iPoints);
            iApicals = new List <Circle>();
            DA.GetDataList <Circle>("Apicals", iApicals);
            iMasses = new List <double>();
            DA.GetDataList <double>("Masses", iMasses);
            DA.GetData <Curve>("Boundary Curve", ref iBoundaryCurve);
            DA.GetData <double>("Rest Length Scale", ref iRestLengthScale);
            DA.GetData <double>("Rest Length Offset", ref iRestLengthOffset);
            DA.GetData <double>("Stiffness", ref iStiffness);
            DA.GetData <double>("Bending Stiffness", ref iBendingStiffness);
            DA.GetData <bool>("In/Out Switch", ref iInOutSwitch);
            DA.GetData <double>("In/Out Threshold", ref iInOutThreshold);
            DA.GetData <double>("Boundary Vertex Threshold", ref iBoundaryVertexThreshold);
            iFixedPointExclusion = new List <Curve>();
            DA.GetDataList <Curve>("Fixed Point Exclusion", iFixedPointExclusion);
            iFixedPointInclusion = new List <Curve>();
            DA.GetDataList <Curve>("Fixed Point Inclusion", iFixedPointInclusion);


            // ===========================================================================================
            // Compute Delaunay Triangulation
            // ===========================================================================================

            List <DelaunayVertex> delaunayVertices = new List <DelaunayVertex>();

            foreach (Point3d point in iPoints)
            {
                delaunayVertices.Add(new DelaunayVertex(point.X, point.Y));
            }

            List <Triad> triads = new DelaunayTriangulator().Triangulation(delaunayVertices);

            HashSet <Tuple <int, int> > delaunayEdgeTuples = new HashSet <Tuple <int, int> >();


            for (int i = 0; i < triads.Count; i++)
            {
                Triad triad = triads[i];
                delaunayEdgeTuples.Add(triad.a < triad.b ? new Tuple <int, int>(triad.a, triad.b) : new Tuple <int, int>(triad.b, triad.a));
                delaunayEdgeTuples.Add(triad.b < triad.c ? new Tuple <int, int>(triad.b, triad.c) : new Tuple <int, int>(triad.c, triad.b));
                delaunayEdgeTuples.Add(triad.c < triad.a ? new Tuple <int, int>(triad.c, triad.a) : new Tuple <int, int>(triad.a, triad.c));
            }


            // ===========================================================================================
            // Convert Delaunay mesh to particle-spring mesh
            // ===========================================================================================

            oSpringMesh = new SpringMesh();
            Curve boundaryCurveXY = Curve.ProjectToPlane(iBoundaryCurve, Plane.WorldXY);

            // Create edge list -----------------------------------------------------------------------------------------------

            foreach (Tuple <int, int> delaunayEdgeTuple in delaunayEdgeTuples)
            {
                Point3d A = iPoints[delaunayEdgeTuple.Item1];
                Point3d B = iPoints[delaunayEdgeTuple.Item2];
                Point3d M = 0.5 * (A + B);

                // Skip if the edge lies outside of the boundary
                double t;
                boundaryCurveXY.ClosestPoint(M, out t);
                Point3d N = boundaryCurveXY.PointAt(t);
                if (Vector3d.CrossProduct(boundaryCurveXY.TangentAt(t), M - N).Z *(iInOutSwitch ? -1.0 : 1.0) < 0.0 &&
                    Utils.DistanceSquared(M, N) > iInOutThreshold * iInOutThreshold)
                {
                    continue;
                }

                double edgeLength = Utils.Distance(A, B);
                double restLength = iRestLengthScale * edgeLength + iRestLengthOffset;
                oSpringMesh.Edges.Add(new Edge(delaunayEdgeTuple.Item1, delaunayEdgeTuple.Item2, restLength, iStiffness, Math.PI, iBendingStiffness));
            }

            // Create vertex list -----------------------------------------------------------------------------------------------

            List <HashSet <int> > neighborVerticesSets = new List <HashSet <int> >();

            for (int i = 0; i < iPoints.Count; i++)
            {
                neighborVerticesSets.Add(new HashSet <int>());
            }

            foreach (Edge edge in oSpringMesh.Edges)
            {
                neighborVerticesSets[edge.FirstVertexIndex].Add(edge.SecondVertexIndex);
                neighborVerticesSets[edge.SecondVertexIndex].Add(edge.FirstVertexIndex);
            }

            for (int i = 0; i < iPoints.Count; i++)
            {
                Point3d p = iPoints[i];
                double  t;
                boundaryCurveXY.ClosestPoint(p, out t);

                bool vertexFixedness  = false;
                bool isBoundaryVertex = false;
                bool isColumnVertex   = false;

                if (Utils.Distance(p, boundaryCurveXY.PointAt(t)) < iBoundaryVertexThreshold)
                {
                    vertexFixedness  = true;
                    isBoundaryVertex = true;
                }
                else
                {
                    foreach (Curve curve in iFixedPointInclusion)
                    {
                        if (curve.Contains(p) == PointContainment.Inside)
                        {
                            vertexFixedness = true;
                            isColumnVertex  = true;
                            break;
                        }
                    }
                }


                Vertex vertex = new Vertex(p, Vector3d.Zero, neighborVerticesSets[i].ToList <int>(), iMasses.Count == 1 ? iMasses[0] : iMasses[i], vertexFixedness);
                vertex.IsBoundaryVertex = isBoundaryVertex;
                vertex.IsColumnVertex   = isColumnVertex;
                oSpringMesh.Vertices.Add(vertex);
            }


            // Set boundary edge -----------------------------------------------------------------------------------------------

            foreach (Edge edge in oSpringMesh.Edges)
            {
                if (oSpringMesh.Vertices[edge.FirstVertexIndex].IsBoundaryVertex && oSpringMesh.Vertices[edge.SecondVertexIndex].IsBoundaryVertex)
                {
                    edge.IsBoundaryEdge = true;
                }
                else if (oSpringMesh.Vertices[edge.FirstVertexIndex].IsColumnVertex && oSpringMesh.Vertices[edge.SecondVertexIndex].IsColumnVertex)
                {
                    edge.IsColumnEdge = true;
                }
            }

            // Create triangle list ------------------------------------------------------------------------------------------------

            Dictionary <Tuple <int, int, int>, int> tripletDict = new Dictionary <Tuple <int, int, int>, int>();

            for (int k = 0; k < oSpringMesh.Edges.Count; k++)
            {
                Edge   edge = oSpringMesh.Edges[k];
                Vertex A    = oSpringMesh.Vertices[edge.FirstVertexIndex];
                Vertex B    = oSpringMesh.Vertices[edge.SecondVertexIndex];

                for (int i = 0; i < A.NeighborVertexIndices.Count; i++)
                {
                    for (int j = 0; j < B.NeighborVertexIndices.Count; j++)
                    {
                        if (A.NeighborVertexIndices[i] == B.NeighborVertexIndices[j])
                        {
                            Tuple <int, int, int> triplet = sortTriplet(edge.FirstVertexIndex, edge.SecondVertexIndex, A.NeighborVertexIndices[i]);

                            if (tripletDict.ContainsKey(triplet))
                            {
                                if (edge.FirstTriangleIndex < 0)
                                {
                                    edge.FirstTriangleIndex       = tripletDict[triplet];
                                    edge.FirstAdjacentVertexIndex = A.NeighborVertexIndices[i];
                                }
                                else
                                {
                                    edge.SecondTriangleIndex       = tripletDict[triplet];
                                    edge.SecondAdjacentVertexIndex = A.NeighborVertexIndices[i];
                                }
                            }
                            else
                            {
                                oSpringMesh.Triangles.Add(new Triangle(triplet.Item1, triplet.Item2, triplet.Item3));

                                int triangleIndex = oSpringMesh.Triangles.Count - 1;

                                if (edge.FirstTriangleIndex < 0)
                                {
                                    edge.FirstTriangleIndex       = triangleIndex;
                                    edge.FirstAdjacentVertexIndex = A.NeighborVertexIndices[i];
                                }
                                else
                                {
                                    edge.SecondTriangleIndex       = triangleIndex;
                                    edge.SecondAdjacentVertexIndex = A.NeighborVertexIndices[i];
                                }

                                tripletDict.Add(triplet, triangleIndex);
                            }
                        }
                    }
                }
            }

            // ===========================================================================================
            // Compute edge indices for each triangle
            // ===========================================================================================

            for (int i = 0; i < oSpringMesh.Edges.Count; i++)
            {
                Edge edge = oSpringMesh.Edges[i];

                Triangle triangle = oSpringMesh.Triangles[edge.FirstTriangleIndex];
                if (triangle.FirstEdgeIndex == -1)
                {
                    triangle.FirstEdgeIndex = i;
                }
                else if (triangle.SecondEdgeIndex == -1)
                {
                    triangle.SecondEdgeIndex = i;
                }
                else
                {
                    triangle.ThirdEdgeIndex = i;
                }

                if (edge.SecondTriangleIndex == -1)
                {
                    continue;
                }

                triangle = oSpringMesh.Triangles[edge.SecondTriangleIndex];
                if (triangle.FirstEdgeIndex == -1)
                {
                    triangle.FirstEdgeIndex = i;
                }
                else if (triangle.SecondEdgeIndex == -1)
                {
                    triangle.SecondEdgeIndex = i;
                }
                else
                {
                    triangle.ThirdEdgeIndex = i;
                }
            }


            // ===========================================================================================
            // Rearange the vertex order in each triangle so the normal calculation is consistent
            // ===========================================================================================

            for (int i = 0; i < oSpringMesh.Triangles.Count; i++)
            {
                if (oSpringMesh.ComputeTriangleNormal(i).Z < 0.0)
                {
                    int temp = oSpringMesh.Triangles[i].SecondVertexIndex;
                    oSpringMesh.Triangles[i].SecondVertexIndex = oSpringMesh.Triangles[i].ThirdVertexIndex;
                    oSpringMesh.Triangles[i].ThirdVertexIndex  = temp;
                }
            }


            // ===========================================================================================
            // Rearranging edge adjacent vertex indices for consitency
            // ===========================================================================================

            foreach (Edge edge in oSpringMesh.Edges)
            {
                if (edge.SecondAdjacentVertexIndex == -1)
                {
                    Point3d A = oSpringMesh.Vertices[edge.FirstVertexIndex].Position;
                    Point3d B = oSpringMesh.Vertices[edge.SecondVertexIndex].Position;
                    Point3d M = oSpringMesh.Vertices[edge.FirstAdjacentVertexIndex].Position;

                    if (Vector3d.CrossProduct(B - A, M - A) * oSpringMesh.ComputeTriangleNormal(edge.FirstTriangleIndex) < 0.0)
                    {
                        Point3d temp = A;
                        A = B;
                        B = temp;
                    }
                }
                else
                {
                    Point3d A = oSpringMesh.Vertices[edge.FirstVertexIndex].Position;
                    Point3d B = oSpringMesh.Vertices[edge.SecondVertexIndex].Position;
                    Point3d M = oSpringMesh.Vertices[edge.FirstAdjacentVertexIndex].Position;
                    Point3d N = oSpringMesh.Vertices[edge.SecondAdjacentVertexIndex].Position;

                    if (Vector3d.CrossProduct(B - A, M - A) * oSpringMesh.ComputeTriangleNormal(edge.FirstAdjacentVertexIndex) < 0.0)
                    {
                        int temp = edge.FirstAdjacentVertexIndex;
                        edge.FirstAdjacentVertexIndex  = edge.SecondAdjacentVertexIndex;
                        edge.SecondAdjacentVertexIndex = temp;

                        temp = edge.FirstTriangleIndex;
                        edge.FirstTriangleIndex  = edge.SecondTriangleIndex;
                        edge.SecondTriangleIndex = temp;
                    }
                }
            }

            // ===========================================================================================
            // Compute adjacent vertex index for each triangle
            // ===========================================================================================

            //foreach (Triangle triangle in oSpringMesh.Triangles)
            //{
            //    Vertex firstVertex = oSpringMesh.Vertices[triangle.FirstVertexIndex];
            //    Vertex secondVertex = oSpringMesh.Vertices[triangle.SecondVertexIndex];
            //    Vertex thirdVertex = oSpringMesh.Vertices[triangle.ThirdVertexIndex];

            //    foreach (int firstNeighbourIndex in firstVertex.NeighborVertexIndices)
            //        foreach (int secondNeighbourIndex in secondVertex.NeighborVertexIndices)
            //            if (firstNeighbourIndex == secondNeighbourIndex && firstNeighbourIndex != triangle.ThirdVertexIndex)
            //                triangle.FirstSecondAdjacentVertexIndex = firstNeighbourIndex;

            //    foreach (int secondNeighbourIndex in secondVertex.NeighborVertexIndices)
            //        foreach (int thirdNeighbourIndex in thirdVertex.NeighborVertexIndices)
            //            if (secondNeighbourIndex == thirdNeighbourIndex && secondNeighbourIndex != triangle.FirstVertexIndex)
            //                triangle.SecondThirdAdjacentVertexIndex = secondNeighbourIndex;

            //    foreach (int thirdNeighbourIndex in thirdVertex.NeighborVertexIndices)
            //        foreach (int firstNeighbourIndex in firstVertex.NeighborVertexIndices)
            //            if (thirdNeighbourIndex == firstNeighbourIndex && thirdNeighbourIndex != triangle.SecondVertexIndex)
            //                triangle.ThirdFirstAdjacentVertexIndex = thirdNeighbourIndex;
            //}


            // ===========================================================================================
            // 3D Boundary Curve
            // ===========================================================================================

            //Brep brep = Brep.CreatePatch(new List<GeometryBase>() { iBoundaryCurve }, null, DocumentTolerance());

            //DA.SetDataList(2, new List<Brep>() { brep });

            foreach (Vertex vertex in oSpringMesh.Vertices)
            {
                if (vertex.IsBoundaryVertex)
                {
                    double t;
                    boundaryCurveXY.ClosestPoint(vertex.Position, out t);
                    Plane frame;
                    boundaryCurveXY.PerpendicularFrameAt(t, out frame);

                    CurveIntersections curveInteresections = Intersection.CurvePlane(iBoundaryCurve, frame, DocumentTolerance());

                    Point3d intersection = Point3d.Unset;
                    double  minDist      = 999999.0;

                    for (int i = 0; i < curveInteresections.Count; i++)
                    {
                        double d = vertex.Position.DistanceTo(curveInteresections[i].PointA);
                        if (d < minDist)
                        {
                            minDist      = d;
                            intersection = curveInteresections[i].PointA;
                        }
                    }

                    vertex.Position = intersection;
                }
                else
                {
                    //LineCurve lineCurve = new LineCurve(
                    //    new Point3d(vertex.Position.X, vertex.Position.Y, vertex.Position.Z - 10.0),
                    //    new Point3d(vertex.Position.X, vertex.Position.Y, vertex.Position.Z + 10.0)
                    //    );

                    //Curve[] overlapCurves;
                    //Point3d[] intersectionPoints;
                    //Intersection.CurveBrep(lineCurve, brep, DocumentTolerance(), out overlapCurves, out intersectionPoints);

                    //if (intersectionPoints.Length > 0)
                    //    vertex.Position = intersectionPoints[0];
                }
            }

            // ===========================================================================================
            // Initial curving bias
            // ===========================================================================================

            DA.GetData <double>("Initial Curving Bias", ref iInitialCurvingBias);
            DA.GetData <bool>("Bias Apical Regions", ref iBiasApicalRegion);

            foreach (Vertex vertex in oSpringMesh.Vertices)
            {
                if (vertex.IsBoundaryVertex || vertex.IsFixed)
                {
                    continue;
                }
                vertex.Position.Z = computeBiasHeight(vertex.Position, iBiasApicalRegion, boundaryCurveXY);
            }


            // ===========================================================================================
            // Conclusion
            // ===========================================================================================

            foreach (Edge edge in oSpringMesh.Edges)
            {
                oDebugCurves1.Add(new LineCurve(oSpringMesh.Vertices[edge.FirstVertexIndex].Position, oSpringMesh.Vertices[edge.SecondVertexIndex].Position));
            }

            DA.SetData(0, oInfo);
            DA.SetDataList(1, oDebugCurves1);
            DA.SetData(6, oSpringMesh);
        }
Ejemplo 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)
        {
            //Global variables
            PlanktonMesh pMeshOrig = new PlanktonMesh();

            DA.GetData(0, ref pMeshOrig);

            Surface targetSrf = null;

            DA.GetData(1, ref targetSrf);

            List <Vector3d> directions = new List <Vector3d>();

            DA.GetDataList(2, directions);

            Matrix mV = null;

            DA.GetData(3, ref mV);

            int k = 1;

            DA.GetData(4, ref k);
            if (k < 1)
            {
                k = 1;
            }
            else if (k > mV.ColumnCount)
            {
                k = mV.ColumnCount;
            }

            int opt = 0;

            DA.GetData(5, ref opt);
            if (opt < 0)
            {
                opt = 0;
            }
            else if (opt > 1)
            {
                opt = 1;
            }

            bool preset = false;

            DA.GetData(6, ref preset);

            //--------------------------------------------------------

            //Distance signal
            List <double> distanceSignal = calcDistSignal(pMeshOrig, directions, targetSrf);

            //All weights
            List <double> weights = calcMHT(distanceSignal, mV);
            double        scale   = calcScaleFactor(weights);

            List <double> weightsN = calcNormalisedWeights(weights, scale);          //normalised by scale factor


            //Sorting - eigenvector indices
            List <int> eigsVIndices = new List <int>();

            //k most significant eigenvectors
            if (opt == 0)
            {
                eigsVIndices = calcSignificantEigs(weightsN, k);
            }
            //first k eigenvectors
            else if (opt == 1)
            {
                for (int j = 0; j < k; j++)
                {
                    eigsVIndices.Add(j);
                }
            }


            //Extract the weights accordingly
            List <double> weightsNExtract = extractWeights(weightsN, eigsVIndices);


            //RMS
            double rms = calcRMS(pMeshOrig, mV, eigsVIndices, weightsNExtract, scale, directions, distanceSignal);


            //Preset slider values
            if (preset)
            {
                List <String> nicknames = new List <string>();
                List <double> values    = new List <double>();

                for (int i = 0; i < weightsNExtract.Count; i++)
                {
                    nicknames.Add(String.Format("w{0}", i));
                    values.Add(weightsNExtract[i]);
                }

                nicknames.Add("scale");
                values.Add(scale);

                presetSliders(nicknames, values);
            }


            //-------------------------------------------------------

            //Output
            DA.SetDataList(0, eigsVIndices);
            DA.SetDataList(1, weightsNExtract);
            DA.SetData(2, scale);
            DA.SetData(3, rms);
        }
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            // get input
            Types.DataObject <DB.CompoundStructure> dataObj = default;
            if (!DA.GetData("Compound Structure", ref dataObj))
            {
                return;
            }

            DB.CompoundStructure cstruct = dataObj.Value;

            // Deconstruct the data object into output params
            DA.SetData("Width", cstruct.GetWidth());
            DA.SetDataList("Layers", cstruct.GetLayers().Select(x => new Types.DataObject <DB.CompoundStructureLayer>(apiObject: x, srcDocument: dataObj.Document)).ToList());
            DA.SetData("Layer Count", cstruct.LayerCount);
            DA.SetData("Cutoff Height", cstruct.CutoffHeight);
            DA.SetData("End Cap Condition", new Types.EndCapCondition(cstruct.EndCap));
            DA.SetData("Has Structural Deck", cstruct.HasStructuralDeck);
            DA.SetData("Is Vertically Compound", cstruct.IsVerticallyCompound);
            DA.SetData("Sample Height", cstruct.SampleHeight);
            DA.SetData("Minimum Sample Height", cstruct.MinimumSampleHeight);
            DA.SetData("Opening Wrapping Condition", new Types.OpeningWrappingCondition(cstruct.OpeningWrapping));
            DA.SetData("Structural Material Index", cstruct.StructuralMaterialIndex);
            DA.SetData("Variable Layer Index", cstruct.VariableLayerIndex);
            DA.SetData("First Core Layer Index", cstruct.GetFirstCoreLayerIndex());
            DA.SetData("Last Core Layer Index", cstruct.GetLastCoreLayerIndex());
            DA.SetData("Minimum Allowable Layer Thickness", DB.CompoundStructure.GetMinimumLayerThickness());
        }