public override void SetData(IGH_DataAccess DA) { // Report all conversion errors as warnings if (Converter != null) { foreach (var error in Converter.ConversionErrors) { Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, error.Message + ": " + error.InnerException?.Message); } } switch (value) { case null: Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key not found in object: " + key); break; case List <object> list: { DA.SetDataList(0, list.Select(GH_Convert.ToGoo).ToList()); break; } default: DA.SetData(0, GH_Convert.ToGoo(value)); break; } }
protected override void SolveInstance(IGH_DataAccess DA) { if (InPreSolve) { DA.DisableGapLogic(); var speckleObj = new GH_SpeckleBase(); var key = ""; DA.GetData(0, ref speckleObj); DA.GetData(1, ref key); if (DA.Iteration == 0) { Tracker.TrackPageview("objects", "valueByKey"); } var @base = speckleObj?.Value; var task = Task.Run(() => DoWork(@base, key, CancelToken)); TaskList.Add(task); return; } if (!GetSolveResults(DA, out object value)) { // No result could be obtained. 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(); } switch (value) { case null: AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key not found in object"); break; case IList <object> list: { var ghGoos = list.Select(GH_Convert.ToGoo).ToList(); DA.SetDataList(0, ghGoos); break; } default: Params.Output[0].Access = GH_ParamAccess.item; DA.SetData(0, GH_Convert.ToGoo(value)); break; } }
public static IGH_Goo TryConvertItemToNative(object value, ISpeckleConverter converter) { if (value == null) { return(null); } if (value is IGH_Goo) { value = value.GetType().GetProperty("Value")?.GetValue(value); } if (value is Base @base && converter.CanConvertToNative(@base)) { var converted = converter.ConvertToNative(@base); var geomgoo = GH_Convert.ToGoo(converted); if (geomgoo != null) { return(geomgoo); } var goo = new GH_ObjectWrapper { Value = converted }; return(goo); } if (value is Base @base2) { var goo = new GH_SpeckleBase { Value = @base2 }; return(goo); } if (value.GetType().IsSimpleType()) { return(GH_Convert.ToGoo(value)); } if (value is Enum) { var i = (Enum)value; return(new GH_ObjectWrapper { Value = i }); } return(null); }
public override void SetData(IGH_DataAccess DA) { switch (value) { case null: Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key not found in object: " + key); break; case List <object> list: { DA.SetDataList(0, list.Select(GH_Convert.ToGoo).ToList()); break; } default: DA.SetData(0, GH_Convert.ToGoo(value)); break; } }
/*******************************************/ protected override IGH_Goo PreferredCast(object data) { if (data is IObject) { return(new GH_Variable(data)); } else { IGH_Goo goo = GH_Convert.ToGoo(RuntimeHelpers.GetObjectValue(data)); if (goo != null) { return(goo); } else { return(null); } } }
protected override void CollectVolatileData_Custom() { List <GH_ValueListItem> .Enumerator enumerator = new List <GH_ValueListItem> .Enumerator(); this.m_data.Clear(); try { List <int> DOFs = new List <int>(); bool physical = false; enumerator = this.SelectedItems.GetEnumerator(); while (enumerator.MoveNext()) { GH_ValueListItem item = enumerator.Current; int DOF; item.Value.CastTo <int>(out DOF); DOFs.Add(DOF); if (DOF == 100) { physical = true; DOFs = new List <int> { 1, 2, 3 }; break; } } Guanaco.SupportType supportType = new SupportType(DOFs, physical); this.m_data.Append(GH_Convert.ToGoo(supportType), new GH_Path(0)); } finally { enumerator.Dispose(); } }
public override IGH_Goo Duplicate() { return(GH_Convert.ToGoo(Value)); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { if (GH_Document.IsEscapeKeyDown()) { GH_Document GHDocument = OnPingDocument(); GHDocument.RequestAbortSolution(); return; } ikvm.runtime.Startup.addBootClassPathAssemby(Assembly.Load("culebra")); ikvm.runtime.Startup.addBootClassPathAssemby(Assembly.Load("IKVM.OpenJDK.Core")); bool reset = new bool(); int iterations = new int(); List <object> init_Settings = new List <object>(); List <object> move_Settings = new List <object>(); IGH_VisualData visual_Settings = null; object behavioral_Settings = null; if (!DA.GetDataList(0, init_Settings) || init_Settings.Count == 0 || init_Settings == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Init Settings Detected, please connect Init Settings to enable the component"); return; } if (!DA.GetDataList(1, move_Settings) || move_Settings.Count == 0 || move_Settings == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Move Settings Detected, please connect Move Settings to enable the component"); return; } if (!DA.GetData(3, ref visual_Settings) || visual_Settings == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Visual Settings Detected, please connect Visual Settings to enable the component"); return; } if (!DA.GetData(4, ref iterations)) { return; } if (!DA.GetData(5, ref reset)) { return; } Random rnd = new Random(); if (!DA.GetData(2, ref behavioral_Settings) || behavioral_Settings == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input Object is Null"); return; } string objtype = behavioral_Settings.GetType().Name.ToString(); if (!(behavioral_Settings.GetType() == typeof(IGH_BehaviorData))) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "You did not input a Behavior Data Object, please ensure input is Behavior Data Object and not " + objtype); return; } else { #region Initialize / Data Parse //------------------------Init Settings-------------------------- if (init_Settings.Count != 0) { String init_Convert = ""; if (init_Settings[0].GetType() == typeof(GH_String)) { GH_String value = (GH_String)init_Settings[0]; init_Convert = value.Value; } if (init_Convert == "Box") { this.spawnData = "box"; GH_Convert.ToBox_Primary(init_Settings[3], ref this.box); GH_Convert.ToInt32(init_Settings[4], out this.spawnType, GH_Conversion.Primary); GH_Convert.ToInt32(init_Settings[5], out this.pointCount, GH_Conversion.Primary); GH_Convert.ToInt32(init_Settings[1], out this.dimensions, GH_Conversion.Primary); } else if (init_Convert == "Points") { this.spawnData = "Points"; var wrapperToGoo = GH_Convert.ToGoo(init_Settings[3]); wrapperToGoo.CastTo <List <Point3d> >(out this.ptList); GH_Convert.ToInt32(init_Settings[1], out this.dimensions, GH_Conversion.Primary); GH_Convert.ToBox_Primary(init_Settings[4], ref this.box); } GH_Convert.ToInt32(init_Settings[2], out this.bounds, GH_Conversion.Primary); } //------------------------Move Settings-------------------------- Vector3d initialVector = new Vector3d(); if (move_Settings.Count != 0) { if (move_Settings[0].GetType() == typeof(GH_Vector)) { GH_Vector value = (GH_Vector)move_Settings[0]; initialVector = value.Value; } else if (move_Settings[0].GetType() == typeof(GH_Number)) { GH_Number value = (GH_Number)move_Settings[0]; this.initialSpeed = value.Value; } GH_Convert.ToDouble(move_Settings[1], out this.maxSpeed, GH_Conversion.Primary); GH_Convert.ToDouble(move_Settings[2], out this.maxForce, GH_Conversion.Primary); GH_Convert.ToDouble(move_Settings[3], out this.velMultiplier, GH_Conversion.Primary); } //------------------------Visual Settings-------------------------- TrailData td = visual_Settings.Value.trailData; ColorData cd = visual_Settings.Value.colorData; this.trail = td.createTrail; this.displayMode = visual_Settings.Value.displayMode; this.trailStep = td.trailStep; this.maxTrailSize = td.maxTrailSize; this.particleTexture = cd.particleTexture; this.graphicType = cd.colorDataType; this.useTexture = visual_Settings.Value.useTexture; if (cd.colorDataType == "Gradient") { this.maxthick = cd.maxThickness; this.minthick = cd.minThickness; this.redValues[0] = cd.redChannel[0]; this.redValues[1] = cd.redChannel[1]; this.greenValues[0] = cd.greenChannel[0]; this.greenValues[1] = cd.greenChannel[1]; this.blueValues[0] = cd.blueChannel[0]; this.blueValues[1] = cd.blueChannel[1]; } else if (cd.colorDataType == "GraphicPolyline") { this.polylineColor = cd.color; this.dotted = cd.dotted; this.maxthick = cd.maxThickness; } else if (cd.colorDataType == "Disco") { this.maxthick = cd.maxThickness; this.minthick = cd.minThickness; } else if (cd.colorDataType == "Base") { this.maxthick = 3; this.minthick = 1; } //----------------------------------------------------------------- IGH_PreviewObject comp = (IGH_PreviewObject)this; if (comp.Hidden && (this.displayMode == 0)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Component preview must be enabled to see Graphic Mode on Canvas, right click on component and set preview on"); } #endregion #region Pre Simulation Code //------------------------RESET STARTS HERE-------------------------- if (reset) { //We are using the reset to reinitialize all the variables and positions //----------------------------------------------------------------- this.bb = new BoundingBox(); int loopCount = new int(); bool create = new bool(); if (this.spawnData == "box") { this.bb = this.box.BoundingBox; loopCount = this.pointCount; create = true; } else if (this.spawnData == "Points") { loopCount = this.ptList.Count; create = false; this.bb = this.box.BoundingBox; } //----------------------------------------------------------------- this.moveList = new List <Vector3d>(); this.startList = new List <Vector3d>(); this.creepList = new List <CulebraObject>(); this.currentPosList = new List <Point3d>(); this.networkList = new List <Line>(); flattenedTrails = new List <Vector3d>(); for (int i = 0; i < loopCount; i++) { if (this.dimensions == 0) { //If we want 2D General.setViewport("Top", "Shaded"); if (create) { //If are creating random points inside bbox if (this.spawnType == 0 || this.spawnType == 2) { this.startPos = new Vector3d((int)bb.Min[0], rnd.Next((int)bb.Min[1], (int)bb.Max[1]), 0); //spawn along the y axis of the bounding area } else if (this.spawnType == 1 || this.spawnType == 3) { this.startPos = new Vector3d(rnd.Next((int)bb.Min[0], (int)bb.Max[0]), rnd.Next((int)bb.Min[1], (int)bb.Max[1]), 0); //spawn randomly inside the bounding area } if (initialVector.Length > 0) { this.moveVec = initialVector; //move in the user specified direction } else { this.moveVec = new Vector3d(rnd.Next(-1, 2) * initialSpeed, rnd.Next(-1, 2) * initialSpeed, 0); //move randomly in any direction 2d } } else { //If we are using user defined points this.startPos = (Vector3d)this.ptList[i]; if (initialVector.Length > 0) { this.moveVec = initialVector; //move in the user specified direction } else { this.moveVec = new Vector3d(rnd.Next(-1, 2) * initialSpeed, rnd.Next(-1, 2) * initialSpeed, 0); //move randomly in any direction 2d } } this.creep = new Creeper(this.startPos, this.moveVec, true, false); this.creepList.Add(this.creep); } else { //If we want 3D General.setViewport("Perspective", "Shaded"); if (create) { //If are creating random points inside bbox if (this.spawnType == 0 || this.spawnType == 2) { this.startPos = new Vector3d(rnd.Next((int)bb.Min[0], (int)bb.Max[0]), rnd.Next((int)bb.Min[1], (int)bb.Max[1]), (int)bb.Min[2]); //start randomly on the lowest plane of the 3d bounds if (initialVector.Length > 0) { this.moveVec = initialVector; //move in the user specified direction } else { this.moveVec = new Vector3d(rnd.Next(-2, 2) * initialSpeed, rnd.Next(-2, 2) * initialSpeed, 1 * initialSpeed); //move randomly in the xy axis and up in the z axis } } else if (this.spawnType == 1 || this.spawnType == 3) { this.startPos = new Vector3d(rnd.Next((int)bb.Min[0], (int)bb.Max[0]), rnd.Next((int)bb.Min[1], (int)bb.Max[1]), rnd.Next((int)bb.Min[2], (int)bb.Max[2])); //start randomly inside the 3d bounds if (initialVector.Length > 0) { this.moveVec = initialVector; //move in the user specified direction } else { this.moveVec = new Vector3d(rnd.Next(-2, 2) * initialSpeed, rnd.Next(-2, 2) * initialSpeed, rnd.Next(-2, 2) * initialSpeed); //move randomly in any direction 3d } } } else { //If we are using user defined points this.startPos = (Vector3d)this.ptList[i]; if (initialVector.Length > 0) { this.moveVec = initialVector; //move in the user specified direction } else { this.moveVec = new Vector3d(rnd.Next(-2, 2) * initialSpeed, rnd.Next(-2, 2) * initialSpeed, rnd.Next(-2, 2) * initialSpeed); //move randomly in any direction 3d } } this.creep = new Creeper(this.startPos, this.moveVec, true, true); this.creepList.Add(this.creep); } this.startList.Add(this.startPos); //add the initial starting positions to the list to pass once we start running this.moveList.Add(this.moveVec); //add the initial move vectors to the list to pass once we start running } #endregion #region Simulation Code this.trailTree = new DataTree <Point3d>(); this.globalEngine = new Engine_Global(); for (int z = 0; z < iterations; z++) { this.particleSet = new DataTree <Point3d>(); this.currentPosList = new List <Point3d>(); this.trailTree.Clear(); this.networkTree.Clear(); this.trailTree.TrimExcess(); this.networkTree.TrimExcess(); if (this.moveList == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Please Reset the CreepyCrawlers Component"); return; } try { globalEngine.Action(this.creepList, this.dimensions, behavioral_Settings, this.displayMode, this.networkList, this.maxSpeed, this.maxForce, this.velMultiplier, this.flattenedTrails, this.particleList, this.particleSet, networkTree, trailStep, maxTrailSize, bounds, bb, currentPosList, trail, trailTree); } catch (Exception e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message.ToString()); return; } this.flattenedTrails.Clear(); this.flattenedTrails.TrimExcess(); #endregion } DA.SetDataList(0, this.currentPosList); DA.SetDataTree(2, networkTree); if (this.displayMode == 1 && this.trail) { DA.SetDataTree(1, trailTree); } } } }
/// <summary> /// Try to convert a given object into native (Grasshopper) format. /// </summary> /// <param name="value">Object to convert</param> /// <param name="converter">Converter instance to use.</param> /// <param name="recursive">Indicates if any non-convertible <see cref="Base"/> instances should be traversed too.</param> /// <returns>An <see cref="IGH_Goo"/> instance holding the converted object. </returns> public static IGH_Goo TryConvertItemToNative(object value, ISpeckleConverter converter, bool recursive = false) { if (converter == null) { return(new GH_ObjectWrapper(value)); } if (value == null) { return(null); } if (value is IGH_Goo) { value = value.GetType().GetProperty("Value")?.GetValue(value); } if (value is Base @base) { if (converter.CanConvertToNative(@base)) { try { var converted = converter.ConvertToNative(@base); var geomgoo = GH_Convert.ToGoo(converted); if (geomgoo != null) { return(geomgoo); } var goo = new GH_ObjectWrapper { Value = converted }; return(goo); } catch (Exception e) { converter.ConversionErrors.Add(new Exception($"Could not convert {@base}", e)); } } if (recursive) { // Object is base but cannot convert directly, traverse!!! var x = TraverseAndConvertToNative(@base, converter); return(new GH_SpeckleBase(x)); } } if (value is Base @base2) { return new GH_SpeckleBase { Value = @base2 } } ; if (value.GetType().IsSimpleType()) { return(GH_Convert.ToGoo(value)); } if (value is Enum) { var i = (Enum)value; return(new GH_ObjectWrapper { Value = i }); } return(new GH_ObjectWrapper(value)); }
protected override void SolveInstance(IGH_DataAccess DA) { if (error != null) { Message = null; AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message); error = null; stream = null; } else if (streams == null) { if (!DA.GetDataTree(0, out GH_Structure <GH_SpeckleStream> ghStreamTree)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Could not convert object to Stream."); Message = null; return; } Message = "Fetching"; if (ghStreamTree.DataCount == 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input S failed to collect data."); return; } if (ghStreamTree.DataCount >= 20) { tooManyItems = true; } Task.Run(async() => { try { int count = 0; var tasks = new Dictionary <GH_Path, Task <Stream> >(); ghStreamTree.Paths.ToList().ForEach(path => { if (count >= 20) { return; } var branch = ghStreamTree[path]; var itemCount = 0; branch.ForEach(item => { if (item == null || count >= 20) { itemCount++; return; } var account = item.Value.AccountId == null ? AccountManager.GetDefaultAccount() : AccountManager.GetAccounts().FirstOrDefault(a => a.id == item.Value.AccountId); if (account == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find default account in this machine. Use the Speckle Manager to add an account."); return; } var client = new Client(account); var task = client.StreamGet(item.Value?.StreamId); tasks[path.AppendElement(itemCount)] = task; count++; itemCount++; }); }); var values = await Task.WhenAll(tasks.Values); var fetchedStreams = new Dictionary <GH_Path, Stream>(); for (int i = 0; i < tasks.Keys.ToList().Count; i++) { var key = tasks.Keys.ToList()[i]; fetchedStreams[key] = values[i]; } streams = fetchedStreams; } catch (Exception e) { error = e; } finally { Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); }); } }); } else { if (tooManyItems) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Input data has too many items. Only the first 20 streams will be fetched."); tooManyItems = false; } var id = new GH_Structure <IGH_Goo>(); var name = new GH_Structure <IGH_Goo>(); var description = new GH_Structure <IGH_Goo>(); var createdAt = new GH_Structure <IGH_Goo>(); var updatedAt = new GH_Structure <IGH_Goo>(); var isPublic = new GH_Structure <GH_Boolean>(); var collaborators = new GH_Structure <IGH_Goo>(); var branches = new GH_Structure <IGH_Goo>(); streams.AsEnumerable()?.ToList().ForEach(pair => { id.Append(GH_Convert.ToGoo(pair.Value.id), pair.Key); name.Append(GH_Convert.ToGoo(pair.Value.name), pair.Key); description.Append(GH_Convert.ToGoo(pair.Value.description), pair.Key); createdAt.Append(GH_Convert.ToGoo(pair.Value.createdAt), pair.Key); updatedAt.Append(GH_Convert.ToGoo(pair.Value.updatedAt), pair.Key); isPublic.Append(new GH_Boolean(pair.Value.isPublic), pair.Key); collaborators.AppendRange(pair.Value.collaborators.Select(GH_Convert.ToGoo).ToList(), pair.Key); branches.AppendRange(pair.Value.branches.items.Select(GH_Convert.ToGoo), pair.Key); }); Message = "Done"; DA.SetDataTree(0, id); DA.SetDataTree(1, name); DA.SetDataTree(2, description); DA.SetDataTree(3, createdAt); DA.SetDataTree(4, updatedAt); DA.SetDataTree(5, isPublic); DA.SetDataTree(6, collaborators); DA.SetDataTree(7, branches); streams = null; } }
protected override void SolveInstance(IGH_DataAccess DA) { string path = Environment.SpecialFolder.MyDocuments.ToString() + @"\"; string sheet = "Sheet1"; bool run = false; if (!DA.GetData(0, ref path)) { return; } if (!DA.GetData(1, ref sheet)) { return; } if (!DA.GetData(2, ref run)) { return; } // Uses the GH_Structure instead of DataTree<T> inside a component. GH_Structure <IGH_Goo> headers = new GH_Structure <IGH_Goo>(); GH_Structure <IGH_Goo> values = new GH_Structure <IGH_Goo>(); if (run) { try { System.IO.FileInfo file = new System.IO.FileInfo(path); var package = new ExcelPackage(file); ExcelWorksheet workSheet = package.Workbook.Worksheets[sheet]; for (int j = workSheet.Dimension.Start.Column; j <= workSheet.Dimension.End.Column; j++) { GH_Path ghp = new GH_Path(j); IGH_Goo obj = GH_Convert.ToGoo(workSheet.Cells[1, j].Value); headers.EnsurePath(ghp); headers.Append(obj, ghp); } for (int i = workSheet.Dimension.Start.Row + 1; i <= workSheet.Dimension.End.Row; i++) { for (int j = workSheet.Dimension.Start.Column; j <= workSheet.Dimension.End.Column; j++) { GH_Path ghp = new GH_Path(j); GH_String cellValue = new GH_String(); // Excel does not use zero-base indexing, also, we have skipped the headers. IGH_Goo obj = GH_Convert.ToGoo(workSheet.Cells[i, j].Value); values.EnsurePath(ghp); values.Append(obj, ghp); } } } catch (Exception ex) { log.Add("Read from Excel failed: " + ex.Message); } } DA.SetDataList(0, log); DA.SetDataTree(1, headers); DA.SetDataTree(2, values); }
/// <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) { Frame frameComponent; if (!BasicFunction.ConnectToFrame(this, out frameComponent)) { return; } if (!frameComponent.Play) { if (GetValue("InPut", @default: false)) { Message = "InPut"; } else { Message = "OutPut"; } return; } string numberofMaxFrame = "D" + ((int)frameComponent.MaxFrame).ToString().Length.ToString(); string location = frameComponent.FilePath + this.NickName + " " + frameComponent.RightFrame.ToString(numberofMaxFrame) + ".3dm"; if (GetValue("InPut", @default: false)) { Message = "InPut"; List <IGH_Goo> list = new List <IGH_Goo>(); try { File3dm val = File3dm.Read(location); if (val == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "File could not be read"); return; } foreach (File3dmObject item in (CommonComponentTable <File3dmObject>)(object) val.Objects) { IGH_Goo iGH_Goo = GH_Convert.ToGoo(item.Geometry); if (iGH_Goo != null) { list.Add(iGH_Goo); } } Message += " " + frameComponent.RightFrame.ToString(); } catch (Exception ex) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Error during file reading: " + ex.Message); return; } DA.SetDataList("Geometry", list); } else { Message = "OutPut"; List <Mesh> meshes = new List <Mesh>(); DA.GetDataList("Mesh", meshes); File3dm file3d = new File3dm(); foreach (Mesh mesh in meshes) { file3d.Objects.AddMesh(mesh); } file3d.Write(location, 6); Message += " " + frameComponent.RightFrame.ToString(); } }