/// <summary> /// Bakes the problem geometry to the document on a special layer /// Geometry is colored -> Orange and will have the a name that is showing what the problem is! /// </summary> /// <param name="erGeo">List of error geometry</param> /// <param name="erName">List of error names</param> public static IList <Guid> BakeErrorGeo(IEnumerable <GeometryBase> erGeo, IEnumerable <string> erName) { var addedGeoIds = new List <Guid>(); var doc = Rhino.RhinoDoc.ActiveDoc; var errLayer = new Rhino.DocObjects.Layer() { Name = "<<Error_Geometry>>" }; if (!doc.Layers.Any(x => x.Name == errLayer.Name)) { doc.Layers.Add(errLayer); } errLayer = doc.Layers.First(x => x.Name == "<<Error_Geometry>>"); doc.Views.RedrawEnabled = false; foreach (var geoName in erGeo.Zip(erName, (x, y) => new { geo = x, name = y })) { var attributesError = new Rhino.DocObjects.ObjectAttributes { ObjectColor = System.Drawing.Color.OrangeRed, ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject, Name = geoName.name, LayerIndex = errLayer.LayerIndex }; addedGeoIds.Add(doc.Objects.Add(geoName.geo, attributesError)); } return(addedGeoIds); }
/* * public override void AppendAdditionalMenuItems(ToolStripDropDown menu) * { * Menu_AppendItem(menu, "Select Layer", Do_Select_Layer); * base.AppendAdditionalMenuItems(menu); * } * * private void Do_Select_Layer(object sender, EventArgs e) * { * this.ExpireSolution(true); * }*/ protected override GH_GetterResult Prompt_Singular(ref Types.Hu_Layer value) { Forms.LayerDialog Dialog = new Forms.LayerDialog(); Dialog.StartPosition = FormStartPosition.CenterParent; LayerTable LT = Rhino.RhinoDoc.ActiveDoc.Layers; if (Dialog.ShowDialog() == DialogResult.OK) { int LayerIndex = Dialog.LayerIndex; Rhino.DocObjects.Layer La = LT.FindIndex(LayerIndex); if (La == null) { value = null; this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "设置图层在工作空间中不存在"); } else { value = new Types.Hu_Layer(La); } return(GH_GetterResult.success); } else { return(GH_GetterResult.cancel); } }
public void BakeLayer(string layerId) { SpeckleCore.Layer myLayer = Client.Stream.Layers.FirstOrDefault(l => l.Guid == layerId); // create or get parent string parent = String.Format("{1} | {0}", Client.Stream.StreamId, Client.Stream.Name); var parentId = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parent, true); if (parentId == -1) { var parentLayer = new Rhino.DocObjects.Layer() { Color = System.Drawing.Color.Black, Name = parent }; parentId = Rhino.RhinoDoc.ActiveDoc.Layers.Add(parentLayer); } else { int prev = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parent + "::" + myLayer.Name, true); if (prev != -1) { Rhino.RhinoDoc.ActiveDoc.Layers.Purge(prev, true); } } int theLayerId = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parent + "::" + myLayer.Name, true); if (theLayerId == -1) { var layer = new Rhino.DocObjects.Layer() { Name = myLayer.Name, Id = Guid.Parse(myLayer.Guid), ParentLayerId = Rhino.RhinoDoc.ActiveDoc.Layers[parentId].Id, Color = GetColorFromLayer(myLayer), IsVisible = true }; var index = Rhino.RhinoDoc.ActiveDoc.Layers.Add(layer); for (int i = ( int )myLayer.StartIndex; i < myLayer.StartIndex + myLayer.ObjectCount; i++) { if (Display.Geometry[i] != null) { Rhino.RhinoDoc.ActiveDoc.Objects.Add(Display.Geometry[i], new ObjectAttributes() { LayerIndex = index }); } } } Rhino.RhinoDoc.ActiveDoc?.Views.Redraw(); }
/// <summary> /// /// </summary> /// <param name="parentLayerName"></param> /// <param name="parentLayerIndex"></param> /// <param name="childLayerName"></param> /// <returns></returns> public static int AddChildLayer(string parentLayerName, int parentLayerIndex, string childLayerName, Rhino.RhinoDoc doc) { if (!Rhino.DocObjects.Layer.IsValidName(childLayerName)) { throw new ParasiteArgumentException($"{childLayerName} is not a valid layer name"); } if (string.IsNullOrEmpty(childLayerName)) { throw new ParasiteArgumentException($"{childLayerName} cant be blank"); } if (parentLayerIndex < 0) { throw new ParasiteArgumentException($"The parent layer specified:{parentLayerName} does not exists in the current Rhino Document"); } Rhino.DocObjects.Layer parent_layer = doc.Layers[parentLayerIndex]; int childLayerIndex = doc.Layers.Find(childLayerName, true); if (childLayerIndex < 0) //This layer does not exist, we add it { LayerTable layerTable = doc.Layers; int R = parent_layer.Color.R, G = parent_layer.Color.G, B = parent_layer.Color.B; Layer childlayer = new Layer { ParentLayerId = parent_layer.Id, Name = childLayerName, Color = System.Drawing.Color.FromArgb(ran.Next(R, 255), ran.Next(G, 255), ran.Next(B, 255)) }; childLayerIndex = layerTable.Add(childlayer); //Add the layer to the layer table if (childLayerIndex < 0) { throw new ParasiteArgumentException(string.Format("Unable to add {0} layer.", parentLayerName)); } } return(childLayerIndex); }
public static string EnsureLayer(string layerName, string parentLayer) { RhinoDoc doc = RhinoDoc.ActiveDoc; //Get a fresh copy of the LayerTable Rhino.DocObjects.Tables.LayerTable layerTable = doc.Layers; //Build a search string to see if the layer exists already string layerNameSearchString = ""; if (parentLayer != null && parentLayer != "") { layerNameSearchString += parentLayer + "::"; } layerNameSearchString += layerName; //Run the actual check to see if the Layer exists RhinoApp.WriteLine("Checking '" + layerNameSearchString + "' to see if it exists."); int layerIndex = layerTable.FindByFullPath(layerNameSearchString, -1); //The layer was found, return it if (layerIndex >= 0) { RhinoApp.WriteLine("Layer '" + layerNameSearchString + "' was found."); RhinoApp.WriteLine("Moving on."); return(layerNameSearchString); } //This layer was not found/ does not exist... yet else { RhinoApp.WriteLine("Layer '" + layerNameSearchString + "' was not found."); //Create the layer RhinoApp.WriteLine("Creating layer '" + layerName + "'."); Rhino.DocObjects.Layer layer = new Rhino.DocObjects.Layer(); layer.Name = layerName; //Make the new layer a child of the parent layer (if there was one) if (parentLayer != null && parentLayer != "") { RhinoApp.WriteLine("Setting layer '" + layerName + "' as a child of layer '" + parentLayer + "'."); int parentLayerIndex = layerTable.FindByFullPath(parentLayer, -1); Rhino.DocObjects.Layer parentLayerObject = layerTable.FindIndex(parentLayerIndex); layer.ParentLayerId = parentLayerObject.Id; } //Add the layer to the document layerTable.Add(layer); //Return the newly created layer return(layerNameSearchString); } }
public static Rhino.DocObjects.Layer EnsureFullPath(string fullpath) { RhinoDoc doc = RhinoDoc.ActiveDoc; //Get a fresh copy of the LayerTable Rhino.DocObjects.Tables.LayerTable layerTable = doc.Layers; //Run the actual check to see if the Layer exists RhinoApp.WriteLine("Checking " + fullpath + " to see if it exists."); int layerIndex = layerTable.FindByFullPath(fullpath, -1); //The layer was found, return it if (layerIndex >= 0) { RhinoApp.WriteLine("That layer does exist."); return(layerTable.FindIndex(layerIndex)); } //This layer was not found/ does not exist... yet else { RhinoApp.WriteLine("That layer does not exist."); //Ensure the layer's parent exists (recursive) int splitPoint = fullpath.LastIndexOf("::"); string parentPath = fullpath.Substring(0, splitPoint); string childLayer = fullpath.Substring(1, splitPoint); Rhino.DocObjects.Layer parentLayer = null; if (parentPath.Length > 0) { RhinoApp.WriteLine("Checking to see if parent layer exists..."); parentLayer = EnsureFullPath(parentPath); } //Create this new layer (on the parent path) RhinoApp.WriteLine("Creating layer " + childLayer + "..."); Rhino.DocObjects.Layer layer = new Rhino.DocObjects.Layer(); layer.Name = childLayer; //Make the new layer a child of the parent layer (if there was one) if (parentLayer != null) { RhinoApp.WriteLine("Assigning layer " + childLayer + " as of child of " + parentPath); //That layer does not exist."); layer.ParentLayerId = parentLayer.Id; } //Add the layer to the document layerTable.Add(layer); //Return the newly created layer return(layer); } }
/// <summary> /// Set or create a new layer - with a parent /// </summary> /// <param name="doc"></param> /// <returns></returns> public static Rhino.DocObjects.Layer SetLayer(RhinoDoc doc, string layername, System.Drawing.Color color, Rhino.DocObjects.Layer parentlayer) //this is an overloaded function!! it has the saame name as above 'SetLayer' but with different parameters. { //https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_DocObjects_Tables_LayerTable.htm if (string.IsNullOrEmpty(layername) || !Rhino.DocObjects.Layer.IsValidName(layername)) { return(null); } Rhino.DocObjects.Layer layer = doc.Layers.FindName(layername); if (layer != null) { //the layer already exists if (layer.Index >= 0) { doc.Layers.SetCurrentLayerIndex(layer.Index, false); } } else { layer = new Rhino.DocObjects.Layer(); if (parentlayer.Id != null) { layer.ParentLayerId = parentlayer.Id; } layer.Name = layername; layer.Color = color; //we have to create a new layer int layer_index = doc.Layers.Add(layer); if (layer_index >= 0) { doc.Layers.SetCurrentLayerIndex(layer_index, false); } } return(doc.Layers[layer.Index]); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { int layerIndex = -1; bool currentState = false; DialogResult rc = Rhino.UI.Dialogs.ShowSelectLayerDialog(ref layerIndex, "Select Layer Objects", false, false, ref currentState); if (rc != DialogResult.OK) { return(Result.Cancel); } if (layerIndex >= 0 && layerIndex < doc.Layers.Count) { Rhino.DocObjects.Layer layer = doc.Layers[layerIndex]; if (layer.IsDeleted) { return(Result.Nothing); } if (!layer.IsVisible) { RhinoApp.WriteLine("{0} layer is hidden.", layer.Name); return(Result.Nothing); } Rhino.DocObjects.RhinoObject[] rh_objects = doc.Objects.FindByLayer(layer); foreach (RhinoObject rh_object in rh_objects) { if (rh_object.IsSelectable()) { rh_object.Select(true); } } doc.Views.Redraw(); } return(Result.Success); }
/// <summary> /// Set or create a new layer /// </summary> /// <param name="doc"></param> /// <returns></returns> public static Rhino.DocObjects.Layer SetLayer(RhinoDoc doc, string layername, System.Drawing.Color color) { //https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_DocObjects_Tables_LayerTable.htm if (string.IsNullOrEmpty(layername) || !Rhino.DocObjects.Layer.IsValidName(layername)) { return(null); } Rhino.DocObjects.Layer layer = doc.Layers.FindName(layername); if (layer != null) { //the layer already exists if (layer.Index >= 0) { doc.Layers.SetCurrentLayerIndex(layer.Index, false); } } else { layer = new Rhino.DocObjects.Layer(); layer.Name = layername; layer.Color = color; //we have to create a new layer int layer_index = doc.Layers.Add(layer); if (layer_index >= 0) { doc.Layers.SetCurrentLayerIndex(layer_index, false); } } return(doc.Layers[layer.Index]); }
/// <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) { /* * Original Version Written by Giulio Piacentino - 2010 11 21 - for Grasshopper 0.8.002 * Enhanced by Co-de-iT (Alessio) - now bakes on chosen layer(s) and in groups */ GeometryBase obj = null; if (!DA.GetData(0, ref obj)) { return; } string name = ""; DA.GetData(1, ref name); string layer = ""; DA.GetData(2, ref layer); Color color = new Color(); DA.GetData(3, ref color); Object material = new Object(); DA.GetData(4, ref material); int group_n = 0; DA.GetData(5, ref group_n); bool group = false; DA.GetData(6, ref group); bool bake_iT = false; DA.GetData(7, ref bake_iT); if (!bake_iT) { return; } //Make new attribute to set name Rhino.DocObjects.ObjectAttributes att = new Rhino.DocObjects.ObjectAttributes(); //Set object name if (!string.IsNullOrEmpty(name)) { att.Name = name; } //Set color if (!color.IsEmpty) { att.ColorSource = Rhino.DocObjects.ObjectColorSource.ColorFromObject; //Make the color type "by object" att.ObjectColor = color; att.PlotColorSource = Rhino.DocObjects.ObjectPlotColorSource.PlotColorFromObject; //Make the plot color type "by object" att.PlotColor = color; } // Set group if (group) { Rhino.RhinoDoc.ActiveDoc.Groups.Add(Convert.ToString(group_n)); att.AddToGroup(group_n); } //Set layer if (!string.IsNullOrEmpty(layer) && Rhino.DocObjects.Layer.IsValidName(layer)) { //Get the current layer index Rhino.DocObjects.Tables.LayerTable layerTable = Rhino.RhinoDoc.ActiveDoc.Layers; //int layerIndex = layerTable.Find(layer, true); int layerIndex = layerTable.FindByFullPath(layer, -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 = layer; onlayer.Color = Color.Gainsboro; // sets new layer color - future dev: choose new layers color layerIndex = layerTable.Add(onlayer); //Add the layer to the layer table if (layerIndex > -1) //We managed to add the layer! { att.LayerIndex = layerIndex; //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 } } //Set plotweight //if (pWidth > 0) //{ // att.PlotWeightSource = Rhino.DocObjects.ObjectPlotWeightSource.PlotWeightFromObject; // att.PlotWeight = pWidth; //} //Set material bool materialByName = !string.IsNullOrEmpty(material as string); Rhino.Display.DisplayMaterial inMaterial; if (material is GH_Material) { GH_Material gMat = material as GH_Material; inMaterial = gMat.Value as Rhino.Display.DisplayMaterial; } else { inMaterial = material as Rhino.Display.DisplayMaterial; } if (material is Color) { inMaterial = new Rhino.Display.DisplayMaterial((Color)material); } if (material != null && inMaterial == null && !materialByName) { if (!(material is string)) { try //We also resort to try with IConvertible { inMaterial = (Rhino.Display.DisplayMaterial)Convert.ChangeType(material, typeof(Rhino.Display.DisplayMaterial)); } catch (InvalidCastException) { } } } if (inMaterial != null || materialByName) { string matName; if (!materialByName) { matName = string.Format("D:{0}-E:{1}-S:{2},{3}-T:{4}", Format(inMaterial.Diffuse), Format(inMaterial.Emission), Format(inMaterial.Specular), inMaterial.Shine.ToString(), inMaterial.Transparency.ToString() ); } else { matName = (string)material; } int materialIndex = Rhino.RhinoDoc.ActiveDoc.Materials.Find(matName, true); if (materialIndex < 0 && !materialByName) //Material does not exist and we have its specs { materialIndex = Rhino.RhinoDoc.ActiveDoc.Materials.Add(); //Let's add it if (materialIndex > -1) { //Print("Added new material at position " + materialIndex + " named \"" + matName + "\". "); Rhino.DocObjects.Material m = Rhino.RhinoDoc.ActiveDoc.Materials[materialIndex]; m.Name = matName; m.DiffuseColor = inMaterial.Diffuse; m.EmissionColor = inMaterial.Emission; //m.ReflectionColor = inMaterial.Specular; m.SpecularColor = inMaterial.Specular; m.Shine = inMaterial.Shine; m.Transparency = inMaterial.Transparency; //m.TransparentColor = no equivalent m.CommitChanges(); att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; att.MaterialIndex = materialIndex; } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Material did not add. Try cleaning up your materials."); //This never happened to me. } } else if (materialIndex < 0 && materialByName) //Material does not exist and we do not have its specs. We do nothing { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Warning: material name not found. I cannot set the source to this material name. Add a material with name: " + matName); } else { //If this material exists, we do not replace it! att.MaterialSource = Rhino.DocObjects.ObjectMaterialSource.MaterialFromObject; att.MaterialIndex = materialIndex; } } //Set wire density //if (wires == -1 || wires > 0) //{ // att.WireDensity = wires; //} //Bake to the right type of object switch (obj.ObjectType) { case Rhino.DocObjects.ObjectType.Brep: Rhino.RhinoDoc.ActiveDoc.Objects.AddBrep(obj as Brep, att); break; case Rhino.DocObjects.ObjectType.Curve: Rhino.RhinoDoc.ActiveDoc.Objects.AddCurve(obj as Curve, att); break; case Rhino.DocObjects.ObjectType.Point: Rhino.RhinoDoc.ActiveDoc.Objects.AddPoint((obj as Rhino.Geometry.Point).Location, att); break; case Rhino.DocObjects.ObjectType.Surface: Rhino.RhinoDoc.ActiveDoc.Objects.AddSurface(obj as Surface, att); break; case Rhino.DocObjects.ObjectType.Mesh: Rhino.RhinoDoc.ActiveDoc.Objects.AddMesh(obj as Mesh, att); break; case Rhino.DocObjects.ObjectType.Extrusion: typeof(Rhino.DocObjects.Tables.ObjectTable).InvokeMember("AddExtrusion", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, Rhino.RhinoDoc.ActiveDoc.Objects, new object[] { obj, att }); break; case Rhino.DocObjects.ObjectType.PointSet: Rhino.RhinoDoc.ActiveDoc.Objects.AddPointCloud(obj as Rhino.Geometry.PointCloud, att); //This is a speculative entry break; default: AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "The script does not know how to handle this type of geometry: " + obj.GetType().FullName); break; } }
public void Bake( ) { string parent = String.Format("{0} | {1}", Client.Stream.Name, Client.Stream.StreamId); var parentId = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parent, -1); if (parentId == -1) { //There is no layer in the document with the Stream Name | Stream Id as a name, so create one var parentLayer = new Rhino.DocObjects.Layer() { Color = System.Drawing.Color.Black, Name = parent }; //Maybe could be useful in the future parentLayer.SetUserString("spk", Client.Stream.StreamId); parentId = Rhino.RhinoDoc.ActiveDoc.Layers.Add(parentLayer); } else { //Layer with this name does exist. //This is either a coincidence or a receiver has affected this file before. //In any case, delete any sublayers and any objects within them. foreach (var layer in Rhino.RhinoDoc.ActiveDoc.Layers[parentId].GetChildren()) { Rhino.RhinoDoc.ActiveDoc.Layers.Purge(layer.LayerIndex, false); } } foreach (var spkLayer in Client.Stream.Layers) { var layerId = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parent + "::" + spkLayer.Name, -1); //This is always going to be the case. if (layerId == -1) { var index = -1; if (spkLayer.Name.Contains("::")) { var spkLayerPath = spkLayer.Name.Split(new string[] { "::" }, StringSplitOptions.None); var parentLayerId = Guid.Empty; foreach (var layerPath in spkLayerPath) { if (parentLayerId == Guid.Empty) { parentLayerId = Rhino.RhinoDoc.ActiveDoc.Layers[parentId].Id; } var layer = new Rhino.DocObjects.Layer() { Name = layerPath, ParentLayerId = parentLayerId, Color = GetColorFromLayer(spkLayer), IsVisible = true }; var parentLayerName = Rhino.RhinoDoc.ActiveDoc.Layers.First(l => l.Id == parentLayerId).FullPath; var layerExist = Rhino.RhinoDoc.ActiveDoc.Layers.FindByFullPath(parentLayerName + "::" + layer.Name, -1); if (layerExist == -1) { index = Rhino.RhinoDoc.ActiveDoc.Layers.Add(layer); parentLayerId = Rhino.RhinoDoc.ActiveDoc.Layers[index].Id; } else { parentLayerId = Rhino.RhinoDoc.ActiveDoc.Layers[layerExist].Id; } } } else { var layer = new Rhino.DocObjects.Layer() { Name = spkLayer.Name, Id = Guid.Parse(spkLayer.Guid), ParentLayerId = Rhino.RhinoDoc.ActiveDoc.Layers[parentId].Id, Color = GetColorFromLayer(spkLayer), IsVisible = true }; index = Rhino.RhinoDoc.ActiveDoc.Layers.Add(layer); } for (int i = ( int )spkLayer.StartIndex; i < spkLayer.StartIndex + spkLayer.ObjectCount; i++) { if (Display.Geometry[i] != null && !Display.Geometry[i].IsDocumentControlled) { Rhino.RhinoDoc.ActiveDoc.Objects.Add(Display.Geometry[i], new ObjectAttributes() { LayerIndex = index }); } } } } Rhino.RhinoDoc.ActiveDoc?.Views.Redraw(); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { //create a single object of our brand new Panel class //Panel panel = new Panel(); // we are calling our constructor that initializes the corner points and nothing else UsefulFunctions.XSelectPoints("Select four points in the right order", out Point3dList newcornerpts); if (newcornerpts.Count != 4) { return(Result.Failure); } Rhino.DocObjects.Layer parentlayer = UsefulFunctions.SetLayer(doc, "L", System.Drawing.Color.Coral); //not overloaded, sets layer to work on int rep = 20; Random rnd = new Random(); for (var i = 0; i < rep; i++) { Panel panel = new Panel(); panel.SetCornerPts(newcornerpts); panel.SetDotName(new TextDot(i.ToString(), newcornerpts.BoundingBox.Center)); if (panel.Rebuild()) { UsefulFunctions.SetLayer(doc, "Panels", System.Drawing.Color.Turquoise, parentlayer); //overloaded, sets the layer so we can draw on it doc.Objects.AddBrep(panel.brep); // add the brep UsefulFunctions.SetLayer(doc, "Panel dots", System.Drawing.Color.DarkRed, parentlayer); //overloaded, sets the layer so we can draw on it doc.Objects.AddTextDot(panel.GetDotName()); //add the dot doc.Views.Redraw(); } else { continue; } //translation var xform = Transform.Translation(new Vector3d(newcornerpts[1] - newcornerpts[0])); newcornerpts.Transform(xform); //rotation int rndrange = rnd.Next(-10, 10); double rndanglerad = ((double)rndrange / 180) * Math.PI; var xformrot = Transform.Rotation(rndanglerad, newcornerpts[0]); newcornerpts.Transform(xformrot); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { const Rhino.DocObjects.ObjectType geometryFilter = Rhino.DocObjects.ObjectType.Surface | Rhino.DocObjects.ObjectType.PolysrfFilter; Rhino.DocObjects.ObjRef objref; Result rc = Rhino.Input.RhinoGet.GetOneObject("Select first/main polysurface or surface to bool", false, geometryFilter, out objref); if (rc != Rhino.Commands.Result.Success) { return(rc); } if (objref == null) { return(Rhino.Commands.Result.Failure); } Rhino.Geometry.Brep brep = objref.Brep(); bool resIssolid = brep.IsSolid; if (!resIssolid) { Dialogs.ShowMessage("Your polysurface or surface is not solid! Result might not be valid!", "Warning!"); } Guid firstBrep = objref.ObjectId; doc.Objects.UnselectAll(true); //Select rest of polysurfaces or surfaces to bool Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject(); go.SetCommandPrompt("Select rest of polysurfaces or surfaces to bool"); go.GeometryFilter = geometryFilter | Rhino.DocObjects.ObjectType.InstanceReference; go.GroupSelect = true; go.GetMultiple(1, 0); bool isSolid = true; //Add set to breps list List <Rhino.Geometry.Brep> breps = new List <Rhino.Geometry.Brep>(); for (int i = 0; i < go.ObjectCount; i++) { //Explode if instance object and add to breps list if (go.Object(i).Object() is InstanceObject) { InstanceObject instObj = go.Object(i).Object() as InstanceObject; RhinoObject[] explodedObjects; ObjectAttributes[] attributesOfExplodedObjects; Transform[] transformOfExplodedObjects; instObj.Explode(false, out explodedObjects, out attributesOfExplodedObjects, out transformOfExplodedObjects); Guid addedObjectID = doc.Objects.Add(explodedObjects[0].Geometry, explodedObjects[0].Attributes); ObjRef objrefs = new Rhino.DocObjects.ObjRef(addedObjectID); Rhino.Geometry.Brep brepd = objrefs.Brep(); brepd.Transform(transformOfExplodedObjects[0]); resIssolid = brepd.IsSolid; if (!resIssolid) { isSolid = false; } if (brepd != null && firstBrep != addedObjectID) { breps.Add(brepd); } doc.Objects.Delete(addedObjectID, true); } else { Rhino.DocObjects.ObjRef objrefs = go.Object(i); Rhino.Geometry.Brep brepd = objrefs.Brep(); resIssolid = brepd.IsSolid; if (!resIssolid) { isSolid = false; } if (brepd != null && firstBrep != objrefs.ObjectId) { breps.Add(brepd); } } } if (!isSolid) { Dialogs.ShowMessage("At least on polysurface or surface to subtract is not solid! Result might not be valid!", "Warning!"); } doc.Objects.UnselectAll(true); //Create layers for failed and successfull booleans if not already existing var fail_layer_index = doc.Layers.FindName("FJ Boolean Fails"); if (fail_layer_index == null) { string name_fail_layer = "FJ Boolean Fails"; Rhino.DocObjects.Layer boolFail = new Rhino.DocObjects.Layer(); boolFail.Name = name_fail_layer; boolFail.Color = System.Drawing.Color.Red; doc.Layers.Add(boolFail); fail_layer_index = doc.Layers.FindName(name_fail_layer); } var done_layer_index = doc.Layers.FindName("FJ Boolean Done"); if (done_layer_index == null) { string name_done_layer = "FJ Boolean Done"; Rhino.DocObjects.Layer boolDone = new Rhino.DocObjects.Layer(); boolDone.Name = name_done_layer; boolDone.Color = System.Drawing.Color.BlueViolet; doc.Layers.Add(boolDone); done_layer_index = doc.Layers.FindName(name_done_layer); } //Compute boolean union double tolerance = doc.ModelAbsoluteTolerance; int a = 0; for (int i = 0; i < breps.Count; i++) { RhinoApp.WriteLine("computing number: " + i + " of: " + breps.Count + " operations..."); List <Brep> brepBool = new List <Brep>(); brepBool.Add(brep); brepBool.Add(breps[i]); Rhino.Geometry.Brep[] brepBoolNew = Rhino.Geometry.Brep.CreateBooleanUnion(brepBool, tolerance, true); if (brepBoolNew == null || brepBoolNew.Length > 1) { a++; doc.Objects.Delete(go.Object(i).Object()); var boolresultfail = doc.Objects.AddBrep(breps[i]); ObjRef objFailref = new ObjRef(boolresultfail); Rhino.DocObjects.RhinoObject objFail = objFailref.Object(); objFail.Attributes.LayerIndex = fail_layer_index.Index; objFail.CommitChanges(); } else { brep = brepBoolNew[0]; doc.Objects.Delete(go.Object(i).Object()); var boolresult = doc.Objects.AddBrep(breps[i]); ObjRef obj20ref = new ObjRef(boolresult); Rhino.DocObjects.RhinoObject obj2Org = obj20ref.Object(); obj2Org.Attributes.LayerIndex = done_layer_index.Index; obj2Org.CommitChanges(); } doc.Views.Redraw(); } RhinoApp.WriteLine(a + " of " + breps.Count + " operations failed!"); Rhino.DocObjects.RhinoObject obj1Org = objref.Object(); doc.Objects.Delete(obj1Org); doc.Objects.AddBrep(brep); doc.Views.Redraw(); return(Rhino.Commands.Result.Success); }
public async void SendStaggeredUpdate(bool force = false) { if (Paused && !force) { Context.NotifySpeckleFrame("client-expired", StreamId, ""); return; } else { // create a clone var cloneResult = Client.StreamCloneAsync(StreamId).Result; Client.Stream.Children.Add(cloneResult.Clone.StreamId); Client.BroadcastMessage("stream", StreamId, new { eventType = "update-children" }); } if (IsSendingUpdate) { Expired = true; return; } IsSendingUpdate = true; Context.NotifySpeckleFrame("client-is-loading", StreamId, ""); var objs = RhinoDoc.ActiveDoc.Objects.FindByUserString("spk_" + this.StreamId, "*", false).OrderBy(obj => obj.Attributes.LayerIndex); Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converting " + objs.Count() + " objects..."); // layer list creation var pLayers = new List <SpeckleCore.Layer>(); int lindex = -1, count = 0, orderIndex = 0; foreach (RhinoObject obj in objs) { Rhino.DocObjects.Layer layer = RhinoDoc.ActiveDoc.Layers[obj.Attributes.LayerIndex]; if (lindex != obj.Attributes.LayerIndex) { var spkLayer = new SpeckleCore.Layer() { Name = layer.FullPath, Guid = layer.Id.ToString(), ObjectCount = 1, StartIndex = count, OrderIndex = orderIndex++, Properties = new LayerProperties() { Color = new SpeckleCore.SpeckleBaseColor() { A = 1, Hex = System.Drawing.ColorTranslator.ToHtml(layer.Color) }, } }; pLayers.Add(spkLayer); lindex = obj.Attributes.LayerIndex; } else { var spkl = pLayers.FirstOrDefault(pl => pl.Name == layer.FullPath); spkl.ObjectCount++; } count++; } // convert objects var convertedObjects = new List <SpeckleObject>(); foreach (RhinoObject obj in objs) { var myObj = Converter.Serialise(obj.Geometry); myObj.ApplicationId = obj.Id.ToString(); convertedObjects.Add(myObj); } LocalContext.PruneExistingObjects(convertedObjects, Client.BaseUrl); List <SpeckleObject> persistedObjects = new List <SpeckleObject>(); if (convertedObjects.Count(obj => obj.Type == "Placeholder") != convertedObjects.Count) { // create the update payloads count = 0; var objectUpdatePayloads = new List <List <SpeckleObject> >(); long totalBucketSize = 0; long currentBucketSize = 0; var currentBucketObjects = new List <SpeckleObject>(); var allObjects = new List <SpeckleObject>(); foreach (SpeckleObject convertedObject in convertedObjects) { if (count++ % 100 == 0) { Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converted " + count + " objects out of " + objs.Count() + "."); } // size checking & bulk object creation payloads creation long size = Converter.getBytes(convertedObject).Length; currentBucketSize += size; totalBucketSize += size; currentBucketObjects.Add(convertedObject); // Object is too big? if (size > 2e6) { Context.NotifySpeckleFrame("client-error", StreamId, JsonConvert.SerializeObject("This stream contains a super big object. These will fail. Sorry for the bad error message - we're working on improving this.")); currentBucketObjects.Remove(convertedObject); } if (currentBucketSize > 5e5) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. { Debug.WriteLine("Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count); objectUpdatePayloads.Add(currentBucketObjects); currentBucketObjects = new List <SpeckleObject>(); currentBucketSize = 0; } } // add in the last bucket if (currentBucketObjects.Count > 0) { objectUpdatePayloads.Add(currentBucketObjects); } Debug.WriteLine("Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000); // create bulk object creation tasks int k = 0; List <ResponseObject> responses = new List <ResponseObject>(); foreach (var payload in objectUpdatePayloads) { Context.NotifySpeckleFrame("client-progress-message", StreamId, String.Format("Sending payload {0} out of {1}", k++, objectUpdatePayloads.Count)); try { var objResponse = await Client.ObjectCreateAsync(payload); responses.Add(objResponse); persistedObjects.AddRange(objResponse.Resources); int m = 0; foreach (var oL in payload) { oL._id = objResponse.Resources[m++]._id; } // push sent objects in the cache non-blocking Task.Run(() => { foreach (var oL in payload) { if (oL.Type != "Placeholder") { LocalContext.AddSentObject(oL, Client.BaseUrl); } } }); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); IsSendingUpdate = false; return; } } } else { persistedObjects = convertedObjects; } Context.NotifySpeckleFrame("client-progress-message", StreamId, "Updating stream..."); // finalise layer creation foreach (var layer in pLayers) { layer.Topology = "0-" + layer.ObjectCount + " "; } // create placeholders for stream update payload List <SpeckleObject> placeholders = new List <SpeckleObject>(); //foreach ( var myResponse in responses ) foreach (var obj in persistedObjects) { placeholders.Add(new SpecklePlaceholder() { _id = obj._id }); } // create stream update payload SpeckleStream streamUpdatePayload = new SpeckleStream(); streamUpdatePayload.Layers = pLayers; streamUpdatePayload.Objects = placeholders; streamUpdatePayload.Name = Client.Stream.Name; // set some base properties (will be overwritten) var baseProps = new Dictionary <string, object>(); baseProps["units"] = RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); baseProps["tolerance"] = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; baseProps["angleTolerance"] = RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; streamUpdatePayload.BaseProperties = baseProps; // update the stream ResponseBase response = null; try { response = await Client.StreamUpdateAsync(Client.Stream.StreamId, streamUpdatePayload); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); IsSendingUpdate = false; return; } // emit events, etc. Client.Stream.Layers = streamUpdatePayload.Layers.ToList(); Client.Stream.Objects = placeholders; Context.NotifySpeckleFrame("client-metadata-update", StreamId, Client.Stream.ToJson()); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); Client.BroadcastMessage("stream", StreamId, new { eventType = "update-global" }); IsSendingUpdate = false; if (Expired) { DataSender.Start(); } Expired = false; }
public bool IsParentOf(Layer otherLayer) { return(IsParentOf(otherLayer.LayerIndex)); }
public bool IsChildOf(Layer otherLayer) { return(IsChildOf(otherLayer.LayerIndex)); }
/// <summary> /// Draws the panel. /// </summary> /// <param name="xLowerBound">The x lower bound.</param> /// <param name="xUpperBound">The x upper bound.</param> /// <param name="yLowerBound">The y lower bound.</param> /// <param name="yUpperBound">The y upper bound.</param> /// <param name="panel">The panel.</param> /// <param name="para">The para.</param> public static void drawPanel(double xLowerBound, double xUpperBound, double yLowerBound, double yUpperBound, PerforationPanel panel, bool fixingHolesManipulated, bool enablePerf) { RhinoDoc doc = RhinoDoc.ActiveDoc; List <Guid> guidList = new List <Guid>(); string layerName = null; //name of layers int layerIndex = 0; //index of layers Rhino.DocObjects.Layer parent_layer_Approval = null; //create variable to hold approval layer Rhino.DocObjects.Layer parent_layer_Nesting = null; //create variable to hold nesting layer //Rhino.DocObjects.Layer childlayer = null; //Create a variable to hold child layers string text = ""; double height = panel.labelHeight / 3; const string font = "Arial"; Guid burrLeader; RhinoObject labelText; Rhino.Geometry.Point3d pt = new Rhino.Geometry.Point3d(0, 0, 0); Rhino.Geometry.Plane plane = doc.Views.ActiveView.ActiveViewport.ConstructionPlane(); //start //Creating layer called "Layers for Approval Drawings" to make it a parent layer layerName = "LAYERS FOR APPROVAL DRAWINGS"; // Does a layer with the same name already exist? layerIndex = doc.Layers.Find(layerName, true); // If layer does not exist if (layerIndex == -1) { // Add a new layer to the document layerIndex = doc.Layers.Add(layerName, System.Drawing.Color.Black); parent_layer_Approval = doc.Layers[layerIndex]; //set the layer as parent layer } else { parent_layer_Approval = doc.Layers[layerIndex]; } layerName = "LAYERS FOR NESTING"; // Does a layer with the same name already exist? layerIndex = doc.Layers.Find(layerName, true); // If layer does not exist if (layerIndex == -1) { // Add a new layer to the document layerIndex = doc.Layers.Add(layerName, System.Drawing.Color.Black); parent_layer_Nesting = doc.Layers[layerIndex]; } else { parent_layer_Nesting = doc.Layers[layerIndex]; } // Create a new layer called Perimeter layerName = "PANEL PERIMETER"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Black, parent_layer_Nesting); //make Nesting layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); //Bottom and left justified the panels in the grid (panel x0,x1,y0,y1 - refers to the folds edg (folds layer) double panelX0 = xLowerBound; double panelX1 = panelX0 + panel.X; double panelY0 = yUpperBound; double panelY1 = panelY0 + panel.Y; List <Point3d> list = new List <Point3d>(); panel.Perimeter = doc.Objects.AddLine(new Point3d(panelX0, panelY1, 0), new Point3d(panelX1, panelY1, 0)); guidList.Add(panel.Perimeter); panel.Perimeter = doc.Objects.AddLine(new Point3d(panelX0, panelY0, 0), new Point3d(panelX0, panelY1, 0)); guidList.Add(panel.Perimeter); panel.Perimeter = doc.Objects.AddLine(new Point3d(panelX0, panelY0, 0), new Point3d(panelX1, panelY0, 0)); guidList.Add(panel.Perimeter); panel.Perimeter = doc.Objects.AddLine(new Point3d(panelX1, panelY0, 0), new Point3d(panelX1, panelY1, 0)); guidList.Add(panel.Perimeter); //MetrixUtilities.joinCurves(doc.Layers.Find("PANEL PERIMETER", true)); //join the closed curves using the method //Calculating the borders double borderX0 = panelX0 + panel.LeftBorder; //refers to the borders corners double borderY0 = panelY0 + panel.BottomBorder; double borderX1 = panelX1 - panel.RightBorder; double borderY1 = panelY1 - panel.TopBorder; BoundingBox panelBox = new BoundingBox(borderX0, borderY0, 0, borderX1, borderY1, 0); List <Point3d> rectangle_corners = panelBox.GetCorners().Distinct().ToList(); // add 1st point at last to close the loop rectangle_corners.Add(rectangle_corners[0]); // Create a new layer called Border layerName = "BORDERS"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Purple, parent_layer_Approval); //pass to the method, make Approval layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); //Add the borders only if the panel is not solid if (panel.DrawPerf != 3) { //Create a bounding box for the borders panel.Border = doc.Objects.AddPolyline(rectangle_corners); guidList.Add(panel.Border); } // Create a new layer called LABELS layerName = "LABELS"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Red, parent_layer_Nesting); //pass to the method, make Nesting layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); text = panel.PartName; height = panel.labelHeight; pt = new Rhino.Geometry.Point3d(borderX0, borderY0 + 4 + height, 0); plane = doc.Views.ActiveView.ActiveViewport.ConstructionPlane(); plane.Origin = pt; panel.Label = doc.Objects.AddText(text, plane, height, font, false, false); guidList.Add(panel.Label); RhinoApp.RunScript("SelNone", true); labelText = doc.Objects.Find(panel.Label); labelText.Select(true); BoundingBox bbox = labelText.Geometry.GetBoundingBox(true); double minX = bbox.Corner(true, true, true).X; double maxX = bbox.Corner(false, true, true).X; double minY = bbox.Corner(true, true, true).Y; double maxY = bbox.Corner(true, false, true).Y; if (maxX - minX >= panel.X - panel.LeftBorder - panel.RightBorder) { double ratio = 1; labelText.Select(true); if (panel.Y > panel.X) { RhinoApp.RunScript("_-rotate " + bbox.Center.X + "," + bbox.Center.Y + " " + "90", true); } if (maxY - minY + 4 >= panel.X - panel.LeftBorder - panel.RightBorder) { ratio = (panel.X - panel.LeftBorder - panel.RightBorder) / (2 * (maxY - minY)); if (ratio * (maxX - minX) >= (panel.Y - panel.TopBorder - panel.BottomBorder)) { ratio = ratio * (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * ratio * (maxX - minX)); } } else if (maxX - minX >= panel.Y - panel.TopBorder - panel.BottomBorder) { ratio = (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * (maxX - minX)); } RhinoApp.RunScript("_-Scale " + bbox.Center.X + "," + bbox.Center.Y + " " + ratio, true); BoundingBox bbox3 = labelText.Geometry.GetBoundingBox(true); double distance1 = borderX0 + ratio * (bbox3.Max.X - bbox3.Min.X) / 2; double distance2 = borderY0 + ratio * (bbox3.Max.Y - bbox3.Min.Y) / 2; if (panel.Y > panel.X) { distance1 = borderX0 + ratio * (bbox3.Max.Y - bbox3.Min.Y) / 2; distance2 = borderY0 + ratio * (bbox3.Max.X - bbox3.Min.X) / 2; } RhinoApp.WriteLine(bbox3.Center.ToString()); RhinoApp.RunScript("_-Move " + bbox3.Center.X + "," + bbox3.Center.Y + ",0 " + distance1 + "," + distance2 + ",0", true); } else if (maxY - minY >= panel.Y - panel.TopBorder - panel.BottomBorder) { double ratio = (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * (maxY - minY)); labelText.Select(true); RhinoApp.RunScript("_-Scale " + bbox.Center.X + "," + bbox.Center.Y + " " + ratio, true); BoundingBox bbox2 = labelText.Geometry.GetBoundingBox(true); double distanceX = borderX0 + ratio * (bbox2.Center.X - bbox2.Min.X) / 2; double distanceY = panelBox.Min.Y + ratio * (bbox2.Center.Y - bbox.Min.Y) / 2; RhinoApp.WriteLine(bbox2.Center.ToString()); RhinoApp.RunScript("_-Move " + bbox2.Center.X + "," + bbox2.Center.Y + ",0 " + distanceX + "," + distanceY + ",0", true); } labelText.Select(false); // If dotFontLabel is more than 0 draw the dot font text on the panel, else skip // if (para.DotFont == 1) if (panel.DotFontLabel > 0) { // Create a new layer called DOT SCRIBE LABEL layerName = "DOT SCRIBE LABEL"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Black, parent_layer_Nesting); //make Nesting layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); // Put in the Dot Matrix Label // Draw at the right side of the border aand 10mm from the bottom and 100mm from the left edge double panelOffset = 0; if (panel.BottomBorder - 8.7 <= 6) { panelOffset = (panel.BottomBorder - 8.7) / 2; } else { panelOffset = 3.1; } if (panel.X < 160) { pt = new Point3d(1 * (panelX0 + panelX1) / 2, panelY0 + panelOffset + 8.7, 0); } else { pt = new Point3d(panelX1 - 100, panelY0 + panelOffset + 8.7, 0); } if (panel.DotFontLabellerSide.Equals("Rear")) { DotMatrixLabellerCommand.Instance.drawDotMatrix(pt, panel.PartName, 8.7, panel.X); //set the size of dotfont } else //If not revered use front labeller { DotMatrixFrontLabellerCommand.Instance.drawDotMatrix(pt, panel.PartName, 8.7); } } //checks whether the perforation layers exists, if not create layer and make Approval layer the parent layer //If exists, make Approval layer the parent layer layerName = "PERFORATION"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Green, parent_layer_Approval); // doc.Layers.SetCurrentLayerIndex(layerIndex, true); //Create Temporary Layer if (panel.DrawPerf == 1) { RhinoUtilities.SetActiveLayer("TemporaryPerfLayer", System.Drawing.Color.Green); doc.Views.Redraw(); RhinoApp.RunScript("SelAll", true); RhinoApp.RunScript("-_Rotate 0,0,0 -" + panel.patternDirection, true); PerforationForm perforationForm = new PerforationForm(new Rhino.DocObjects.ObjRef(panel.Border).Curve()); perforationForm.enablePerforation = enablePerf; perforationForm.drawPerforationDesign(panel.PatternName, true, enablePerf); RhinoApp.RunScript("SelAll", true); RhinoApp.RunScript("-_Rotate 0,0,0 " + panel.patternDirection, true); RhinoApp.RunScript("SelNone", true); var rhinoObjects = doc.Objects.FindByLayer("TemporaryPerfLayer"); var toolHitObjects = doc.Objects.FindByLayer("TemporaryToolHit"); var temporaryTool2Layer = doc.Objects.FindByLayer("TemporaryTool2Layer"); //Perf objects if (rhinoObjects != null && rhinoObjects.Length > 1) { foreach (var rhinObj in rhinoObjects) { rhinObj.Select(true); } if (panel.patternDirection == 1) { RhinoApp.RunScript("-_Rotate 0,0,0 -90", true); RhinoApp.RunScript("-_Rotate 0,0,0 90", true); } RhinoUtilities.SetActiveLayer(Properties.Settings.Default.PerforationLayerName, System.Drawing.Color.Green); RhinoApp.RunScript("-_ChangeLayer PERFORATION", true); int index = doc.Layers.Find("TemporaryPerfLayer", true); doc.Layers.Delete(index, true); } //tool hit objects if (toolHitObjects != null && toolHitObjects.Length > 1) { foreach (var toolhitObj in toolHitObjects) { toolhitObj.Select(true); } if (panel.patternDirection == 1) { RhinoApp.RunScript("-_Rotate 0,0,0 -90", true); RhinoApp.RunScript("-_Rotate 0,0,0 90", true); } RhinoUtilities.SetActiveLayer(Properties.Settings.Default.ToolHitLayerName, System.Drawing.Color.Black); RhinoApp.RunScript("-_ChangeLayer TOOL HIT", true); int index = doc.Layers.Find("TemporaryToolHit", true); doc.Layers.Delete(index, true); } //Tool 2 objects if (temporaryTool2Layer != null && temporaryTool2Layer.Length > 1) { foreach (var tool2Objs in temporaryTool2Layer) { tool2Objs.Select(true); } if (panel.patternDirection == 1) { RhinoApp.RunScript("-_Rotate 0,0,0 -90", true); RhinoApp.RunScript("-_Rotate 0,0,0 90", true); } RhinoUtilities.SetActiveLayer("Tool 2 Layer", System.Drawing.Color.Yellow); RhinoApp.RunScript("-_ChangeLayer Tool 2 Layer", true); int index = doc.Layers.Find("TemporaryTool2Layer", true); doc.Layers.Delete(index, true); } doc.Views.Redraw(); } DimensionStyle dimStyle = MetrixUtilities.createMetrixRealDimension(); //sets the metrix real dimension Point3d origin = new Point3d(0, 0, 0); Point3d offset = new Point3d(0, 0, 0); Point2d ext1; Point2d ext2; Point2d linePt; LinearDimension dimension; Guid dimGuid = new Guid(); double u, v; // Create a new layer called DIMENSIONS BLACK layerName = "DIMENSIONS BLACK"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Black, parent_layer_Approval); //pass to the method, make Approval layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); // Add the word perforated area to the panel if (panel.DrawPerf != 3) //Add the text only if the panel is not a solid panel { //pt = new Rhino.Geometry.Point3d(((borderX1 + borderX0) / 2) - 117.5, ((borderY1 + borderY0) / 2) + 33, 0); text = System.Text.RegularExpressions.Regex.Unescape(panel.PerfText); height = panel.labelHeight / 2; pt = new Rhino.Geometry.Point3d(((borderX1 + borderX0) / 2) - 117.5, ((borderY1 + borderY0) / 2) + 10 + height, 0); plane.Origin = pt; Guid perforatedAreaLabel = doc.Objects.AddText(text, plane, height, font, false, false); guidList.Add(perforatedAreaLabel); double ratio = 1; if (panel.X - panel.LeftBorder - panel.RightBorder < 230) { RhinoApp.RunScript("SelNone", true); labelText = doc.Objects.Find(perforatedAreaLabel); labelText.Select(true); bbox = labelText.Geometry.GetBoundingBox(true); if (panel.Y > panel.X) { RhinoApp.RunScript("_-rotate " + bbox.Center.X + "," + bbox.Center.Y + " " + "90", true); } minX = bbox.Corner(true, true, true).X; maxX = bbox.Corner(false, true, true).X; minY = bbox.Corner(true, true, true).Y; maxY = bbox.Corner(true, false, true).Y; if (maxY - minY > panel.X - panel.LeftBorder - panel.RightBorder) { ratio = (panel.X - panel.LeftBorder - panel.RightBorder) / (2 * (maxY - minY)); if (ratio * (maxX - minX) > (panel.Y - panel.TopBorder - panel.BottomBorder)) { ratio = ratio * (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * ratio * (maxX - minX)); } } else if (maxX - minX >= panel.Y - panel.TopBorder - panel.BottomBorder) { ratio = (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * (maxX - minX)); } labelText.Select(true); RhinoApp.RunScript("_-Scale " + bbox.Center.X + "," + bbox.Center.Y + " " + ratio, true); BoundingBox bbox2 = labelText.Geometry.GetBoundingBox(true); double distanceX = (borderX0 + borderX1) / 2; double distanceY = (borderY0 + borderY1) / 2; RhinoApp.WriteLine(bbox2.Center.ToString()); RhinoApp.RunScript("_-Move " + bbox2.Center.X + "," + bbox2.Center.Y + ",0 " + distanceX + "," + distanceY + ",0", true); } else { RhinoApp.RunScript("SelNone", true); labelText = doc.Objects.Find(perforatedAreaLabel); labelText.Select(true); bbox = labelText.Geometry.GetBoundingBox(true); minX = bbox.Corner(true, true, true).X; maxX = bbox.Corner(false, true, true).X; minY = bbox.Corner(true, true, true).Y; maxY = bbox.Corner(true, false, true).Y; if (maxX - minX > panel.Y - panel.TopBorder - panel.BottomBorder) { ratio = (panel.Y - panel.TopBorder - panel.BottomBorder) / (2 * (maxY - minY)); labelText.Select(true); RhinoApp.RunScript("_-Scale " + bbox.Center.X + "," + bbox.Center.Y + " " + ratio, true); } BoundingBox bbox2 = labelText.Geometry.GetBoundingBox(true); double distanceX = (borderX0 + borderX1) / 2; double distanceY = (borderY0 + borderY1) / 2; RhinoApp.WriteLine(bbox2.Center.ToString()); RhinoApp.RunScript("_-Move " + bbox2.Center.X + "," + bbox2.Center.Y + ",0 " + distanceX + "," + distanceY + ",0", true); } } // Add horizontal dimension origin = new Point3d(panelX1, panelY0 - 50, 0); offset = new Point3d(panelX0, panelY0 - 50, 0); pt = new Point3d((offset.X - origin.X) / 2, panelY0 - 100, 0); plane = Plane.WorldXY; plane.Origin = origin; //double u, v; plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); //add the bottom dimension(vertical line) guidList.Add(dimGuid); // Add vertical dimension for panel origin = new Point3d(panelX0 - 20, panelY0, 0); offset = new Point3d(panelX0 - 20, panelY1, 0); pt = new Point3d(panelX0 - 100, (offset.Y - origin.Y) / 2, 0); plane = Plane.WorldXY; plane.XAxis = new Vector3d(0, -1, 0); plane.YAxis = new Vector3d(-1, 0, 0); plane.ZAxis = new Vector3d(0, 0, -1); plane.Origin = origin; plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); //adds the left dimension guidList.Add(dimGuid); MetrixUtilities.createMetrixBordersDimension(); //sets the dimension style for borders // Draw Border dimension on BORDERS layer if (panel.DrawPerf != 3) ///Add only if the panel is not a solid panel { layerName = "BORDERS"; layerIndex = doc.Layers.Find(layerName, true); doc.Layers.SetCurrentLayerIndex(layerIndex, true); // Add horizontal borders dimension origin = new Point3d(panelX1, (panelY0 + panelY1) / 2, 0); offset = new Point3d(borderX1, (panelY0 + panelY1) / 2, 0); pt = new Point3d((offset.X - origin.X) / 2, (borderY0 + borderY1) / 2, 0); plane = Plane.WorldXY; plane.Origin = origin; plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); guidList.Add(dimGuid); // Add horizontal borders dimension origin = new Point3d(panelX0, (panelY0 + panelY1) / 2, 0); offset = new Point3d(borderX0, (panelY0 + panelY1) / 2, 0); pt = new Point3d((offset.X - origin.X) / 2, (borderY0 + borderY1) / 2, 0); plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); guidList.Add(dimGuid); // Add vertical border dimension for panel origin = new Point3d((panelX0 + panelX1) / 2, panelY0, 0); offset = new Point3d((panelX0 + panelX1) / 2, borderY0, 0); pt = new Point3d((borderX0 + borderX1) / 2, (offset.Y - origin.Y) / 2, 0); plane = Plane.WorldXY; plane.XAxis = new Vector3d(0, -1, 0); plane.YAxis = new Vector3d(-1, 0, 0); plane.ZAxis = new Vector3d(0, 0, -1); plane.Origin = origin; plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); guidList.Add(dimGuid); origin = new Point3d((panelX0 + panelX1) / 2, panelY1, 0); offset = new Point3d((panelX0 + panelX1) / 2, borderY1, 0); pt = new Point3d((borderX0 + borderX1) / 2, (offset.Y - origin.Y) / 2, 0); plane.ClosestParameter(origin, out u, out v); ext1 = new Point2d(u, v); plane.ClosestParameter(offset, out u, out v); ext2 = new Point2d(u, v); plane.ClosestParameter(pt, out u, out v); linePt = new Point2d(u, v); dimension = new LinearDimension(plane, ext1, ext2, linePt); dimGuid = doc.Objects.AddLinearDimension(dimension); guidList.Add(dimGuid); } MetrixUtilities.createMetrixRealDimension(); //sets the default dimension style layerName = "VIEWPORT"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Black, parent_layer_Approval); //pass to the method, make Approval layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); Rhino.DocObjects.RhinoObject label = doc.Objects.Find(panel.Label); string exportFileName = "1"; if (label != null) { label.Select(true); Rhino.Geometry.TextEntity textentity = label.Geometry as Rhino.Geometry.TextEntity; exportFileName = textentity.Text + ".dxf"; } /** * Checks if the dxf files are required by the user, if yes check whether the panel is perforated * using the drawPerf property in the panel. If it is a perforated panel then check if the directory * for perforated panels dxf files already exists, if does not exist create directory and run command. * If panel is not perforated, create directory to save not perforated panels dxf files if the directory * does not exist. Then run the dxf file create command. * */ if (panel.DXFFilesRequired.Equals("Yes")) { String path; String immediateFolderName = Path.GetFileName(Path.GetDirectoryName(doc.Path)); //get the immediate foldername which the file is located in //split the path to get the parent folder. String[] newPath = MetrixUtilities.splitString(Path.GetDirectoryName(doc.Path), immediateFolderName); if (panel.DrawPerf == 1) //checks if panel is perforated { path = newPath[0] + ("5TRUMPF") + ("\\WITH PERF"); //merge path for perforated files if (!Directory.Exists(path)) //check if directory already exists { System.IO.Directory.CreateDirectory(path); //create directory if not exist } } else { path = newPath[0] + ("5TRUMPF") + ("\\NO PERF"); //merge path for not perforated files if (!Directory.Exists(path)) //check if directory already exists { System.IO.Directory.CreateDirectory(path); //create directory if not exist } } string command = string.Format("-_Export \"" + path + @"\" + exportFileName + "\" Scheme \"R12 Lines & Arcs\" Enter"); // Export the selected curves RhinoApp.RunScript(command, true); } // Unselect all objects doc.Objects.UnselectAll(); // Default layer index int defaultLayerIndex = doc.Layers.Find("Default", true); doc.Layers.SetCurrentLayerIndex(layerIndex, true); ////if draw perf is false, turnoff the toolhit layer //if (Convert.ToBoolean(panel.DrawPerf) != true) //{ // layerName = "Tool Hit"; // layerIndex = doc.Layers.Find(layerName, true); // doc.Layers[layerIndex].IsVisible = false; //} MetrixUtilities.joinCurves(doc.Layers.Find("PANEL PERIMETER", true)); if (panel.FixingHoles == "1") { //if fixing holes are not manipulated, recalculate distances if (!fixingHolesManipulated) { //panel = reCalculateDistances(panel); //Below method is if fixing holes are automated guidList = FixingHoles.drawFixingFoles(panel, null, false, 0, 0, panelY0, panelY1, dimStyle, guidList, panelX0, panelX1, 0, 0, 0, 0, 0); //add fixing holes } else { //Below method is if fixing holes have been manipulated guidList = CustomFixingHoles.drawFixingFoles(panel, null, false, 0, 0, panelY0, panelY1, dimStyle, guidList, panelX0, panelX1, 0, 0, 0, 0, 0); //add fixing holes } } layerName = "VIEWPORT"; layerIndex = createSubLayers.createSubLayer(layerName, System.Drawing.Color.Black, parent_layer_Approval); //pass to the method, make Approval layer the parent layer doc.Layers.SetCurrentLayerIndex(layerIndex, true); foreach (Guid g in guidList) { int idx = RhinoDoc.ActiveDoc.Groups.Find(panel.PartName, false); if (idx < 0) { idx = RhinoDoc.ActiveDoc.Groups.Add(panel.PartName); } RhinoDoc.ActiveDoc.Groups.AddToGroup(idx, g); } //end }
protected override void SolveInstance(IGH_DataAccess DA) { var run = false; var geometry = new List <IGH_GeometricGoo>(); var exportPath = ""; var atts = new List <ObjectAttributes>(); var layerNames = new List <string>(); if (!DA.GetData("Run", ref run)) { return; } if (!DA.GetDataList("Geometry to Export", geometry)) { return; } if (!DA.GetData("Export Path", ref exportPath)) { return; } var hasAtts = DA.GetDataList("Attributes", atts); var hasLayerName = DA.GetDataList("Layer Names", layerNames); if (hasAtts && hasLayerName) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Supply EITHER layer names or attributes - not both. Since both are supplied, layer names will be ignored."); } if (!run) { var inputButtons = Params.Input[0].Sources.OfType <Grasshopper.Kernel.Special.GH_ButtonObject>(); foreach (var btn in inputButtons) { Grasshopper.Instances.ActiveCanvas.ActiveObject = null; } return; } var addedLayers = new List <Layer>(); var RhinoDocument = Rhino.RhinoDoc.ActiveDoc; var layerTable = RhinoDocument.Layers; if (hasLayerName && !hasAtts) { foreach (var layerName in layerNames) { int index; //var index = RhinoDocument.Layers.Find(layerName, true); Rhino.DocObjects.Layer layer = layerTable.FindName(layerName); //if (index < 0) //{ // index = RhinoDocument.Layers.Add(layerName, Color.Black); // addedLayers.Add(RhinoDocument.Layers[index]); //} if (layer == null) { index = layerTable.Add(layerName, Color.Black); addedLayers.Add(layerTable[index]); } else { index = layer.Index; } atts.Add(new ObjectAttributes { LayerIndex = index }); } } if (atts.Count == 0) { atts.Add(new ObjectAttributes()); } //bake everything var bakedObjects = new List <ObjRef>(); for (var i = 0; i < geometry.Count; i++) { var goo = geometry[i]; var bakeable = goo as IGH_BakeAwareData; if (bakeable != null) { try { bakeable.BakeGeometry(RhinoDocument, atts[Math.Min(i, atts.Count - 1)], out Guid guid); bakedObjects.Add(new ObjRef(guid)); } catch { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some objects failed to bake."); } } else { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some objects were not bakeable."); } } //select and export everything RhinoDocument.Objects.UnselectAll(); RhinoDocument.Objects.Select(bakedObjects.Where(o => o.ObjectId != Guid.Empty)); var extension = Path.GetExtension(exportPath).ToUpper(); String script; switch (extension) { case ".OBJ": script = $"-_Export \"{exportPath}\" _Enter _Enter _Enter"; break; case ".AI": case ".3DS": case ".FBX": script = $"-_Export \"{exportPath}\" _Enter _Enter"; break; case ".3DM": script = $"-_Export \"{exportPath}\" _Enter"; break; case ".DWG": case ".SAT": default: script = $"-_Export \"{exportPath}\" Default _Enter"; break; } RhinoApp.RunScript(script, false); bakedObjects.ForEach(o => RhinoDocument.Objects.Delete(o, true)); foreach (var layer in addedLayers) { RhinoDocument.Layers.Delete(layer.Index, true); } }
// TODO: This method, or an abstracted version of it, should move to Speckle Core. public async void SendStaggeredUpdate(bool force = false) { if (Paused && !force) { Context.NotifySpeckleFrame("client-expired", StreamId, ""); return; } if (IsSendingUpdate) { Expired = true; return; } IsSendingUpdate = true; Context.NotifySpeckleFrame("client-is-loading", StreamId, ""); var objs = RhinoDoc.ActiveDoc.Objects.FindByUserString("spk_" + this.StreamId, "*", false).OrderBy(obj => obj.Attributes.LayerIndex); Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converting " + objs.Count() + " objects..."); List <SpeckleCore.Layer> pLayers = new List <SpeckleCore.Layer>(); List <SpeckleObject> convertedObjects = new List <SpeckleObject>(); List <List <SpeckleObject> > objectUpdatePayloads = new List <List <SpeckleObject> >(); long totalBucketSize = 0; long currentBucketSize = 0; List <SpeckleObject> currentBucketObjects = new List <SpeckleObject>(); List <SpeckleObject> allObjects = new List <SpeckleObject>(); int lindex = -1, count = 0, orderIndex = 0; foreach (RhinoObject obj in objs) { // layer list creation Rhino.DocObjects.Layer layer = RhinoDoc.ActiveDoc.Layers[obj.Attributes.LayerIndex]; if (lindex != obj.Attributes.LayerIndex) { var spkLayer = new SpeckleCore.Layer() { Name = layer.FullPath, Guid = layer.Id.ToString(), ObjectCount = 1, StartIndex = count, OrderIndex = orderIndex++, Properties = new LayerProperties() { Color = new SpeckleCore.SpeckleBaseColor() { A = 1, Hex = System.Drawing.ColorTranslator.ToHtml(layer.Color) }, } }; pLayers.Add(spkLayer); lindex = obj.Attributes.LayerIndex; } else { var spkl = pLayers.FirstOrDefault(pl => pl.Name == layer.FullPath); spkl.ObjectCount++; } count++; // object conversion SpeckleObject convertedObject; convertedObject = Converter.Serialise(obj.Geometry); convertedObject.ApplicationId = obj.Id.ToString(); allObjects.Add(convertedObject); if (count % 10 == 0) { Context.NotifySpeckleFrame("client-progress-message", StreamId, "Converted " + count + " objects out of " + objs.Count() + "."); } // check cache and see what the response from the server is when sending placeholders // in the ObjectCreateBulkAsyncRoute if (Context.SpeckleObjectCache.ContainsKey(convertedObject.Hash)) { convertedObject = new SpecklePlaceholder() { Hash = convertedObject.Hash, _id = Context.SpeckleObjectCache[convertedObject.Hash]._id, ApplicationId = Context.SpeckleObjectCache[convertedObject.Hash].ApplicationId }; } // size checking & bulk object creation payloads creation long size = Converter.getBytes(convertedObject).Length; currentBucketSize += size; totalBucketSize += size; currentBucketObjects.Add(convertedObject); if (currentBucketSize > 2e6) { // means we're around fooking bazillion mb of an upload. FAIL FAIL FAIL Context.NotifySpeckleFrame("client-error", StreamId, JsonConvert.SerializeObject("This stream contains a super big object. These are not supported yet :(")); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); IsSendingUpdate = false; return; } if (currentBucketSize > 5e5) // restrict max to ~500kb; should it be user config? anyway these functions should go into core. at one point. { Debug.WriteLine("Reached payload limit. Making a new one, current #: " + objectUpdatePayloads.Count); objectUpdatePayloads.Add(currentBucketObjects); currentBucketObjects = new List <SpeckleObject>(); currentBucketSize = 0; } // catch overflows early if (totalBucketSize >= 50e6) { Context.NotifySpeckleFrame("client-error", StreamId, JsonConvert.SerializeObject("This is a humongous update, in the range of ~50mb. For now, create more streams instead of just one massive one! Updates will be faster and snappier, and you can combine them back together at the other end easier. " + totalBucketSize / 1000 + "(kb)")); IsSendingUpdate = false; Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); return; } } // last bucket if (currentBucketObjects.Count > 0) { objectUpdatePayloads.Add(currentBucketObjects); } Debug.WriteLine("Finished, payload object update count is: " + objectUpdatePayloads.Count + " total bucket size is (kb) " + totalBucketSize / 1000); if (objectUpdatePayloads.Count > 100 || totalBucketSize >= 50e6) { // means we're around fooking bazillion mb of an upload. FAIL FAIL FAIL Context.NotifySpeckleFrame("client-error", StreamId, JsonConvert.SerializeObject("This is a humongous update, in the range of ~50mb. For now, create more streams instead of just one massive one! Updates will be faster and snappier, and you can combine them back together at the other end easier. " + totalBucketSize / 1000 + "(kb)")); IsSendingUpdate = false; Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); return; } // create bulk object creation tasks int k = 0; List <ResponseObject> responses = new List <ResponseObject>(); foreach (var payload in objectUpdatePayloads) { Context.NotifySpeckleFrame("client-progress-message", StreamId, String.Format("Sending payload {0} out of {1}", k++, objectUpdatePayloads.Count)); try { responses.Add(await Client.ObjectCreateAsync(payload)); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); IsSendingUpdate = false; return; } } Context.NotifySpeckleFrame("client-progress-message", StreamId, "Updating stream..."); // finalise layer creation foreach (var layer in pLayers) { layer.Topology = "0-" + layer.ObjectCount + " "; } // create placeholders for stream update payload List <SpeckleObject> placeholders = new List <SpeckleObject>(); int m = 0; foreach (var myResponse in responses) { foreach (var obj in myResponse.Resources) { placeholders.Add(new SpecklePlaceholder() { _id = obj._id, ApplicationId = allObjects[m++].ApplicationId }); } } // create stream update payload SpeckleStream streamUpdatePayload = new SpeckleStream(); streamUpdatePayload.Layers = pLayers; streamUpdatePayload.Objects = placeholders; streamUpdatePayload.Name = Client.Stream.Name; // set some base properties (will be overwritten) var baseProps = new Dictionary <string, object>(); baseProps["units"] = RhinoDoc.ActiveDoc.ModelUnitSystem.ToString(); baseProps["tolerance"] = RhinoDoc.ActiveDoc.ModelAbsoluteTolerance; baseProps["angleTolerance"] = RhinoDoc.ActiveDoc.ModelAngleToleranceRadians; streamUpdatePayload.BaseProperties = baseProps; // push it to the server yo! ResponseBase response = null; try { response = await Client.StreamUpdateAsync(Client.Stream.StreamId, streamUpdatePayload); } catch (Exception err) { Context.NotifySpeckleFrame("client-error", Client.Stream.StreamId, JsonConvert.SerializeObject(err.Message)); IsSendingUpdate = false; return; } // put the objects in the cache int l = 0; foreach (var obj in streamUpdatePayload.Objects) { obj._id = placeholders[l]._id; Context.SpeckleObjectCache[allObjects[l].Hash] = placeholders[l]; l++; } // emit events, etc. Client.Stream.Layers = streamUpdatePayload.Layers.ToList(); Client.Stream.Objects = placeholders; Context.NotifySpeckleFrame("client-metadata-update", StreamId, Client.Stream.ToJson()); Context.NotifySpeckleFrame("client-done-loading", StreamId, ""); Client.BroadcastMessage(new { eventType = "update-global" }); IsSendingUpdate = false; if (Expired) { DataSender.Start(); } Expired = false; }