protected override Result RunCommand(RhinoDoc doc, RunMode mode) { StreamReader reader = File.OpenText("point_cloud.txt"); string line; while ((line = reader.ReadLine()) != null) { string[] items = line.Split(null); double x = double.Parse(items[0]); double y = double.Parse(items[1]); double z = double.Parse(items[2]); double w = double.Parse(items[3]); double radius = Math.Pow(Math.Abs(w) * 3.0 / (4.0 * Math.PI), 1.0 / 3.0); Point3d point = new Point3d(x, y, z); Sphere sp = new Sphere(point, radius); var attributes = new Rhino.DocObjects.ObjectAttributes(); if (w > 0) { attributes.ObjectColor = System.Drawing.Color.Blue; } else { attributes.ObjectColor = System.Drawing.Color.Gray; } attributes.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject; doc.Objects.AddSphere(sp, attributes); } reader.Close(); doc.Views.Redraw(); return(Result.Success); }
public override void BakeGeometry(Rhino.RhinoDoc doc, Rhino.DocObjects.ObjectAttributes att, List <Guid> obj_ids) { if (lpS != null) { foreach (GH_particleSystem pS in lpS) { if (pS != null) { if (pS.BKGT != null) { pS.BKGT(doc, att, obj_ids); } } } } if (_VN) { var x = FriedChiken.getParticles(); for (int i = 0; i < FriedChiken.nParticles; i++) { Rhino.DocObjects.ObjectAttributes a2 = att.Duplicate(); a2.LayerIndex = 2; obj_ids.Add(doc.Objects.AddTextDot(new Rhino.Geometry.TextDot(i.ToString("000"), new Rhino.Geometry.Point3d(x[i, 0] + __dist, x[i, 1], x[i, 2])), a2)); } } base.BakeGeometry(doc, att, obj_ids); }
Rhino.DocObjects.ObjectAttributes CreateColorAttribute(int R, int G, int B) { Rhino.DocObjects.ObjectAttributes output = new Rhino.DocObjects.ObjectAttributes(); output.ObjectColor = System.Drawing.Color.FromArgb(255, R, G, B); return(output); }
public override void BakeGeometry(Rhino.RhinoDoc doc, Rhino.DocObjects.ObjectAttributes att, List <Guid> obj_ids) { if (this.BKGT != null) { this.BKGT(doc, att, obj_ids); } }
public Cut(ref Scene scene) : base(ref scene) { mScene = scene; //sending cut postion Rhino.DocObjects.ObjectAttributes attr2 = new Rhino.DocObjects.ObjectAttributes(); attr2.Name = "cut:"; Point3d cutP = new Point3d(0, 0, 0); cutPGuid = mScene.rhinoDoc.Objects.AddPoint(cutP, attr2); //hiding the aprint model only show the printStroke /* * Rhino.DocObjects.ObjectEnumeratorSettings settings = new Rhino.DocObjects.ObjectEnumeratorSettings(); * settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.Brep; * foreach (Rhino.DocObjects.RhinoObject rhObj in mScene.rhinoDoc.Objects.GetObjectList(settings)) * { * if (rhObj.Attributes.Name.Contains("aprint")){ * SceneNode sn = mScene.brepToSceneNodeDic[rhObj.Id]; * Material.LambertianMaterial hide_m = new Material.LambertianMaterial(((Material.LambertianMaterial)sn.material).mColor.R, ((Material.LambertianMaterial)sn.material).mColor.G, ((Material.LambertianMaterial)sn.material).mColor.B, 0); * sn.material = hide_m; * } * }*/ //clear the stroke foreach (SceneNode sn in mScene.tableGeometry.children) { if (sn.name == "PrintStroke") { mScene.tableGeometry.children.Remove(sn); break; } } }
public BakeGeometry GetBKGT(Rhino.Geometry.Polyline m) { return(new BakeGeometry((d, a, o) => { Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate(); a2.LayerIndex = 4; o.Add(d.Objects.AddPolyline(m, a2)); })); }
public BakeGeometry GetBKGT(Rhino.Geometry.Point3d[] m) { return(new BakeGeometry((d, a, o) => { Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate(); a2.LayerIndex = 3; Rhino.Collections.RhinoList <Guid> id = d.Objects.AddPoints(m, a2); o.AddRange(id); })); }
public Guid DrawObjectWithSpecificLayer(Rhino.Display.Text3d text, NamedLayer layername) { Rhino.RhinoDoc.ActiveDoc.Layers.SetCurrentLayerIndex(layerIndexes[(int)layername], false); Rhino.DocObjects.ObjectAttributes attribute = new Rhino.DocObjects.ObjectAttributes(); var result = Rhino.RhinoDoc.ActiveDoc.Objects.AddText(text.Text, text.TextPlane, 200, "Arial", false, false, Rhino.Geometry.TextJustification.Center); Rhino.RhinoDoc.ActiveDoc.Layers.SetCurrentLayerIndex(0, false); return(result); }
public BakeGeometry GetBKGT(Rhino.Geometry.Mesh m) { return(new BakeGeometry((d, a, o) => { Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate(); a2.LayerIndex = 1; Guid id = d.Objects.AddMesh(m, a2); o.Add(id); })); }
public BakeGeometry GetBKGT(List <Rhino.Geometry.Line> m) { return(new BakeGeometry((d, a, o) => { Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate(); a2.LayerIndex = 4; foreach (Rhino.Geometry.Line l in m) { o.Add(d.Objects.AddLine(l, a2)); } })); }
public BakeGeometry GetBKGT(List <Rhino.Geometry.Point3d> m) { return(new BakeGeometry((d, a, o) => { Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate(); a2.LayerIndex = 2; for (int i = 0; i < m.Count; i++) { Guid id = d.Objects.AddLine(new Rhino.Geometry.Line(m[i], m[i] + v), a2); o.Add(id); } })); }
public static string Initialize() { var site = new MedinaSite(); site.Sectors = LoadSite(@"G:\My Drive\medina\protocol_site_v0.5.0.3dm"); //site.Motifs.Add(LoadMotif(@"G:\My Drive\medina\motifs\boxtest.ghx", "test")); site.Motifs.Add(LoadMotif(@"G:\My Drive\medina\motifs\Arc_Construct.ghx", "arch")); //site.Motifs.Add(LoadMotif(@"G:\My Drive\medina\motifs\Dome_Construct.ghx", "dome")); //site.Motifs.Add(LoadMotif(@"G:\My Drive\medina\motifs\Fountain_Construct.ghx", "fountain")); foreach (var sector in site.Sectors) { sector.Audit(); } foreach (var motif in site.Motifs) { motif.Audit(); } var sectorG13 = site.Sectors.First(x => x.Id.ToString() == "G13"); site.Motifs[0].StageSector(sectorG13); var pts = sectorG13.Base.GetBoundingBox(false).PopulateBoundingBox(25); var anchors = pts.Select(x => new Point3d(x.X, x.Y, 0)).ToList(); var atts = new Rh.DocObjects.ObjectAttributes() { LayerIndex = 0, }; anchors = new List <Point3d>() { new Point3d(-280, 143, 0), new Point3d(-280, 110, 0) }; for (int i = 0; i < anchors.Count; i++) { site.Sectors[0].File.Objects.AddPoint(anchors[i]); var res = site.Motifs[0].SolveAt(anchors[i]); Console.WriteLine($"[{(i + 1).ToString().PadLeft(3, '0')}/{anchors.Count.ToString().PadLeft(3, '0')}] [{anchors[i].ToString()}] Solution with {res.Count.ToString()} objects."); } ; return("ok"); }
protected override void SolveInstance(IGH_DataAccess DA) { List <GH_ObjectWrapper> lines = new List <GH_ObjectWrapper>(); List <GH_Guid> cakes = new List <GH_Guid>(); GH_String layername = new GH_String(""); GH_Boolean bake = new GH_Boolean(false); DA.GetData <GH_String>("layer", ref layername); DA.GetData <GH_Boolean>("bake", ref bake); if (!DA.GetDataList <GH_ObjectWrapper>("dough", lines)) { lines = new List <GH_ObjectWrapper>(); } if (lines.Count > 0 && bake.Value) { foreach (GH_ObjectWrapper line in lines) { int layerindex = 0; Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes(); foreach (Rhino.DocObjects.Layer layer in Rhino.RhinoDoc.ActiveDoc.Layers) { if (layer.Name == layername.Value) { layerindex = layer.LayerIndex; } } att.LayerIndex = layerindex; Guid g = Guid.Empty; line.BakeGeometry(Rhino.RhinoDoc.ActiveDoc, att, ref g); if (g != Guid.Empty) { cakes.Add(new GH_Guid(g)); } } DA.SetDataList("cake", cakes); } }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { List <Point3d> points = RNNPlugin.Instance.rnn.GetMarkers(); Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes(); int layer_index = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath("RhinoNatNet::RNN_Markers", true); if (layer_index < 0) { RNNContext.CreateLayers(); } attr.LayerIndex = RhinoDoc.ActiveDoc.Layers.FindByFullPath("RhinoNatNet::RNN_Markers", true); attr.Name = "RNN_Marker"; doc.Objects.AddPoints(points, attr); return(Result.Success); }
/// <summary> /// Get target Rhino layer (or create it if it doesn't already exist) and assign it to attributes /// </summary> /// <param name="layer">FeatureLayer</param> /// <param name="rhinoDoc">RhinoDoc</param> /// <returns></returns> private static Rhino.DocObjects.ObjectAttributes getLayerAttrs(FeatureLayer layer, RhinoDoc rhinoDoc) { if (!rhinoDoc.Layers.Any(l => l.Name == layer.Name)) { var color = getColor(layer); // TODO: set layer color based on some logic rhinoDoc.Layers.Add(layer.Name, color); } var layerIndex = rhinoDoc.Layers.FindName(layer.Name).Index; var attrs = new Rhino.DocObjects.ObjectAttributes() { LayerIndex = layerIndex }; return(attrs); }
/// <summary> /// Creates the cell geometry as polySurfaces /// </summary> /// <param name="randomCol">If true each group of faces will be with a random colour</param> /// <returns>The guids for each cell</returns> public IList <Guid> SaveAsCells(bool randomCol = false, bool asMesh = false) { var doc = Rhino.RhinoDoc.ActiveDoc; var foamCells = new List <Guid>(); string primal = SerializeJson(); string dual = Dual?.SerializeJson() ?? ""; bool foamSaved = false; foreach (var cell in Cells) { Color color = Color.FromArgb(rand.Next(50, 200), rand.Next(50, 200), rand.Next(50, 200)); var attributes = new Rhino.DocObjects.ObjectAttributes { ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = cell.Id.ToString() }; if (randomCol) { attributes.ObjectColor = color; } GeometryBase cellGeo; if (!asMesh) { cellGeo = cell.CreateBrepMatched(); } else { cellGeo = cell.CreateCellMesh(); } if (!foamSaved && !cell.Exterior) { cellGeo.UserDictionary.Set("Primal", primal); cellGeo.UserDictionary.Set("Dual", dual); foamSaved = true; } foamCells.Add(doc.Objects.Add(cellGeo, attributes)); } doc.Groups.Add(Id.ToString(), foamCells); return(foamCells); }
public void BakeGeometry(Rhino.RhinoDoc doc, Rhino.DocObjects.ObjectAttributes att, List <Guid> obj_ids) { if (att == null) { att = doc.CreateDefaultAttributes(); } foreach (IGH_BakeAwareData item in m_data) { if (item != null) { Guid id; if (item.BakeGeometry(doc, att, out id)) { obj_ids.Add(id); } } } }
/// <summary> /// bake an object in the given rhino document /// </summary> /// <param name="doc">document to bake into</param> /// <param name="att">attributes to bake with (should not be null)</param> /// <param name="obj_guid">the id of the baked object</param> /// <returns>true on success. ifalse, obj_guid and obj_inst are not guaranteed to be valid pointers</returns> public bool BakeGeometry(Rhino.RhinoDoc doc, Rhino.DocObjects.ObjectAttributes att, out Guid obj_guid) { obj_guid = Guid.Empty; if (Value == null) { return(false); } if (!Value.IsValid) { return(false); } doc.Objects.AddMesh(Value.Display); return(true); }
private void Button_Click_Build(object sender, RoutedEventArgs e) { Rhino.RhinoDoc doc = Rhino.RhinoDoc.ActiveDoc; int ExpLayerIndex = doc.Layers.Find("Exploration", true); if (ExpLayerIndex < 0) { Rhino.DocObjects.Layer ExpLayer = new Rhino.DocObjects.Layer(); ExpLayer.Name = "Exploration"; doc.Layers.Add(ExpLayer); ExpLayerIndex = doc.Layers.Find("Exploration", true); } int subExpLayerIndex = 0; if (!(doc.Layers[ExpLayerIndex].GetChildren() == null)) { subExpLayerIndex = doc.Layers[ExpLayerIndex].GetChildren().Length; } Rhino.DocObjects.Layer subExpLayer = new Rhino.DocObjects.Layer(); subExpLayer.Name = "Exploration" + subExpLayerIndex.ToString(); subExpLayer.ParentLayerId = doc.Layers[ExpLayerIndex].Id; doc.Layers.Add(subExpLayer); subExpLayerIndex = doc.Layers.Find(subExpLayer.Name, true); Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes(); attr.LayerIndex = subExpLayerIndex; foreach (Rhino.Geometry.Line l in Component.DesignLines) { doc.Objects.AddLine(l, attr); } foreach (Rhino.Geometry.Curve c in Component.DesignCurves) { doc.Objects.AddCurve(c, attr); } foreach (Rhino.Geometry.Brep b in Component.DesignBreps) { doc.Objects.AddBrep(b, attr); } foreach (Rhino.Geometry.Mesh m in Component.DesignMeshes) { doc.Objects.AddMesh(m, attr); } }
public static void Write <T>(string name, T geometry) where T : GeometryBase { var doc = Rhino.RhinoDoc.ActiveDoc; var layer = doc.Layers.FindName(_layerName); if (layer is null) { int index = doc.Layers.Add(_layerName, Color.Black); layer = doc.Layers.FindIndex(index); } var attributes = new Rhino.DocObjects.ObjectAttributes { LayerIndex = layer.Index, Name = name }; doc.Objects.Add(geometry, attributes); }
/// <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) { // code for accessing GUID by Fraser Greenroyd // https://frasergreenroyd.com/how-to-access-geometry-guids-in-grasshopper-components/ IGH_GeometricGoo geom = null; if (!DA.GetData(0, ref geom)) { return; } Guid id = geom.ReferenceID; Rhino.DocObjects.ObjectAttributes objAtt = Rhino.RhinoDoc.ActiveDoc.Objects.Find(id).Attributes; int layerIndex = objAtt.LayerIndex; string layer = Rhino.RhinoDoc.ActiveDoc.Layers[layerIndex].Name; DA.SetData(0, layer); }
public static void BakeFacades(IEnumerable <Facade> faces, bool bake = false, Curve crv = null) { Rhino.DocObjects.Tables.ObjectTable ot = Rhino.RhinoDoc.ActiveDoc.Objects; foreach (Facade face in faces) { Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes { Name = face.Id }; if (crv != null) { if (PointContainmentCheck(face.Centroid, crv)) { ot.AddMesh(face.Geometry, att); } } else { ot.AddMesh(face.Geometry, att); } } }
protected override void SolveInstance(IGH_DataAccess DA) { IGH_GeometricGoo g = null; DA.GetData <IGH_GeometricGoo>(0, ref g); string geoType = g.TypeName; string name = null; DA.GetData(1, ref name); bool activate = false; DA.GetData(2, ref activate); Rhino.DocObjects.ObjectAttributes atts = new Rhino.DocObjects.ObjectAttributes(); string newID = null; atts.Name = name; if (activate) { GH_Point p = g as GH_Point; if (p != null) { GeometryBase geo = GH_Convert.ToGeometryBase(p); newID = RhinoDoc.ActiveDoc.Objects.Add(geo, atts).ToString(); } GH_Curve c = g as GH_Curve; if (c != null) { GeometryBase geo = GH_Convert.ToGeometryBase(c); newID = RhinoDoc.ActiveDoc.Objects.Add(geo, atts).ToString(); } } DA.SetData(0, newID); }
public static Rhino.Commands.Result AddMaterial(Rhino.RhinoDoc doc) { // materials are stored in the document's material table int index = doc.Materials.Add(); Rhino.DocObjects.Material mat = doc.Materials[index]; mat.DiffuseColor = System.Drawing.Color.Chocolate; mat.SpecularColor = System.Drawing.Color.CadetBlue; mat.CommitChanges(); // set up object attributes to say they use a specific material Rhino.Geometry.Sphere sp = new Rhino.Geometry.Sphere(Rhino.Geometry.Plane.WorldXY, 5); Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes(); attr.MaterialIndex = index; attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; doc.Objects.AddSphere(sp, attr); // add a sphere without the material attributes set sp.Center = new Rhino.Geometry.Point3d(10, 10, 0); doc.Objects.AddSphere(sp); doc.Views.Redraw(); return Rhino.Commands.Result.Success; }
public static Rhino.Commands.Result AddMaterial(Rhino.RhinoDoc doc) { // materials are stored in the document's material table int index = doc.Materials.Add(); Rhino.DocObjects.Material mat = doc.Materials[index]; mat.DiffuseColor = System.Drawing.Color.Chocolate; mat.SpecularColor = System.Drawing.Color.CadetBlue; mat.CommitChanges(); // set up object attributes to say they use a specific material Rhino.Geometry.Sphere sp = new Rhino.Geometry.Sphere(Rhino.Geometry.Plane.WorldXY, 5); Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes(); attr.MaterialIndex = index; attr.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; doc.Objects.AddSphere(sp, attr); // add a sphere without the material attributes set sp.Center = new Rhino.Geometry.Point3d(10, 10, 0); doc.Objects.AddSphere(sp); doc.Views.Redraw(); return(Rhino.Commands.Result.Success); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { List <IGH_GeometricGoo> objs = new List <IGH_GeometricGoo>(); DA.GetDataList(0, objs); string layerName = "Default"; object material = null; bool clearL = false; DA.GetData(1, ref layerName); DA.GetData(2, ref material); /*Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes(); * att.LayerIndex = doc.Layers.Find(layerName, true); * att.MaterialIndex = doc.Materials.Find(matName, true);*/ Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes(); //Set material if (material != null) { string matName = ""; DisplayMaterial mat = new DisplayMaterial(); Color col = new Color(); int isName = -1; int materialIndex = -1; try { matName = (material as GH_String).Value; isName = 1; } catch { try { mat = (material as GH_Material).Value; isName = 0; } catch { try { col = (material as GH_Colour).Value; mat = new DisplayMaterial(col); isName = 0; } catch { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Can't identify material object. Please supply render material name, GH material or color."); } } } if (isName == 1) { materialIndex = doc.Materials.Find(matName, true); att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; if (materialIndex < 0) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Couldn't find material by name. If you're sure the material exists in the Rhino Material list, try adding it to one object manually. After that it should work."); } att.MaterialIndex = materialIndex; } else { materialIndex = doc.Materials.Add(); if (materialIndex > -1) { Rhino.DocObjects.Material m = doc.Materials[materialIndex]; m.Name = matName; m.AmbientColor = mat.Ambient; m.DiffuseColor = mat.Diffuse; m.EmissionColor = mat.Emission; //m.ReflectionColor = no equivalent m.SpecularColor = mat.Specular; m.Shine = mat.Shine; m.Transparency = mat.Transparency; //m.TransparentColor = no equivalent m.CommitChanges(); att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; att.MaterialIndex = materialIndex; } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Couldn't add material. Try cleaning up your materials."); //This never happened to me. } } } DA.GetData(3, ref att); DA.GetData(4, ref clearL); //Delete objects by GUID doc.Objects.Delete(ids, true); for (int i = 0; i < objs.Count; i++) { GeometryBase gb; Point3d pt; Brep b; if (ids.Count <= i) { ids.Add(Guid.NewGuid()); } att.ObjectId = ids[i]; if (objs[i].CastTo <Point3d>(out pt)) { doc.Objects.AddPoint(pt, att); } else if (objs[i].CastTo <Brep>(out b)) { doc.Objects.AddBrep(b, att); } else if (objs[i].CastTo <GeometryBase>(out gb)) { doc.Objects.Add(gb, att); } else { throw new Exception("Object nr. " + i + " is not bakeable:\n" + objs[i].ToString() + ".\nIf it's a box or a curve, try turning it into a Brep by wiring it through a Brep container component before feeding it to Instant Bake."); } } if (clearL) { foreach (Rhino.DocObjects.RhinoObject o in doc.Objects.FindByLayer(layerName)) { doc.Objects.Delete(o, true); } } if (counter >= 10) { Rhino.RhinoDoc.ActiveDoc.ClearUndoRecords(true); counter = 0; } DA.SetDataList(0, ids); counter++; }
public bool init() { // Set up HMD EVRInitError eError = EVRInitError.None; mHMD = OpenVR.Init(ref eError, EVRApplicationType.VRApplication_Scene); if (eError == EVRInitError.None) { Rhino.RhinoApp.WriteLine("Booted VR System"); renderPoseArray = new TrackedDevicePose_t[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount]; gamePoseArray = new TrackedDevicePose_t[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount]; } else { Rhino.RhinoApp.WriteLine("Failed to boot"); mTitleBase = "SparrowHawk (No VR Detected)"; } // // THIS IS FOR UNCLIPPED // Width = 864; // Height = 820; // THIS IS FOR CLIPPED RECTANGLE Width = 691; Height = 692; // Window Setup Info mStrDriver = UtilOld.GetTrackedDeviceString(ref mHMD, OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_TrackingSystemName_String); mStrDisplay = UtilOld.GetTrackedDeviceString(ref mHMD, OpenVR.k_unTrackedDeviceIndex_Hmd, ETrackedDeviceProperty.Prop_SerialNumber_String); mTitleBase = "SparrowHawk - " + mStrDriver + " " + mStrDisplay; Title = mTitleBase; MakeCurrent(); setupScene(); if (eError == EVRInitError.None) { mRenderer = new VrRenderer(ref mHMD, ref mScene, mRenderWidth, mRenderHeight); } else { mRenderer = new VrRenderer(ref mHMD, ref mScene, mRenderWidth, mRenderHeight); } //use other 8 points for calibrartion robotCallibrationPointsTest.Add(new Vector3(22, 15, -100) / 1000); robotCallibrationPointsTest.Add(new Vector3(-10, 40, -153) / 1000); robotCallibrationPointsTest.Add(new Vector3(25, -25, -181) / 1000); foreach (Vector3 v in robotCallibrationPointsTest) { Vector4 v4 = new Vector4(v.X, v.Y, v.Z, 1); v4 = mScene.vrToRobot.Inverted() * v4; UtilOld.MarkPoint(ref mScene.staticGeometry, new Vector3(v4.X, v4.Y, v4.Z), 1, 1, 1); } robotCallibrationPointsTest.Clear(); //set default matrix if (mRenderer.ovrvision_controller != null) { mRenderer.ovrvision_controller.setDefaultMatrixHC(); } //detecting whether users in control or left Rhino.DocObjects.ObjectAttributes attr = new Rhino.DocObjects.ObjectAttributes(); attr.Name = "user:out"; Point3d userP = new Point3d(0, 0, 0); uGuid = mScene.rhinoDoc.Objects.AddPoint(userP, attr); //testing - rotate rhino object as well /* * Transform transM = new Transform(); * for (int row = 0; row < 4; row++) * { * for (int col = 0; col < 4; col++) * { * transM[row, col] = mScene.platformRotation[row, col]; * } * } * Rhino.DocObjects.ObjectEnumeratorSettings settings = new Rhino.DocObjects.ObjectEnumeratorSettings(); * settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.Brep; * foreach (Rhino.DocObjects.RhinoObject rhObj in mScene.rhinoDoc.Objects.GetObjectList(settings)) * { * mDoc.Objects.Transform(rhObj.Id, transM, true); * } * mScene.rhinoDoc.Views.Redraw(); */ //testing visualize printStroke printStroke = new Geometry.RobotPrintStroke(ref mScene); printStroke_m = new Material.SingleColorMaterial(1, 1, 0, 1.0f); return(eError == EVRInitError.None); }
public static void OptToRhino(OptFile opt, string rhinoPath, bool scale) { if (opt == null) { throw new ArgumentNullException("opt"); } string rhinoDirectory = Path.GetDirectoryName(rhinoPath); string rhinoName = Path.GetFileNameWithoutExtension(rhinoPath); var distances = opt.Meshes .SelectMany(t => t.Lods) .Select(t => t.Distance) .Distinct() .OrderByDescending(t => t) .ToArray(); for (int distance = 0; distance < distances.Length; distance++) { using (var file = new Rhino.FileIO.File3dm()) { file.Settings.ModelUnitSystem = Rhino.UnitSystem.Meters; int objectsIndex = 0; List<string> textureNames = new List<string>(); foreach (var mesh in opt.Meshes) { var lod = mesh.Lods.FirstOrDefault(t => t.Distance <= distances[distance]); if (lod == null) { continue; } foreach (var textureName in lod.FaceGroups .Where(t => t.Textures.Count > 0) .Select(t => t.Textures[0])) { if (!textureNames.Contains(textureName)) { textureNames.Add(textureName); } } string meshName = string.Format(CultureInfo.InvariantCulture, "{0}.{1:D3}", mesh.Descriptor.MeshType, objectsIndex); using (var layer = new Rhino.DocObjects.Layer()) { layer.Name = meshName; file.Layers.Add(layer); } foreach (var faceGroup in lod.FaceGroups) { using (var rhinoMesh = new Rhino.Geometry.Mesh()) using (var rhinoAttributes = new Rhino.DocObjects.ObjectAttributes()) { rhinoAttributes.Name = meshName; rhinoAttributes.LayerIndex = objectsIndex; if (faceGroup.Textures.Count > 0) { rhinoAttributes.MaterialIndex = textureNames.IndexOf(faceGroup.Textures[0]); } Action<Vector> addVertex; if (scale) { addVertex = vertex => rhinoMesh.Vertices.Add(vertex.X * OptFile.ScaleFactor, vertex.Y * OptFile.ScaleFactor, vertex.Z * OptFile.ScaleFactor); } else { addVertex = vertex => rhinoMesh.Vertices.Add(vertex.X, vertex.Y, vertex.Z); } Action<TextureCoordinates> addTexCoords = texCoords => rhinoMesh.TextureCoordinates.Add(texCoords.U, -texCoords.V); Action<Vector> addNormal = normal => rhinoMesh.Normals.Add(normal.X, normal.Y, normal.Z); int facesIndex = 0; foreach (var face in faceGroup.Faces) { var verticesIndex = face.VerticesIndex; var texCoordsIndex = face.TextureCoordinatesIndex; var normalsIndex = face.VertexNormalsIndex; addVertex(mesh.Vertices[verticesIndex.A]); addTexCoords(mesh.TextureCoordinates[texCoordsIndex.A]); addNormal(mesh.VertexNormals[normalsIndex.A]); facesIndex++; addVertex(mesh.Vertices[verticesIndex.B]); addTexCoords(mesh.TextureCoordinates[texCoordsIndex.B]); addNormal(mesh.VertexNormals[normalsIndex.B]); facesIndex++; addVertex(mesh.Vertices[verticesIndex.C]); addTexCoords(mesh.TextureCoordinates[texCoordsIndex.C]); addNormal(mesh.VertexNormals[normalsIndex.C]); facesIndex++; if (verticesIndex.D >= 0) { addVertex(mesh.Vertices[verticesIndex.D]); addTexCoords(mesh.TextureCoordinates[texCoordsIndex.D]); addNormal(mesh.VertexNormals[normalsIndex.D]); facesIndex++; } if (verticesIndex.D < 0) { rhinoMesh.Faces.AddFace(facesIndex - 1, facesIndex - 2, facesIndex - 3); } else { rhinoMesh.Faces.AddFace(facesIndex - 1, facesIndex - 2, facesIndex - 3, facesIndex - 4); } } rhinoMesh.Compact(); file.Objects.AddMesh(rhinoMesh, rhinoAttributes); } } objectsIndex++; } foreach (var textureName in textureNames) { Texture texture; opt.Textures.TryGetValue(textureName, out texture); using (var material = new Rhino.DocObjects.Material()) { material.Name = textureName; if (texture == null) { material.DiffuseColor = System.Drawing.Color.White; } else { texture.Save(Path.Combine(rhinoDirectory, textureName + ".png")); material.SetBitmapTexture(textureName + ".png"); if (texture.HasAlpha) { texture.SaveAlphaMap(Path.Combine(rhinoDirectory, textureName + "_alpha.png")); material.SetTransparencyTexture(textureName + "_alpha.png"); } } file.Materials.Add(material); } } file.Write(Path.Combine(rhinoDirectory, string.Format(CultureInfo.InvariantCulture, "{0}_{1}.3dm", rhinoName, distance)), 4); } } }
protected override Result RunCommand(Rhino.RhinoDoc doc, RunMode mode) { var dirname = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string[] pathComponent = new string[] { dirname.ToString(), @"common_paper_sizes.json" }; var jsonPath = Path.Combine(pathComponent); GetPoint gp = new GetPoint(); string text = System.IO.File.ReadAllText(jsonPath); gp.SetCommandPrompt("Set Origin of Paper Rectangle"); OptionToggle boolOption = new OptionToggle(false, "Off", "On"); gp.AddOptionToggle("Portrait", ref boolOption); var listNames = new List <string>(); var listValues = new List <Point2d>(); List <Paper> papers = JsonConvert.DeserializeObject <List <Paper> >(text); //foreach(var paper in papers) //{ var count = 0; foreach (var format in papers[0].formats) { var num = int.Parse(Regex.Match(format.name, @"\d+").Value); if (num < 6 && !format.name.Contains("C")) { listNames.Add(format.name); listValues.Add(new Point2d(format.size.mm[0], format.size.mm[1])); count++; } } //} var listNamesArr = listNames.ToArray(); int listIndex = 0; int opList = gp.AddOptionList("PaperType", listNamesArr, listIndex); while (true) { // perform the get operation. This will prompt the user to input a point, but also // allow for command line options defined above Rhino.Input.GetResult get_rc = gp.Get(); if (gp.CommandResult() != Rhino.Commands.Result.Success) { return(gp.CommandResult()); } if (get_rc == Rhino.Input.GetResult.Point) { var plane = doc.Views.ActiveView.ActiveViewport.GetConstructionPlane().Plane; plane.Origin = gp.Point(); var item = listValues[listIndex]; var isPortrait = boolOption.CurrentValue; var rect = new Rectangle3d(plane, isPortrait ? item.X : item.Y, isPortrait ? item.Y : item.X); var attr = new Rhino.DocObjects.ObjectAttributes(); attr.Name = listNames[listIndex]; attr.LayerIndex = doc.Layers.CurrentLayerIndex; doc.Objects.AddRectangle(rect, attr); doc.Views.Redraw(); } else if (get_rc == Rhino.Input.GetResult.Option) { if (gp.OptionIndex() == opList) { listIndex = gp.Option().CurrentListOptionIndex; } continue; } break; } return(Rhino.Commands.Result.Success); }
/// <summary> /// Executes the platonic command /// </summary> protected override Rhino.Commands.Result RunCommand(Rhino.RhinoDoc doc, Rhino.Commands.RunMode mode) { // Get the platonic geometry Rhino.Geometry.Brep[] faces = Platonic.Faces(); if (null == faces) { return(Rhino.Commands.Result.Failure); } // Prompt for center point string prompt = string.Format("Center of {0}", Platonic.DisplayName.ToLower()); Rhino.Geometry.Point3d origin; Rhino.Commands.Result rc = Rhino.Input.RhinoGet.GetPoint(prompt, false, out origin); if (rc != Rhino.Commands.Result.Success) { return(rc); } double length = m_length; bool create_solid = m_create_solid; bool group_faces = m_group_faces; // Prompt for edge length PlatonicGetPoint get = new PlatonicGetPoint(faces, origin); get.SetCommandPrompt(Platonic.Prompt); get.SetDefaultNumber(length); get.SetBasePoint(origin, true); get.DrawLineFromPoint(origin, true); get.AcceptNumber(true, false); Rhino.Geometry.Transform xform = new Rhino.Geometry.Transform(1.0); rc = Rhino.Commands.Result.Cancel; for (; ;) { get.ClearCommandOptions(); Rhino.Input.Custom.OptionToggle output_toggle = null; Rhino.Input.Custom.OptionToggle group_toggle = null; output_toggle = new Rhino.Input.Custom.OptionToggle(create_solid, "Faces", "Solid"); get.AddOptionToggle("Output", ref output_toggle); if (!create_solid) { group_toggle = new Rhino.Input.Custom.OptionToggle(group_faces, "No", "Yes"); get.AddOptionToggle("Group", ref group_toggle); } Rhino.Input.GetResult res = get.Get(); if (res == Rhino.Input.GetResult.Point) { if (get.CalculateTransform(get.View().ActiveViewport, get.Point(), ref xform)) { m_length = get.Length; rc = Rhino.Commands.Result.Success; break; } } else if (res == Rhino.Input.GetResult.Number) { length = System.Math.Abs(get.Number()); if (get.CalculateTransform(get.View().ActiveViewport, length, ref xform)) { m_length = get.Length; rc = Rhino.Commands.Result.Success; break; } } else if (res == Rhino.Input.GetResult.Option) { if (null != output_toggle && create_solid != output_toggle.CurrentValue) { create_solid = output_toggle.CurrentValue; } if (null != group_toggle && group_faces != group_toggle.CurrentValue) { group_faces = group_toggle.CurrentValue; } continue; } else { break; } } // If we got here, then we have the center point and edge length, // any any command options. Time to add the geomtry to the document. if (rc == Rhino.Commands.Result.Success && xform.IsValid) { m_create_solid = create_solid; m_group_faces = group_faces; Rhino.DocObjects.ObjectAttributes attribs = doc.CreateDefaultAttributes(); attribs.Name = Platonic.Name; attribs.WireDensity = 0; // solid looks "nicer" with wires turned off... if (m_create_solid) { Rhino.Geometry.Brep[] breps = Rhino.Geometry.Brep.JoinBreps(faces, 2.1 * doc.ModelAbsoluteTolerance); foreach (Brep t in breps) { if (null == t) { continue; } t.Transform(xform); doc.Objects.AddBrep(t, attribs, null, false, false); } } else { if (m_group_faces) { attribs.AddToGroup(doc.Groups.Add()); } foreach (Brep t in faces) { if (null == t) { continue; } t.Transform(xform); doc.Objects.AddBrep(t, attribs, null, false, false); } } doc.Views.Redraw(); } return(Rhino.Commands.Result.Success); }
/// <summary> /// Saves the foam as a group of color-coded lines in the Rhino document /// For each line a user dictionary is saved with the following entries: /// EdgeId, StartVertexId, EndVertexId /// The first line contains a JSON serialization for the whole foam + /// If available the dual will also be saved /// </summary> public IList <Guid> SaveAsEdges() { // first determine if form or force // if foam has naked edges then it is form else it is force var doc = Rhino.RhinoDoc.ActiveDoc; doc.Views.RedrawEnabled = false; var form = Edges.Where(e => e.Id > 0).Any(x => x.Faces.Count < 2); var positiveEdges = Edges.Where(x => x.Id > 0); var edgeUserDict = new Dictionary <int, Dictionary <string, int> >(); bool foamSaved = false; var guids = new List <Guid>(); string primal = SerializeJson(); string dual = Dual?.SerializeJson() ?? ""; // pre-make the data for the user dictionary for each edge foreach (var edge in positiveEdges) { var edgeDict = new Dictionary <string, int>(); edgeDict.Add("Id", edge.Id); edgeDict.Add("V0", edge.Vertices[0].Id); edgeDict.Add("V1", edge.Vertices[1].Id); edgeUserDict.Add(edge.Id, edgeDict); } // handling different behaviors for form and force if (form) { var intEdges = new List <PFEdge>(); var halfExtEdges = new List <PFEdge>(); var fullExtEdges = new List <PFEdge>(); foreach (var edge in positiveEdges) { if (edge.Id > 0) { if (edge.Vertices[0].External && edge.Vertices[1].External) { fullExtEdges.Add(edge); } else if (edge.Vertices[0].External ^ edge.Vertices[1].External) { halfExtEdges.Add(edge); } else { intEdges.Add(edge); } } } var areas = intEdges.Select(x => x.Dual?.Area ?? 0.0); var maxArea = areas.Count() > 0 ? areas.Max() : 1.0; var minArea = areas.Count() > 0 ? areas.Min() : 0.0; // create all layers var intLineLayer = new Rhino.DocObjects.Layer() { Name = "_Form_InternalLines" }; if (doc.Layers.All(x => x.Name != intLineLayer.Name)) { doc.Layers.Add(intLineLayer); } intLineLayer = doc.Layers.First(x => x.Name == "_Form_InternalLines"); var extForceLayer = new Rhino.DocObjects.Layer() { Name = "_Form_ExternalForces" }; if (doc.Layers.All(x => x.Name != extForceLayer.Name)) { doc.Layers.Add(extForceLayer); } extForceLayer = doc.Layers.First(x => x.Name == "_Form_ExternalForces"); var externalPolyLayer = new Rhino.DocObjects.Layer() { Name = "_Form_ExternalPoly" }; if (doc.Layers.All(x => x.Name != externalPolyLayer.Name)) { doc.Layers.Add(externalPolyLayer); } externalPolyLayer = doc.Layers.First(x => x.Name == "_Form_ExternalPoly"); // handle the interior edges foreach (var edge in intEdges) { var attributes = new Rhino.DocObjects.ObjectAttributes { ObjectColor = Util.CreateBlue(Util.ValueUnitizer(edge.Dual?.Area ?? 1.0, new List <double> { minArea, maxArea }, new List <double> { 0.0, 1.0 })), PlotWeight = Math.Round(Util.ValueUnitizer(edge.Dual?.Area ?? 1.0, new List <double> { minArea, maxArea }, new List <double> { 0, 11 }) * 0.05 + 0.15), ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = edge.Id.ToString(), LayerIndex = intLineLayer.LayerIndex, }; var lineCrv = edge.CreateLine().ToNurbsCurve(); foreach (var keyVal in edgeUserDict[edge.Id]) { lineCrv.UserDictionary.Set(keyVal.Key, keyVal.Value); } // the foam will be serialized with the first interior edge // this will include the dual if present if (!foamSaved) { lineCrv.UserDictionary.Set("Primal", primal); lineCrv.UserDictionary.Set("Dual", dual); foamSaved = true; } guids.Add(doc.Objects.AddCurve(lineCrv, attributes)); } // handle applied forces - or half ext edges foreach (var edge in halfExtEdges) { var attributes = new Rhino.DocObjects.ObjectAttributes { ObjectColor = System.Drawing.Color.FromArgb(0, 100, 0), ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = edge.Id.ToString(), LayerIndex = extForceLayer.LayerIndex, }; if (edge.Vertices[1].External) { attributes.ObjectDecoration = Rhino.DocObjects.ObjectDecoration.StartArrowhead; } else { attributes.ObjectDecoration = Rhino.DocObjects.ObjectDecoration.EndArrowhead; } var lineCrv = edge.CreateLine().ToNurbsCurve(); foreach (var keyVal in edgeUserDict[edge.Id]) { lineCrv.UserDictionary.Set(keyVal.Key, keyVal.Value); } if (!foamSaved) { lineCrv.UserDictionary.Set("Primal", primal); lineCrv.UserDictionary.Set("Dual", dual); foamSaved = true; } guids.Add(doc.Objects.AddCurve(lineCrv, attributes)); } // handle external polyhedron or full external edges foreach (var edge in fullExtEdges) { var attributes = new Rhino.DocObjects.ObjectAttributes { ObjectColor = System.Drawing.Color.LightGray, ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = edge.Id.ToString(), LayerIndex = externalPolyLayer.LayerIndex, }; var lineCrv = edge.CreateLine().ToNurbsCurve(); foreach (var keyVal in edgeUserDict[edge.Id]) { lineCrv.UserDictionary.Set(keyVal.Key, keyVal.Value); } guids.Add(doc.Objects.AddCurve(lineCrv, attributes)); } } else { var forceLineLayer = new Rhino.DocObjects.Layer() { Name = "_Force_Lines" }; if (doc.Layers.All(x => x.Name != forceLineLayer.Name)) { doc.Layers.Add(forceLineLayer); } forceLineLayer = doc.Layers.First(x => x.Name == "_Force_Lines"); foreach (var edge in positiveEdges) { var attributes = new Rhino.DocObjects.ObjectAttributes { ObjectColor = System.Drawing.Color.DarkSlateGray, ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = edge.Id.ToString(), LayerIndex = forceLineLayer.LayerIndex, }; var lineCrv = edge.CreateLine().ToNurbsCurve(); foreach (var keyVal in edgeUserDict[edge.Id]) { lineCrv.UserDictionary.Set(keyVal.Key, keyVal.Value); } // the foam will be serialized with the first interior edge // this will include the dual if present if (!foamSaved) { lineCrv.UserDictionary.Set("Primal", primal); lineCrv.UserDictionary.Set("Dual", dual); foamSaved = true; } guids.Add(doc.Objects.AddCurve(lineCrv, attributes)); } } doc.Views.RedrawEnabled = true; doc.Groups.Add(Id.ToString(), guids); return(guids); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param> protected override void SolveInstance(IGH_DataAccess DA) { List <Curve> C = new List <Curve>(); List <string> Layer = new List <string>(); List <Color> LColor = new List <Color>(); if (!DA.GetDataList(0, C)) { return; } if (C == null || C.Count == 0) { return; } if (!DA.GetDataList(1, Layer)) { for (int i = 0; i < C.Count; i++) { Layer.Add("Default"); } } if (Layer == null || Layer.Count != C.Count) { return; } if (!DA.GetDataList(2, LColor)) { for (int i = 0; i < C.Count; i++) { LColor.Add(Color.Black); } } if (LColor == null || LColor.Count != C.Count) { return; } bool PreserveUnits = true, ViewBound = true, ColStyle = true, SolidHatch = true, OrderLayers = true; DA.GetData(3, ref PreserveUnits); DA.GetData(4, ref ViewBound); DA.GetData(5, ref ColStyle); DA.GetData(6, ref SolidHatch); DA.GetData(7, ref OrderLayers); string path = "", name = ""; if (!DA.GetData(8, ref path)) { return; } if (!DA.GetData(9, ref name)) { return; } bool export = false; DA.GetData(10, ref export); // NOTE // normally, a button would freeze GH canvas after a RunScript operation, while a Toggle would not; // this fix (use a pending variable) was suggested by Florian Frank here: // https://www.grasshopper3d.com/forum/topics/boolean-button-runscript if (!export && !pending) { return; } // as suggested by Rutten here: https://discourse.mcneel.com/t/rhino-command-export-in-c/63610/4 if (Rhino.RhinoDoc.ActiveDoc == null) { return; } if (!pending) { pending = true; return; } pending = false; // export options string presUn = PreserveUnits ? "Yes" : "No"; string vBound = ViewBound ? "Yes" : "No"; string cs = ColStyle ? "RGB" : "CMYK"; string solHatch = SolidHatch ? "Yes" : "No"; string ordLay = OrderLayers ? "Yes" : "No"; // Yes/No Yes/No RGB/CMYK Yes/No Yes/No string scriptOptions = " PreserveUnits=" + presUn + " ViewportBoundary=" + vBound + " Color=" + cs + " HatchesAsSolidFills=" + solHatch + " OrderLayers=" + ordLay; string scriptString = "-_Export " + '"' + path + name + ".ai" + '"' + scriptOptions + " _Enter"; Guid[] id = new Guid[C.Count]; string[] lay = Layer.ToArray(); Color[] col = LColor.ToArray(); // lists of effectively added layers List <int> addedLayers = new List <int>(); //Make new attribute to set name Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes(); if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } Rhino.RhinoApp.RunScript("_SelNone", false); IEnumerator it = C.GetEnumerator(); int k = 0; int ind = 0; int cInd = 0; foreach (Curve curve in C) { //Set layer if (!string.IsNullOrEmpty(lay[ind]) && Rhino.DocObjects.Layer.IsValidName(lay[ind])) { //Get the current layer index Rhino.DocObjects.Tables.LayerTable layerTable = Rhino.RhinoDoc.ActiveDoc.Layers; //int layerIndex = layerTable.Find(lay[ind], true); int layerIndex = layerTable.FindByFullPath(lay[ind], -1); if (layerIndex < 0) //This layer does not exist, we add it { Rhino.DocObjects.Layer onlayer = new Rhino.DocObjects.Layer(); //Make a new layer onlayer.Name = lay[ind]; onlayer.Color = col[ind]; layerIndex = layerTable.Add(onlayer); //Add the layer to the layer table if (layerIndex > -1) //We managed to add layer! { att.LayerIndex = layerIndex; addedLayers.Add(layerIndex); // add index to the newly added layers list //Print("Added new layer to the document at position " + layerIndex + " named " + Layer + ". "); } //else //Print("Layer did not add. Try cleaning up your layers."); //This never happened to me. } else { att.LayerIndex = layerIndex; //We simply add to the existing layer } } // bake and select the object id[k] = Rhino.RhinoDoc.ActiveDoc.Objects.AddCurve(curve, att); Rhino.RhinoDoc.ActiveDoc.Objects.Select(id[k], true); // increment indexes k++; if (ind < lay.Length - 1) { ind++; } if (cInd < col.Length - 1) { cInd++; } } Rhino.RhinoApp.RunScript(scriptString, false); Rhino.RhinoApp.RunScript("_delete", false); // delete only the added layers Rhino.DocObjects.Tables.LayerTable layerTableNew = Rhino.RhinoDoc.ActiveDoc.Layers; foreach (int lInd in addedLayers) { layerTableNew.Delete(lInd, true); } }