protected override Result RunCommand(Rhino.RhinoDoc doc, RunMode mode) { var apartmentHousesPercetage = new double(); var population = new double(); ObjRef[] srcCurves; RhinoGet.GetMultipleObjects("ClosedPolygones", false, ObjectType.Curve, out srcCurves); RhinoGet.GetNumber("Insert population", false, ref population, 0, 1000000); RhinoGet.GetNumber("Percent of population living in apartment houses", false, ref apartmentHousesPercetage, 0, 100000); var dicts = new Dictionary <Guid, DataDto>(); for (var i = 0; i < srcCurves.Count(); i++) { var o = GetDto(srcCurves[i]); dicts.Add(srcCurves[i].ObjectId, o); } var optimalLivingArea = GetOptimalLivingArea((int)Math.Round(population), (int)Math.Round(apartmentHousesPercetage)); var excistingLivingArea = GetExcistingLivingArea(dicts); if (optimalLivingArea > 0 && excistingLivingArea > 0) { var overStockPercent = (excistingLivingArea - optimalLivingArea) * 100 / excistingLivingArea; RhinoApp.WriteLine($"Overstock {overStockPercent} percent"); } else { RhinoApp.WriteLine($"No info to calculate overstock percent"); } return(Result.Success); }
/// <summary> /// Called by Rhino when the user wants to run the command. /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var rc = RockfishClientPlugIn.VerifyServerHostName(); if (rc != Result.Success) { return(rc); } var message = "Hello Rhino!"; rc = RhinoGet.GetString("String to echo", false, ref message); if (rc != Result.Success) { return(rc); } try { RockfishClientPlugIn.ServerHostName(); using (var channel = new RockfishClientChannel()) { channel.Create(); message = channel.Echo(message); } } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); return(Result.Failure); } RhinoApp.WriteLine(message); return(Result.Success); }
/// <summary> /// Returns the Land area [m2]. -1 if error /// </summary> /// <returns></returns> public static double LandArea() { string layername1 = "Site boundary"; // Get all of the objects on the layer. If layername is bogus, you will // just get an empty list back Rhino.DocObjects.RhinoObject[] rhobjs1 = RhinoDoc.ActiveDoc.Objects.FindByLayer(layername1).Where(x => x.ObjectType == Rhino.DocObjects.ObjectType.Curve).ToArray(); if (rhobjs1 == null || rhobjs1.Length < 1) { RhinoApp.WriteLine("Error: No boundary in project found"); return(-1); } var curves1 = new Curve[rhobjs1.Length]; for (int i = 0; i < rhobjs1.Length; i++) { GeometryBase geom = rhobjs1[i].Geometry; Curve x = geom as Curve; if (x != null && x.IsValid) { curves1[i] = x; } } double area = new double(); foreach (var o in curves1) { var areaMassP = AreaMassProperties.Compute(o); if (areaMassP != null) { area = area + areaMassP.Area; } } return(area); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { RhinoApp.RunScript(@"-_Open C:\model.3dm"); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { { // Creating the folder into with the load profiles files will be saved string workspacepath = FileSettings.WorkingFolder.ToString(); string extractionfolder = FileSettings.WorkingFolder.ToString() + "\\Trnsys"; string BundlePath = FileSettings.WorkingFolder.ToString(); bool exists1 = System.IO.Directory.Exists(workspacepath); if (!exists1) { System.IO.Directory.CreateDirectory(workspacepath); } bool exists2 = System.IO.Directory.Exists(extractionfolder); if (!exists2) { System.IO.Directory.CreateDirectory(extractionfolder); } // For each objects in the global context, create one csv file containing two columns // The first column is the simulation timestep and the second column is the the values // of the selected output foreach (var o in UmiContext.Current.GetObjects()) { // Create and Save File string csvFileName = o.Id.ToString(); string filePath = extractionfolder + "\\" + csvFileName + ".csv"; try { File.Create(filePath).Close(); } catch (IOException) { string mess = "Creation of file " + csvFileName + ".csv" + "did not work"; RhinoApp.WriteLine(mess); } // Creating new string array for printing lines StringBuilder newsb = new StringBuilder(); newsb.AppendLine($"{o.Name ?? o.Id}:"); File.AppendAllText(filePath, newsb.ToString()); var series = o.Data.Select(kvp => kvp.Value); List <string> lines = new List <string>(); var m = series.ToArray()[6]; StringBuilder sbline = new StringBuilder(); string line1 = "Time" + delimiter + $"\t{m.Name}"; lines.Add(line1); string line2 = $"\t" + $"\t{m.Units}"; for (int i = 0; i < m.Data.Count; i++) { string line = i + delimiter + m.Data[i].ToString(); lines.Add(line); } File.AppendAllLines(filePath, lines); } } 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.ObjectType.Mesh; int integer1 = 300; int integer2 = 300; Rhino.Input.Custom.OptionInteger optionInteger1 = new Rhino.Input.Custom.OptionInteger(integer1, 200, 900); Rhino.Input.Custom.OptionInteger optionInteger2 = new Rhino.Input.Custom.OptionInteger(integer2, 200, 900); Rhino.Input.Custom.GetObject go = new Rhino.Input.Custom.GetObject(); go.SetCommandPrompt("Select surfaces, polysurfaces, or meshes"); go.GeometryFilter = geometryFilter; go.AddOptionInteger("Option1", ref optionInteger1); go.AddOptionInteger("Option2", ref optionInteger2); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; bool bHavePreselectedObjects = false; for (; ;) { var res = go.GetMultiple(1, 0); if (res == Rhino.Input.GetResult.Option) { go.EnablePreSelect(false, true); continue; } else if (res != Rhino.Input.GetResult.Object) { return(Result.Cancel); } if (go.ObjectsWerePreselected) { bHavePreselectedObjects = true; go.EnablePreSelect(false, true); continue; } break; } if (bHavePreselectedObjects) { // Normally, pre-selected objects will remain selected, when a // command finishes, and post-selected objects will be unselected. // This this way of picking, it is possible to have a combination // of pre-selected and post-selected. So, to make sure everything // "looks the same", lets unselect everything before finishing // the command. for (int i = 0; i < go.ObjectCount; i++) { Rhino.DocObjects.RhinoObject rhinoObject = go.Object(i).Object(); if (null != rhinoObject) { rhinoObject.Select(false); } } doc.Views.Redraw(); } int objectCount = go.ObjectCount; integer1 = optionInteger1.CurrentValue; integer2 = optionInteger2.CurrentValue; RhinoApp.WriteLine("Select object count = {0}", objectCount); RhinoApp.WriteLine("Value of integer1 = {0}", integer1); RhinoApp.WriteLine("Value of integer2 = {0}", integer2); return(Result.Success); }
public override bool OnApply() { RhinoApp.WriteLine("SampleCsOptionsPage.OnApply"); return(true); }
/// <summary> /// Draws the perforation. /// </summary> /// <returns></returns> public override double drawPerforation(Curve boundaryCurve) { List <PointMap> pointMapList = new List <PointMap>(); PointMap pointMapTool1 = new PointMap(); PointMap pointMapTool2 = new PointMap(); PointMap pointMapTool3 = new PointMap(); pointMapList.Add(pointMapTool1); // Find the boundary BoundingBox boundingBox = boundaryCurve.GetBoundingBox(Plane.WorldXY); Point3d min = boundingBox.Min; Point3d max = boundingBox.Max; double spanX = max.X - min.X; double spanY = max.Y - min.Y; double gap = XSpacing - punchingToolList[0].X; int punchQtyX = ((int)((spanX - punchingToolList[0].X - gap) / XSpacing)) + 1; double marginX = (spanX - (((punchQtyX - 1) * XSpacing) - gap)) / 2; // Debug purpose // marginX = 0; double YSpacing = XSpacing; int punchQtyY = ((int)((spanY - punchingToolList[0].Y) / YSpacing)) + 1; double marginY = (spanY - ((punchQtyY - 1) * YSpacing)) / 2; Point3d point; RhinoDoc doc = RhinoDoc.ActiveDoc; double firstX = min.X + marginX + gap; double firstY = min.Y + marginY; // Set the current layer int currentLayer = doc.Layers.CurrentLayerIndex; doc.Layers.SetCurrentLayerIndex(currentLayer, false); // We don't use cluster tool so just perf it onto Tool Hit layer //if (!MetrixUtilities.IsLayerFound("TemporaryPerfLayer")){ // RhinoUtilities.SetActiveLayer(Properties.Settings.Default.ToolHitLayerName, System.Drawing.Color.Black); //}else{ // RhinoUtilities.SetActiveLayer("TemporaryToolHit", System.Drawing.Color.Black); //} double runningX = firstX - punchingToolList[0].X / 2; double twoToolTest; double threeToolTest; Random random = new Random(); int roundToolCounter = 0; int slotToolCounter = 0; int tool0Counter = 0; int tool1Counter = 0; int tool2Counter = 0; bool isToolHit = false; int toolMissingCounter = 0; // Generate the pattern for (int y = 0; y < punchQtyY; y++) { // For even rows if (random.NextDouble() < randomness || toolMissingCounter > 0) { isToolHit = true; toolMissingCounter = 0; } else { isToolHit = false; toolMissingCounter++; } if (y % 2 == 0) { // firstX = min.X + marginX + gap; runningX = min.X + gap; twoToolTest = random.Next(42); // Small slot if (twoToolTest < 14) { point = new Point3d(runningX + punchingToolList[1].X / 2, firstY + y * YSpacing, 0); pointMapTool2.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[1].X + gap; punchingToolList[1].drawTool(point); if (isToolHit) { slotToolCounter = 1; tool1Counter++; } } else // Big slot { point = new Point3d(runningX + punchingToolList[2].X / 2, firstY + y * YSpacing, 0); pointMapTool3.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[2].X + gap; slotToolCounter = 1; if (isToolHit) { tool2Counter++; punchingToolList[2].drawTool(point); } } } else { //firstX = min.X + marginX; //runningX = firstX - punchingToolList[0].X / 2; runningX = min.X; point = new Point3d(runningX + punchingToolList[0].X / 2, firstY + y * YSpacing, 0); pointMapTool1.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[0].X + gap; roundToolCounter = 1; if (isToolHit) { tool0Counter++; punchingToolList[0].drawTool(point); } } // for (int x = 0; x < punchQtyX; x++) { // Skip if the point already taken up by the tool if (runningX > firstX + x * XSpacing) { continue; } if (random.NextDouble() < randomness || toolMissingCounter > 0) { isToolHit = true; toolMissingCounter = 0; } else { isToolHit = false; toolMissingCounter++; } threeToolTest = random.Next(100); if (threeToolTest < 16 && slotToolCounter < 2) { point = new Point3d(runningX + punchingToolList[1].X / 2, firstY + y * YSpacing, 0); pointMapTool2.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[1].X + gap; roundToolCounter = 0; slotToolCounter++; if (isToolHit) { tool1Counter++; punchingToolList[1].drawTool(point); } } else if (threeToolTest < 47 && slotToolCounter < 2) { point = new Point3d(runningX + punchingToolList[2].X / 2, firstY + y * YSpacing, 0); pointMapTool3.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[2].X + gap; roundToolCounter = 0; slotToolCounter++; if (isToolHit) { tool2Counter++; punchingToolList[2].drawTool(point); } } else if (threeToolTest >= 47 && roundToolCounter < 4) { point = new Point3d(runningX + punchingToolList[0].X / 2, firstY + y * YSpacing, 0); pointMapTool1.AddPoint(new PunchingPoint(point)); runningX = runningX + punchingToolList[0].X + gap; roundToolCounter++; slotToolCounter = 0; if (isToolHit) { tool0Counter++; punchingToolList[0].drawTool(point); } } else { x--; } } } // Display the open area calculation AreaMassProperties area = AreaMassProperties.Compute(boundaryCurve); RhinoApp.WriteLine("Total area: {0} mm^2", area.Area.ToString("#.##")); double tool0Area = punchingToolList[0].getArea() * tool0Counter; double tool1Area = punchingToolList[1].getArea() * tool1Counter; double tool2Area = punchingToolList[2].getArea() * tool2Counter; double totalToolArea = tool0Area + tool1Area + tool2Area; RhinoApp.WriteLine("Tool 1 area: {0} mm^2", tool0Area.ToString("#.##")); RhinoApp.WriteLine("Tool 2 area: {0} mm^2", tool1Area.ToString("#.##")); RhinoApp.WriteLine("Tool 3 area: {0} mm^2", tool2Area.ToString("#.##")); double openArea = (totalToolArea * 100) / area.Area; RhinoApp.WriteLine("Open area: {0} %", openArea.ToString("#.##")); //int testResult; //int slotNumber = 1; //PunchingTools.Obround threeHoleSlot = new PunchingTools.Obround(); //threeHoleSlot.X = 2*this.XSpacing + punchingToolList[0].X; //threeHoleSlot.Y = punchingToolList[0].X; //PunchingTools.Obround fiveHoleSlot = new PunchingTools.Obround(); //fiveHoleSlot.X = 4 * this.XSpacing + punchingToolList[0].X; //fiveHoleSlot.Y = punchingToolList[0].X; //int chanceForHoles = 60; //int chanceForMidSlot = 86; //int chanceForLargeSlot = 100; //int holeCounter = 0; //int midSlotCounter = 0; //int largeSlotCounter = 0; //double toolArea = 0; // // Go through each point in the point Map list to determine whether it is a hole or a slot. //for (int i = 0; i < pointMapTool1.YCount; i++) //{ // SortedDictionary<int, PunchingPoint> xDict = pointMapTool1.getXDictionary(i); // chanceForHoles = 60; // chanceForMidSlot = 86; // chanceForLargeSlot = 100; // for (int j = 0; j < xDict.Count; j = j + slotNumber) // { // if (xDict.Count - j > 4) // { // // Generate whether the current hole // testResult = random.Next(1, chanceForLargeSlot); // } // else if (xDict.Count - j > 2) // { // chanceForHoles = 30; // chanceForMidSlot = 66; // chanceForLargeSlot = 100; // // Generate whether the current slot // testResult = random.Next(1, chanceForMidSlot); // } // else // { // chanceForHoles = 30; // chanceForMidSlot = 66; // chanceForLargeSlot = 100; // // Generate whether the current large slot // testResult = random.Next(1, chanceForHoles); // } // if (testResult >= 1 && testResult <= chanceForHoles) // { // slotNumber = 1; // holeCounter++; // midSlotCounter = 0; // largeSlotCounter = 0; // if (holeCounter == 1) // { // chanceForHoles = 60; // chanceForMidSlot = 86; // chanceForLargeSlot = 100; // } // else if(holeCounter == 2) // { // chanceForHoles = 30; // chanceForMidSlot = 66; // chanceForLargeSlot = 100; // } // else if(holeCounter > 2) // { // chanceForHoles = 10; // chanceForMidSlot = 53; // chanceForLargeSlot = 100; // } // // Draw circle // punchingToolList[0].drawTool(xDict.ElementAt(j).Value.Point); // toolArea += punchingToolList[0].getArea(); // } // else if (testResult > chanceForHoles && testResult <= chanceForMidSlot) // { // slotNumber = 3; // holeCounter = 0; // midSlotCounter++; // largeSlotCounter = 0; // if (midSlotCounter == 1) // { // chanceForHoles = 80; // chanceForMidSlot = 90; // chanceForLargeSlot = 100; // } // else if(midSlotCounter > 1) // { // chanceForHoles = 85; // chanceForMidSlot = 93; // chanceForLargeSlot = 100; // } // // Draw slot that span over 3 holes // threeHoleSlot.drawTool(xDict.ElementAt(j + 1).Value.Point); // toolArea += threeHoleSlot.getArea(); // } // else if (testResult > chanceForMidSlot && testResult <= chanceForLargeSlot) // { // slotNumber = 5; // holeCounter = 0; // midSlotCounter = 0; // largeSlotCounter++; // if(largeSlotCounter >= 1) // { // chanceForHoles = 80; // chanceForMidSlot = 100; // chanceForLargeSlot = 100; // } // // Draw slot that span over 5 holes // fiveHoleSlot.drawTool(xDict.ElementAt(j + 2).Value.Point); // toolArea += fiveHoleSlot.getArea(); // } // } //} // Display the open area calculation //AreaMassProperties area = AreaMassProperties.Compute(boundaryCurve); //RhinoApp.WriteLine("Total area: {0} mm^2", area.Area.ToString("#.##")); // RhinoApp.WriteLine("Tool area: {0} mm^2", toolArea.ToString("#.##")); // openArea = toolArea * 100 / area.Area; // RhinoApp.WriteLine("Open area: {0}%", openArea.ToString("#.")); //for (int y = 0; y < punchQtyY; y++) //{ // for (int x = 0; x < punchQtyX; x++) // { // point = new Point3d(firstX + x * XSpacing, firstY + y * YSpacing, 0); // if (punchingToolList[0].isInside(boundaryCurve, point) == true) // { // pointMap.AddPoint(new PunchingPoint(point)); // punchingToolList[0].drawTool(point); // } // if(random.NextDouble() < randomness) // { // if (punchingToolList[1].isInside(boundaryCurve, point) == true) // { // doc.Layers.SetCurrentLayerIndex(brailleLayerIndex, true); // punchingToolList[1].drawTool(point); // doc.Layers.SetCurrentLayerIndex(perforationlayerIndex, true); // } // } // } //} doc.Views.Redraw(); doc.Layers.SetCurrentLayerIndex(currentLayer, true); return(openArea); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Check the selected dot GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.GeometryFilter = Rhino.DocObjects.ObjectType.Point | Rhino.DocObjects.ObjectType.Annotation; go.SetCommandPrompt("Select Label and a point:"); GetResult result = go.GetMultiple(2, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); Point pt = null; TextEntity textEntity = null; int pointCounter = 0; int textCounter = 0; // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); if (rhinoObject.ObjectType == ObjectType.Annotation) { textEntity = rhinoObject.Geometry as TextEntity; if (textEntity != null && textCounter == 0) { textCounter++; } } else if (rhinoObject.ObjectType == ObjectType.Point) { pt = rhinoObject.Geometry as Point; if (pt != null && pointCounter == 0) { pointCounter++; } } } //if (go.Object(0).Point() != null && go.Object(1).TextEntity() != null) //{ // pt = go.Object(0).Point(); // textEntity = go.Object(1).TextEntity(); //} //else if (go.Object(1).Point() != null && go.Object(0).TextEntity() != null) //{ // pt = go.Object(1).Point(); // textEntity = go.Object(0).TextEntity(); //} //else //{ // RhinoApp.WriteLine("Two of the same objects are selected."); // return Result.Failure; //} if (textCounter > 1) { RhinoApp.WriteLine("More than one text has been selected."); } if (pointCounter > 1) { RhinoApp.WriteLine("More than one point has been selected."); } if (pt != null && textEntity != null) { drawDotMatrix(pt.Location, textEntity.Text, Properties.Settings.Default.DotMatrixHeight); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: remember to change to versions every time publish a new one!! RhinoApp.WriteLine($"CodeListener Version: {Version}"); return(Result.Success); }
public static void ShowRhinoWindow() { ShowWindow(RhinoApp.MainWindowHandle(), 1); BringWindowToTop(RhinoApp.MainWindowHandle()); }
/// <summary> /// Print some debug output onto Rhino's console /// </summary> private static void Log(string text) { RhinoApp.WriteLine(text); }
/// <summary> /// Export the render mesh associated with a certain object /// </summary> /// <param name="parent">The parent node in the output XML document</param> /// <param name="obj">The RhinoObject instance to be exported</param> /// <returns>true if any content was exported</returns> private bool ExportRenderMesh(XmlElement parent, RhinoObject obj, bool serialized) { ObjectType type = obj.ObjectType; if (type != ObjectType.Surface && type != ObjectType.Brep && type != ObjectType.Mesh && type != ObjectType.Extrusion) { Log("Not exporting object of type " + type); return(false); } ObjRef[] meshes = RhinoObject.GetRenderMeshes( new RhinoObject[] { obj }, true, true); if (meshes == null) { return(false); } foreach (ObjRef meshRef in meshes) { if (meshRef == null) { continue; } XmlElement shapeElement = m_xmlDocument.CreateElement("shape"); if (obj.Name != null && obj.Name.Length > 0) { shapeElement.AppendChild(m_xmlDocument.CreateComment(" Rhino object '" + obj.Name + "' ")); } RhinoDoc doc = obj.Document; Mesh mesh = meshRef.Mesh(); if (mesh.Faces == null) { continue; } int matIdx = -1; switch (obj.Attributes.MaterialSource) { case ObjectMaterialSource.MaterialFromLayer: matIdx = doc.Layers[obj.Attributes.LayerIndex].RenderMaterialIndex; break; case ObjectMaterialSource.MaterialFromObject: matIdx = obj.Attributes.MaterialIndex; break; } RhinoApp.WriteLine("Exporting Mesh:" + obj.Name); if (m_meshStore.WriteSerialized) { int index = m_meshStore.StoreSerialized(mesh, obj.Name); shapeElement.AppendChild(MakeProperty("filename", m_meshStore.Filename)); shapeElement.AppendChild(MakeProperty("shapeIndex", index)); shapeElement.SetAttribute("type", "serialized"); } else { String filename = m_meshStore.StoreOBJ(mesh, obj.Name); shapeElement.AppendChild(MakeProperty("filename", filename)); shapeElement.SetAttribute("type", "obj"); } parent.AppendChild(shapeElement); if (matIdx >= 0 && m_xmlIdMap.ContainsKey(matIdx)) { shapeElement.AppendChild(MakeReference(m_xmlIdMap[matIdx])); /* Create an area emitter if requested */ Material mat = doc.Materials[matIdx]; if (mat.EmissionColor.GetBrightness() > 0) { XmlElement emitterElement = m_xmlDocument.CreateElement("emitter"); emitterElement.SetAttribute("type", "area"); emitterElement.AppendChild(MakeProperty("radiance", mat.EmissionColor)); shapeElement.AppendChild(emitterElement); } } } return(meshes.Length > 0); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { doc.Objects.UnselectAll(); ObjRef obj_ref1; var rc1 = RhinoGet.GetOneObject("first curve", true, ObjectType.Curve, out obj_ref1); if (rc1 != Result.Success) { return(rc1); } Curve curve_a = null; if (obj_ref1 != null) { curve_a = obj_ref1.Curve(); } if (curve_a == null) { return(Result.Failure); } // Since you already selected a curve if you don't unselect it // the next GetOneObject won't stop as it considers that curve // input, i.e., curveA and curveB will point to the same curve. // Another option would be to use an instance of Rhino.Input.Custom.GetObject // instead of Rhino.Input.RhinoGet as GetObject has a DisablePreSelect() method. doc.Objects.UnselectAll(); ObjRef obj_ref2; var rc2 = RhinoGet.GetOneObject("second curve", true, ObjectType.Curve, out obj_ref2); if (rc2 != Result.Success) { return(rc2); } Curve curve_b = null; if (obj_ref2 != null) { curve_b = obj_ref2.Curve(); } if (curve_b == null) { return(Result.Failure); } var tolerance = doc.ModelAbsoluteTolerance; double max_distance; double max_distance_parameter_a; double max_distance_parameter_b; double min_distance; double min_distance_parameter_a; double min_distance_parameter_b; DeviationConduit conduit; if (!Curve.GetDistancesBetweenCurves(curve_a, curve_b, tolerance, out max_distance, out max_distance_parameter_a, out max_distance_parameter_b, out min_distance, out min_distance_parameter_a, out min_distance_parameter_b)) { RhinoApp.WriteLine("Unable to find overlap intervals."); return(Result.Success); } else { if (min_distance <= RhinoMath.ZeroTolerance) { min_distance = 0.0; } var max_dist_pt_a = curve_a.PointAt(max_distance_parameter_a); var max_dist_pt_b = curve_b.PointAt(max_distance_parameter_b); var min_dist_pt_a = curve_a.PointAt(min_distance_parameter_a); var min_dist_pt_b = curve_b.PointAt(min_distance_parameter_b); conduit = new DeviationConduit(curve_a, curve_b, min_dist_pt_a, min_dist_pt_b, max_dist_pt_a, max_dist_pt_b) { Enabled = true }; doc.Views.Redraw(); RhinoApp.WriteLine("Minimum deviation = {0} pointA({1}), pointB({2})", min_distance, min_dist_pt_a, min_dist_pt_b); RhinoApp.WriteLine("Maximum deviation = {0} pointA({1}), pointB({2})", max_distance, max_dist_pt_a, max_dist_pt_b); } var str = ""; RhinoGet.GetString("Press Enter when done", true, ref str); conduit.Enabled = false; return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { string fname = null; var rc = RhinoGet.GetString("Name of file to extract", false, ref fname); if (rc != Result.Success) { return(rc); } fname = fname.Trim(); if (string.IsNullOrEmpty(fname)) { return(Result.Nothing); } var text = doc.Strings.GetValue(fname); if (string.IsNullOrEmpty(text)) { RhinoApp.WriteLine("File not found."); return(Result.Nothing); } string path = null; if (mode == RunMode.Interactive) { var dialog = new SaveFileDialog { Title = EnglishName, Filter = @"Text Documents|*.txt", FileName = fname }; if (dialog.ShowDialog() != DialogResult.OK) { return(Result.Cancel); } path = dialog.FileName; } else { rc = RhinoGet.GetString("Save file name", false, ref path); if (rc != Result.Success) { return(rc); } } path = path.Trim(); if (string.IsNullOrEmpty(path)) { return(Result.Nothing); } try { File.WriteAllText(path, text); // Optional, purge embedded text doc.Strings.Delete(fname); } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); return(Result.Failure); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { //First, collect all the breps to split ObjRef[] obj_refs; var rc = RhinoGet.GetMultipleObjects("Select breps to split", false, ObjectType.Brep, out obj_refs); if (rc != Result.Success || obj_refs == null) { return(rc); } // Get the final plane Plane plane; rc = RhinoGet.GetPlane(out plane); if (rc != Result.Success) { return(rc); } //Iterate over all object references foreach (var obj_ref in obj_refs) { var brep = obj_ref.Brep(); var bbox = brep.GetBoundingBox(false); //Grow the boundingbox in all directions //If the boundingbox is flat (zero volume or even zero area) //then the CreateThroughBox method will fail. var min_point = bbox.Min; min_point.X -= 1.0; min_point.Y -= 1.0; min_point.Z -= 1.0; bbox.Min = min_point; var max_point = bbox.Max; max_point.X += 1.0; max_point.Y += 1.0; max_point.Z += 1.0; bbox.Max = max_point; var plane_surface = PlaneSurface.CreateThroughBox(plane, bbox); if (plane_surface == null) { //This is rare, it will most likely not happen unless either the plane or the boundingbox are invalid RhinoApp.WriteLine("Cutting plane could not be constructed."); } else { var breps = brep.Split(plane_surface.ToBrep(), doc.ModelAbsoluteTolerance); if (breps == null || breps.Length == 0) { RhinoApp.Write("Plane does not intersect brep (id:{0})", obj_ref.ObjectId); continue; } foreach (var brep_piece in breps) { doc.Objects.AddBrep(brep_piece); } doc.Objects.AddSurface(plane_surface); doc.Objects.Delete(obj_ref, false); } } doc.Views.Redraw(); return(Result.Success); }
/// <summary> /// Creates the layout. /// </summary> /// <param name="doc">The document.</param> /// <param name="panel">The panel.</param> /// <param name="panelParas">The panel paras.</param> /// <returns></returns> public Result createLayout(RhinoDoc doc, FoldedPerforationPanel panel, PanelParameters panelParas) { if (panelParas == null) { panelParas = new PanelParameters(); } if (panel == null) { panel = new FoldedPerforationPanel(); } // Get all selected Objects GetObject go = new GetObject(); go.GroupSelect = true; go.SubObjectSelect = false; go.EnableClearObjectsOnEntry(false); go.EnableUnselectObjectsOnExit(false); go.DeselectAllBeforePostSelect = false; go.EnableSelPrevious(true); go.EnablePreSelect(true, false); go.EnablePressEnterWhenDonePrompt(false); go.SetCommandPrompt("Select items for the new layout:"); // Disable the scaling RhinoApp.RunScript("_-DocumentProperties AnnotationStyles ModelSpaceScaling=Disabled LayoutSpaceScaling=Disabled _Enter _Enter", true); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Total Objects Selected: {0}", go.ObjectCount); string labelName = panel.PartName; string area = string.Format("{0:0.00}", panel.Area); Point2d minPoint = new Point2d(0, 0); Point2d maxPoint = new Point2d(0, 0); // Loop through all the objects to find Text for (int i = 0; i < go.ObjectCount; i++) { BoundingBox bBox = go.Object(i).Object().Geometry.GetBoundingBox(true); if (bBox.Min.X < minPoint.X) { minPoint.X = bBox.Min.X; } if (bBox.Min.Y < minPoint.Y) { minPoint.Y = bBox.Min.Y; } if (bBox.Max.X > maxPoint.X) { maxPoint.X = bBox.Max.X; } if (bBox.Max.Y > maxPoint.Y) { maxPoint.Y = bBox.Max.Y; } } // If the selected items has no label, return failure if (labelName == null) { return(Rhino.Commands.Result.Failure); } // Hide all the non selected objects foreach (var obj in doc.Objects) { if (obj.IsSelected(true) == 0) { doc.Objects.Hide(obj, false); } } // Add layout doc.PageUnitSystem = Rhino.UnitSystem.Millimeters; RhinoView currentView = doc.Views.ActiveView; var pageview = doc.Views.AddPageView(string.Format("{0}", labelName), 210, 297); Point2d bottomLeft = new Point2d(10, 70); Point2d topRight = new Point2d(200, 287); if (pageview != null) { pageview.SetPageAsActive(); var detail = pageview.AddDetailView("Panel", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); // Show all objects RhinoApp.RunScript("_-Show _Enter", true); if (detail != null) { pageview.SetActiveDetail(detail.Id); doc.Views.ActiveView = pageview; //doc.Views.Redraw(); // Select all the objects for (int i = 0; i < go.ObjectCount; i++) { RhinoObject rhinoObject = go.Object(i).Object(); rhinoObject.Select(true); } // Hide all the non selected objects var filter = new ObjectEnumeratorSettings { NormalObjects = true, LockedObjects = false, HiddenObjects = false, ActiveObjects = true, ReferenceObjects = true }; var rh_objects = doc.Objects.FindByFilter(filter); pageview.SetPageAsActive(); //doc.Views.Redraw(); foreach (var rh_obj in rh_objects) { var select = 0 == rh_obj.IsSelected(false) && rh_obj.IsSelectable(); rh_obj.Select(select); } RhinoApp.RunScript("_-HideInDetail Enter", true); detail.IsActive = false; } bottomLeft = new Point2d(10, 40); topRight = new Point2d(135, 70); detail = pageview.AddDetailView("Sample", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); // doc.Views.Redraw(); pageview.SetActiveDetail(detail.Id); detail.Viewport.SetCameraLocation(new Point3d(50, 160, 0), true); detail.CommitViewportChanges(); // doc.Views.Redraw(); detail.DetailGeometry.IsProjectionLocked = true; detail.DetailGeometry.SetScale(4.5, doc.ModelUnitSystem, 1, doc.PageUnitSystem); detail.CommitChanges(); // doc.Views.Redraw(); detail.IsActive = true; pageview.SetActiveDetail(detail.Id); RhinoApp.WriteLine("Name = {0}: Width = {1}, Height = {2}", detail.Viewport.Name, detail.Viewport.Size.Width, detail.Viewport.Size.Height); detail.CommitViewportChanges(); // doc.Views.Redraw(); detail.IsActive = false; bottomLeft = new Point2d(5, 5); topRight = new Point2d(205, 35); detail = pageview.AddDetailView("Block", bottomLeft, topRight, Rhino.Display.DefinedViewportProjection.Top); // doc.Views.Redraw(); detail.IsActive = true; pageview.SetActiveDetail(detail.Id); detail.Viewport.SetCameraLocation(new Point3d(105, 520, 0), true); detail.CommitViewportChanges(); // doc.Views.Redraw(); detail.DetailGeometry.IsProjectionLocked = true; detail.DetailGeometry.SetScale(1, doc.ModelUnitSystem, 1, doc.PageUnitSystem); detail.CommitChanges(); detail.IsActive = false; // doc.Views.Redraw(); drawBlock(doc, labelName, area, panel.PanelNumber, panelParas); // doc.Views.Redraw(); } // Show all objects RhinoApp.RunScript("_-Show _Enter", true); doc.Views.DefaultViewLayout(); doc.Views.ActiveView = currentView; return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { RhinoApp.WriteLine("The {0} command is under construction.", EnglishName); return(Result.Success); }
/** * Method contains the logic to draw fixing holes evening on the panel based on the user's criteria * */ public static List <Guid> drawFixingFoles(PerforationPanel panel, FoldedPerforationPanel foldPanel, Boolean Folded, double panelBottom, double panelLeft, int folds, double panelY0, double panelY1, DimensionStyle dimStyle, List <Guid> guidList, double panelX0, double panelX1, double panelRight, double panelTop) { RhinoDoc doc = RhinoDoc.ActiveDoc; Rhino.Geometry.Point3d pt; Point3d offset; Plane plane = Rhino.Geometry.Plane.WorldXY; Point3d origin; double pointOne = 0; //Execute the method only if atleast one of the side contain fixing holes if (panel.TopFixingHoles.Equals("1") || panel.BottomFixingHoles.Equals("1") || panel.LeftFixingHoles.Equals("1") || panel.RightFixingHoles.Equals("1")) { int tempLayerIndex = 0; tempLayerIndex = createSubLayers.createSubLayer("FIXING HOLES DIMENSIONS", System.Drawing.Color.DarkGreen, doc.Layers[doc.Layers.Find("LAYERS FOR APPROVAL DRAWINGS", true)]); Rhino.DocObjects.RhinoObject[] go = null; int layerIndex = createSubLayers.createSubLayer("FIXING HOLES", System.Drawing.Color.Black, doc.Layers[doc.Layers.Find("LAYERS FOR NESTING", true)]); doc.Layers.SetCurrentLayerIndex(layerIndex, true); go = doc.Objects.FindByLayer("Fixing"); double holeSize = panel.HoleDiameter; double totalTopFixingHoles = panel.TopFixingHoleQuantity; double totalBottomFixingHoles = panel.BottomFixingHoleQuantity; double totalLeftFixingHoles = panel.LeftFixingHoleQuantity; double totalRightFixingHoles = panel.RightFixingHoleQuantity; int objecTCount = go.Length; foreach (RhinoObject ob in go) { ObjRef objRef = new ObjRef(ob); Curve curve = objRef.Curve(); // If curve is null, means objRef is not a curve if (curve == null) { continue; } // If curve is not Closed Curve if (curve.IsClosed == false) { RhinoApp.WriteLine(objRef.ToString() + " curve is open"); continue; } if (curve.IsPlanar() == false) { RhinoApp.WriteLine(objRef.ToString() + " curve is not planar"); continue; } // Find the boundary BoundingBox boundingBox = curve.GetBoundingBox(Plane.WorldXY); Point3d min = boundingBox.Min; Point3d max = boundingBox.Max; List <Point3d> pointsList = new List <Point3d>(); double runningX = 0; double runningY = 0; runningY = max.Y - panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) if (Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackTop + foldPanel.KFactor + panel.TopHoleSetbackLeft; } else { runningX = min.X + panel.TopHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } int points = 1; Point3d point; //Draw the top holes if (panel.TopFixingHoles.Equals("1")) { if (Folded) { if (folds == 4) { if (foldPanel != null) { point = new Point3d(panelX1 - panel.TopHoleSetbackRight - foldPanel.TopFirstFoldSetbackRight, runningY, 0); //adds the top right fixing hole } else { point = new Point3d(panelX1 - foldPanel.RightFirstFoldSetbackBottom - foldPanel.KFactor - panel.TopHoleSetbackRight, runningY, 0); //adds the top right fixing hole } pointsList.Add(point); point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); while (points <= (panel.TopFixingHoleQuantity - 2)) { runningX = runningX + panel.TopFixingHoleDistance; //multiply by 2 to increase width (for equaliity) point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); points++; } } } else { point = new Point3d(max.X - panel.TopHoleSetbackRight, runningY, 0); //adds the top right fixing hole pointsList.Add(point); point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); while (points <= (panel.TopFixingHoleQuantity - 2)) { runningX = runningX + panel.TopFixingHoleDistance; //multiply by 2 to increase width (for equaliity) point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); points++; } } } //Draw the top horizontal fixing holes dimension (between the fixing holes) doc.Layers.SetCurrentLayerIndex(tempLayerIndex, true); if (foldPanel.TopFixingHoles == "1") { runningY = max.Y - panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) if (Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackTop + foldPanel.KFactor + panel.TopHoleSetbackLeft; } else { runningX = min.X + panel.TopHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } points = 0; while (points <= (panel.TopFixingHoleQuantity) - 2) { origin = new Point3d(runningX + panel.TopFixingHoleDistance, runningY + 15, 0); //right offset = new Point3d(runningX, runningY + 15, 0); //left pt = new Point3d((offset.X - origin.X) / 2, (runningY + 15) + (dimStyle.TextHeight * 4), 0); plane = Plane.WorldXY; plane.Origin = origin; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension runningX = runningX + panel.TopFixingHoleDistance; //multiply by 2 to increase width (for equaliity) points++; } //Draw the setback dimension of top fixing hole (left) runningY = max.Y - panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) if (Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackTop + foldPanel.KFactor + panel.TopHoleSetbackLeft; } else { runningX = min.X + panel.TopHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } origin = new Point3d(runningX, runningY + 15, 0); offset = new Point3d(runningX - panel.TopHoleSetbackLeft, runningY + 15, 0); pt = new Point3d((offset.X - origin.X) / 2, (runningY + 15) + (dimStyle.TextHeight * 2), 0); plane = Plane.WorldXY; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension runningY = max.Y - panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) //Draw the setback dimension of top fixing hole (right) if (Folded) { runningX = panelX1 - foldPanel.LeftFirstFoldSetbackTop - foldPanel.KFactor - panel.TopHoleSetbackLeft; } else { runningX = max.X - panel.TopHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } origin = new Point3d(runningX, runningY + 15, 0); offset = new Point3d(runningX + panel.TopHoleSetbackLeft, runningY + 15, 0); pt = new Point3d((offset.X - origin.X) / 2, (runningY + 15) + (dimStyle.TextHeight * 2), 0); plane = Plane.WorldXY; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension //Draw the dimension between the top folded line and the center of the fixing hole origin = new Point3d(min.X - 30, runningY, 0); //upper horizontal line of dimension offset = new Point3d(min.X - 30, max.Y, 0); //bottom horizontal line of the dimension pt = new Point3d(min.X - 30, (offset.Y - origin.Y) / 2, 0); //addjust the text position 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; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension } //Draw the bottom holes doc.Layers.SetCurrentLayerIndex(layerIndex, true); if (panel.BottomFixingHoles.Equals("1")) { runningY = min.Y + panel.BottomHoleSetbackBottom; //calculate the starting point for the first from the right (with setback) if (Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackBottom + foldPanel.KFactor + panel.BottomHoleSetbackLeft; } else { runningX = min.X + panel.BottomHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } if (Folded) { point = new Point3d(runningX, runningY, 0); //adds the bottom Left fixing hole pointsList.Add(point); if (foldPanel != null) { point = new Point3d(panelX1 - panel.BottomHoleSetbackRight - foldPanel.BottomFirstFoldSetbackRight, runningY, 0); //adds the bottom right fixing hole } else { point = new Point3d(panelX1 - foldPanel.LeftFirstFoldSetbackBottom - foldPanel.KFactor - panel.BottomHoleSetbackRight, runningY, 0); //adds the bottom right fixing hole } pointsList.Add(point); points = 1; while (points <= panel.BottomFixingHoleQuantity - 2) { runningX = runningX + panel.BottomFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //adds the bottom fixing hole pointsList.Add(point); points++; } } else { point = new Point3d(runningX, runningY, 0); //adds the bottom Left fixing hole pointsList.Add(point); point = new Point3d(max.X - panel.BottomHoleSetbackRight, runningY, 0); //adds the bottom right fixing hole pointsList.Add(point); points = 1; while (points <= panel.BottomFixingHoleQuantity - 2) { runningX = runningX + panel.BottomFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //adds the bottom fixing hole pointsList.Add(point); points++; } } } //Draw the Bottom horizontal fixing holes dimension (between the fixing holes) doc.Layers.SetCurrentLayerIndex(tempLayerIndex, true); if (panel.BottomFixingHoles == "1") { runningY = min.Y + panel.BottomHoleSetbackBottom; //calculate the starting point for the first from the right (with setback) if (Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackBottom + foldPanel.KFactor + panel.BottomHoleSetbackLeft; } else { runningX = min.X + panel.BottomHoleSetbackLeft; //calculate the starting point for the first hole from the left(with set back) } points = 0; while (points <= (panel.BottomFixingHoleQuantity) - 2) { origin = new Point3d(runningX + panel.BottomFixingHoleDistance, runningY + panel.BottomHoleSetbackBottom, 0); //right offset = new Point3d(runningX, runningY + panel.BottomHoleSetbackBottom, 0); //left pt = new Point3d((offset.X - origin.X) / 2, (runningY + panel.BottomHoleSetbackBottom) - (dimStyle.TextHeight * 4), 0); plane = Plane.WorldXY; plane.Origin = origin; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension runningX = runningX + panel.BottomFixingHoleDistance; //multiply by 2 to increase width (for equaliity) points++; } } //Draw the Left holes doc.Layers.SetCurrentLayerIndex(layerIndex, true); if (panel.LeftFixingHoles.Equals("1")) { runningX = min.X + panel.LeftHoleSetbackLeft; if (Folded) //if the panel is folded x value should be within the fold { runningY = panelY1 - foldPanel.LeftFirstFoldSetbackTop - foldPanel.KFactor - panel.LeftHoleSetbackTop; } else //if the panel is flat panel the x value should be between the folded panel finished and the borders { runningY = max.Y - panel.LeftHoleSetbackTop; } if (!panel.TopFixingHoles.Equals("1") || folds == 4) //check if there is top fixing holes { point = new Point3d(runningX, runningY, 0); //adds the Left top fixing hole pointsList.Add(point); } if (!panel.BottomFixingHoles.Equals("1") || folds == 4) //check if there is bottom fixing holes { if (foldPanel != null) { point = new Point3d(runningX, panelY0 + panel.LeftHoleSetbackBottom + foldPanel.LeftFirstFoldSetbackBottom, 0); //adds the left bottom fixing hole } else { point = new Point3d(runningX, panelY0 + panel.LeftHoleSetbackBottom, 0); //adds the left bottom fixing hole } pointsList.Add(point); } points = 1; if (Folded) { while (points <= panel.LeftFixingHoleQuantity - 2) { runningY = runningY - panel.LeftFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //draw the left fixing holes pointsList.Add(point); points++; } } else { while (points <= panel.LeftFixingHoleQuantity - 2) { runningY = runningY - panel.LeftFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //draw the left fixing holes pointsList.Add(point); points++; } } } //Draw the left vertical fixing holes dimension (between the left fixing holes) doc.Layers.SetCurrentLayerIndex(tempLayerIndex, true); if (panel.LeftFixingHoles == "1") { runningX = min.X + panel.LeftHoleSetbackLeft; if (Folded) //if the panel is folded x value should be within the fold { runningY = panelY1 - foldPanel.LeftFirstFoldSetbackTop - foldPanel.KFactor - panel.LeftHoleSetbackTop; } else //if the panel is flat panel the x value should be between the folded panel finished and the borders { runningY = max.Y - panel.LeftHoleSetbackTop; } points = 0; while (points < (panel.LeftFixingHoleQuantity) - 1) { if (Folded) { origin = new Point3d(min.X - foldPanel.LeftFirstFoldWidth, runningY - panel.LeftFixingHoleDistance, 0); //right offset = new Point3d(min.X - foldPanel.LeftFirstFoldWidth, runningY, 0); //left pt = new Point3d(min.X - foldPanel.LeftFirstFoldWidth, runningY + (dimStyle.TextHeight * 4), 0); } else { origin = new Point3d(min.X + 20, runningY - panel.LeftFixingHoleDistance, 0); //right offset = new Point3d(min.X + 20, runningY, 0); //left pt = new Point3d(min.X - 20, runningY + (dimStyle.TextHeight * 4), 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; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension runningY = runningY - panel.LeftFixingHoleDistance; //multiply by 2 to increase width (for equaliity) pointOne = runningY; points++; } } //Draw the Right holes doc.Layers.SetCurrentLayerIndex(layerIndex, true); if (panel.RightFixingHoles.Equals("1")) { runningX = max.X - panel.RightHoleSetbackRight; if (Folded) //if the panel is folded x value should be within the fold { runningY = panelY1 - foldPanel.RightFirstFoldSetbackTop - foldPanel.KFactor - panel.RightHoleSetbackTop; } else //if the panel is flat panel the x value should be between the folded panel finished and the borders { runningY = max.Y - panel.RightHoleSetbackTop; } if (!panel.TopFixingHoles.Equals("1") || folds == 4) { point = new Point3d(runningX, runningY, 0); //adds the Right top fixing hole pointsList.Add(point); } if (!panel.BottomFixingHoles.Equals("1") || folds == 4) { if (foldPanel != null) { point = new Point3d(runningX, panelY0 + panel.RightHoleSetbackBottom + foldPanel.RightFirstFoldSetbackBottom, 0); //adds the RIght bottom fixing hole } else { point = new Point3d(runningX, panelY0 + panel.RightHoleSetbackBottom, 0); //adds the RIght bottom fixing hole } pointsList.Add(point); } points = 1; while (points <= panel.RightFixingHoleQuantity - 2) { runningY = runningY - panel.RightFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //draw the right fixing holes pointsList.Add(point); points++; } } //Draw the right vertical fixing holes dimension (between the right fixing holes) doc.Layers.SetCurrentLayerIndex(tempLayerIndex, true); if (panel.RightFixingHoles == "1") { runningX = max.X - panel.RightHoleSetbackRight; if (Folded) //if the panel is folded x value should be within the fold { runningY = panelY1 - foldPanel.RightFirstFoldSetbackTop - foldPanel.KFactor - panel.RightHoleSetbackTop; } else //if the panel is flat panel the x value should be between the folded panel finished and the borders { runningY = max.Y - panel.RightHoleSetbackTop; } points = 0; while (points < (panel.LeftFixingHoleQuantity) - 1) { //multiply by 2 to increase width (for equaliity) origin = new Point3d(max.X + 50, runningY - panel.RightFixingHoleDistance, 0); //right offset = new Point3d(max.X + 50, runningY, 0); //left pt = new Point3d(max.X + 50, runningY + (dimStyle.TextHeight * 4), 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; guidList = drawDimension(plane, pt, offset, origin, guidList, doc); //draw the dimension runningY = runningY - panel.RightFixingHoleDistance; points++; } } //Drawing fixings holes on the dimensions doc.Layers.SetCurrentLayerIndex(layerIndex, true); //Draw the top hole if (panel.TopFixingHoles.Equals("1") && Folded) { runningX = panelX0 + foldPanel.LeftFirstFoldSetbackTop + foldPanel.KFactor + panel.TopHoleSetbackLeft; runningY = (panelBottom + foldPanel.TopFirstFoldWidth) - panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) points = 1; if (foldPanel != null) { if (foldPanel.TopFirstFoldDirection == 1) { runningY = (panelTop - foldPanel.TopFirstFoldWidth) + panel.TopHoleSetbackTop; //calculate the starting point for the first from the right (with setback) } } else { point = new Point3d(panelX1 - foldPanel.LeftFirstFoldSetbackTop - foldPanel.KFactor - panel.TopHoleSetbackRight, (panelBottom + foldPanel.TopFirstFoldWidth) - panel.TopHoleSetbackTop, 0); //adds the top right fixing hole in the dimensions blue (use panel bottom) pointsList.Add(point); } point = new Point3d(panelX1 - panel.TopHoleSetbackRight - foldPanel.TopFirstFoldSetbackRight, runningY, 0); //adds the top right fixing hole in the dimensions blue (use panel bottom) pointsList.Add(point); point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); while (points <= (panel.TopFixingHoleQuantity - 2)) { runningX = runningX + panel.TopFixingHoleDistance; //multiply by 2 to increase width (for equaliity) point = new Point3d(runningX, runningY, 0); //adds the top left fixing hole pointsList.Add(point); points++; } } //Draw the Left holes if (panel.LeftFixingHoles.Equals("1") && Folded && folds == 4) //draw the fixing holes on the left dimension only on folded panels because flat panels do not have the left dimension { runningY = panelY1 - foldPanel.LeftFirstFoldSetbackTop - foldPanel.KFactor - panel.LeftHoleSetbackTop; runningX = panelRight - foldPanel.LeftFirstFoldWidth + panel.LeftHoleSetbackLeft; if (foldPanel != null) { if (foldPanel.TopFirstFoldDirection == 1) { runningX = (panelLeft + foldPanel.LeftFirstFoldWidth) - panel.LeftHoleSetbackLeft; } } else { point = new Point3d(runningX, panelY0 + panel.LeftHoleSetbackBottom, 0); //adds the left bottom fixing hole pointsList.Add(point); } point = new Point3d(runningX, runningY, 0); //adds the Left top fixing hole pointsList.Add(point); point = new Point3d(runningX, panelY0 + panel.LeftHoleSetbackBottom + foldPanel.LeftFirstFoldSetbackBottom, 0); //adds the left bottom fixing hole pointsList.Add(point); points = 1; while (points <= panel.LeftFixingHoleQuantity - 2) { runningY = runningY - panel.LeftFixingHoleDistance; point = new Point3d(runningX, runningY, 0); //draw the left fixing holes pointsList.Add(point); points++; } } // Process the curve // Draw all the holes Round round = new Round(); round.X = holeSize; foreach (Point3d p in pointsList) { round.drawTool(p); } } } return(guidList); }
private void RunThread(CancellationToken token) { Intel.RealSense.PointCloud pc = new Intel.RealSense.PointCloud(); DecimationFilter dec_filter = new DecimationFilter(); SpatialFilter spat_filter = new SpatialFilter(); TemporalFilter temp_filter = new TemporalFilter(); dec_filter.Options[Option.FilterMagnitude].Value = DecimationMagnitude; spat_filter.Options[Option.FilterMagnitude].Value = SpatialMagnitude; spat_filter.Options[Option.FilterSmoothAlpha].Value = Math.Min(1.0f, (float)SpatialSmoothAlpha); spat_filter.Options[Option.FilterSmoothDelta].Value = (float)SpatialSmoothDelta; temp_filter.Options[Option.FilterSmoothAlpha].Value = Math.Min(1.0f, (float)TemporalSmoothAlpha); temp_filter.Options[Option.FilterSmoothDelta].Value = (float)TemporalSmoothDelta; List <ProcessingBlock> filters = new List <ProcessingBlock> { dec_filter, spat_filter, temp_filter }; Align align_to_depth = new Align(Stream.Depth); var cfg = new Config(); cfg.EnableStream(Stream.Depth, 640, 480); cfg.EnableStream(Stream.Color, 1280, 720, Format.Rgb8); var pipeline = new Pipeline(); PipelineProfile pp = null; try { pp = pipeline.Start(cfg); } catch (Exception e) { RhinoApp.WriteLine("RsToolkit: " + e.Message); return; } while (!token.IsCancellationRequested) { try { using (var frames = pipeline.WaitForFrames()) { var aligned = align_to_depth.Process <FrameSet>(frames).DisposeWith(frames); var color = aligned.ColorFrame.DisposeWith(frames); pc.MapTexture(color); var filtered = aligned[Stream.Depth].DisposeWith(frames); foreach (var filter in filters) { filtered = filter.Process(filtered).DisposeWith(frames); } Points points = pc.Process <Points>(filtered); var vertices = new Point3f[points.Count]; var tex_coords = new Point2f[points.Count]; points.CopyVertices <Point3f>(vertices); points.CopyTextureCoords <Point2f>(tex_coords); Debug.Assert(vertices.Length == tex_coords.Length); // ======== CULL INVALID POINTS ======== if (true) { var flags = new bool[vertices.Length]; int new_size = 0; for (int i = 0; i < vertices.Length; ++i) { if (vertices[i].Z > 0.1) { flags[i] = true; new_size++; } } var new_vertices = new Point3f[new_size]; var new_tex_coords = new Point2f[new_size]; for (int i = 0, j = 0; i < vertices.Length; ++i) { if (flags[i]) { new_vertices[j] = vertices[i]; new_tex_coords[j] = tex_coords[i]; ++j; } } vertices = new_vertices; tex_coords = new_tex_coords; } // ======== TRANSFORM ======== if (m_xform.IsValid) { Parallel.For(0, vertices.Length - 1, (i) => { vertices[i].Transform(m_xform); }); } // ======== CLIP TO BOX ======== if (m_clipping_box.IsValid && m_clipping_box.X.Length > 0 && m_clipping_box.Y.Length > 0 && m_clipping_box.Z.Length > 0) { Point3d box_centre = m_clipping_box.Plane.Origin; double minx = m_clipping_box.X.Min + box_centre.X, maxx = m_clipping_box.X.Max + box_centre.X; double miny = m_clipping_box.Y.Min + box_centre.Y, maxy = m_clipping_box.Y.Max + box_centre.Y; double minz = m_clipping_box.Z.Min + box_centre.Z, maxz = m_clipping_box.Z.Max + box_centre.Z; var flags = new bool[vertices.Length]; int new_size = 0; for (int i = 0; i < vertices.Length; ++i) { if ( vertices[i].X <maxx && vertices[i].X> minx && vertices[i].Y <maxy && vertices[i].Y> miny && vertices[i].Z <maxz && vertices[i].Z> minz ) { flags[i] = true; new_size++; } } var new_vertices = new Point3f[new_size]; var new_tex_coords = new Point2f[new_size]; for (int i = 0, j = 0; i < vertices.Length; ++i) { if (flags[i]) { new_vertices[j] = vertices[i]; new_tex_coords[j] = tex_coords[i]; ++j; } } vertices = new_vertices; tex_coords = new_tex_coords; } Debug.Assert(vertices.Length == tex_coords.Length); var point_colors = GetPointColors(color, tex_coords); RPointCloud new_pointcloud = new RPointCloud(); new_pointcloud.AddRange(vertices.Select(x => new Point3d(x)), point_colors); lock (m_pointcloud) m_pointcloud = new_pointcloud; } } catch (Exception e) { RhinoApp.WriteLine("RsToolkit: " + e.Message); m_is_on = false; break; } } RhinoApp.WriteLine("RsToolkit: Task cancelled."); if (pipeline != null) { pipeline.Stop(); } }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { int counter = 0; GetObject go = new GetObject(); go.SetCommandPrompt("Select curves to offset."); go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve; go.GroupSelect = true; go.SubObjectSelect = true; go.DeselectAllBeforePostSelect = true; go.OneByOnePostSelect = false; go.GetMultiple(1, 0); GetOption gop = new GetOption(); var dist = new Rhino.Input.Custom.OptionDouble(distVal); gop.SetCommandPrompt("Set values. Press enter when done."); gop.AddOptionDouble("Distance", ref dist); int optList = gop.AddOptionList("CornerStyle", corners, cornerIndex); gop.AcceptNothing(true); while (true) { if (gop.Get() == GetResult.Nothing) { break; } else if (gop.OptionIndex() == optList) { cornerIndex = gop.Option().CurrentListOptionIndex; } else { distVal = dist.CurrentValue; } } for (int i = 0; i < go.ObjectCount; i++) { Rhino.DocObjects.ObjRef objref = go.Object(i); var curve = objref.Curve(); if (curve == null) { return(Result.Nothing); } Plane plane; if (!curve.TryGetPlane(out plane)) { curve.DivideByCount(3, true, out Point3d[] curvePoints); plane = new Plane(curvePoints[0], curvePoints[1], curvePoints[2]); } try { var curves = curve.Offset(plane, distVal, doc.ModelAbsoluteTolerance, cornerStyle[cornerIndex]); foreach (var offsetcurve in curves) { doc.Objects.AddCurve(offsetcurve); } } catch { counter++; } } if (counter > 0) { RhinoApp.WriteLine(counter + " out of " + go.ObjectCount + " offset values were out of scope!"); } doc.Views.Redraw(); // --- return(Result.Success); }
public void SelectByParameter(RhinoDoc doc, ParametersSelectorForm form) { Rhino.DocObjects.Tables.ObjectTable rhobjs = doc.Objects; string paramName = form.GetParamName(); if (paramName != "") { // List to store all the objects that match. List <Rhino.DocObjects.RhinoObject> matched = new List <Rhino.DocObjects.RhinoObject>(); string paramValue = form.GetParamValue(); // TODO Filter also by type of obj? // rhobjs = filter( lambda x: va.IsColumn(x.Id) , Rhino.RhinoDoc.ActiveDoc.Objects) if (paramValue != "") // Search by name and value. { // If the input param value can be converted to num then compare as num and as text. if (Double.TryParse(paramValue, out double numValue)) { int comparison = form.GetComparisonType(); if (comparison == 0) // Equality comparison. { foreach (Rhino.DocObjects.RhinoObject o in rhobjs) { Guid paramId = GetObjectParameterId(paramName, o.Id, true); if (paramId != Guid.Empty && GetParameterValue(paramId, o.Id) != null) { ParameterType t = GetParameterType(paramId); // First type number comparison. if (IsDirectNumericalType(t) && numValue == Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type angle comparison. else if (t == ParameterType.Angle && DegreeToRadian(numValue) == Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type percentage comparison. else if (t == ParameterType.Percentage && (numValue / 100.0) == Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // If it is a number but as a string. else if (GetParameterValue(paramId, o.Id) != null && paramValue == GetParameterValue(paramId, o.Id).ToString()) { matched.Add(o); } } } } else if (comparison == 1) // Less than comparison. { foreach (Rhino.DocObjects.RhinoObject o in rhobjs) { Guid paramId = GetObjectParameterId(paramName, o.Id, true); if (paramId != Guid.Empty && GetParameterValue(paramId, o.Id) != null) { ParameterType t = GetParameterType(paramId); // First type number comparison. if (IsDirectNumericalType(t) && numValue > Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type angle comparison. else if (t == ParameterType.Angle && DegreeToRadian(numValue) > Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type percentage comparison. else if (t == ParameterType.Percentage && (numValue / 100.0) > Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } } } } else if (comparison == 2) // Greater than comparison. { foreach (Rhino.DocObjects.RhinoObject o in rhobjs) { Guid paramId = GetObjectParameterId(paramName, o.Id, true); if (paramId != Guid.Empty && GetParameterValue(paramId, o.Id) != null) { ParameterType t = GetParameterType(paramId); // First type number comparison. if (IsDirectNumericalType(t) && numValue < Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type angle comparison. else if (t == ParameterType.Angle && DegreeToRadian(numValue) < Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } // Type percentage comparison. else if (t == ParameterType.Percentage && (numValue / 100.0) < Convert.ToDouble(GetParameterValue(paramId, o.Id))) { matched.Add(o); } } } } } else // If it cannot be converted to num then only compare as bool and text. { int comparison = form.GetComparisonType(); if (comparison == 0) // Equality comparison. { foreach (Rhino.DocObjects.RhinoObject o in rhobjs) { Guid paramId = GetObjectParameterId(paramName, o.Id, true); if (paramId != Guid.Empty && GetParameterValue(paramId, o.Id) != null) { ParameterType t = GetParameterType(paramId); if (t == ParameterType.Boolean) { if ((string.Equals(paramValue, "yes", StringComparison.OrdinalIgnoreCase) || string.Equals(paramValue, "true", StringComparison.OrdinalIgnoreCase)) && "True" == GetParameterValue(paramId, o.Id).ToString()) { matched.Add(o); } else if ((string.Equals(paramValue, "no", StringComparison.OrdinalIgnoreCase) || string.Equals(paramValue, "false", StringComparison.OrdinalIgnoreCase)) && "False" == GetParameterValue(paramId, o.Id).ToString()) { matched.Add(o); } } else if (paramValue == GetParameterValue(paramId, o.Id).ToString()) { matched.Add(o); } } } } } } else // Search only by parameter name. { foreach (Rhino.DocObjects.RhinoObject o in rhobjs) { Guid paramId = GetObjectParameterId(paramName, o.Id, true); if (paramId != Guid.Empty) { matched.Add(o); } } } if (form.GetAddToSelection() == null || form.GetAddToSelection() == false) { rhobjs.UnselectAll(); } // Select all the ones that matched. if (matched.Count > 0) { foreach (Rhino.DocObjects.RhinoObject o in matched) { o.Select(true); } if (matched.Count == 1) { RhinoApp.WriteLine("1 object was selected."); } else { RhinoApp.WriteLine("{0} objects were selected.", matched.Count); } } else { RhinoApp.WriteLine("No objects were found."); } } }
public override void OnCancel() { RhinoApp.WriteLine("SampleCsOptionsPage.OnCancel"); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curves"); go.GeometryFilter = ObjectType.Curve; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } for (var i = 0; i < go.ObjectCount; i++) { var curve = go.Object(i).Curve(); if (null == curve) { return(Result.Failure); } if (curve is LineCurve) { RhinoApp.WriteLine("Curve {0} is a line.", i); } else if (curve is ArcCurve) { RhinoApp.WriteLine(curve.IsClosed ? "Curve {0} is a circle." : "Curve {0} is an arc.", i); } else if (curve is PolylineCurve) { RhinoApp.WriteLine("Curve {0} is a polyline.", i); } else if (curve is PolyCurve) { RhinoApp.WriteLine("Curve {0} is a polycurve.", i); } else if (curve is NurbsCurve) { if (curve.IsEllipse()) { if (curve.IsClosed) { RhinoApp.WriteLine("Curve {0} is an ellipse.", i); } else { RhinoApp.WriteLine("Curve {0} is an elliptical arc.", i); } } else { RhinoApp.WriteLine("Curve {0} is a NURBS curve.", i); } } else { RhinoApp.WriteLine("Curve {0} is an unknown type.", i); } } return(Result.Success); }
/// <summary> /// RunCommand /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { Tolerance = doc.ModelAbsoluteTolerance; // Get persistent settings var settings = Settings; var radius = settings.GetDouble("Radius", RADIUS); var cut_type = settings.GetEnumValue("CutType", CUTTYPE); // Select closed,planar curve var go = new GetClosedPlanarPolyline(Tolerance); go.SetCommandPrompt("Select closed, planar polyline"); go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } // Get curve var obj_ref = go.Object(0); var curve = obj_ref.Curve(); if (null == curve || !curve.IsClosed || !curve.IsPlanar()) { return(Result.Failure); } // Get polyline Polyline polyline; if (!curve.TryGetPolyline(out polyline)) { return(Result.Failure); } // Since first and last point are the same, remove the last point. polyline.RemoveAt(polyline.Count - 1); // Get curve plane Plane plane; if (!curve.TryGetPlane(out plane, Tolerance)) { return(Result.Failure); } // Get corner point indices var indices = FindInnerCornerPoints(curve, polyline, plane); if (0 == indices.Length) { RhinoApp.WriteLine("No inner corners found."); return(Result.Nothing); } // Show preview conduit var conduit = new SampleCsOverCutConduit { Circles = CalculateCuttingCircles(curve, polyline, indices, plane, radius, cut_type), Enabled = true }; doc.Views.Redraw(); Result rc; // Choose overcut options var gp = new GetOption(); gp.SetCommandPrompt("Choose overcut option"); gp.AcceptNothing(true); for (;;) { gp.ClearCommandOptions(); var cut_type_index = gp.AddOptionEnumList("CutType", cut_type); var radius_option = new OptionDouble(radius, true, Tolerance); var radius_index = gp.AddOptionDouble("Radius", ref radius_option); var res = gp.Get(); if (res == GetResult.Option) { var option = gp.Option(); if (null != option) { if (option.Index == cut_type_index) { var list = Enum.GetValues(typeof(CutType)).Cast <CutType>().ToList(); cut_type = list[option.CurrentListOptionIndex]; } else if (option.Index == radius_index) { radius = radius_option.CurrentValue; } conduit.Circles = CalculateCuttingCircles(curve, polyline, indices, plane, radius, cut_type); doc.Views.Redraw(); } continue; } if (res == GetResult.Nothing) { rc = Result.Success; break; } rc = Result.Cancel; break; } conduit.Enabled = false; if (rc == Result.Success) { // Try differencing circles from curve var success = true; var new_curve = curve; for (var i = 0; i < conduit.Circles.Count && success; i++) { var new_curves = Curve.CreateBooleanDifference(new_curve, new ArcCurve(conduit.Circles[i]), doc.ModelAbsoluteTolerance); if (1 == new_curves.Length && null != new_curves[0]) { new_curve = new_curves[0]; } else { success = false; } } // Add geometry to document if (success && null != new_curve) { doc.Objects.Replace(obj_ref, new_curve); } else { for (var i = 0; i < conduit.Circles.Count; i++) { doc.Objects.AddCircle(conduit.Circles[i]); } } // Set persistent settings settings.SetDouble("Radius", radius); settings.SetEnumValue("CutType", cut_type); } doc.Views.Redraw(); return(rc); }
internal void displayProgress(float progress) { RhinoApp.WriteLine(progress.ToString()); progressVal = progress; }
void Test(TestFunc func, RhinoDoc doc) { RhinoApp.WriteLine("[TEST START] - " + func.Method.ToString()); Rhino.Commands.Result rc = func(doc); RhinoApp.WriteLine("[TEST DONE] - result = " + rc.ToString()); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { Point3dList points = new Point3dList(); // Point3dList is from the Collections class, we add a new variable points then initialize it and add // empty array Result commandres; //calls class Point3dList and initializes a new empty array with the name 'points' while (true) //make an infinite loop. every time we click on screen we will create a point which will // be added to the document and the screen will be refreshed. it happens fast!! { var gp = new GetPoint(); //prompt user string prompt; prompt = "set point(s) by click"; gp.SetCommandPrompt(prompt); //set up what to do with the result var res = gp.Get(); //get function returns a really cool type of enumeration // https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_Input_GetResult.htm if (res == GetResult.Point) //using Rhino.Input, double equal sign is necessary... { doc.Objects.AddPoint(gp.Point()); //adds a point object to the document to object table doc.Views.Redraw(); //refreshes the views points.Add(gp.Point()); // add the point to our points array declared above commandres = Result.Success; } else if (res == GetResult.Nothing) { commandres = Result.Failure; break; } else { commandres = Result.Cancel; break; } } RhinoApp.WriteLine("The user drew {0} point(s) successfully", points.Count.ToString()); // access the points array and cast it to a string, outside the function so that it will only // show how many ponints you've drawn when the function is complete. return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // Select objects to define block var go = new GetObject(); go.SetCommandPrompt("Select objects to define block"); go.ReferenceObjectSelect = false; go.SubObjectSelect = false; go.GroupSelect = true; // Phantoms, grips, lights, etc., cannot be in blocks. var forbidden_geometry_filter = ObjectType.Light | ObjectType.Grip | ObjectType.Phantom; var geometry_filter = forbidden_geometry_filter ^ ObjectType.AnyObject; go.GeometryFilter = geometry_filter; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } // Block base point Point3d base_point; var rc = RhinoGet.GetPoint("Block base point", false, out base_point); if (rc != Result.Success) { return(rc); } // Block definition name string idef_name = ""; rc = RhinoGet.GetString("Block definition name", false, ref idef_name); if (rc != Result.Success) { return(rc); } // Validate block name idef_name = idef_name.Trim(); if (string.IsNullOrEmpty(idef_name)) { return(Result.Nothing); } // See if block name already exists InstanceDefinition existing_idef = doc.InstanceDefinitions.Find(idef_name); if (existing_idef != null) { RhinoApp.WriteLine("Block definition {0} already exists", idef_name); return(Result.Nothing); } // Gather all of the selected objects var geometry = new List <GeometryBase>(); var attributes = new List <ObjectAttributes>(); for (int i = 0; i < go.ObjectCount; i++) { var rh_object = go.Object(i).Object(); if (rh_object != null) { geometry.Add(rh_object.Geometry); attributes.Add(rh_object.Attributes); } } // Gather all of the selected objects var idef_index = doc.InstanceDefinitions.Add(idef_name, string.Empty, base_point, geometry, attributes); if (idef_index < 0) { RhinoApp.WriteLine("Unable to create block definition", idef_name); return(Result.Failure); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: complete command. // get picture object ObjRef objRef = null; using (var go = new GetObject()) { go.SetCommandPrompt("Select a picture object to sample"); go.GeometryFilter = ObjectType.Surface; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } objRef = go.Object(0); } // get rhino object RhinoObject rhinoObject = objRef.Object(); // extract bitmap texture from render material Xml RenderMaterial renderMaterial = rhinoObject.RenderMaterial; XmlDocument xml = new XmlDocument(); xml.LoadXml(renderMaterial.Xml); var node = xml.SelectSingleNode("material/simulation/Texture-1-filename"); var filePath = node.InnerText; var bitmap = new Bitmap(Image.FromFile(filePath)); // get bounding box var bbox = rhinoObject.Geometry.GetBoundingBox(Plane.WorldXY, out var worldBox); // get width / height of bbox double bboxWidth = bbox.Corner(false, true, true).DistanceTo(bbox.Corner(true, true, true)); double bboxHeight = bbox.Corner(true, false, true).DistanceTo(bbox.Corner(true, true, true)); // get width / height of image int imgWidth = bitmap.Width; int imgHeight = bitmap.Height; // Calculate stretch factor double stretchFactor = bboxWidth / imgWidth; // Test stretch factor consistency if (!(Math.Abs(imgHeight * stretchFactor - bboxHeight) < doc.ModelAbsoluteTolerance)) { RhinoApp.WriteLine("Selected Picture object is scaled non-uniform! Aborting command"); return(Result.Failure); } // get starting position var startPt = bbox.Min; // create grid of points var plane = worldBox.Plane; plane.Origin = startPt; Point3d[] points = new Point3d[imgWidth * imgHeight]; Color[] colors = new Color[imgWidth * imgHeight]; Vector3d[] normals = new Vector3d[imgWidth * imgHeight]; Vector3d normal = Vector3d.ZAxis; for (int i = 0; i < imgHeight; i++) { for (int j = 0; j < imgWidth; j++) { points[(i + 1) * j] = plane.PointAt(j * stretchFactor, i * stretchFactor); colors[(i + 1) * j] = bitmap.GetPixel(j, i); normals[(i + 1) * j] = normal; } } // create Point cloud from grid PointCloud pc = new PointCloud(); pc.AddRange(points, normals, colors); // add point cloud to doc doc.Objects.AddPointCloud(pc); // redraw doc.Views.Redraw(); // return success return(Result.Success); }