public override bool CastFrom(object source) { // This function is called when Grasshopper needs to convert other data // into GsaProp2d. if (source == null) { return(false); } //Cast from GsaProp2d if (typeof(GsaProp2d).IsAssignableFrom(source.GetType())) { Value = (GsaProp2d)source; return(true); } //Cast from double if (GH_Convert.ToDouble(source, out double thk, GH_Conversion.Both)) { //Value.Prop2d.Thickness = thk; // To be added; GsaAPI bug } return(false); }
void MenuKeyDown(GH_MenuTextBox sender, System.Windows.Forms.KeyEventArgs e, bool lineWidth) { switch (e.KeyCode) { case System.Windows.Forms.Keys.Enter: string text = sender.Text; e.Handled = true; double val; if ((GH_Convert.ToDouble(text, out val, GH_Conversion.Secondary)) && val > 0) { if (lineWidth) { _model.glLineWidth = val; } else { _model.glPointSize = val; } ExpirePreview(true); } break; case System.Windows.Forms.Keys.Escape: sender.CloseEntireMenuStructure(); break; } RedrawViewportControl(); }
public static object To_Double(object in_val) { double n = new double(); var y = GH_Convert.ToDouble(in_val, out n, GH_Conversion.Both); return((object)n); }
public override bool CastFrom(object source) { // This function is called when Grasshopper needs to convert other data // into GsaSpring. if (source == null) { return(false); } //Cast from GsaSpring if (typeof(GsaSpring).IsAssignableFrom(source.GetType())) { Value = (GsaSpring)source; return(true); } //Cast from double if (GH_Convert.ToDouble(source, out double myval, GH_Conversion.Both)) { Value.X = myval; // if input to parameter is a single number convert it to an axial spring return(true); } return(false); }
protected override void HandleTextInputAccepted(string text) { if (GH_Convert.ToDouble(text, out var number, GH_Conversion.Both)) { _input.PersistentData.Clear(); _input.PersistentData.Append(new GH_Number(number), new GH_Path(0)); _input.ExpireSolution(true); } }
protected override void SolveInstance(IGH_DataAccess DA) { double x = 0; double y = 0; double z = 0; double xx = 0; double yy = 0; double zz = 0; GH_Number ghSprX = new GH_Number(); if (DA.GetData(0, ref ghSprX)) { GH_Convert.ToDouble(ghSprX, out x, GH_Conversion.Both); } GH_Number ghSprY = new GH_Number(); if (DA.GetData(1, ref ghSprY)) { GH_Convert.ToDouble(ghSprY, out y, GH_Conversion.Both); } GH_Number ghSprZ = new GH_Number(); if (DA.GetData(2, ref ghSprZ)) { GH_Convert.ToDouble(ghSprZ, out z, GH_Conversion.Both); } GH_Number ghSprXX = new GH_Number(); if (DA.GetData(3, ref ghSprXX)) { GH_Convert.ToDouble(ghSprXX, out xx, GH_Conversion.Both); } GH_Number ghSprYY = new GH_Number(); if (DA.GetData(4, ref ghSprYY)) { GH_Convert.ToDouble(ghSprYY, out yy, GH_Conversion.Both); } GH_Number ghSprZZ = new GH_Number(); if (DA.GetData(5, ref ghSprZZ)) { GH_Convert.ToDouble(ghSprZZ, out zz, GH_Conversion.Both); } GsaSpring Spring = new GsaSpring { X = x, Y = y, Z = z, XX = xx, YY = yy, ZZ = zz }; DA.SetData(0, new GsaSpringGoo(Spring.Duplicate())); }
protected override void SolveInstance(IGH_DataAccess DA) { Util.Gears gear = new Util.Gears(); LModules.Clear(); Tangents.Clear(); HelicalRacks.Clear(); DA.GetDataList <Line>("Line", Tangents); DA.GetDataList <System.Object>("CircleModule", LModules); DA.GetData <double>("Teeth", ref Teeth); DA.GetData <double>("Angle", ref Angle); DA.GetData <double>("HelicalAngle", ref betaAngle); DA.GetData <double>("Depth", ref Depth); DA.GetData <double>("addendum", ref addendum); DA.GetData <double>("dedendum", ref dedendum); for (int i = 0; i < Tangents.Count; i++) { System.Object obj = LModules[0]; if (LModules.Count - 1 < i) { obj = LModules[LModules.Count - 1]; } else { obj = LModules[i]; } double n; Circle c = new Circle(); if (GH_Convert.ToCircle(obj, ref c, GH_Conversion.Both)) { HelicalRacks.Add(gear.buildHelicalRack(Tangents[i], c, Teeth, Angle, betaAngle, Depth, addendum, dedendum)); } if (GH_Convert.ToDouble(obj, out n, GH_Conversion.Primary)) { HelicalRacks.Add(gear.buildHelicalRack(Tangents[i], n, Teeth, Angle, betaAngle, Depth, addendum, dedendum)); } } DA.SetDataList(0, HelicalRacks); texts = gear.texts; locations = gear.locations; sizes = gear.sizes; }
//private void OnSolutionEnd(object sender, GH_SolutionEventArgs e) //{ // waitHandle.Set(); //} // GetFitnessValues: Collects the Fitness values from the component input internal List <double> GetFitnessValues() { var fitnesses = new List <double>(); foreach (IGH_Param source in gh.Params.Input[1].Sources) { foreach (var item in source.VolatileData.AllData(false)) { double fitness; if (GH_Convert.ToDouble(item, out fitness, GH_Conversion.Both)) { fitnesses.Add(fitness); } } } return(fitnesses); }
protected override void SolveInstance(IGH_DataAccess DA) { Util.Gears gear = new Util.Gears(); LModules = new List <System.Object>(); Tangents = new List <Line>(); Rack = new List <Curve>(); DA.GetDataList <Line>(0, Tangents); DA.GetDataList <System.Object>(1, LModules); DA.GetData <double>(2, ref Teeth); DA.GetData <double>(3, ref Angle); DA.GetData <double>(4, ref addendum); DA.GetData <double>(5, ref dedendum); for (int i = 0; i < Tangents.Count; i++) { System.Object obj = LModules[0]; if (LModules.Count - 1 < i) { obj = LModules[LModules.Count - 1]; } else { obj = LModules[i]; } double n; Circle c = new Circle(); if (GH_Convert.ToCircle(obj, ref c, GH_Conversion.Both)) { Rack.Add(gear.buildRack(Tangents[i], c, Teeth, Angle, addendum, dedendum)); } if (GH_Convert.ToDouble(obj, out n, GH_Conversion.Primary)) { Rack.Add(gear.buildRack(Tangents[i], n, Teeth, Angle, addendum, dedendum)); } } DA.SetDataList(0, Rack); texts = gear.texts; locations = gear.locations; sizes = gear.sizes; }
void Menu_SingleDoubleValueTextChanged(GH_MenuTextBox sender, string text) { if ((text.Length == 0)) { sender.TextBoxItem.ForeColor = System.Drawing.SystemColors.WindowText; } else { double d; if ((GH_Convert.ToDouble(text, out d, GH_Conversion.Secondary) && d > 0)) { sender.TextBoxItem.ForeColor = System.Drawing.SystemColors.WindowText; } else { sender.TextBoxItem.ForeColor = System.Drawing.Color.Red; } } }
protected override void SolveInstance(IGH_DataAccess DA) { double x1 = 0; double x2 = 0; double y = 0; double z = 0; GH_Number ghOffsetX1 = new GH_Number(); if (DA.GetData(0, ref ghOffsetX1)) { GH_Convert.ToDouble(ghOffsetX1, out x1, GH_Conversion.Both); } GH_Number ghOffsetX2 = new GH_Number(); if (DA.GetData(1, ref ghOffsetX2)) { GH_Convert.ToDouble(ghOffsetX2, out x2, GH_Conversion.Both); } GH_Number ghOffsetY = new GH_Number(); if (DA.GetData(2, ref ghOffsetY)) { GH_Convert.ToDouble(ghOffsetY, out y, GH_Conversion.Both); } GH_Number ghOffsetZ = new GH_Number(); if (DA.GetData(3, ref ghOffsetZ)) { GH_Convert.ToDouble(ghOffsetZ, out z, GH_Conversion.Both); } GsaOffset offset = new GsaOffset { X1 = x1, X2 = x2, Y = y, Z = z }; DA.SetData(0, new GsaOffsetGoo(offset.Duplicate())); }
protected override void SolveInstance(IGH_DataAccess DA) { GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(0, ref gh_typ)) { if (gh_typ == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Solid input is null"); } GsaMember3d mem = new GsaMember3d(); Brep brep = new Brep(); Mesh mesh = new Mesh(); if (GH_Convert.ToBrep(gh_typ.Value, ref brep, GH_Conversion.Both)) { mem = new GsaMember3d(brep); } else if (GH_Convert.ToMesh(gh_typ.Value, ref mesh, GH_Conversion.Both)) { mem = new GsaMember3d(mesh); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert Geometry input to a 3D Member"); return; } // 1 prop3d to be implemented GsaAPI // 2 mesh size GH_Number ghmsz = new GH_Number(); if (DA.GetData(2, ref ghmsz)) { GH_Convert.ToDouble(ghmsz, out double m_size, GH_Conversion.Both); mem.Member.MeshSize = m_size; } DA.SetData(0, new GsaMember3dGoo(mem)); } }
protected override void SolveInstance(IGH_DataAccess DA) { checked { var Points = new List <Point3d>(); DA.GetDataList(0, Points); var attrition = 1.0; DA.GetData("Attrition", ref attrition); var nodeTwoList = new Grasshopper.Kernel.Geometry.Node2List(Points); var delaunayFaces = Grasshopper.Kernel.Geometry.Delaunay.Solver.Solve_Faces(nodeTwoList, 1); var delaunayMesh = Grasshopper.Kernel.Geometry.Delaunay.Solver.Solve_Mesh(nodeTwoList, 1, ref delaunayFaces); delaunayMesh.Weld(Math.PI); var list = new List <object>(); var circles = new SurfaceComponents.MeshComponents.Component_MeshFaceCircles(); var param = circles.Params.Input[0] as Grasshopper.Kernel.GH_PersistentGeometryParam <Grasshopper.Kernel.Types.GH_Mesh>; param.PersistentData.ClearData(); param.PersistentData.Append(new GH_Mesh(delaunayMesh)); circles.ExpireSolution(true); //add to a dummy document so we can read outputs var doc = new Grasshopper.Kernel.GH_Document(); doc.AddObject(circles, false); //read output circles circles.Params.Output[0].CollectData(); var ratio = new double[circles.Params.Output[1].VolatileDataCount]; for (int i = 0; i < circles.Params.Output[0].VolatileDataCount; ++i) { //ratio[i] = circles.Params.Output[1].VolatileData.get_Branch(0)[i]; GH_Convert.ToDouble(circles.Params.Output[1].VolatileData.get_Branch(0)[i], out ratio[i], GH_Conversion.Both); list.Add(circles.Params.Output[0].VolatileData.get_Branch(0)[i]); } var arcsList = new double[list.Count]; var arcs = new AnalysisComponents.Component_DeconstructArc(); var arcParams = arcs.Params.Input[0] as Grasshopper.Kernel.GH_PersistentParam <Grasshopper.Kernel.Types.GH_Arc>; arcParams.PersistentData.ClearData(); var circle = new Arc[delaunayMesh.Faces.Count]; for (int i = 0; i < list.Count; ++i) { GH_Convert.ToArc(list[i], ref circle[i], GH_Conversion.Both); arcParams.PersistentData.Append(new GH_Arc(circle[i])); } arcs.ExpireSolution(true); var docOne = new Grasshopper.Kernel.GH_Document(); docOne.AddObject(arcs, false); arcs.Params.Output[0].CollectData(); for (int i = 0; i < arcs.Params.Output[1].VolatileDataCount; ++i) { GH_Convert.ToDouble(arcs.Params.Output[1].VolatileData.get_Branch(0)[i], out arcsList[i], GH_Conversion.Both); //arcsList.Add(arcs.Params.Output[1].VolatileData.get_Branch(0)[i]); } var faceMesh = new List <object>(); var verticesMesh = new List <object>(); var deMesh = new SurfaceComponents.MeshComponents.Component_DeconstructMesh(); var meshParams = deMesh.Params.Input[0] as Grasshopper.Kernel.GH_PersistentParam <Grasshopper.Kernel.Types.GH_Mesh>; meshParams.PersistentData.ClearData(); meshParams.PersistentData.Append(new GH_Mesh(delaunayMesh)); deMesh.ExpireSolution(true); var docTwo = new Grasshopper.Kernel.GH_Document(); docTwo.AddObject(deMesh, false); deMesh.Params.Output[0].CollectData(); for (int i = 0; i < deMesh.Params.Output[0].VolatileDataCount; ++i) { verticesMesh.Add(deMesh.Params.Output[0].VolatileData.get_Branch(0)[i]); } for (int i = 0; i < deMesh.Params.Output[1].VolatileDataCount; ++i) { faceMesh.Add(deMesh.Params.Output[1].VolatileData.get_Branch(0)[i]); } var faceCullRadius = RadiusSorting(faceMesh, arcsList); Array.Sort(ratio); var splitListIndex = Convert.ToInt32((ratio[ratio.Length - 1] * faceMesh.Count) * attrition); //var splitListIndex = Convert.ToInt32(Attrition); var splitList = SplitList(faceCullRadius, splitListIndex); var constructMesh = new Mesh(); var meshPoints = new Point3d[verticesMesh.Count]; for (int i = 0; i < verticesMesh.Count; ++i) { GH_Convert.ToPoint3d(verticesMesh[i], ref meshPoints[i], GH_Conversion.Both); constructMesh.Vertices.Add(meshPoints[i]); } var meshFaces = new Grasshopper.Kernel.Types.GH_MeshFace[splitList.Count]; for (int i = 0; i < splitList.Count; ++i) { GH_Convert.ToGHMeshFace(splitList[i], GH_Conversion.Both, ref meshFaces[i]); constructMesh.Faces.AddFace(meshFaces[i].Value); } var ConcaveHull = constructMesh.GetNakedEdges(); DA.SetDataList(0, ConcaveHull); } }
protected override void SolveInstance(IGH_DataAccess DA) { // Set up Utility object and start process Utility utility = new Utility(DA); utility.Print("Starting Curtain Walls."); List <string> instructionData = new List <string>(); // Get Inputs string folderPath = null, fileName = null; bool write = false; if (!utility.GetInput(0, ref write)) // Write command is required { utility.WriteOut(); return; } if (!utility.GetInput(1, ref folderPath)) // Folder path is required { utility.WriteOut(); return; } utility.GetInput(2, ref fileName, true, true, true); // File name is optional if (fileName == null) { fileName = this.DEFAULT_FILE_NAME; } GH_Structure <GH_Curve> curvesDataTree = null; // curves in Data Tree required if (!utility.GetInput(3, out curvesDataTree)) { return; } string wallTypeName = null; // Type is optional (no family, just type) utility.GetInput(4, ref wallTypeName); double wallHeight = 0; // Wall Height is optional utility.GetInput(5, ref wallHeight); GH_Structure <GH_String> gridMullionsDataTree = null; // Grids/Mullions are optional; might make sense during development utility.GetInput(6, out gridMullionsDataTree); if (write) { try { // Create RevitModelBuilderUtility object and link to CSV file CsvWriter csvWriter = new CsvWriter(); utility.Print("CsvWriter Version: " + csvWriter.Version); if (!utility.EstablishCsvLink(csvWriter, folderPath, fileName)) { utility.Print("EstablishCsvLink() failed"); utility.WriteOut(); return; } // Set Wall Type if (wallTypeName != null) { csvWriter.SetWallType(wallTypeName); } //Set Wall Height double revitWallHeight = 10.0; if (wallHeight != 0) { GH_Convert.ToDouble(wallHeight, out revitWallHeight, GH_Conversion.Both); csvWriter.SetWallHeight(revitWallHeight); } List <List <HbCurve> > curvesListListRevit = new List <List <HbCurve> >(); // Loop through the data tree of curves and process each one. for (int i = 0; i < curvesDataTree.Branches.Count; i++) { if (!utility.ReadDataTreeBranch(curvesDataTree.Branches[i], ref curvesListListRevit)) { utility.Print("ReadDataTreeBranch() failed at curvesDataTree"); utility.WriteOut(); return; } } //TODO test missing input List <List <String> > stringsListListRevit = new List <List <string> >(); // Loop through the data tree of mullions and process each one. for (int i = 0; i < gridMullionsDataTree.Branches.Count; i++) { if (!utility.ReadDataTreeBranch(gridMullionsDataTree.Branches[i], ref stringsListListRevit)) { utility.Print("ReadDataTreeBranch() failed at stringsListListRevit"); utility.WriteOut(); return; } } string familyNameCurrent = null; string typeNameCurrrent = null; for (int i = 0; i < curvesListListRevit.Count; i++) { List <HbCurve> curvesListRevit = curvesListListRevit[i]; csvWriter.AddWall(curvesListRevit); instructionData.Add("Add Curtain Wall:"); // Stop if (stringsListListRevit.Count > i) // Ignore mismatched list? Better would be to reuse? //outputStrings.Add("<" + direction + "><" + primaryOffset.ToString() + "><" + secondaryOffset.ToString() + "><" + familyName + "><" + typeName + ">"); { string direction; string primaryOffsetString; string secondaryOffsetString; string familyName; string typeName; //bool oneSegmentOnly; foreach (string stringSource in stringsListListRevit[i]) { if (!parseString(stringSource, out direction, out primaryOffsetString, out secondaryOffsetString, out familyName, out typeName)) { continue; // Silent ignore bad values } direction = direction.ToUpper(); if (!(direction == "U" || direction == "V")) { continue; } double primaryOffset, secondaryOffset; double.TryParse(primaryOffsetString, out primaryOffset); if (double.IsNaN(primaryOffset) || double.IsInfinity(primaryOffset)) { continue; } double.TryParse(secondaryOffsetString, out secondaryOffset); if (double.IsNaN(secondaryOffset) || double.IsInfinity(secondaryOffset)) { secondaryOffset = 0.0; } if (familyName != null && familyName != "" && typeName != null && typeName != "") { if (familyName != familyNameCurrent || typeName != typeNameCurrrent) { if (!(familyName == "$none$" || typeName == "$none$")) { csvWriter.SetMullionType(familyName, typeName); } familyNameCurrent = familyName; typeNameCurrrent = typeName; } } if (direction == "U") { if (secondaryOffset == 0) // full length case { if (familyName == "$none$" || typeName == "$none$") // - grid case { csvWriter.ModifyCurtainGridUAdd(primaryOffset); } else // - mullion case { csvWriter.ModifyMullionUAdd(primaryOffset); } } else // oneSegmentOnly case { if (familyName == "$none$" || typeName == "$none$") // - grid case { csvWriter.ModifyCurtainGridUAdd(primaryOffset, secondaryOffset); } else // - mullion case { csvWriter.ModifyMullionUAdd(primaryOffset, secondaryOffset); } } } else // direction == "V" case { if (secondaryOffset == 0) // full length case { if (familyName == "$none$" || typeName == "$none$") // - grid case { csvWriter.ModifyCurtainGridVAdd(primaryOffset); } else // - mullion case { csvWriter.ModifyMullionVAdd(primaryOffset); } } else // oneSegmentOnly case { if (familyName == "$none$" || typeName == "$none$") // - grid case { csvWriter.ModifyCurtainGridVAdd(primaryOffset, secondaryOffset); } else // - mullion case { csvWriter.ModifyMullionVAdd(primaryOffset, secondaryOffset); } } } instructionData.Add("Add Grid/Mullion:"); } } //if (gridMullionsDataTree == null) continue; // Not sure if this occurs //if (gridMullionsDataTree.Count == 0) continue; // Valid but no grids or mullions included //string currentMullionFamilyName = ""; //string currentMullionTypeName = ""; //for (int j = 0; j < gridMullionsDataTree.Count; j++) { //} } csvWriter.WriteFile(); utility.Print("Add Curtain Wall completed successfully."); } catch (Exception exception) { utility.Print(exception.Message); } } utility.WriteOut(); DA.SetDataList(1, instructionData); // Temp //DA.SetDataList(1, gridMullionsDataTree); }
protected override void SolveInstance(IGH_DataAccess DA) { GsaMember3d gsaMember3d = new GsaMember3d(); if (DA.GetData(0, ref gsaMember3d)) { if (gsaMember3d == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Member3D input is null"); } GsaMember3d mem = gsaMember3d.Duplicate(); // #### inputs #### // 1 ID GH_Integer ghID = new GH_Integer(); if (DA.GetData(1, ref ghID)) { if (GH_Convert.ToInt32(ghID, out int id, GH_Conversion.Both)) { mem.ID = id; } } // 2 geometry GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(2, ref gh_typ)) { GsaMember3d tempMem = new GsaMember3d(); Brep brep = new Brep(); Mesh mesh = new Mesh(); if (GH_Convert.ToBrep(gh_typ.Value, ref brep, GH_Conversion.Both)) { tempMem = new GsaMember3d(brep); } else if (GH_Convert.ToMesh(gh_typ.Value, ref mesh, GH_Conversion.Both)) { tempMem = new GsaMember3d(mesh); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert Geometry input to a 3D Member"); return; } mem.SolidMesh = tempMem.SolidMesh; } // 3 prop3d -- to be implemented GsaAPI gh_typ = new GH_ObjectWrapper(); if (DA.GetData(3, ref gh_typ)) { if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both)) { mem.Member.Property = idd; } //GsaProp3d prop3d = new GsaProp3d(); //if (gh_typ.Value is GsaProp3dGoo) // gh_typ.CastTo(ref prop3d); //else //{ // if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both)) // prop3d.ID = idd; // else // { // AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert PA input to a 3D Property of reference integer"); // return; // } //} //mem.Property = prop3d; } // 4 mesh size GH_Number ghmsz = new GH_Number(); if (DA.GetData(4, ref ghmsz)) { if (GH_Convert.ToDouble(ghmsz, out double msz, GH_Conversion.Both)) { mem.Member.MeshSize = msz; } } // 5 mesh with others GH_Boolean ghbool = new GH_Boolean(); if (DA.GetData(5, ref ghbool)) { if (GH_Convert.ToBoolean(ghbool, out bool mbool, GH_Conversion.Both)) { //mem.member.MeshWithOthers } } // 6 name GH_String ghnm = new GH_String(); if (DA.GetData(6, ref ghnm)) { if (GH_Convert.ToString(ghnm, out string name, GH_Conversion.Both)) { mem.Member.Name = name; } } // 7 Group GH_Integer ghgrp = new GH_Integer(); if (DA.GetData(7, ref ghgrp)) { if (GH_Convert.ToInt32(ghgrp, out int grp, GH_Conversion.Both)) { mem.Member.Group = grp; } } // 8 Colour GH_Colour ghcol = new GH_Colour(); if (DA.GetData(8, ref ghcol)) { if (GH_Convert.ToColor(ghcol, out System.Drawing.Color col, GH_Conversion.Both)) { mem.Member.Colour = col; } } // 9 Dummy GH_Boolean ghdum = new GH_Boolean(); if (DA.GetData(9, ref ghdum)) { if (GH_Convert.ToBoolean(ghdum, out bool dum, GH_Conversion.Both)) { mem.Member.IsDummy = dum; } } // #### outputs #### DA.SetData(0, new GsaMember3dGoo(mem)); DA.SetData(1, mem.ID); DA.SetData(2, mem.SolidMesh); //DA.SetData(3, mem.Property); DA.SetData(4, mem.Member.MeshSize); //DA.SetData(5, mem.Member.MeshWithOthers); DA.SetData(6, mem.Member.Name); DA.SetData(7, mem.Member.Group); DA.SetData(8, mem.Member.Colour); DA.SetData(9, mem.Member.IsDummy); } }
/// <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) { bool IsPointData = false; GH_Structure <IGH_Goo> data = new GH_Structure <IGH_Goo>(); List <double> eps = new List <double>(); List <int> minP = new List <int>(); if (!DA.GetDataTree(0, out data)) { return; } if (!DA.GetDataList(1, eps)) { return; } if (!DA.GetDataList(2, minP)) { return; } data.Simplify(GH_SimplificationMode.CollapseAllOverlaps); List <DataSetItemPoint[]> points = new List <DataSetItemPoint[]>(); for (int i = 0; i < data.Branches.Count; i++) { DataSetItemPoint[] pp = new DataSetItemPoint[data.Branches[i].Count]; for (int j = 0; j < data.Branches[i].Count; j++) { if (data.Branches[i][j] is GH_Point) { IsPointData = true; GH_Point target = new GH_Point(); if (GH_Convert.ToGHPoint(data.Branches[i][j], GH_Conversion.Both, ref target)) { pp[j] = new DataSetItemPoint(target.Value.X, target.Value.Y, target.Value.Z, 0.0); } } else { break; } } if (IsPointData) { points.Add(pp); } else { break; } } // double data if (!IsPointData) { DataSetItemPoint[] pp = new DataSetItemPoint[data.Branches.Count]; for (int i = 0; i < data.Branches.Count; i++) { DataSetItemPoint p = new DataSetItemPoint(); for (int j = 0; j < data.Branches[i].Count; j++) { if (data.Branches[i][j] is GH_Number) { if (GH_Convert.ToDouble(data.Branches[i][j], out double value, GH_Conversion.Both)) { switch (j) { case 0: p.X = value; break; case 1: p.Y = value; break; case 2: p.Z = value; break; case 3: p.W = value; break; } } } } pp[i] = p; } points.Add(pp); } if (IsPointData) { DataTree <IGH_Goo> output = new DataTree <IGH_Goo>(); for (int i = 0; i < points.Count; i++) { DbscanAlgorithm <DataSetItemPoint> dbs = new DbscanAlgorithm <DataSetItemPoint>((x, y) => Math.Sqrt(((x.X - y.X) * (x.X - y.X)) + ((x.Y - y.Y) * (x.Y - y.Y)) + ((x.Z - y.Z) * (x.Z - y.Z)) + ((x.W - y.W) * (x.W - y.W)))); dbs.ComputeClusterDbscan(points[i].ToArray(), eps[i], minP[i], out HashSet <DataSetItemPoint[]> clusters3d); for (int j = 0; j < clusters3d.Count; j++) { ConcurrentQueue <GH_Point> _points = new ConcurrentQueue <GH_Point>(); Parallel.ForEach(clusters3d.ElementAt(j), p => { _points.Enqueue(new GH_Point(new Point3d(p.X, p.Y, p.Z))); }); output.AddRange(_points.ToList(), new GH_Path(i, j)); } } DA.SetDataTree(0, output); } else { DataTree <GH_Number> output = new DataTree <GH_Number>(); for (int i = 0; i < points.Count; i++) { DbscanAlgorithm <DataSetItemPoint> dbs = new DbscanAlgorithm <DataSetItemPoint>((x, y) => Math.Sqrt(((x.X - y.X) * (x.X - y.X)) + ((x.Y - y.Y) * (x.Y - y.Y)) + ((x.Z - y.Z) * (x.Z - y.Z)) + ((x.W - y.W) * (x.W - y.W)))); dbs.ComputeClusterDbscan(points[i].ToArray(), eps[i], minP[i], out HashSet <DataSetItemPoint[]> clusters3d); for (int j = 0; j < clusters3d.Count; j++) { ConcurrentQueue <List <double> > _points = new ConcurrentQueue <List <double> >(); for (int k = 0; k < clusters3d.ElementAt(j).Length; k++) { List <GH_Number> ii = new List <GH_Number>(); GH_Number target1 = new GH_Number(); GH_Number target2 = new GH_Number(); GH_Number target3 = new GH_Number(); GH_Number target4 = new GH_Number(); if (GH_Convert.ToGHNumber(clusters3d.ElementAt(j).ElementAt(k).X, GH_Conversion.Both, ref target1)) { ii.Add(target1); } if (GH_Convert.ToGHNumber(clusters3d.ElementAt(j).ElementAt(k).Y, GH_Conversion.Both, ref target2)) { ii.Add(target2); } if (GH_Convert.ToGHNumber(clusters3d.ElementAt(j).ElementAt(k).Z, GH_Conversion.Both, ref target3)) { ii.Add(target3); } if (GH_Convert.ToGHNumber(clusters3d.ElementAt(j).ElementAt(k).W, GH_Conversion.Both, ref target4)) { ii.Add(target4); } output.AddRange(ii, new GH_Path(i, j, k)); } } } DA.SetDataTree(0, output); } }
protected override void SolveInstance(IGH_DataAccess DA) { GH_Brep ghbrep = new GH_Brep(); if (DA.GetData(0, ref ghbrep)) { if (ghbrep == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Brep input is null"); } Brep brep = new Brep(); if (GH_Convert.ToBrep(ghbrep, ref brep, GH_Conversion.Both)) { // 1 Points List <GH_ObjectWrapper> gh_types = new List <GH_ObjectWrapper>(); List <Point3d> pts = new List <Point3d>(); List <GsaNode> nodes = new List <GsaNode>(); if (DA.GetDataList(1, gh_types)) { for (int i = 0; i < gh_types.Count; i++) { Point3d pt = new Point3d(); if (gh_types[i].Value is GsaNodeGoo) { GsaNode gsanode = new GsaNode(); gh_types[i].CastTo(ref gsanode); nodes.Add(gsanode); } else if (GH_Convert.ToPoint3d(gh_types[i].Value, ref pt, GH_Conversion.Both)) { pts.Add(pt); } else { string type = gh_types[i].Value.GetType().ToString(); type = type.Replace("GhSA.Parameters.", ""); type = type.Replace("Goo", ""); AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert incl. Point/Node input parameter of type " + type + " to point or node"); } } } // 2 Curves gh_types = new List <GH_ObjectWrapper>(); List <Curve> crvs = new List <Curve>(); List <GsaMember1d> mem1ds = new List <GsaMember1d>(); if (DA.GetDataList(2, gh_types)) { for (int i = 0; i < gh_types.Count; i++) { Curve crv = null; if (gh_types[i].Value is GsaMember1dGoo) { GsaMember1d gsamem1d = new GsaMember1d(); gh_types[i].CastTo(ref gsamem1d); mem1ds.Add(gsamem1d); } else if (GH_Convert.ToCurve(gh_types[i].Value, ref crv, GH_Conversion.Both)) { crvs.Add(crv); } else { string type = gh_types[i].Value.GetType().ToString(); type = type.Replace("GhSA.Parameters.", ""); type = type.Replace("Goo", ""); AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert incl. Curve/Mem1D input parameter of type " + type + " to curve or 1D Member"); } } } // 4 mesh size GH_Number ghmsz = new GH_Number(); double meshSize = 0; if (DA.GetData(4, ref ghmsz)) { GH_Convert.ToDouble(ghmsz, out double m_size, GH_Conversion.Both); meshSize = m_size; } // build new element2d with brep, crv and pts GsaElement2d elem2d = new GsaElement2d(brep, crvs, pts, meshSize, mem1ds, nodes); // 3 section GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); GsaProp2d prop2d = new GsaProp2d(); if (DA.GetData(3, ref gh_typ)) { if (gh_typ.Value is GsaProp2dGoo) { gh_typ.CastTo(ref prop2d); } else { if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both)) { prop2d.ID = idd; } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert PA input to a 2D Property of reference integer"); return; } } } else { prop2d.ID = 1; } List <GsaProp2d> prop2Ds = new List <GsaProp2d>(); for (int i = 0; i < elem2d.Elements.Count; i++) { prop2Ds.Add(prop2d); } elem2d.Properties = prop2Ds; DA.SetData(0, new GsaElement2dGoo(elem2d)); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { GH_Structure <IGH_GeometricGoo> gGoo = new GH_Structure <IGH_GeometricGoo>(); DA.GetDataTree <IGH_GeometricGoo>("Feature Geometry", out gGoo); GH_Structure <GH_Number> bufferInt = new GH_Structure <GH_Number>(); DA.GetDataTree <GH_Number>("Buffer Distance", out bufferInt); GH_Structure <IGH_GeometricGoo> gGooBuffered = new GH_Structure <IGH_GeometricGoo>(); ///GDAL setup RESTful.GdalConfiguration.ConfigureOgr(); ///Use WGS84 spatial reference OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference(""); dst.SetWellKnownGeogCS("WGS84"); Transform transform = new Transform(1); // Heron.Convert.XYZToWGSTransform(); Transform revTransform = new Transform(1); //Heron.Convert.WGSToXYZTransform(); ///Create virtual datasource to be converted later ///Using geojson as a flexiblle base file type which can be converted later with ogr2ogr OSGeo.OGR.Driver drv = Ogr.GetDriverByName("GeoJSON"); DataSource ds = drv.CreateDataSource("/vsimem/out.geojson", null); ///Use OGR catch-all for geometry types var gtype = wkbGeometryType.wkbGeometryCollection; ///Create layer OSGeo.OGR.Layer layer = ds.CreateLayer("temp", dst, gtype, null); FeatureDefn def = layer.GetLayerDefn(); var branchPaths = gGoo.Paths; for (int a = 0; a < gGoo.Branches.Count; a++) { ///create feature OSGeo.OGR.Feature feature = new OSGeo.OGR.Feature(def); ///Get geometry type(s) in branch var geomList = gGoo.Branches[a]; string geomType = string.Empty; List <string> geomTypeList = geomList.Select(o => o.TypeName).ToList(); ///Test if geometry in the branch is of the same type. ///If there is more than one element of a type, tag as multi, if there is more than one type, tag as mixed if (geomTypeList.Count == 1) { geomType = geomTypeList.First(); } else if (geomTypeList.Count > 1 && geomTypeList.All(gt => gt == geomTypeList.First())) { geomType = "Multi" + geomTypeList.First(); } else { geomType = "Mixed"; } //var buffList = bufferInt.Branches[a]; var buffList = new List <GH_Number>(); //var path = new GH_Path(a); var path = branchPaths[a]; if (path.Valid) { buffList = (List <GH_Number>)bufferInt.get_Branch(path); } else { buffList = bufferInt.Branches[0]; } int buffIndex = 0; double buffDist = 0; GH_Convert.ToDouble(buffList[buffIndex], out buffDist, GH_Conversion.Primary); ///For testing //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, geomType); ///Add geomtery to feature ///Create containers for translating from GH Goo Point3d pt = new Point3d(); List <Point3d> pts = new List <Point3d>(); Curve crv = null; List <Curve> crvs = new List <Curve>(); Mesh mesh = new Mesh(); Mesh multiMesh = new Mesh(); int quadsecs = 10; switch (geomType) { case "Point": geomList.First().CastTo <Point3d>(out pt); var bufferPt = Heron.Convert.Point3dToOgrPoint(pt, transform).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPt, revTransform), new GH_Path(a)); break; case "MultiPoint": foreach (var point in geomList) { point.CastTo <Point3d>(out pt); pts.Add(pt); } var bufferPts = Heron.Convert.Point3dsToOgrMultiPoint(pts, transform).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPts, revTransform), new GH_Path(a)); break; case "Curve": geomList.First().CastTo <Curve>(out crv); var bufferCrv = Heron.Convert.CurveToOgrLinestring(crv, transform).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrv, revTransform), new GH_Path(a)); break; case "MultiCurve": bool allClosed = true; foreach (var curve in geomList) { curve.CastTo <Curve>(out crv); if (!crv.IsClosed) { allClosed = false; } crvs.Add(crv); } if (allClosed) { var bufferCrvs = Heron.Convert.CurvesToOgrPolygon(crvs, transform).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrvs, revTransform), new GH_Path(a)); } else { var bufferCrvs = Heron.Convert.CurvesToOgrMultiLinestring(crvs, transform).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCrvs, revTransform), new GH_Path(a)); } break; case "Mesh": geomList.First().CastTo <Mesh>(out mesh); mesh.Ngons.AddPlanarNgons(DocumentTolerance()); var bufferPoly = Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(mesh, transform)).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPoly, revTransform), new GH_Path(a)); break; case "MultiMesh": foreach (var m in geomList) { Mesh meshPart = new Mesh(); m.CastTo <Mesh>(out meshPart); meshPart.Ngons.AddPlanarNgons(DocumentTolerance()); multiMesh.Append(meshPart); } var bufferPolys = Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(multiMesh, transform)).Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferPolys, revTransform), new GH_Path(a)); break; case "Mixed": OSGeo.OGR.Geometry geoCollection = new OSGeo.OGR.Geometry(wkbGeometryType.wkbGeometryCollection); for (int gInt = 0; gInt < geomList.Count; gInt++) { string geomTypeMixed = geomTypeList[gInt]; switch (geomTypeMixed) { case "Point": geomList[gInt].CastTo <Point3d>(out pt); geoCollection.AddGeometry(Heron.Convert.Point3dToOgrPoint(pt, transform)); break; case "Curve": geomList[gInt].CastTo <Curve>(out crv); geoCollection.AddGeometry(Heron.Convert.CurveToOgrLinestring(crv, transform)); break; case "Mesh": geomList[gInt].CastTo <Mesh>(out mesh); geoCollection.AddGeometry(Ogr.ForceToMultiPolygon(Heron.Convert.MeshToMultiPolygon(mesh, transform))); break; default: AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Not able to export " + geomType + " geometry at branch " + gGoo.get_Path(a).ToString() + ". Geometry must be a Point, Curve or Mesh."); break; } } var bufferCol = geoCollection.Buffer(buffDist, quadsecs); gGooBuffered.AppendRange(Heron.Convert.OgrGeomToGHGoo(bufferCol, revTransform), new GH_Path(a)); break; default: AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Not able to export " + geomType + " geometry at branch " + gGoo.get_Path(a).ToString() + ". Geometry must be a Point, Curve or Mesh."); break; } } def.Dispose(); layer.Dispose(); ds.Dispose(); DA.SetDataTree(0, gGooBuffered); }
protected override void SolveInstance(IGH_DataAccess DA) { GsaProp2d prop = new GsaProp2d(); prop.Prop2d = new Prop2D(); prop.ID = 0; // element type (picked in dropdown) prop.Prop2d.Type = Property2D_Type.UNDEF; if (_mode == FoldMode.PlaneStress) prop.Prop2d.Type = Property2D_Type.PL_STRESS; if (_mode == FoldMode.Fabric) prop.Prop2d.Type = Property2D_Type.FABRIC; if (_mode == FoldMode.FlatPlate) prop.Prop2d.Type = Property2D_Type.PLATE; if (_mode == FoldMode.Shell) prop.Prop2d.Type = Property2D_Type.SHELL; if (_mode == FoldMode.CurvedShell) prop.Prop2d.Type = Property2D_Type.CURVED_SHELL; if (_mode == FoldMode.LoadPanel) prop.Prop2d.Type = Property2D_Type.LOAD; if (_mode != FoldMode.LoadPanel) { prop.Prop2d.AxisProperty = 0; if (_mode != FoldMode.Fabric) { // 0 Material GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(0, ref gh_typ)) { GsaMaterial material = new GsaMaterial(); if (gh_typ.Value is GsaMaterialGoo) { gh_typ.CastTo(ref material); prop.Material = material; } else { if (GH_Convert.ToInt32(gh_typ.Value, out int idd, GH_Conversion.Both)) { prop.Material = new GsaMaterial(idd); } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Unable to convert PB input to a Section Property of reference integer"); return; } } } else prop.Material = new GsaMaterial(2); // 1 thickness //GH_String gh_THK = new GH_String(); //string thickness = "0.2"; //if (DA.GetData(1, ref gh_THK)) // GH_Convert.ToString(gh_THK, out thickness, GH_Conversion.Both); //prop.Prop2d.Description = thickness; GH_Number gh_THK = new GH_Number(); double thickness = 200; if (DA.GetData(1, ref gh_THK)) GH_Convert.ToDouble(gh_THK, out thickness, GH_Conversion.Both); prop.Thickness = thickness; }
protected override void SolveInstance(IGH_DataAccess DA) { // Model to work on GsaModel in_Model = new GsaModel(); // Get Model GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(0, ref gh_typ)) { #region Inputs if (gh_typ.Value is GsaModelGoo) { gh_typ.CastTo(ref in_Model); if (gsaModel != null) { if (in_Model.GUID != gsaModel.GUID) { gsaModel = in_Model; getresults = true; } } else { gsaModel = in_Model; } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Error converting input to GSA Model"); return; } // Get analysis case GH_Integer gh_aCase = new GH_Integer(); DA.GetData(1, ref gh_aCase); GH_Convert.ToInt32(gh_aCase, out int tempanalCase, GH_Conversion.Both); // Get element filter list GH_String gh_elList = new GH_String(); DA.GetData(2, ref gh_elList); GH_Convert.ToString(gh_elList, out string tempelemList, GH_Conversion.Both); // Get number of divisions GH_Integer gh_Div = new GH_Integer(); DA.GetData(3, ref gh_Div); GH_Convert.ToInt32(gh_Div, out int temppositionsCount, GH_Conversion.Both); // Get colours List <Grasshopper.Kernel.Types.GH_Colour> gh_Colours = new List <Grasshopper.Kernel.Types.GH_Colour>(); List <System.Drawing.Color> colors = new List <System.Drawing.Color>(); if (DA.GetDataList(4, gh_Colours)) { for (int i = 0; i < gh_Colours.Count; i++) { System.Drawing.Color color = new System.Drawing.Color(); GH_Convert.ToColor(gh_Colours[i], out color, GH_Conversion.Both); colors.Add(color); } } Grasshopper.GUI.Gradient.GH_Gradient gH_Gradient = UI.Colour.Stress_Gradient(colors); // Get scalar GH_Number gh_Scale = new GH_Number(); DA.GetData(5, ref gh_Scale); double scale = 1; GH_Convert.ToDouble(gh_Scale, out scale, GH_Conversion.Both); #endregion #region get results? // check if we must get results or just update display if (analCase == 0 || analCase != tempanalCase) { analCase = tempanalCase; getresults = true; } if (elemList == "" || elemList != tempelemList) { elemList = tempelemList; getresults = true; } if (positionsCount == 0 || positionsCount != temppositionsCount) { positionsCount = temppositionsCount; getresults = true; } #endregion #region Create results output if (getresults) { #region Get results from GSA // ### Get results ### //Get analysis case from model AnalysisCaseResult analysisCaseResult = null; gsaModel.Model.Results().TryGetValue(analCase, out analysisCaseResult); if (analysisCaseResult == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No results exist for Analysis Case " + analCase + " in file"); return; } IReadOnlyDictionary <int, Element1DResult> globalResults = analysisCaseResult.Element1DResults(elemList, positionsCount); IReadOnlyDictionary <int, Element> elems = gsaModel.Model.Elements(elemList); IReadOnlyDictionary <int, Node> nodes = gsaModel.Model.Nodes(); #endregion // ### Loop through results ### // clear existing result lists xyz_out = new DataTree <Vector3d>(); xxyyzz_out = new DataTree <Vector3d>(); segmentlines = new DataTree <Line>(); List <int> elemID = new List <int>(); List <int> parentMember = new List <int>(); // maximum and minimum result values for colouring later dmax_x = 0; dmax_y = 0; dmax_z = 0; dmax_xx = 0; dmax_yy = 0; dmax_zz = 0; dmax_xyz = 0; dmax_xxyyzz = 0; dmin_x = 0; dmin_y = 0; dmin_z = 0; dmin_xx = 0; dmin_yy = 0; dmin_zz = 0; dmin_xyz = 0; dmin_xxyyzz = 0; double unitfactorxyz = 1; double unitfactorxxyyzz = 1; foreach (int key in globalResults.Keys) { // lists for results Element1DResult elementResults; globalResults.TryGetValue(key, out elementResults); List <Double6> values = new List <Double6>(); List <Vector3d> xyz = new List <Vector3d>(); List <Vector3d> xxyyzz = new List <Vector3d>(); // list for element geometry and info Element element = new Element(); elems.TryGetValue(key, out element); Node start = new Node(); nodes.TryGetValue(element.Topology[0], out start); Node end = new Node(); nodes.TryGetValue(element.Topology[1], out end); Line ln = new Line( new Point3d(start.Position.X, start.Position.Y, start.Position.Z), new Point3d(end.Position.X, end.Position.Y, end.Position.Z)); elemID.Add(key); parentMember.Add(element.ParentMember.Member); // set the result type dependent on user selection in dropdown switch (_mode) { case (FoldMode.Displacement): values = elementResults.Displacement.ToList(); unitfactorxyz = 0.001; unitfactorxxyyzz = 1; break; case (FoldMode.Force): values = elementResults.Force.ToList(); unitfactorxyz = 1000; unitfactorxxyyzz = 1000; break; } // prepare the line segments int segments = Math.Max(1, values.Count - 1); // number of segment lines is 1 less than number of points int segment = 0; // counter for segments List <Line> segmentedlines = new List <Line>(); // loop through the results foreach (Double6 result in values) { // update max and min values if (result.X / unitfactorxyz > dmax_x) { dmax_x = result.X / unitfactorxyz; } if (result.Y / unitfactorxyz > dmax_y) { dmax_y = result.Y / unitfactorxyz; } if (result.Z / unitfactorxyz > dmax_z) { dmax_z = result.Z / unitfactorxyz; } if (Math.Sqrt(Math.Pow(result.X, 2) + Math.Pow(result.Y, 2) + Math.Pow(result.Z, 2)) / unitfactorxyz > dmax_xyz) { dmax_xyz = Math.Sqrt(Math.Pow(result.X, 2) + Math.Pow(result.Y, 2) + Math.Pow(result.Z, 2)) / unitfactorxyz; } if (result.XX / unitfactorxxyyzz > dmax_xx) { dmax_xx = result.XX / unitfactorxxyyzz; } if (result.YY / unitfactorxxyyzz > dmax_yy) { dmax_yy = result.YY / unitfactorxxyyzz; } if (result.ZZ / unitfactorxxyyzz > dmax_zz) { dmax_zz = result.ZZ / unitfactorxxyyzz; } if (Math.Sqrt(Math.Pow(result.XX, 2) + Math.Pow(result.YY, 2) + Math.Pow(result.ZZ, 2)) / unitfactorxxyyzz > dmax_xxyyzz) { dmax_xxyyzz = Math.Sqrt(Math.Pow(result.XX, 2) + Math.Pow(result.YY, 2) + Math.Pow(result.ZZ, 2)) / unitfactorxxyyzz; } if (result.X / unitfactorxyz < dmin_x) { dmin_x = result.X / unitfactorxyz; } if (result.Y / unitfactorxyz < dmin_y) { dmin_y = result.Y / unitfactorxyz; } if (result.Z / unitfactorxyz < dmin_z) { dmin_z = result.Z / unitfactorxyz; } if (Math.Sqrt(Math.Pow(result.X, 2) + Math.Pow(result.Y, 2) + Math.Pow(result.Z, 2)) / unitfactorxyz < dmin_xyz) { dmin_xyz = Math.Sqrt(Math.Pow(result.X, 2) + Math.Pow(result.Y, 2) + Math.Pow(result.Z, 2)) / unitfactorxyz; } if (result.XX / unitfactorxxyyzz < dmin_xx) { dmin_xx = result.XX / unitfactorxxyyzz; } if (result.YY / unitfactorxxyyzz < dmin_yy) { dmin_yy = result.YY / unitfactorxxyyzz; } if (result.ZZ / unitfactorxxyyzz < dmin_zz) { dmin_zz = result.ZZ / unitfactorxxyyzz; } if (Math.Sqrt(Math.Pow(result.XX, 2) + Math.Pow(result.YY, 2) + Math.Pow(result.ZZ, 2)) / unitfactorxxyyzz < dmin_xxyyzz) { dmin_xxyyzz = Math.Sqrt(Math.Pow(result.XX, 2) + Math.Pow(result.YY, 2) + Math.Pow(result.ZZ, 2)) / unitfactorxxyyzz; } // add the values to the vector lists xyz.Add(new Vector3d(result.X / unitfactorxyz, result.Y / unitfactorxyz, result.Z / unitfactorxyz)); xxyyzz.Add(new Vector3d(result.XX / unitfactorxxyyzz, result.YY / unitfactorxxyyzz, result.ZZ / unitfactorxxyyzz)); // create ResultLines if (segment < segments) { Line segmentline = new Line( ln.PointAt((double)segment / segments), ln.PointAt((double)(segment + 1) / segments) ); segment++; segmentedlines.Add(segmentline); } } // add the vector list to the out tree xyz_out.AddRange(xyz, new GH_Path(key - 1)); xxyyzz_out.AddRange(xxyyzz, new GH_Path(key - 1)); segmentlines.AddRange(segmentedlines, new GH_Path(key - 1)); } getresults = false; } #endregion #region Result line values // ### Coloured Result Lines ### // round max and min to reasonable numbers double dmax = 0; double dmin = 0; switch (_disp) { case (DisplayValue.X): dmax = dmax_x; dmin = dmin_x; break; case (DisplayValue.Y): dmax = dmax_y; dmin = dmin_y; break; case (DisplayValue.Z): dmax = dmax_z; dmin = dmin_z; break; case (DisplayValue.resXYZ): dmax = dmax_xyz; dmin = dmin_xyz; break; case (DisplayValue.XX): dmax = dmax_xx; dmin = dmin_xx; break; case (DisplayValue.YY): dmax = dmax_yy; dmin = dmin_yy; break; case (DisplayValue.ZZ): dmax = dmax_zz; dmin = dmin_zz; break; case (DisplayValue.resXXYYZZ): dmax = dmax_xxyyzz; dmin = dmin_xxyyzz; break; } List <double> rounded = Util.Gsa.ResultHelper.SmartRounder(dmax, dmin); dmax = rounded[0]; dmin = rounded[1]; // Loop through segmented lines and set result colour into ResultLine format DataTree <ResultLine> lines_out = new DataTree <ResultLine>(); DataTree <System.Drawing.Color> col_out = new DataTree <System.Drawing.Color>(); foreach (GH_Path path in segmentlines.Paths) { List <ResultLine> lns = new List <ResultLine>(); List <System.Drawing.Color> col = new List <System.Drawing.Color>(); List <Line> segmentedlines = segmentlines.Branch(path); for (int j = 0; j < segmentedlines.Count; j++) { if (!(dmin == 0 & dmax == 0)) { Vector3d startTranslation = new Vector3d(0, 0, 0); Vector3d endTranslation = new Vector3d(0, 0, 0); double t1 = 0; double t2 = 0; // pick the right value to display switch (_disp) { case (DisplayValue.X): t1 = xyz_out[path, j].X; t2 = xyz_out[path, j + 1].X; startTranslation.X = t1 * Value / 1000; endTranslation.X = t2 * Value / 1000; break; case (DisplayValue.Y): t1 = xyz_out[path, j].Y; t2 = xyz_out[path, j + 1].Y; startTranslation.Y = t1 * Value / 1000; endTranslation.Y = t2 * Value / 1000; break; case (DisplayValue.Z): t1 = xyz_out[path, j].Z; t2 = xyz_out[path, j + 1].Z; startTranslation.Z = t1 * Value / 1000; endTranslation.Z = t2 * Value / 1000; break; case (DisplayValue.resXYZ): t1 = Math.Sqrt(Math.Pow(xyz_out[path, j].X, 2) + Math.Pow(xyz_out[path, j].Y, 2) + Math.Pow(xyz_out[path, j].Z, 2)); t2 = Math.Sqrt(Math.Pow(xyz_out[path, j + 1].X, 2) + Math.Pow(xyz_out[path, j + 1].Y, 2) + Math.Pow(xyz_out[path, j + 1].Z, 2)); startTranslation.X = xyz_out[path, j].X * Value / 1000; endTranslation.X = xyz_out[path, j + 1].X * Value / 1000; startTranslation.Y = xyz_out[path, j].Y * Value / 1000; endTranslation.Y = xyz_out[path, j + 1].Y * Value / 1000; startTranslation.Z = xyz_out[path, j].Z * Value / 1000; endTranslation.Z = xyz_out[path, j + 1].Z * Value / 1000; break; case (DisplayValue.XX): t1 = xxyyzz_out[path, j].X; t2 = xxyyzz_out[path, j + 1].X; break; case (DisplayValue.YY): t1 = xxyyzz_out[path, j].Y; t2 = xxyyzz_out[path, j + 1].Y; break; case (DisplayValue.ZZ): t1 = xxyyzz_out[path, j].Z; t2 = xxyyzz_out[path, j + 1].Z; break; case (DisplayValue.resXXYYZZ): t1 = Math.Sqrt(Math.Pow(xxyyzz_out[path, j].X, 2) + Math.Pow(xxyyzz_out[path, j].Y, 2) + Math.Pow(xxyyzz_out[path, j].Z, 2)); t2 = Math.Sqrt(Math.Pow(xxyyzz_out[path, j + 1].X, 2) + Math.Pow(xxyyzz_out[path, j + 1].Y, 2) + Math.Pow(xxyyzz_out[path, j + 1].Z, 2)); break; } Point3d start = new Point3d(segmentedlines[j].PointAt(0)); start.Transform(Transform.Translation(startTranslation)); Point3d end = new Point3d(segmentedlines[j].PointAt(1)); end.Transform(Transform.Translation(endTranslation)); Line segmentline = new Line(start, end); //normalised value between -1 and 1 double tnorm1 = 2 * (t1 - dmin) / (dmax - dmin) - 1; double tnorm2 = 2 * (t2 - dmin) / (dmax - dmin) - 1; // get colour for that normalised value System.Drawing.Color valcol1 = double.IsNaN(tnorm1) ? System.Drawing.Color.Black : gH_Gradient.ColourAt(tnorm1); System.Drawing.Color valcol2 = double.IsNaN(tnorm2) ? System.Drawing.Color.Black : gH_Gradient.ColourAt(tnorm2); // set the size of the line ends for ResultLine class. Size is calculated from 0-base, so not a normalised value between extremes float size1 = (t1 >= 0 && dmax != 0) ? Math.Max(2, (float)(t1 / dmax * scale)) : Math.Max(2, (float)(Math.Abs(t1) / Math.Abs(dmin) * scale)); if (double.IsNaN(size1)) { size1 = 1; } float size2 = (t2 >= 0 && dmax != 0) ? Math.Max(2, (float)(t2 / dmax * scale)) : Math.Max(2, (float)(Math.Abs(t2) / Math.Abs(dmin) * scale)); if (double.IsNaN(size2)) { size2 = 1; } // add our special resultline to the list of lines lns.Add(new ResultLine(segmentline, t1, t2, valcol1, valcol2, size1, size2)); // add the colour to the colours list col.Add(valcol1); if (j == segmentedlines.Count - 1) { col.Add(valcol2); } } } lines_out.AddRange(lns, path); col_out.AddRange(col, path); } #endregion #region Legend // ### Legend ### // loop through number of grip points in gradient to create legend //Find Colour and Values for legend output List <double> ts = new List <double>(); List <System.Drawing.Color> cs = new List <System.Drawing.Color>(); for (int i = 0; i < gH_Gradient.GripCount; i++) { double t = dmin + (dmax - dmin) / ((double)gH_Gradient.GripCount - 1) * (double)i; double scl = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(t))) + 1); scl = Math.Max(scl, 1); t = scl * Math.Round(t / scl, 3); ts.Add(t); System.Drawing.Color gradientcolour = gH_Gradient.ColourAt(2 * (double)i / ((double)gH_Gradient.GripCount - 1) - 1); cs.Add(gradientcolour); } #endregion // set outputs DA.SetDataTree(0, xyz_out); DA.SetDataTree(1, xxyyzz_out); DA.SetDataTree(2, lines_out); DA.SetDataTree(3, col_out); DA.SetDataList(4, cs); DA.SetDataList(5, ts); } }
protected override void SolveInstance(IGH_DataAccess DA) { GsaProfile profile = new GsaProfile(); #region catalogue if (_mode == FoldMode.Catalogue) { profile.profileType = GsaProfile.ProfileTypes.Catalogue; // need to implement the lists of cross sections profile.catalogueIndex = catalogueIndex; profile.catalogueProfileIndex = catalogueProfileIndex; profile.catalogueTypeIndex = catalogueTypeIndex; } #endregion #region geometric if (_mode == FoldMode.Geometric) { profile.profileType = GsaProfile.ProfileTypes.Geometric; GH_Brep gh_Brep = new GH_Brep(); if (DA.GetData(0, ref gh_Brep)) { Brep brep = new Brep(); if (GH_Convert.ToBrep(gh_Brep, ref brep, GH_Conversion.Both)) { // get edge curves from Brep Curve[] edgeSegments = brep.DuplicateEdgeCurves(); Curve[] edges = Curve.JoinCurves(edgeSegments); // find the best fit plane List <Point3d> ctrl_pts = new List <Point3d>(); if (edges[0].TryGetPolyline(out Polyline tempCrv)) { ctrl_pts = tempCrv.ToList(); } else { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot convert edge to Polyline"); } Plane.FitPlaneToPoints(ctrl_pts, out Plane plane); Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.ChangeBasis(Plane.WorldXY, plane); profile.geoType = GsaProfile.GeoTypes.Perim; List <Point2d> pts = new List <Point2d>(); foreach (Point3d pt3d in ctrl_pts) { pt3d.Transform(xform); Point2d pt2d = new Point2d(pt3d); pts.Add(pt2d); } profile.perimeterPoints = pts; if (edges.Length > 1) { List <List <Point2d> > voidPoints = new List <List <Point2d> >(); for (int i = 1; i < edges.Length; i++) { ctrl_pts.Clear(); if (!edges[i].IsPlanar()) { for (int j = 0; j < edges.Length; j++) { edges[j] = Curve.ProjectToPlane(edges[j], plane); } } if (edges[i].TryGetPolyline(out tempCrv)) { ctrl_pts = tempCrv.ToList(); pts = new List <Point2d>(); foreach (Point3d pt3d in ctrl_pts) { pt3d.Transform(xform); Point2d pt2d = new Point2d(pt3d); pts.Add(pt2d); } voidPoints.Add(pts); } else { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot convert internal edge to Polyline"); } } profile.voidPoints = voidPoints; } } } } #endregion #region standard section if (_mode != FoldMode.Geometric & _mode != FoldMode.Catalogue) { profile.profileType = GsaProfile.ProfileTypes.Standard; GH_Number gh_d = new GH_Number(); GH_Number gh_b1 = new GH_Number(); GH_Number gh_b2 = new GH_Number(); GH_Number gh_tw1 = new GH_Number(); GH_Number gh_tw2 = new GH_Number(); GH_Number gh_tf1 = new GH_Number(); GH_Number gh_tf2 = new GH_Number(); switch (selections[1]) { case "Rectangle": profile.stdShape = GsaProfile.StdShapeOptions.Rectangle; // 0 d DA.GetData(0, ref gh_d); // 1 b1 DA.GetData(1, ref gh_b1); if (isTapered) { // 2 b2 DA.GetData(2, ref gh_b2); } else { if (isHollow) { // 2 tw DA.GetData(2, ref gh_tw1); // 3 tw DA.GetData(3, ref gh_tf1); } } break; case "Circle": profile.stdShape = GsaProfile.StdShapeOptions.Circle; // 0 d DA.GetData(0, ref gh_d); if (isHollow) { if (isElliptical) { // 1 b1 DA.GetData(1, ref gh_b1); // 2 tw DA.GetData(2, ref gh_tw1); } else { // 1 tw DA.GetData(1, ref gh_tw1); } } else { if (isElliptical) { // 1 b1 DA.GetData(1, ref gh_b1); } } break; case "I section": profile.stdShape = GsaProfile.StdShapeOptions.I_section; // 0 d DA.GetData(0, ref gh_d); // 1 b1 DA.GetData(1, ref gh_b1); // 2 tw1 DA.GetData(2, ref gh_tw1); // 3 tf1 DA.GetData(3, ref gh_tf1); if (isGeneral) { if (isTapered) { // 4 b2 DA.GetData(4, ref gh_b2); // 5 tw2 DA.GetData(5, ref gh_tw2); // 6 tf2 DA.GetData(6, ref gh_tf2); } else { // 4 b2 DA.GetData(4, ref gh_b2); // 5 tf2 DA.GetData(5, ref gh_tf2); } } break; case "Tee": profile.stdShape = GsaProfile.StdShapeOptions.Tee; // 0 d DA.GetData(0, ref gh_d); // 1 b1 DA.GetData(1, ref gh_b1); // 2 tf1 DA.GetData(2, ref gh_tf1); // 3 tw1 DA.GetData(3, ref gh_tw1); if (isTapered) { // 4 tw2 DA.GetData(4, ref gh_tw2); } break; case "Channel": profile.stdShape = GsaProfile.StdShapeOptions.Channel; // 0 d DA.GetData(0, ref gh_d); // 1 b1 DA.GetData(1, ref gh_b1); // 2 tf1 DA.GetData(2, ref gh_tf1); // 3 tw1 DA.GetData(3, ref gh_tw1); break; case "Angle": profile.stdShape = GsaProfile.StdShapeOptions.Angle; // 0 d DA.GetData(0, ref gh_d); // 1 b1 DA.GetData(1, ref gh_b1); // 2 tf1 DA.GetData(2, ref gh_tf1); // 3 tw1 DA.GetData(3, ref gh_tw1); break; } if (gh_d != null) { if (GH_Convert.ToDouble(gh_d, out double d, GH_Conversion.Both)) { profile.d = d; } } if (gh_b1 != null) { if (GH_Convert.ToDouble(gh_b1, out double b1, GH_Conversion.Both)) { profile.b1 = b1; } } if (gh_b2 != null) { if (GH_Convert.ToDouble(gh_b2, out double b2, GH_Conversion.Both)) { profile.b2 = b2; } } if (gh_tw1 != null) { if (GH_Convert.ToDouble(gh_tw1, out double tw1, GH_Conversion.Both)) { profile.tw1 = tw1; } } if (gh_tw2 != null) { if (GH_Convert.ToDouble(gh_tw2, out double tw2, GH_Conversion.Both)) { profile.tw2 = tw2; } } if (gh_tf1 != null) { if (GH_Convert.ToDouble(gh_tf1, out double tf1, GH_Conversion.Both)) { profile.tf1 = tf1; } } if (gh_tf2 != null) { if (GH_Convert.ToDouble(gh_tf2, out double tf2, GH_Conversion.Both)) { profile.tf2 = tf2; } } profile.isB2B = isB2B; profile.isElliptical = isElliptical; profile.isGeneral = isGeneral; profile.isHollow = isHollow; profile.isTapered = isTapered; } #endregion #region units switch (Util.Unit.LengthSection) { case "mm": profile.sectUnit = GsaProfile.SectUnitOptions.u_mm; break; case "cm": profile.sectUnit = GsaProfile.SectUnitOptions.u_cm; break; case "m": profile.sectUnit = GsaProfile.SectUnitOptions.u_m; break; case "in": profile.sectUnit = GsaProfile.SectUnitOptions.u_in; break; case "ft": profile.sectUnit = GsaProfile.SectUnitOptions.u_ft; break; } #endregion // build string and output DA.SetData(0, ConvertSection.ProfileConversion(profile)); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { GH_Structure <GH_Curve> crvs = new GH_Structure <GH_Curve>(); DA.GetDataTree <GH_Curve>(0, out crvs); GH_Structure <GH_Number> height = new GH_Structure <GH_Number>(); DA.GetDataTree <GH_Number>(1, out height); double tol = DocumentTolerance(); //reserve one processor for GUI //create a dictionary that works in parallel var mPatchTree = new System.Collections.Concurrent.ConcurrentDictionary <GH_Path, GH_Mesh>(); //Multi-threading the loop System.Threading.Tasks.Parallel.ForEach(crvs.Paths, new System.Threading.Tasks.ParallelOptions { MaxDegreeOfParallelism = totalMaxConcurrancy }, pth => { List <Curve> branchCrvs = new List <Curve>(); double offset = 0; if (crvs.get_Branch(pth).Count > 0) { foreach (var ghCrv in crvs.get_Branch(pth)) { Curve c = null; GH_Convert.ToCurve(ghCrv, ref c, 0); if (extrudeDir == "Extrude Z") { ///Ensure boundary winds clockwise if (c.ClosedCurveOrientation(Vector3d.ZAxis) < 0) { c.Reverse(); } } branchCrvs.Add(c); } ///Convert first curve in branch to polyline ///Don't know why the boundary parameter can't be a Curve if the holes are allowed to be Curves Polyline pL = null; branchCrvs[0].TryGetPolyline(out pL); branchCrvs.RemoveAt(0); if (!pL.IsClosed) { pL.Add(pL[0]); } ///Check validity of pL if (!pL.IsValid) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Outer boundary curve could not be converted to polyline or is invalid"); } ///The magic found here: ///https://discourse.mcneel.com/t/mesh-with-holes-from-polylines-in-rhinowip-to-c/45589 Mesh mPatch = Mesh.CreatePatch(pL, tol, null, branchCrvs, null, null, true, 1); mPatch.Ngons.AddPlanarNgons(tol); //mPatch.UnifyNormals(); mPatch.FaceNormals.ComputeFaceNormals(); mPatch.Normals.ComputeNormals(); mPatch.Compact(); if (height.PathExists(pth)) { if (height.get_Branch(pth).Count > 0) { GH_Convert.ToDouble(height.get_Branch(pth)[0], out offset, 0); if (extrudeDir == "Extrude Z") { mPatch = mPatch.Offset(offset, true, Vector3d.ZAxis); } else { mPatch.Flip(true, true, true); mPatch = mPatch.Offset(offset, true); } } } else if (height.get_FirstItem(true) != null) { GH_Convert.ToDouble(height.get_FirstItem(true), out offset, 0); if (extrudeDir == "Extrude Z") { mPatch = mPatch.Offset(offset, true, Vector3d.ZAxis); } else { mPatch.Flip(true, true, true); mPatch = mPatch.Offset(offset, true); } } else { } if (mPatch != null) { if (mPatch.SolidOrientation() < 0) { mPatch.Flip(true, true, true); } } mPatchTree[pth] = new GH_Mesh(mPatch); } }); ///End of multi-threaded loop ///Convert dictionary to regular old data tree GH_Structure <GH_Mesh> mTree = new GH_Structure <GH_Mesh>(); foreach (KeyValuePair <GH_Path, GH_Mesh> m in mPatchTree) { mTree.Append(m.Value, m.Key); } DA.SetDataTree(0, mTree); }
/// <summary> /// Construct a new population of chromosomes using sliders and genepools /// </summary> /// <param name="popSize"></param> /// <param name="sliders"></param> /// <param name="genePools"></param> public Population(int popSize, List <GH_NumberSlider> sliders, List <GalapagosGeneListObject> genePools, BiomorpherComponent Owner, int runType) { owner = Owner; chromosomes = new Chromosome[popSize]; popSliders = new List <GH_NumberSlider>(sliders); popGenePools = new List <GalapagosGeneListObject>(genePools); for (int i = 0; i < chromosomes.Length; i++) { chromosomes[i] = new Chromosome(popSliders, popGenePools, i); } // Random, Initial or Current population switch (runType) { case 0: GenerateRandomPop(); break; case 1: bool isExisting = false; GH_Structure <GH_Number> tree = owner.existingPopTree; if (tree != null && tree.Branches.Count == popSize) { if (tree.Branches[0].Count == chromosomes[0].GetGenes().Length) { isExisting = true; } owner.AddWarning("Current popuation size, wrong gene size"); } if (isExisting) { for (int i = 0; i < tree.Branches.Count; i++) { // Set up a feature vector of doubles List <double> featureVector = new List <double>(); for (int j = 0; j < tree.get_Branch(i).Count; j++) { double myDouble; GH_Convert.ToDouble(tree.get_Branch(i)[j], out myDouble, GH_Conversion.Primary); featureVector.Add(myDouble); } chromosomes[i] = new Chromosome(popSliders, popGenePools, i); chromosomes[i].GenerateExistingGenes(featureVector); } } else { GenerateCurrentPop(); JigglePop(0.001); owner.AddWarning("existing population data must be same structure as population and gene count; Current parameter state substituted."); } break; case 2: GenerateCurrentPop(); JigglePop(0.001); break; default: break; } }
protected override void SolveInstance(IGH_DataAccess DA) { // Model to work on GsaModel in_Model = new GsaModel(); // Get Model GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(0, ref gh_typ)) { #region Inputs if (gh_typ.Value is GsaModelGoo) { gh_typ.CastTo(ref in_Model); if (gsaModel != null) { if (in_Model.GUID != gsaModel.GUID) { gsaModel = in_Model; getresults = true; } } else { gsaModel = in_Model; } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Error converting input to GSA Model"); return; } // Get analysis case GH_Integer gh_aCase = new GH_Integer(); DA.GetData(1, ref gh_aCase); GH_Convert.ToInt32(gh_aCase, out int tempanalCase, GH_Conversion.Both); // Get node filter list GH_String gh_noList = new GH_String(); DA.GetData(2, ref gh_noList); GH_Convert.ToString(gh_noList, out string tempnodeList, GH_Conversion.Both); // Get colours List <Grasshopper.Kernel.Types.GH_Colour> gh_Colours = new List <Grasshopper.Kernel.Types.GH_Colour>(); List <System.Drawing.Color> colors = new List <System.Drawing.Color>(); if (DA.GetDataList(3, gh_Colours)) { for (int i = 0; i < gh_Colours.Count; i++) { System.Drawing.Color color = new System.Drawing.Color(); GH_Convert.ToColor(gh_Colours[i], out color, GH_Conversion.Both); colors.Add(color); } } Grasshopper.GUI.Gradient.GH_Gradient gH_Gradient = UI.Colour.Stress_Gradient(colors); // Get scalar GH_Number gh_Scale = new GH_Number(); DA.GetData(4, ref gh_Scale); double scale = 1; GH_Convert.ToDouble(gh_Scale, out scale, GH_Conversion.Both); #endregion #region get results? // check if we must get results or just update display if (analCase == 0 || analCase != tempanalCase) { analCase = tempanalCase; getresults = true; } if (nodeList == "" || nodeList != tempnodeList) { nodeList = tempnodeList; getresults = true; } #endregion if (getresults) { #region Get results from GSA // ### Get results ### //Get analysis case from model AnalysisCaseResult analysisCaseResult = null; gsaModel.Model.Results().TryGetValue(analCase, out analysisCaseResult); if (analysisCaseResult == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No results exist for Analysis Case " + analCase + " in file"); return; } IReadOnlyDictionary <int, NodeResult> results = analysisCaseResult.NodeResults(nodeList); IReadOnlyDictionary <int, Node> nodes = gsaModel.Model.Nodes(nodeList); #endregion #region Create results output // ### Loop through results ### // clear any existing lists of vectors to output results in: xyz = new List <Vector3d>(); xxyyzz = new List <Vector3d>(); // maximum and minimum result values for colouring later dmax_x = 0; dmax_y = 0; dmax_z = 0; dmax_xx = 0; dmax_yy = 0; dmax_zz = 0; dmax_xyz = 0; dmax_xxyyzz = 0; dmin_x = 0; dmin_y = 0; dmin_z = 0; dmin_xx = 0; dmin_yy = 0; dmin_zz = 0; dmin_xyz = 0; dmin_xxyyzz = 0; double unitfactorxyz = 1; double unitfactorxxyyzz = 1; // if reaction type, then we reuse the nodeList to filter support nodes from the rest if (_mode == FoldMode.Reaction) { nodeList = ""; } foreach (var key in results.Keys) { NodeResult result; Double6 values = null; if (_mode == FoldMode.Reaction) { bool isSupport = false; Node node = new Node(); nodes.TryGetValue(key, out node); NodalRestraint rest = node.Restraint; if (rest.X || rest.Y || rest.Z || rest.XX || rest.YY || rest.ZZ) { isSupport = true; } if (!isSupport) { continue; } else { if (nodeList == "") { nodeList = key.ToString(); } else { nodeList += " " + key; } } } results.TryGetValue(key, out result); switch (_mode) { case (FoldMode.Displacement): values = result.Displacement; unitfactorxyz = 0.001; unitfactorxxyyzz = 1; break; case (FoldMode.Reaction): values = result.Reaction; unitfactorxyz = 1000; unitfactorxxyyzz = 1000; break; case (FoldMode.SpringForce): values = result.SpringForce; unitfactorxyz = 1000; unitfactorxxyyzz = 1000; break; case (FoldMode.Constraint): values = result.Constraint; break; } // update max and min values if (values.X / unitfactorxyz > dmax_x) { dmax_x = values.X / unitfactorxyz; } if (values.Y / unitfactorxyz > dmax_y) { dmax_y = values.Y / unitfactorxyz; } if (values.Z / unitfactorxyz > dmax_z) { dmax_z = values.Z / unitfactorxyz; } if (Math.Sqrt(Math.Pow(values.X, 2) + Math.Pow(values.Y, 2) + Math.Pow(values.Z, 2)) / unitfactorxyz > dmax_xyz) { dmax_xyz = Math.Sqrt(Math.Pow(values.X, 2) + Math.Pow(values.Y, 2) + Math.Pow(values.Z, 2)) / unitfactorxyz; } if (values.XX / unitfactorxxyyzz > dmax_xx) { dmax_xx = values.XX / unitfactorxxyyzz; } if (values.YY / unitfactorxxyyzz > dmax_yy) { dmax_yy = values.YY / unitfactorxxyyzz; } if (values.ZZ / unitfactorxxyyzz > dmax_zz) { dmax_zz = values.ZZ / unitfactorxxyyzz; } if (Math.Sqrt(Math.Pow(values.XX, 2) + Math.Pow(values.YY, 2) + Math.Pow(values.ZZ, 2)) / unitfactorxxyyzz > dmax_xxyyzz) { dmax_xxyyzz = Math.Sqrt(Math.Pow(values.XX, 2) + Math.Pow(values.YY, 2) + Math.Pow(values.ZZ, 2)) / unitfactorxxyyzz; } if (values.X / unitfactorxyz < dmin_x) { dmin_x = values.X / unitfactorxyz; } if (values.Y / unitfactorxyz < dmin_y) { dmin_y = values.Y / unitfactorxyz; } if (values.Z / unitfactorxyz < dmin_z) { dmin_z = values.Z / unitfactorxyz; } if (Math.Sqrt(Math.Pow(values.X, 2) + Math.Pow(values.Y, 2) + Math.Pow(values.Z, 2)) / unitfactorxyz < dmin_xyz) { dmin_xyz = Math.Sqrt(Math.Pow(values.X, 2) + Math.Pow(values.Y, 2) + Math.Pow(values.Z, 2)) / unitfactorxyz; } if (values.XX / unitfactorxxyyzz < dmin_xx) { dmin_xx = values.XX / unitfactorxxyyzz; } if (values.YY / unitfactorxxyyzz < dmin_yy) { dmin_yy = values.YY / unitfactorxxyyzz; } if (values.ZZ / unitfactorxxyyzz < dmin_zz) { dmin_zz = values.ZZ / unitfactorxxyyzz; } if (Math.Sqrt(Math.Pow(values.XX, 2) + Math.Pow(values.YY, 2) + Math.Pow(values.ZZ, 2)) / unitfactorxxyyzz < dmin_xxyyzz) { dmin_xxyyzz = Math.Sqrt(Math.Pow(values.XX, 2) + Math.Pow(values.YY, 2) + Math.Pow(values.ZZ, 2)) / unitfactorxxyyzz; } // add the values to the vector lists xyz.Add(new Vector3d(values.X / unitfactorxyz, values.Y / unitfactorxyz, values.Z / unitfactorxyz)); xxyyzz.Add(new Vector3d(values.XX / unitfactorxxyyzz, values.YY / unitfactorxxyyzz, values.ZZ / unitfactorxxyyzz)); } #endregion getresults = false; } #region Result point values // ### Coloured Result Points ### // Get nodes for point location and restraint check in case of reaction force IReadOnlyDictionary <int, Node> nDict = gsaModel.Model.Nodes(nodeList); List <GsaNodeGoo> gsanodes = Util.Gsa.FromGSA.GetNodes(nDict, gsaModel.Model); //Find Colour and Values for legend output List <double> ts = new List <double>(); List <System.Drawing.Color> cs = new List <System.Drawing.Color>(); // round max and min to reasonable numbers double dmax = 0; double dmin = 0; switch (_disp) { case (DisplayValue.X): dmax = dmax_x; dmin = dmin_x; break; case (DisplayValue.Y): dmax = dmax_y; dmin = dmin_y; break; case (DisplayValue.Z): dmax = dmax_z; dmin = dmin_z; break; case (DisplayValue.resXYZ): dmax = dmax_xyz; dmin = dmin_xyz; break; case (DisplayValue.XX): dmax = dmax_xx; dmin = dmin_xx; break; case (DisplayValue.YY): dmax = dmax_yy; dmin = dmin_yy; break; case (DisplayValue.ZZ): dmax = dmax_zz; dmin = dmin_zz; break; case (DisplayValue.resXXYYZZ): dmax = dmax_xxyyzz; dmin = dmin_xxyyzz; break; } List <double> rounded = Util.Gsa.ResultHelper.SmartRounder(dmax, dmin); dmax = rounded[0]; dmin = rounded[1]; // Loop through nodes and set result colour into ResultPoint format List <ResultPoint> pts = new List <ResultPoint>(); List <System.Drawing.Color> col = new List <System.Drawing.Color>(); for (int i = 0; i < gsanodes.Count; i++) { if (gsanodes[i].Value != null) { if (!(dmin == 0 & dmax == 0)) { double t = 0; Vector3d translation = new Vector3d(0, 0, 0); // pick the right value to display switch (_disp) { case (DisplayValue.X): t = xyz[i].X; translation.X = t * Value / 1000; break; case (DisplayValue.Y): t = xyz[i].Y; translation.Y = t * Value / 1000; break; case (DisplayValue.Z): t = xyz[i].Z; translation.Z = t * Value / 1000; break; case (DisplayValue.resXYZ): t = Math.Sqrt(Math.Pow(xyz[i].X, 2) + Math.Pow(xyz[i].Y, 2) + Math.Pow(xyz[i].Z, 2)); translation.X = xyz[i].X * Value / 1000; translation.Y = xyz[i].Y * Value / 1000; translation.Z = xyz[i].Z * Value / 1000; break; case (DisplayValue.XX): t = xxyyzz[i].X; break; case (DisplayValue.YY): t = xxyyzz[i].Y; break; case (DisplayValue.ZZ): t = xxyyzz[i].Z; break; case (DisplayValue.resXXYYZZ): t = Math.Sqrt(Math.Pow(xxyyzz[i].X, 2) + Math.Pow(xxyyzz[i].Y, 2) + Math.Pow(xxyyzz[i].Z, 2)); break; } //normalised value between -1 and 1 double tnorm = 2 * (t - dmin) / (dmax - dmin) - 1; // get colour for that normalised value System.Drawing.Color valcol = gH_Gradient.ColourAt(tnorm); // set the size of the point for ResultPoint class. Size is calculated from 0-base, so not a normalised value between extremes float size = (t >= 0 && dmax != 0) ? Math.Max(2, (float)(t / dmax * scale)) : Math.Max(2, (float)(Math.Abs(t) / Math.Abs(dmin) * scale)); // create deflection point Point3d def = new Point3d(gsanodes[i].Value.Point); def.Transform(Transform.Translation(translation)); // add our special resultpoint to the list of points pts.Add(new ResultPoint(def, t, valcol, size)); // add the colour to the colours list col.Add(valcol); } } } #endregion #region Legend // ### Legend ### // loop through number of grip points in gradient to create legend for (int i = 0; i < gH_Gradient.GripCount; i++) { double t = dmin + (dmax - dmin) / ((double)gH_Gradient.GripCount - 1) * (double)i; double scl = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(t))) + 1); scl = Math.Max(scl, 1); t = scl * Math.Round(t / scl, 3); ts.Add(t); System.Drawing.Color gradientcolour = gH_Gradient.ColourAt(2 * (double)i / ((double)gH_Gradient.GripCount - 1) - 1); cs.Add(gradientcolour); } #endregion // set outputs DA.SetDataList(0, xyz); DA.SetDataList(1, xxyyzz); DA.SetDataList(2, pts); DA.SetDataList(3, col); DA.SetDataList(4, cs); DA.SetDataList(5, ts); } }
protected override void SolveInstance(IGH_DataAccess DA) { GsaElement1d gsaElement1d = new GsaElement1d(); if (DA.GetData(0, ref gsaElement1d)) { GsaElement1d elem = gsaElement1d.Duplicate(); // #### inputs #### // 1 curve GH_Line ghcrv = new GH_Line(); if (DA.GetData(1, ref ghcrv)) { Line crv = new Line(); if (GH_Convert.ToLine(ghcrv, ref crv, GH_Conversion.Both)) { LineCurve ln = new LineCurve(crv); GsaElement1d tmpelem = new GsaElement1d(ln) { ID = elem.ID, Element = elem.Element, ReleaseEnd = elem.ReleaseEnd, ReleaseStart = elem.ReleaseStart }; elem = tmpelem; } } // 2 section GH_ObjectWrapper gh_typ = new GH_ObjectWrapper(); if (DA.GetData(2, ref gh_typ)) { GsaSection section = new GsaSection(); if (gh_typ.Value is GsaSection) { gh_typ.CastTo(ref section); } else if (gh_typ.Value is GH_Number) { if (GH_Convert.ToInt32((GH_Number)gh_typ.Value, out int idd, GH_Conversion.Both)) { section.ID = idd; } } elem.Section = section; } // 3 offset GsaOffset offset = new GsaOffset(); if (DA.GetData(3, ref offset)) { elem.Element.Offset.X1 = offset.X1; elem.Element.Offset.X2 = offset.X2; elem.Element.Offset.Y = offset.Y; elem.Element.Offset.Z = offset.Z; } // 4 start release GsaBool6 start = new GsaBool6(); if (DA.GetData(4, ref start)) { elem.ReleaseStart = start; //should handle setting the release in elem.Element.SetRelease } // 5 end release GsaBool6 end = new GsaBool6(); if (DA.GetData(5, ref end)) { elem.ReleaseEnd = end; //should handle setting the release in elem.Element.SetRelease } // 6 orientation angle GH_Number ghangle = new GH_Number(); if (DA.GetData(6, ref ghangle)) { if (GH_Convert.ToDouble(ghangle, out double angle, GH_Conversion.Both)) { elem.Element.OrientationAngle = angle; } } // 7 orientation node GH_Integer ghori = new GH_Integer(); if (DA.GetData(7, ref ghori)) { if (GH_Convert.ToInt32(ghori, out int orient, GH_Conversion.Both)) { elem.Element.OrientationNode = orient; } } // 8 type GH_Integer ghinteg = new GH_Integer(); if (DA.GetData(8, ref ghinteg)) { if (GH_Convert.ToInt32(ghinteg, out int type, GH_Conversion.Both)) { elem.Element.Type = Util.Gsa.GsaToModel.Element1dType(type); } } // 9 ID GH_Integer ghID = new GH_Integer(); if (DA.GetData(9, ref ghID)) { if (GH_Convert.ToInt32(ghID, out int id, GH_Conversion.Both)) { elem.ID = id; } } // 10 name GH_String ghnm = new GH_String(); if (DA.GetData(10, ref ghnm)) { if (GH_Convert.ToString(ghnm, out string name, GH_Conversion.Both)) { elem.Element.Name = name; } } // 11 Group GH_Integer ghgrp = new GH_Integer(); if (DA.GetData(11, ref ghgrp)) { if (GH_Convert.ToInt32(ghgrp, out int grp, GH_Conversion.Both)) { elem.Element.Group = grp; } } // 12 Colour GH_Colour ghcol = new GH_Colour(); if (DA.GetData(12, ref ghcol)) { if (GH_Convert.ToColor(ghcol, out System.Drawing.Color col, GH_Conversion.Both)) { elem.Element.Colour = col; } } // #### outputs #### DA.SetData(0, new GsaElement1dGoo(elem)); DA.SetData(1, elem.Line); DA.SetData(2, elem.Section); GsaOffset offset1 = new GsaOffset { X1 = elem.Element.Offset.X1, X2 = elem.Element.Offset.X2, Y = elem.Element.Offset.Y, Z = elem.Element.Offset.Z }; DA.SetData(3, offset1); DA.SetData(4, elem.ReleaseStart); DA.SetData(5, elem.ReleaseEnd); DA.SetData(6, elem.Element.OrientationAngle); DA.SetData(7, elem.Element.OrientationNode); DA.SetData(8, elem.Element.Type); DA.SetData(9, elem.ID); DA.SetData(10, elem.Element.Name); DA.SetData(11, elem.Element.Group); DA.SetData(12, elem.Element.Colour); try { DA.SetData(13, elem.Element.ParentMember.Member); } catch (Exception) { } //DA.SetData(16, gsaElement1d.Element.IsDummy); } }
/// <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> /// Grasshopper solveinstance /// </summary> /// <param name="DA"></param> protected override void SolveInstance(IGH_DataAccess DA) { List <string> genoGuids = new List <string>(); GH_Structure <GH_Number> populationData; if (!DA.GetDataList <string>("GenoGuids", genoGuids)) { return; } if (!DA.GetDataTree("Population", out populationData)) { if (populationData == null) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No population data!"); return; } else { Message = "Popcount = " + populationData.Branches.Count; } } if (!DA.GetData <GH_Integer>("DesignID", ref designID)) { return; } ; // Horrible workaround for genepools. I'm completely lost finding a better way to be honest. // Maybe only trigger this bit IF the input data has changed in some way? That might solve the Embryo problem. if (isActive) { //GH_Path List <double> genes = new List <double>(); for (int i = 0; i < populationData.get_Branch(i).Count; i++) { double myDouble; GH_Convert.ToDouble(populationData.get_Branch(designID.Value)[i], out myDouble, GH_Conversion.Primary); genes.Add(myDouble); } List <GH_NumberSlider> theSliders = new List <GH_NumberSlider>(); List <GalapagosGeneListObject> theGenePools = new List <GalapagosGeneListObject>(); bool flag = false; int counter = 0; foreach (string myGuid in genoGuids) { try { System.Guid me = new Guid(myGuid); // Try for a slider GH_NumberSlider slidy = OnPingDocument().FindObject <GH_NumberSlider>(me, true); if (slidy != null) { theSliders.Add(slidy); counter++; } // Try for a genepool GalapagosGeneListObject pooly = OnPingDocument().FindObject <GalapagosGeneListObject>(me, true); if (pooly != null) { theGenePools.Add(pooly); counter += pooly.Count; } } catch { flag = true; } } if (flag) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No slider or genepool found at specified guid. Has the definition been altered?"); return; } // Catch an unequal amount of sliders and genes/guids if (genes.Count != counter) { this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Guid count does not equal chromosome gene count"); return; } canvas.Document.Enabled = false; SetSliders(genes, theSliders, theGenePools); canvas.Document.Enabled = true; if (theGenePools.Count > 0) { isActive = false; } } else { // Turn the thing back on without setting all the sliders etc. isActive = true; } }
///////////////////////////////////////// CastFrom ////////////////////////////////////////// public override bool CastFrom(object source) { //Abort immediately on bogus data. if (source == null) { return(false); } //Type t = source.GetType(); // I don't yet understand this method very well. If I use a recommended conversion like: // GH_Convert.ToInt32(source, out val, GH_Conversion.Both) // I think I will get reals converted to ints (?). Likewise, if I do GH_Convert.ToDouble(), I think // I will get integers converted to reals. I don't want either of these, so instead I first try // inspecting the raw type. LAter I fall through to GH_Convert methods. // I don't know what types Grasshopper will ever give me. Maybe it never uses float, for example? What about, say, char or uint? if (source is int || source is long || source is float || source is double || source is bool || source is string) { Value = new Expr(source); return(true); } else if (source is GH_Integer) { int val; GH_Convert.ToInt32(source, out val, GH_Conversion.Both); this.Value = new Expr(val); return(true); } else if (source is GH_Number) { double val; GH_Convert.ToDouble(source, out val, GH_Conversion.Both); this.Value = new Expr(val); return(true); } else if (source is GH_Boolean) { bool val; GH_Convert.ToBoolean(source, out val, GH_Conversion.Both); this.Value = new Expr(val); return(true); } // Try a series of conversions. double dval; if (GH_Convert.ToDouble(source, out dval, GH_Conversion.Both)) { this.Value = new Expr(dval); return(true); } int ival; if (GH_Convert.ToInt32(source, out ival, GH_Conversion.Both)) { this.Value = new Expr(ival); return(true); } string str = null; if (GH_Convert.ToString(source, out str, GH_Conversion.Both)) { this.Value = new Expr(str); return(true); } return(false); }
/// <summary> /// Grasshopper solveinstance /// </summary> /// <param name="DA"></param> protected override void SolveInstance(IGH_DataAccess DA) { // Get Solution and data BiomorpherGoo temp = new BiomorpherGoo(); if (!DA.GetData("Solution", ref temp)) { return; } solutionData = temp.Value; if (!DA.GetData <int>("Branch", ref branch)) { return; } ; if (!DA.GetData <int>("Generation", ref generation)) { return; } ; if (!DA.GetData <int>("Design", ref design)) { return; } ; // Check to see if we have anything at all (population is the lowest possible thing in the hierarchy) if (solutionData.historicData == null) { AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Empty biomorpher solution!"); return; } // If we have then display the number of designs in a typical population else { Message = "Population size = " + solutionData.PopCount; } // Only if things have changed do we actually want to change the sliders and expire the solution if (branch != localBranch || localGeneration != generation || localDesign != design || !localSolutionData.Equals(solutionData)) { localBranch = branch; localGeneration = generation; localDesign = design; localSolutionData = solutionData; active = true; } else { active = false; } // Only do things if there is a design at the location if (solutionData.historicData.get_Branch(new GH_Path(branch, generation, design)) != null) { if (active) { //We need a list of genes for the selected design List <double> genes = new List <double>(); // g for (int i = 0; i < solutionData.historicData.get_Branch(new GH_Path(branch, generation, design)).Count; i++) { double myDouble; GH_Convert.ToDouble(solutionData.historicData.get_Branch(new GH_Path(branch, generation, design))[i], out myDouble, GH_Conversion.Primary); genes.Add(myDouble); } // Set up some local sliders and genepools List <GH_NumberSlider> theSliders = new List <GH_NumberSlider>(); List <GalapagosGeneListObject> theGenePools = new List <GalapagosGeneListObject>(); bool flag = false; // Note that the sliders and genepools are stored in two branches of a GH_Structure try { // Get sliders List <GH_Guid> sliderList = new List <GH_Guid>(); foreach (GH_Guid x in solutionData.genoGuids.get_Branch(0)) { GH_NumberSlider slidy = OnPingDocument().FindObject <GH_NumberSlider>(x.Value, true); if (slidy != null) { theSliders.Add(slidy); } } // Get genepools foreach (GH_Guid x in solutionData.genoGuids.get_Branch(1)) { GalapagosGeneListObject pooly = OnPingDocument().FindObject <GalapagosGeneListObject>(x.Value, true); if (pooly != null) { theGenePools.Add(pooly); } } } catch { flag = true; } if (flag) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Getting sliders and/or genepools from the canvas was unsuccesful. Have they been modified?"); return; } canvas.Document.Enabled = false; //this.Locked = true; SetSliders(genes, theSliders, theGenePools); canvas.Document.Enabled = true; canvas.Document.ExpireSolution(); } } else { // Turn the thing back on without setting all the sliders etc. AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "No historic design found at this reference"); } }
protected override void SolveInstance(IGH_DataAccess DA) { bool update = false; GH_String ghstr = new GH_String(); if (DA.GetData(0, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Force = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(1, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.LengthLarge = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(2, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.LengthSmall = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(3, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.LengthSection = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(4, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Mass = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(5, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Temperature = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(6, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Stress = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(7, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Strain = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(8, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Velocity = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(9, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Acceleration = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(10, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Energy = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(11, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.Angle = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(12, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.TimeShort = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(13, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.TimeMedium = unit; update = true; } } ghstr = new GH_String(); if (DA.GetData(14, ref ghstr)) { if (GH_Convert.ToString(ghstr, out string unit, GH_Conversion.Both)) { Units.TimeLong = unit; update = true; } } GH_Number ghnum = new GH_Number(); if (DA.GetData(15, ref ghnum)) { if (GH_Convert.ToDouble(ghnum, out double tol, GH_Conversion.Both)) { Units.Tolerance = tol; update = true; } } List <string> units = new List <string> { "Force: " + Units.Force, "Length Large: " + Units.LengthLarge + ((Units.LengthLarge == Units.RhinoDocUnit) ? "" : System.Environment.NewLine + "NB: Not similar to Rhino Document units!"), "Length Small: " + Units.LengthSmall, "Length Section: " + Units.LengthSection, "Mass: " + Units.Mass, "Temperature: " + Units.Temperature, "Stress: " + Units.Stress, "Strain: " + Units.Strain, "Velocity: " + Units.Velocity, "Acceleration: " + Units.Acceleration, "Energy: " + Units.Energy, "Angle: " + Units.Angle, "Time - short: " + Units.TimeShort, "Time - medium: " + Units.TimeMedium, "Time - long: " + Units.TimeLong, "Tolerance: " + Units.Tolerance }; if (update) { UpdateCanvas(); } DA.SetDataList(0, units); }