示例#1
0
文件: Util.cs 项目: tsvilans/Robots
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;

            DA.GetData(0, ref program);

            var path        = DA.ParameterTargetPath(0);
            var cellTargets = program.Value.Targets;
            var groupCount  = cellTargets[0].ProgramTargets.Count;

            var planes        = new GH_Structure <GH_Plane>();
            var joints        = new GH_Structure <GH_Number>();
            var configuration = new GH_Structure <GH_String>();
            var deltaTime     = new GH_Structure <GH_Number>();

            for (int i = 0; i < groupCount; i++)
            {
                var tempPath = path.AppendElement(i);
                for (int j = 0; j < cellTargets.Count; j++)
                {
                    planes.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Planes.Select(x => new GH_Plane(x)), tempPath.AppendElement(j));
                    joints.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Joints.Select(x => new GH_Number(x)), tempPath.AppendElement(j));
                    configuration.Append(new GH_String(cellTargets[j].ProgramTargets[i].Kinematics.Configuration.ToString()), tempPath);
                    deltaTime.Append(new GH_Number(cellTargets[j].DeltaTime), tempPath);
                }
            }

            DA.SetDataTree(0, planes);
            DA.SetDataTree(1, joints);
            DA.SetDataTree(2, configuration);
            DA.SetDataTree(3, deltaTime);
        }
示例#2
0
文件: Util.cs 项目: visose/Robots
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GH_Program program = null;
            DA.GetData(0, ref program);

            var path = DA.ParameterTargetPath(0);
            var cellTargets = program.Value.Targets;
            var groupCount = cellTargets[0].ProgramTargets.Count;

            var planes = new GH_Structure<GH_Plane>();
            var joints = new GH_Structure<GH_Number>();
            var configuration = new GH_Structure<GH_String>();
            var deltaTime = new GH_Structure<GH_Number>();

            for (int i = 0; i < groupCount; i++)
            {
                var tempPath = path.AppendElement(i);
                for (int j = 0; j < cellTargets.Count; j++)
                {
                    planes.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Planes.Select(x => new GH_Plane(x)), tempPath.AppendElement(j));
                    joints.AppendRange(cellTargets[j].ProgramTargets[i].Kinematics.Joints.Select(x => new GH_Number(x)), tempPath.AppendElement(j));
                    configuration.Append(new GH_String(cellTargets[j].ProgramTargets[i].Kinematics.Configuration.ToString()), tempPath);
                    deltaTime.Append(new GH_Number(cellTargets[j].DeltaTime), tempPath);
                }
            }

            DA.SetDataTree(0, planes);
            DA.SetDataTree(1, joints);
            DA.SetDataTree(2, configuration);
            DA.SetDataTree(3, deltaTime);
        }
示例#3
0
文件: Program.cs 项目: visose/Robots
        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");
            }
        }
示例#4
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            if (!Params.GetData(DA, "View", out Types.View view, x => x.IsValid))
            {
                return;
            }
            if (!Params.GetDataList(DA, "Elements", out IList <Types.Element> elements))
            {
                return;
            }
            if (!Params.TryGetDataList(DA, "Exclude", out IList <Types.Element> exclude))
            {
                return;
            }

            if (!TryGetCommonDocument(elements.Concat(exclude ?? Enumerable.Empty <Types.Element>()).Concat(Enumerable.Repeat(view, 1)), out var doc))
            {
                return;
            }

            using (var options = new DB.Options()
            {
                View = view.Value
            })
            {
                Params.TrySetDataList(DA, "Elements", () => elements);

                var _Geometry_ = Params.IndexOfOutputParam("Geometry");
                SolveGeometry
                (
                    DA.ParameterTargetPath(_Geometry_),
                    doc,
                    elements,
                    exclude,
                    options,
                    out var Geometry
                );

                DA.SetDataTree(_Geometry_, Geometry);

                var _Categories_ = Params.IndexOfOutputParam("Categories");
                var Categories   = _Categories_ >= 0 ? new GH_Structure <Types.Category>() : default;

                var _Materials_ = Params.IndexOfOutputParam("Materials");
                var Materials   = _Materials_ >= 0 ? new GH_Structure <Types.Material>() : default;

                SolveAttributes(doc, Geometry, Categories, Materials);

                if (Categories is object)
                {
                    DA.SetDataTree(_Categories_, Categories);
                }

                if (Materials is object)
                {
                    DA.SetDataTree(_Materials_, Materials);
                }
            }
        }
示例#5
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            int iterations = 0;
            var algorithm  = new Boa_Algorithm();
            var inputs     = new double[0];

            if (!GetInputs(DA, ref inputs))
            {
                return;
            }
            if (!DA.GetData(2, ref iterations))
            {
                return;
            }
            GetAlgorithm(DA, ref algorithm);

            if (iterations < 1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Number of iterations must be greater than or equal to one.");
                return;
            }

            GH_Structure <GH_Number> outputDataTree = new GH_Structure <GH_Number>();
            GH_Path targetPath = DA.ParameterTargetPath(0);

            //Feedback loop
            for (int i = 0; i < iterations; i++)
            {
                // on the first iteration
                if (i == 0)
                {
                    if (!SolveAlgorithm(ref inputs, algorithm))
                    {
                        return;
                    }
                }
                else
                {
                    if (!SolveAlgorithm(ref inputs, algorithm, "Number of outputs is less than number of inputs. Algorithm cannot support a feedback loop."))
                    {
                        return;
                    }
                }

                GH_Number[] outputList = new GH_Number[inputs.Length];

                for (int j = 0; j < inputs.Length; j++)
                {
                    outputList[j] = new GH_Number(inputs[j]);
                }

                outputDataTree.AppendRange(outputList, targetPath.AppendElement(i));
            }

            DA.SetDataTree(0, outputDataTree);
        }
        private Base DoWork(string item, IGH_DataAccess DA)
        {
            if (string.IsNullOrEmpty(item))
            {
                return(null);
            }

            try
            {
                return(Operations.Deserialize(item));
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  $"Cannot deserialize object at path {{{DA.ParameterTargetPath(0)}}}[{DA.ParameterTargetIndex(0)}]: {e.InnerException?.Message ?? e.Message}");
                return(null);
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            GeometryBase region = null;
            var          curves = new List <Curve>();
            double       radius = 0;
            int          iterations = 0, convergence = 0;

            DA.GetData(0, ref region);
            DA.GetDataList(1, curves);
            DA.GetData(2, ref radius);
            DA.GetData(3, ref iterations);
            DA.GetData(4, ref convergence);

            Polyline polyline = null;
            Mesh     mesh     = null;

            if (region is Curve)
            {
                polyline = (region as Curve).ToPolyline();
            }
            else if (region is Mesh)
            {
                mesh = (region as Mesh);
            }
            else
            {
                throw new Exception(" Region should be polyline or mesh.");
            }

            var inPolylines = curves.Select(c => c.ToPolyline()).ToList();

            var simulation = new Model.Simulations.DifferentialGrowth.DifferentialGrowth(inPolylines, radius, convergence, iterations, polyline, mesh);
            var polylines  = simulation.AllPolylines;

            var outCurves = new GH_Structure <GH_Curve>();
            var path      = DA.ParameterTargetPath(0);

            for (int j = 0; j < polylines.Count; j++)
            {
                outCurves.AppendRange(polylines[j].Select(p => new GH_Curve(p.ToNurbsCurve())), path.AppendElement(j));
            }

            DA.SetDataTree(0, outCurves);
        }
        private string DoWork(GH_SpeckleBase item, IGH_DataAccess DA)
        {
            if (item?.Value != null)
            {
                try
                {
                    return(Operations.Serialize(item.Value));
                }
                catch (Exception e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                    return(null);
                }
            }

            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                              $"Item at path {{{DA.ParameterTargetPath(0)}}}[{DA.ParameterTargetIndex(0)}] is not a Base object.");
            return(null);
        }
示例#9
0
        private IGH_Goo DoWork(object item, IGH_DataAccess DA)
        {
            try
            {
                if (source.Token.IsCancellationRequested)
                {
                    DA.AbortComponentSolution();
                    return(null);
                }
                var converted = Extras.Utilities.TryConvertItemToSpeckle(item, Converter, true);

                if (source.Token.IsCancellationRequested)
                {
                    DA.AbortComponentSolution();
                    return(null);
                }

                if (converted == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                      $"Cannot convert item {DA.ParameterTargetPath(0)}[{DA.ParameterTargetIndex(0)}] to Speckle.");
                    return(new GH_SpeckleBase());
                }

                if (converted.GetType().IsSimpleType())
                {
                    return(new GH_ObjectWrapper(converted));
                }

                return(new GH_SpeckleBase {
                    Value = converted as Base
                });
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                return(new GH_SpeckleBase());
            }
        }
        /// <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)
        {
            Surface destination = null;
            double  naN         = double.NaN;
            double  num2        = double.NaN;
            bool    flag        = true;

            if ((((DA.GetData <Surface>(0, ref destination) && DA.GetData <double>(1, ref naN)) && DA.GetData <double>(2, ref num2)) && DA.GetData <bool>(3, ref flag)) && ((destination.IsValid && (naN > 0.0)) && (num2 > 0.0)))
            {
                if (naN > num2)
                {
                    if ((naN % num2) > 0.0)
                    {
                        this.AddRuntimeMessage((GH_RuntimeMessageLevel)1, "One distance parameter needs to be a multiplier of the other");
                        return;
                    }
                }
                else if ((num2 > naN) && ((num2 % naN) > 0.0))
                {
                    this.AddRuntimeMessage((GH_RuntimeMessageLevel)1, "One distance parameter needs to be a multiplier of the other");
                    return;
                }
                List <Point3d[]>        rhGrid = Utility.DivideSurfaceByChordLength(destination, naN, num2, flag, 0.0, 0.0);
                GH_Structure <GH_Point> grid   = new GH_Structure <GH_Point>();
                GH_Path path = new GH_Path(DA.ParameterTargetPath(0));
                path = path.AppendElement(DA.ParameterTargetIndex(0));
                if (!PtListArrayToGhTreePoint(rhGrid, ref grid, path))
                {
                    this.AddRuntimeMessage((GH_RuntimeMessageLevel)1, "Failed to convert Rhino list array to GH tree.");
                }
                else
                {
                    DA.SetDataTree(0, grid);
                }
            }
        }
示例#11
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            var elements = new List <DB.Element>();

            if (!DA.GetDataList("Elements", elements) || elements.Count == 0)
            {
                return;
            }

            var exclude   = new List <DB.Element>();
            var _Exclude_ = Params.IndexOfInputParam("Exclude");

            if (_Exclude_ >= 0)
            {
                DA.GetDataList(_Exclude_, exclude);
            }

            if (!TryGetCommonDocument(elements.Concat(exclude), out var doc))
            {
                return;
            }

            var detailLevel   = DB.ViewDetailLevel.Undefined;
            var _DetailLevel_ = Params.IndexOfInputParam("Detail Level");

            if (_DetailLevel_ >= 0)
            {
                DA.GetData(_DetailLevel_, ref detailLevel);
                if (detailLevel == DB.ViewDetailLevel.Undefined)
                {
                    detailLevel = DB.ViewDetailLevel.Coarse;
                }
            }

            using (var options = new DB.Options()
            {
                DetailLevel = detailLevel
            })
            {
                Params.TrySetDataList(DA, "Elements", () => elements);

                var _Geometry_ = Params.IndexOfOutputParam("Geometry");
                SolveGeometry
                (
                    DA.ParameterTargetPath(_Geometry_),
                    doc,
                    elements,
                    exclude,
                    options,
                    out var Geometry
                );
                DA.SetDataTree(_Geometry_, Geometry);

                var _Categories_ = Params.IndexOfOutputParam("Categories");
                var Categories   = _Categories_ >= 0 ? new GH_Structure <Types.Category>() : default;

                var _Materials_ = Params.IndexOfOutputParam("Materials");
                var Materials   = _Materials_ >= 0 ? new GH_Structure <Types.Material>() : default;

                SolveAttributes(doc, Geometry, Categories, Materials);

                if (Categories is object)
                {
                    DA.SetDataTree(_Categories_, Categories);
                }

                if (Materials is object)
                {
                    DA.SetDataTree(_Materials_, Materials);
                }
            }
        }
示例#12
0
文件: Program.cs 项目: zimhe/Robots
        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)
        {
            if (InPreSolve)
            {
                GH_SpeckleBase speckleBase = null;
                DA.GetData(0, ref speckleBase);
                var @base     = speckleBase.Value.ShallowCopy();
                var inputData = new Dictionary <string, object>();
                if (Params.Input.Count == 1)
                {
                    inputData = null;
                    return;
                }

                var hasErrors   = false;
                var allOptional = Params.Input.FindAll(p => p.Optional).Count == Params.Input.Count;
                if (Params.Input.Count > 1 && allOptional)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "You cannot set all parameters as optional");
                    inputData = null;
                    return;
                }

                if (DA.Iteration == 0)
                {
                    Tracker.TrackPageview("objects", "extend", "variableinput");
                }

                inputData = new Dictionary <string, object>();
                for (int i = 1; i < Params.Input.Count; i++)
                {
                    var ighParam   = Params.Input[i];
                    var param      = ighParam as GenericAccessParam;
                    var detachable = param.Detachable;
                    var key        = detachable ? "@" + param.NickName : param.NickName;

                    var willOverwrite = @base.GetMembers().ContainsKey(key);
                    var targetIndex   = DA.ParameterTargetIndex(0);
                    var path          = DA.ParameterTargetPath(0);
                    if (willOverwrite)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark,
                                          $"Key {key} already exists in object at {path}[{targetIndex}], its value will be overwritten");
                    }

                    switch (param.Access)
                    {
                    case GH_ParamAccess.item:
                        object value = null;
                        DA.GetData(i, ref value);
                        if (!param.Optional && value == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                              $"Non-optional parameter {param.NickName} cannot be null");
                            hasErrors = true;
                        }

                        inputData[key] = value;
                        break;

                    case GH_ParamAccess.list:
                        var values = new List <object>();
                        DA.GetDataList(i, values);
                        if (!param.Optional)
                        {
                            if (values.Count == 0)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                                  $"Non-optional parameter {param.NickName} cannot be null or empty.");
                                hasErrors = true;
                            }
                        }

                        inputData[key] = values;
                        break;

                    case GH_ParamAccess.tree:
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                if (hasErrors)
                {
                    inputData = null;
                }

                var task = Task.Run(() => DoWork(@base, inputData));
                TaskList.Add(task);
                return;
            }

            // Report all conversion errors as warnings
            if (Converter != null)
            {
                foreach (var error in Converter.Report.ConversionErrors)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                      error.Message + ": " + error.InnerException?.Message);
                }
                Converter.Report.ConversionErrors.Clear();
            }

            if (!GetSolveResults(DA, out Base result))
            {
                // Normal mode not supported
                return;
            }

            if (result != null)
            {
                DA.SetData(0, result);
            }
        }
示例#14
0
        protected override void GroundHogSolveInstance(IGH_DataAccess DA)
        {
            var CURVES  = new List <Curve>();
            var STARTS  = new List <Point3d>();
            var ENDS    = new List <Point3d>();
            var LENGTHS = new List <double>();

            // Access and extract data from the input parameters individually
            if (!DA.GetDataList(0, CURVES))
            {
                return;
            }
            if (!DA.GetDataList(1, STARTS))
            {
                return;
            }
            if (!DA.GetDataList(2, ENDS))
            {
                return;
            }
            DA.GetDataList(3, LENGTHS);

            // Input validation
            int negativeIndex = LENGTHS.FindIndex(_isNegative);

            if (negativeIndex != -1)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  string.Format("Distances cannot be negative. At least one negative value found at index {0}.", negativeIndex));
                return;
            }

            CURVES.RemoveAll(_removeNullAndInvalidDelegate);
            if (CURVES.Count < 1)
            {
                return;
            }

            STARTS.RemoveAll(_removeInvalidDelegate);
            ENDS.RemoveAll(_removeInvalidDelegate);
            if (STARTS.Count != ENDS.Count)
            {
                if (ENDS.Count == 1 && STARTS.Count > 1)
                {
                    // Assume multiple starts going to single end; populate ends to match
                    for (int i = 1; i < STARTS.Count; i++)
                    {
                        ENDS.Add(ENDS[0]);
                    }
                }
                else if (STARTS.Count == 1 && ENDS.Count > 1)
                {
                    // Assume single start going to multiple ends; populate starts to match
                    for (int i = 1; i < ENDS.Count; i++)
                    {
                        STARTS.Add(STARTS[0]);
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The quantity of start points does not match the quantity of end points");
                    return;
                }
            }

            if (LENGTHS.Count > 0 && LENGTHS.Count != CURVES.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "If lengths are provided they must match the number of curves");
                return;
            }

            // Construct topology
            CurvesTopology top = new CurvesTopology(CURVES, GH_Component.DocumentTolerance());
            //CurvesTopologyPreview.Mark(top, Color.BurlyWood, Color.Bisque);
            PathMethod pathSearch;

            if (LENGTHS.Count == 0)
            {
                IList <double> distances = top.MeasureAllEdgeLengths();
                pathSearch = new AStar(top, distances);
            }
            else if (LENGTHS.Count == 1)
            {
                pathSearch = new Dijkstra(top, LENGTHS[0]);
            }
            else
            {
                IList <double> interfLengths = LENGTHS;

                if (interfLengths.Count < top.EdgeLength)
                {
                    interfLengths = new ListByPattern <double>(interfLengths, top.EdgeLength);
                }

                bool isAlwaysShorterOrEqual = true;
                for (int i = 0; i < top.EdgeLength; i++)
                {
                    if (top.LinearDistanceAt(i) > interfLengths[i])
                    {
                        isAlwaysShorterOrEqual = false;
                        break;
                    }
                }

                if (isAlwaysShorterOrEqual)
                {
                    pathSearch = new AStar(top, interfLengths);
                }
                else
                {
                    pathSearch = new Dijkstra(top, interfLengths);
                }
            }

            var resultCurves  = new List <Curve>();
            var resultLinks   = new GH_Structure <GH_Integer>();
            var resultDirs    = new GH_Structure <GH_Boolean>();
            var resultLengths = new List <double>();

            for (int i = 0; i < STARTS.Count; i++)
            {
                int fromIndex = top.GetClosestNode(STARTS[i]);
                int toIndex   = top.GetClosestNode(ENDS[i]);

                if (fromIndex == toIndex)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The start and end positions are equal; perhaps because they are not close enough to one of the curves in the network.");
                    resultCurves.Add(null);
                    continue;
                }

                var current = pathSearch.Cross(fromIndex, toIndex, out int[] nodes, out int[] edges, out bool[] dir, out double tot);

                if (current == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                      string.Format("No walk found for start point at position {0}. Are end points isolated?", i.ToString()));
                }
                else
                {
                    var pathLinks = DA.ParameterTargetPath(1).AppendElement(i);

                    resultLinks.AppendRange(GhWrapTypeArray <int, GH_Integer>(edges), pathLinks);
                    resultDirs.AppendRange(GhWrapTypeArray <bool, GH_Boolean>(dir), pathLinks);
                    resultLengths.Add(tot);
                }

                resultCurves.Add(current);
            }

            DA.SetDataList(0, resultCurves);
            DA.SetDataTree(1, resultLinks);
            DA.SetDataTree(2, resultDirs);
            DA.SetDataList(3, resultLengths);
        }
示例#15
0
        protected override void TrySolveInstance(IGH_DataAccess DA)
        {
            var elements = new List <DB.Element>();

            if (!DA.GetDataList("Elements", elements) || elements.Count == 0)
            {
                return;
            }

            var exclude   = new List <DB.Element>();
            var _Exclude_ = Params.IndexOfInputParam("Exclude");

            if (_Exclude_ >= 0)
            {
                DA.GetDataList(_Exclude_, exclude);
            }

            var view   = default(DB.View);
            var _View_ = Params.IndexOfInputParam("View");

            if (!DA.GetData(_View_, ref view))
            {
                return;
            }

            if (!TryGetCommonDocument(elements.Concat(exclude).Concat(Enumerable.Repeat(view, 1)), out var doc))
            {
                return;
            }

            using (var options = new DB.Options()
            {
                View = view
            })
            {
                var _Geometry_ = Params.IndexOfOutputParam("Geometry");
                SolveGeometry
                (
                    DA.ParameterTargetPath(_Geometry_),
                    doc,
                    elements,
                    exclude,
                    options,
                    out var Geometry
                );

                DA.SetDataTree(_Geometry_, Geometry);

                var _Categories_ = Params.IndexOfOutputParam("Categories");
                var Categories   = _Categories_ >= 0 ? new GH_Structure <Types.Category>() : default;

                var _Materials_ = Params.IndexOfOutputParam("Materials");
                var Materials   = _Materials_ >= 0 ? new GH_Structure <Types.Material>() : default;

                SolveAttributes(doc, Geometry, Categories, Materials);

                if (Categories is object)
                {
                    DA.SetDataTree(_Categories_, Categories);
                }

                if (Materials is object)
                {
                    DA.SetDataTree(_Materials_, Materials);
                }
            }
        }
        /// <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;

            if (!DA.GetData(0, ref goo))
            {
                return;
            }
            ObjectivismObject obj;

            if (goo is GH_ObjectivismObject ghObj)
            {
                obj = ghObj.Value;
            }
            else
            {
                return;
            }
            PropertyNames.UnionWith(obj.AllProperties);



            foreach ((int i, var param) in Params.Output.Enumerate())
            {
                string name = param.NickName;



                var            prop = obj.GetProperty(name);
                PropertyAccess access;
                if (prop != null)
                {
                    access = prop.Access;
                    accessChecker.AccessCheck(prop, name);
                }
                else
                {
                    access = accessChecker.BestGuessAccess(name);
                }



                if (access == PropertyAccess.Item)
                {
                    var item = prop != null
                        ? prop.Data.get_FirstItem(false)
                        : null;

                    var path = DA.ParameterTargetPath(i);
                    if (GraftItems)
                    {
                        int[] index   = { DA.ParameterTargetIndex(0) };
                        var   newPath = new GH_Path(path.Indices.Concat(index).ToArray());
                        var   tree    = new GH_Structure <IGH_Goo>();
                        tree.Append(item, newPath);
                        DA.SetDataTree(i, tree);
                    }
                    else
                    {
                        var tree = new GH_Structure <IGH_Goo>();
                        tree.Append(item, path);
                        DA.SetDataTree(i, tree);
                    }
                }
                if (access == PropertyAccess.List)
                {
                    var list = prop != null
                        ? prop.Data.Branches[0]
                        : new List <IGH_Goo>();

                    var   path    = DA.ParameterTargetPath(i);
                    int[] index   = { DA.ParameterTargetIndex(0) };
                    var   newPath = new GH_Path(path.Indices.Concat(index).ToArray());
                    var   tree    = new GH_Structure <IGH_Goo>();
                    tree.AppendRange(list, newPath);
                    DA.SetDataTree(i, tree);
                }
                if (access == PropertyAccess.Tree)
                {
                    var tree = prop != null
                        ? prop.Data
                        : Util.EmptyTree;
                    var basePath = DA.ParameterTargetPath(i);
                    var outTree  = new GH_Structure <IGH_Goo>();
                    for (int j = 0; j < tree.PathCount; j++)
                    {
                        var   branch         = tree.Branches[j];
                        var   path           = tree.Paths[j];
                        int[] index          = { DA.ParameterTargetIndex(0) };
                        var   newPathIndices = basePath.Indices
                                               .Concat(index)
                                               .Concat(path.Indices)
                                               .ToArray();
                        var newPath = new GH_Path(newPathIndices);
                        outTree.AppendRange(branch, newPath);
                    }
                    DA.SetDataTree(i, outTree);
                }
            }
        }
        /// <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 objs = Params.Input
                       .First()
                       .VolatileData
                       .AllData(true)
                       .ToList <object>();

            //Create An output for all the inputs.
            object myObject = null;

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

            if (DA.Iteration == 0)
            {
                properties = new HashSet <string>();

                if (GetDictionary(myObject, out var data))
                {
                    properties = data.Keys.ToHastSet();
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Valid Format");
                    return;
                }
            }


            if (OutputMismatch() && DA.Iteration == 0)
            {
                OnPingDocument().ScheduleSolution(5, d =>
                {
                    AutoCreateOutputs(false);
                });
            }
            else if (!OutputMismatch())
            {
                //First pass get children
                var data      = new Dictionary <string, object>();
                var nicknames = Params.Output.Select(x => x.NickName).ToList();

                if (!GetDictionary(myObject, out data))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Valid Format");
                    return;
                }

                var notMatching = data.Keys.Where(x => !nicknames.Contains(x)).Any();
                if (notMatching)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Item is not matching the rest. Ignoring");
                    return;
                }

                //Second pass to deserialise objects
                var paramID   = 0; //This is so we can track the id of the Output Parameter.
                var dataItems = new Dictionary <string, object>();
                var dataList  = new Dictionary <string, IEnumerable <object> >();
                var dataTree  = new Dictionary <string, DataTree <object> >();


                foreach (var item in data)
                {
                    if (myObject is SpeckleStream ss)
                    {
                        dataItems.Add(item.Key, new GH_SpeckleStream(ss));
                    }
                    if (item.Value is IEnumerable <SpeckleObject> speckleList)
                    {
                        dataList.Add(item.Key, Converter.Deserialise(speckleList));
                    }
                    else if (item.Value is SpeckleObject speckleObject)
                    {
                        dataItems.Add(item.Key, Converter.Deserialise(speckleObject));
                    }
                    else if (item.Value is IEnumerable <object> objectList)
                    {
                        dataList.Add(item.Key, objectList);
                    }
                    else if (item.Value is Dictionary <string, object> dictionaryObject)
                    {
                        dataItems.Add(item.Key, new GH_ObjectWrapper(dictionaryObject));
                    }
                    else if (item.Value is Dictionary <string, IEnumerable <object> > dictionaryList)
                    {
                        var tree = new DataTree <object>();
                        foreach (var d in dictionaryList)
                        {
                            var listWrapper = new List <GH_ObjectWrapper>();
                            d.Value.ToList().ForEach(x => listWrapper.Add(new GH_ObjectWrapper(x)));
                            if (int.TryParse(d.Key, out var index))
                            {
                                tree.AddRange(d.Value, DA.ParameterTargetPath(paramID).AppendElement(index));
                            }
                        }
                        dataTree.Add(item.Key, tree);
                    }
                    else if (item.Value is object _Object)
                    {
                        dataItems.Add(item.Key, _Object);
                    }
                    else if (myObject is GH_SpeckleStream gH_SpeckleStream2)
                    {
                        dataItems.Add(item.Key, gH_SpeckleStream2);
                    }


                    paramID++;
                }

                //Add The Data Now
                foreach (var item in dataItems)
                {
                    if (item.Value is IEnumerable <object> list)
                    {
                        DA.SetDataList(item.Key, list);
                    }
                    else
                    {
                        DA.SetDataList(item.Key, new List <object>()
                        {
                            item.Value
                        });
                    }
                }
                foreach (var item in dataList)
                {
                    DA.SetDataList(item.Key, item.Value);
                }
                foreach (var item in dataTree)
                {
                    int n = 0;
                    foreach (var nickname in Params.Output.Select(x => x.NickName))
                    {
                        if (nickname.Equals(item.Key))
                        {
                            break;
                        }
                        n++;
                    }
                    DA.SetDataTree(n, item.Value);
                }
            }
        }
示例#18
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Type_KDTree    treeT       = null;
            List <Point3d> pts         = new List <Point3d>();
            List <double>  range       = new List <double>();
            int            maxReturned = 100;

            if (!DA.GetData("KDTree", ref treeT))
            {
                return;
            }
            if (!DA.GetDataList("Points", pts))
            {
                return;
            }
            if (!DA.GetDataList("Range", range))
            {
                return;
            }
            DA.GetData("Number of Neighbors", ref maxReturned);

            Tuple <KDTree <int>, GH_Cloud> KDTreeCloud = treeT.Value;
            KDTree <int> tree  = KDTreeCloud.Item1;
            PointCloud   cloud = KDTreeCloud.Item2.Value;


            if (range.Count > 1 && range.Count < pts.Count)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Amount of Range values should be a single value, or match the amount of search points.");
                return;
            }

            List <int>[] idc = KDTreeLib.NearestNeighborSearch(tree, pts, range, maxReturned);


            var path1 = DA.ParameterTargetPath(0);
            DataTree <Point3d>        pointT    = new DataTree <Point3d>();
            DataTree <Vector3d>       normalT   = new DataTree <Vector3d>();
            DataTree <Color>          colorT    = new DataTree <Color>();
            DataTree <double>         distanceT = new DataTree <double>();
            GH_Structure <GH_Integer> idxT      = new GH_Structure <GH_Integer>();

            for (int i = 0; i < pts.Count; i++)
            {
                List <int> ids = idc[i];
                for (int j = 0; j < ids.Count; j++)
                {
                    pointT.Add(cloud[ids[j]].Location, path1.AppendElement(i));
                    if (cloud.ContainsNormals)
                    {
                        normalT.Add(cloud[ids[j]].Normal, path1.AppendElement(i));
                    }
                    if (cloud.ContainsColors)
                    {
                        colorT.Add(cloud[ids[j]].Color, path1.AppendElement(i));
                    }
                    //Distance betwen Points
                    double D = pts[i].DistanceTo(cloud[ids[j]].Location);
                    distanceT.Add(D, path1.AppendElement(i));
                }
                idxT.AppendRange(ids.Select(x => new GH_Integer(x)), path1.AppendElement(i));
            }


            DA.SetDataTree(0, pointT);
            DA.SetDataTree(1, normalT);
            DA.SetDataTree(2, colorT);
            DA.SetDataTree(3, distanceT);
            DA.SetDataTree(4, idxT);
        }