/// <summary> /// Takes varying RhinoObjects and returns a RhinoMesh, and a RhinoMaterial for each. /// Handles /// </summary> /// <param name="rhinoObjects"></param> /// <returns></returns> public static List <Tuple <Rhino.Geometry.Mesh[], Rhino.DocObjects.Material, Guid, RhinoObject> > SanitizeRhinoObjects(IEnumerable <RhinoObject> rhinoObjects) { var rhinoObjectsRes = new List <Tuple <Rhino.Geometry.Mesh[], Rhino.DocObjects.Material, Guid, RhinoObject> >(); foreach (var rhinoObject in rhinoObjects) { if (!rhinoObject.IsMeshable(MeshType.Any)) { RhinoApp.WriteLine("Skipping " + GetDebugName(rhinoObject) + ", object is not meshable. Object is a " + rhinoObject.ObjectType.ToString()); continue; } // FIXME: This is broken. Even though objects use the same material, different Materials are returned here. var mat = rhinoObject.GetMaterial(true); var renderMatId = mat.Id; bool isPBR = mat.IsPhysicallyBased; // This is always true when called from the Main plugin command, as it uses the same ObjectType array as filter. // Keeping it around in case someone calls this from somewhere else. var isValidGeometry = Constants.ValidObjectTypes.Contains(rhinoObject.ObjectType); if (isValidGeometry && rhinoObject.ObjectType != ObjectType.InstanceReference) { var meshes = GetMeshes(rhinoObject); if (meshes.Length > 0) //Objects need a mesh to export { rhinoObjectsRes.Add(new Tuple <Rhino.Geometry.Mesh[], Rhino.DocObjects.Material, Guid, RhinoObject>(meshes, mat, renderMatId, rhinoObject)); } } else if (rhinoObject.ObjectType == ObjectType.InstanceReference) { InstanceObject instanceObject = rhinoObject as InstanceObject; List <RhinoObject> objects = new List <RhinoObject>(); List <Transform> transforms = new List <Transform>(); ExplodeRecursive(instanceObject, instanceObject.InstanceXform, objects, transforms); // Transform the exploded geo into its correct place foreach (var item in objects.Zip(transforms, (rObj, trans) => (rhinoObject: rObj, trans))) { var meshes = GetMeshes(item.rhinoObject); foreach (var mesh in meshes) { mesh.Transform(item.trans); } if (meshes.Length > 0) //Objects need a mesh to export { rhinoObjectsRes.Add(new Tuple <Rhino.Geometry.Mesh[], Rhino.DocObjects.Material, Guid, RhinoObject>(meshes, mat, renderMatId, item.rhinoObject)); } } } else { RhinoApp.WriteLine("Unknown geo type encountered."); } } return(rhinoObjectsRes); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { if (TimePanel.Instance.Restarted && TimePanel.Instance.TrackbarValue == 0) { RhinoApp.WriteLine("Now it's time to draw a box"); Point3d pt0; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("First corner of the base"); if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No corner point was selected."); return(getPointAction.CommandResult()); } pt0 = getPointAction.Point(); if (pt0.Z != 0) { RhinoApp.WriteLine("The base of the square is not on the plane XY"); return(getPointAction.CommandResult()); } } Point3d pt1; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("Other corner of the base"); getPointAction.SetBasePoint(pt0, true); getPointAction.DynamicDraw += (sender, e) => { e.Display.DrawLine(pt0, new Point3d(pt0.X, e.CurrentPoint.Y, 0), Color.Black); e.Display.DrawLine(pt0, new Point3d(e.CurrentPoint.X, pt0.Y, 0), Color.Black); e.Display.DrawLine(new Point3d(pt0.X, e.CurrentPoint.Y, 0), e.CurrentPoint, Color.Black); e.Display.DrawLine(new Point3d(e.CurrentPoint.X, pt0.Y, 0), e.CurrentPoint, Color.Black); }; if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No corner point was selected."); return(getPointAction.CommandResult()); } pt1 = getPointAction.Point(); if (pt1.Z != 0) { RhinoApp.WriteLine("The base of the square is not on the plane XY"); return(getPointAction.CommandResult()); } if (pt1.Equals(pt0)) { RhinoApp.WriteLine("The second point is the same of the first"); return(getPointAction.CommandResult()); } } Point3d pt2; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("Height"); getPointAction.SetBasePoint(pt1, true); var line = new Rhino.Geometry.Line(pt1, new Point3d(pt1.X, pt1.Y, 1)); getPointAction.Constrain(line); getPointAction.DynamicDraw += (sender, e) => { e.Display.DrawLine(pt0, new Point3d(pt0.X, pt1.Y, 0), Color.Black); e.Display.DrawLine(pt0, new Point3d(pt1.X, pt0.Y, 0), Color.Black); e.Display.DrawLine(new Point3d(pt0.X, pt1.Y, 0), pt1, Color.Black); e.Display.DrawLine(new Point3d(pt1.X, pt0.Y, 0), pt1, Color.Black); e.Display.DrawLine(new Point3d(pt0.X, pt0.Y, e.CurrentPoint.Z), new Point3d(pt0.X, pt1.Y, e.CurrentPoint.Z), Color.Black); e.Display.DrawLine(new Point3d(pt0.X, pt0.Y, e.CurrentPoint.Z), new Point3d(pt1.X, pt0.Y, e.CurrentPoint.Z), Color.Black); e.Display.DrawLine(new Point3d(pt0.X, pt1.Y, e.CurrentPoint.Z), e.CurrentPoint, Color.Black); e.Display.DrawLine(new Point3d(pt1.X, pt0.Y, e.CurrentPoint.Z), e.CurrentPoint, Color.Black); e.Display.DrawLine(pt0, new Point3d(pt0.X, pt0.Y, e.CurrentPoint.Z), Color.Black); e.Display.DrawLine(pt1, new Point3d(pt1.X, pt1.Y, e.CurrentPoint.Z), Color.Black); e.Display.DrawLine(new Point3d(pt0.X, pt1.Y, e.CurrentPoint.Z), new Point3d(pt0.X, pt1.Y, 0), Color.Black); e.Display.DrawLine(new Point3d(pt1.X, pt0.Y, e.CurrentPoint.Z), new Point3d(pt1.X, pt0.Y, 0), Color.Black); }; if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No Height point was selected."); return(getPointAction.CommandResult()); } pt2 = getPointAction.Point(); if (pt2.Z == 0) { RhinoApp.WriteLine("The height of the box must be different of 0"); return(getPointAction.CommandResult()); } } //Find center of the box Point3d middleDiagonal = new Point3d((pt0.X + pt1.X) / 2, (pt0.Y + pt1.Y) / 2, 0); Point3d middleHeight = new Point3d(0, 0, (pt1.Z + pt2.Z) / 2); Point3d centerBox = new Point3d(middleDiagonal.X, middleDiagonal.Y, middleHeight.Z); //Find dimension of the box Shape boxShape = new BoxShape((float)Math.Abs(pt1.X - pt0.X), (float)Math.Abs(pt1.Y - pt0.Y), (float)Math.Abs(pt2.Z)); RigidBody rigidBox = new RigidBody(boxShape); rigidBox.Position = new JVector((float)centerBox.X, (float)centerBox.Y, (float)centerBox.Z); Box box = new Box(new BoundingBox(RigidBodyManager.JVectorToPoint3d(boxShape.BoundingBox.Min), RigidBodyManager.JVectorToPoint3d(boxShape.BoundingBox.Max))); //Original one with the center in 0,0,0 Brep brepBox = box.ToBrep(); //Copy to translate and rotate Brep copyToAdd = brepBox.DuplicateBrep(); //Move the box to the correct position copyToAdd.Translate(centerBox.X, centerBox.Y, centerBox.Z); RigidBodyManager.RigidBodies.Add(rigidBox); RigidBodyManager.GeometryList.Add(brepBox); RigidBodyManager.GuidList.Add(doc.Objects.Add(copyToAdd)); doc.Views.Redraw(); return(Result.Success); } else { Dialogs.ShowMessage("Press Restart before use other commands", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning); return(Result.Success); } }
private void Btn_ExportReport_Click(object sender, RoutedEventArgs e) { List <string> pagename = new List <string>(); List <FixedPage> fps = new List <FixedPage>(); if (tempIndex == -1) { errorMessage tempError = new errorMessage("설계안을 먼저 선택하세요."); return; } // 배치도 테스트 List <CorePlan> tempCorePlans = new List <CorePlan>(); List <FloorPlan> tempFloorPlans = new List <FloorPlan>(); foreach (List <CoreProperties> i in MainPanel_AGOutputList[tempIndex].CoreProperties) { foreach (CoreProperties j in i) { tempCorePlans.Add(new CorePlan(j)); } } for (int i = 0; i < MainPanel_AGOutputList[tempIndex].HouseholdProperties.Count(); i++) { for (int j = 0; j < MainPanel_AGOutputList[tempIndex].HouseholdProperties[i][0].Count(); j++) { tempFloorPlans.Add(new FloorPlan(MainPanel_AGOutputList[tempIndex].HouseholdProperties[i][0][j], MainPanel_planLibraries)); } } foreach (CorePlan i in tempCorePlans) { List <Curve> tempCrvs = i.normals; tempCrvs.AddRange(i.others); tempCrvs.AddRange(i.walls); foreach (Curve j in tempCrvs) { RhinoDoc.ActiveDoc.Objects.AddCurve(j); } } foreach (FloorPlan i in tempFloorPlans) { List <Curve> tempCrvs = i.all; foreach (Curve j in tempCrvs) { RhinoDoc.ActiveDoc.Objects.AddCurve(j); } } // 배치도 테스트 끝 List <System.Windows.Documents.FixedPage> FixedPageList = new List <System.Windows.Documents.FixedPage>(); FixedDocument currentDoc = new FixedDocument(); currentDoc.DocumentPaginator.PageSize = new Size(1240, 1753); List <Page> pagesToVIew = new List <Page>(); //page1 표지 Reports.xmlcover cover = new Reports.xmlcover(); cover.SetTitle = TuringAndCorbusierPlugIn.InstanceClass.page1Settings.ProjectName; fps.Add(cover.fixedPage); pagename.Add("Cover"); //page2 건축개요 Reports.xmlBuildingReport buildingReport = new Reports.xmlBuildingReport(MainPanel_AGOutputList[tempIndex]); fps.Add(buildingReport.fixedPage); pagename.Add("buildingReport"); //page3~ 세대타입별 개요 List <HouseholdStatistics> uniqueHouseHoldProperties = MainPanel_AGOutputList[tempIndex].HouseholdStatistics.ToList(); List <string> typeString = MainPanel_AGOutputList[tempIndex].AreaTypeString(); double coreAreaSum = MainPanel_AGOutputList[tempIndex].GetCoreAreaSum(); double UGParkingLotAreaSum = MainPanel_AGOutputList[tempIndex].ParkingLotUnderGround.GetAreaSum(); double publicFacilityArea = MainPanel_AGOutputList[tempIndex].GetPublicFacilityArea(); double serviceArea = -1000; //***** for (int i = 0; i < uniqueHouseHoldProperties.Count(); i++) { HouseholdProperties i_Copy = new HouseholdProperties(uniqueHouseHoldProperties[i].ToHouseholdProperties()); i_Copy.Origin = new Point3d(i_Copy.Origin.X, i_Copy.Origin.Y, 0); double tempCoreArea = coreAreaSum / MainPanel_AGOutputList[tempIndex].GetExclusiveAreaSum() * i_Copy.GetExclusiveArea(); double tempParkingLotArea = UGParkingLotAreaSum / MainPanel_AGOutputList[tempIndex].GetExclusiveAreaSum() * i_Copy.GetExclusiveArea(); Reports.xmlUnitReport unitReport = new Reports.xmlUnitReport(i_Copy, typeString[i], tempCoreArea, tempParkingLotArea, publicFacilityArea, serviceArea, uniqueHouseHoldProperties[i].Count); unitReport.setUnitPlan(uniqueHouseHoldProperties[i], MainPanel_planLibraries); fps.Add(unitReport.fixedPage); pagename.Add("unitReport" + (i + 1).ToString()); } //page4 /* * //아직 평면 드로잉 안끝남 (20160504); * * ImageFilePath = generateImageFileName(imageFileName, tempImageNumber); * Report.BasicPage plans = new Report.BasicPage("배치도"); * plans.SetTypicalPlan = typicalPlan.drawTipicalPlan(MainPanel_AGOutputList[tempIndex].HouseHoldProperties, MainPanel_AGOutputList[tempIndex].CoreProperties, MainPanel_AGOutputList[tempIndex].buildingOutline, MainPanel_AGOutputList[tempIndex].Plot, 0); * * List<Rectangle3d> tempParkingLotBoundary = new List<Rectangle3d>(); * * foreach(ParkingLot i in MainPanel_AGOutputList[tempIndex].ParkingLot) * { * tempParkingLotBoundary.Add(i.Boundary); * } * * FixedPageList.Add(GeneratePDF.CreateFixedPage(plans)); * /* * * //page5 * * Report.BasicPage section = new Report.BasicPage("단면도"); * * FixedPageList.Add(GeneratePDF.CreateFixedPage(section)); */ //page6 /* * * Reports.xmlRegulationCheck regCheck = new Reports.xmlRegulationCheck(MainPanel_AGOutputList[tempIndex]); * * fps.Add(regCheck.fixedPage); * pagename.Add("regCheck"); */ TuringAndCorbusierPlugIn.InstanceClass.showmewindow.showmeinit(fps, pagename, TuringAndCorbusierPlugIn.InstanceClass.page1Settings.ProjectName); RhinoApp.WriteLine(pagename.ToArray().Length.ToString()); TuringAndCorbusierPlugIn.InstanceClass.showmewindow.Show(); //TuringAndCorbusierPlugIn.InstanceClass.showmewindow //pdf 생성 //GeneratePDF.SaveFixedDocument(FixedPageList); //GeneratePDF.CreatePortableFile(userControlList, "C://Program Files (x86)//이주데이타//가로주택정비//" + "testFile.xps"); /* * GeneratePDF.CreaterPortableFile(FixedPageList, "C://Program Files (x86)//이주데이타//가로주택정비//" + "testFile.xps"); * GeneratePDF.SavePdfFromXps(); */ }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: complete command. MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance; if (p.if_painted_object_set_ == false) { RhinoApp.WriteLine("No mesh"); return(Result.Failure); } Mesh my_mesh = p.painted_object_; DijkstraGraph my_graph = p.graph; GetObject gbrep1 = new GetObject(); gbrep1.SetCommandPrompt("get the brep"); gbrep1.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep1.SubObjectSelect = false; gbrep1.Get(); if (gbrep1.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep1.CommandResult()); } Rhino.DocObjects.ObjRef my_objref1 = gbrep1.Object(0); Rhino.DocObjects.RhinoObject my_obj1 = my_objref1.Object(); if (my_obj1 == null) { return(Rhino.Commands.Result.Failure); } Brep brep1 = my_objref1.Brep(); if (brep1 == null) { return(Result.Failure); } my_obj1.Select(false); GetObject gbrep2 = new GetObject(); gbrep2.SetCommandPrompt("get the brep"); gbrep2.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep2.SubObjectSelect = false; gbrep2.Get(); if (gbrep2.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep2.CommandResult()); } Rhino.DocObjects.ObjRef my_objref2 = gbrep2.Object(0); Rhino.DocObjects.RhinoObject my_obj2 = my_objref2.Object(); if (my_obj2 == null) { return(Rhino.Commands.Result.Failure); } Brep brep2 = my_objref2.Brep(); if (brep2 == null) { return(Result.Failure); } my_obj2.Select(false); Point3d pin_1_position = brep1.UserDictionary.GetPoint3d("CurrentPosition"); Point3d pin_2_position = brep2.UserDictionary.GetPoint3d("CurrentPosition"); Guid pin_1_id = brep1.UserDictionary.GetGuid("PinID"); Guid pin_2_id = brep2.UserDictionary.GetGuid("PinID"); MeshPoint pin_1_meshpoint = my_mesh.ClosestMeshPoint(pin_1_position, 0); MeshPoint pin_2_meshpoint = my_mesh.ClosestMeshPoint(pin_2_position, 0); Stopwatch watch = new Stopwatch(); watch.Start(); NurbsCurve d_path = my_graph.DijkstraPath_Add(pin_1_meshpoint, pin_1_id, pin_2_meshpoint, pin_2_id); watch.Stop(); if (d_path == null) { return(Result.Success); } RhinoApp.WriteLine("link time: {0}", watch.Elapsed); ObjectAttributes my_attributes = new ObjectAttributes(); my_attributes.ObjectColor = Color.Yellow; my_attributes.ColorSource = ObjectColorSource.ColorFromObject; my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject; my_attributes.PlotWeight = 2.0; doc.Objects.AddCurve(d_path, my_attributes); doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var cs_option = new OptionToggle(m_use_cplane, "World", "CPlane"); var go = new GetObject(); go.SetCommandPrompt("Select objects for bounding box calculation"); go.GroupSelect = true; go.SubObjectSelect = false; for (;;) { go.ClearCommandOptions(); go.AddOptionToggle("CoordinateSystem", ref cs_option); var res = go.GetMultiple(1, 0); if (res == GetResult.Option) { continue; } else if (res != GetResult.Object) { return(Result.Cancel); } break; } var plane = go.View().ActiveViewport.ConstructionPlane(); m_use_cplane = cs_option.CurrentValue; var world_to_plane = new Transform(1.0); if (m_use_cplane) { world_to_plane = Transform.ChangeBasis(Plane.WorldXY, plane); } var bounding_box = new BoundingBox(); for (var i = 0; i < go.ObjectCount; i++) { var rhino_obj = go.Object(i).Object(); if (null != rhino_obj) { var box = rhino_obj.Geometry.GetBoundingBox(world_to_plane); if (box.IsValid) { if (i == 0) { bounding_box = box; } else { bounding_box.Union(box); } } } } if (!bounding_box.IsValid) { RhinoApp.WriteLine("BoundingBox failed. Unable to calculate bounding box."); return(Result.Failure); } var box_corners = new Point3d[8]; box_corners[0] = bounding_box.Corner(false, false, false); box_corners[1] = bounding_box.Corner(true, false, false); box_corners[2] = bounding_box.Corner(true, true, false); box_corners[3] = bounding_box.Corner(false, true, false); box_corners[4] = bounding_box.Corner(false, false, true); box_corners[5] = bounding_box.Corner(true, false, true); box_corners[6] = bounding_box.Corner(true, true, true); box_corners[7] = bounding_box.Corner(false, true, true); if (m_use_cplane) { // Transform corners points from cplane coordinates // to world coordinates if necessary. var plane_to_world = Transform.ChangeBasis(plane, Plane.WorldXY); for (var i = 0; i < 8; i++) { box_corners[i].Transform(plane_to_world); } } Point3d[] rect; var type = ClassifyBoundingBox(box_corners, out rect); if (type == BoundingBoxClassification.Point) { RhinoApp.WriteLine("BoundingBox failed. The bounding box is a point."); } else if (type == BoundingBoxClassification.Line) { RhinoApp.WriteLine("BoundingBox failed. The bounding box is a line."); } else if (type == BoundingBoxClassification.Rectangle) { doc.Objects.AddPolyline(rect); } else //if (type == BoundingBoxClassification.Box) { var brep = Brep.CreateFromBox(box_corners); doc.Objects.AddBrep(brep); } doc.Views.Redraw(); return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { RhinoApp.WriteLine("The {0} command is under construction.", EnglishName); return(Result.Success); }
private void Socket_OnError(object sender, ErrorEventArgs e) { RhinoApp.WriteLine(e.Message); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { if (TimePanel.Instance.Restarted && TimePanel.Instance.TrackbarValue == 0) { RhinoApp.WriteLine("Now it's time to draw a cylinder"); Point3d pt0; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("The center of the base"); if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No center point was selected."); return(getPointAction.CommandResult()); } pt0 = getPointAction.Point(); if (pt0.Z != 0) { RhinoApp.WriteLine("The center of the cylinder is not on the plane XY"); return(getPointAction.CommandResult()); } } Point3d pt1; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("The end point of the radius of the cylinder"); getPointAction.SetBasePoint(pt0, true); var line = new Line(pt0, new Point3d(pt0.X, pt0.Y, 1)); getPointAction.Constrain(line); getPointAction.DynamicDraw += (sender, e) => { e.Display.DrawLine(new Line(e.CurrentPoint, new Point3d(e.CurrentPoint.X, e.CurrentPoint.Y, -e.CurrentPoint.Z)), Color.Black); }; if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No radius point was selected."); return(getPointAction.CommandResult()); } pt1 = getPointAction.Point(); } Point3d pt2; using (GetPoint getPointAction = new GetPoint()) { getPointAction.SetCommandPrompt("Height"); getPointAction.SetBasePoint(pt1, true); var line = new Rhino.Geometry.Line(pt1, new Point3d(pt1.X, 1, pt1.Z)); getPointAction.Constrain(line); getPointAction.DynamicDraw += (sender, e) => { e.Display.DrawLine(new Line(pt1, new Point3d(pt1.X, pt1.Y, -pt1.Z)), Color.Black); e.Display.DrawLine(new Line(pt1, e.CurrentPoint), Color.Black); e.Display.DrawLine(new Line(new Point3d(e.CurrentPoint.X, e.CurrentPoint.Y, -e.CurrentPoint.Z), e.CurrentPoint), Color.Black); }; if (getPointAction.Get() != GetResult.Point) //getPointAction.Get() rimane in attesa del punto { RhinoApp.WriteLine("No Height point was selected."); return(getPointAction.CommandResult()); } pt2 = getPointAction.Point(); if (pt2.Z == 0) { RhinoApp.WriteLine("The height of the cylinder must be different of 0"); return(getPointAction.CommandResult()); } } double radius = new Line(pt0, pt1).Length; double height = new Line(pt1, pt2).Length; Shape cylinderShape = new CylinderShape((float)height, (float)radius); RigidBody rigidCylinder = new RigidBody(cylinderShape); //Translate to the user position rigidCylinder.Position = new JVector((float)(pt0.X), (float)(pt0.Y - height / 2), 0); Cylinder cylinder = new Cylinder(new Circle(Point3d.Origin, radius), height); //Original one with the center in 0,0,0 Cylinder copyCylinder = new Cylinder(new Circle(new Point3d(0, 0, 0), radius), height); Brep brepCylinder = copyCylinder.ToBrep(true, true); Transform trafo = MatrixXRotation(90); trafo = trafo.Transpose(); //put center in 0,0,0 brepCylinder.Translate(new Vector3d(0, 0, -height / 2)); brepCylinder.Transform(trafo); //Copy to translate and rotate Brep copyToAdd = cylinder.ToBrep(true, true); copyToAdd.Translate(new Vector3d(0, 0, -height / 2)); copyToAdd.Transform(trafo); if (pt0.Y > pt2.Y) { copyToAdd.Translate(new Vector3d(pt0.X, pt0.Y - height / 2, 0)); } else { copyToAdd.Translate(new Vector3d(pt2.X, pt2.Y - height / 2, 0)); } RigidBodyManager.RigidBodies.Add(rigidCylinder); RigidBodyManager.GeometryList.Add(brepCylinder); RigidBodyManager.GuidList.Add(doc.Objects.Add(copyToAdd)); doc.Views.Redraw(); } else { Dialogs.ShowMessage("Press Restart before use other commands", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: start here modifying the behaviour of your command. // --- RhinoApp.WriteLine("MeshMachine WIP test", EnglishName); Brep SB; using (GetObject getBrep = new GetObject()) { getBrep.SetCommandPrompt("Please select the brep to remesh"); getBrep.Get(); SB = getBrep.Object(0).Brep(); } //GetNumber TargetLength = new GetNumber(); //double L = TargetLength.Number(); Rhino.Input.Custom.GetNumber gn = new Rhino.Input.Custom.GetNumber(); gn.SetCommandPrompt("Specify a Target Edge Length"); gn.SetLowerLimit(0.5, false); gn.Get(); if (gn.CommandResult() != Rhino.Commands.Result.Success) { return(gn.CommandResult()); } double L = gn.Number(); //Point3d pt0; //using (GetPoint getPointAction = new GetPoint()) //{ // getPointAction.SetCommandPrompt("Please select the start point"); // if (getPointAction.Get() != GetResult.Point) // { // RhinoApp.WriteLine("No start point was selected."); // return getPointAction.CommandResult(); // } // pt0 = getPointAction.Point(); //} //Point3d pt1; //using (GetPoint getPointAction = new GetPoint()) //{ // getPointAction.SetCommandPrompt("Please select the end point"); // getPointAction.SetBasePoint(pt0, true); // getPointAction.DynamicDraw += // (sender, e) => e.Display.DrawLine(pt0, e.CurrentPoint, System.Drawing.Color.DarkRed); // if (getPointAction.Get() != GetResult.Point) // { // RhinoApp.WriteLine("No end point was selected."); // return getPointAction.CommandResult(); // } // pt1 = getPointAction.Point(); //} //doc.Objects.AddLine(pt0, pt1); PlanktonMesh P = new PlanktonMesh(); List <int> AnchorV = new List <int>(); List <int> FeatureV = new List <int>(); List <int> FeatureE = new List <int>(); double FixT = 0.00001; double LengthTol = 0.15; //a tolerance for when to split/collapse edges double SmoothStrength = 0.8; //smoothing strength double PullStrength = 0.8; //pull to target mesh strength double CurvDep = 0; int Flip = 1; MeshingParameters MeshParams = new MeshingParameters(); MeshParams.MaximumEdgeLength = 3 * L; MeshParams.MinimumEdgeLength = L; MeshParams.JaggedSeams = false; MeshParams.SimplePlanes = false; Mesh[] BrepMeshes = Mesh.CreateFromBrep(SB, MeshParams); Mesh M = new Mesh(); foreach (var mesh in BrepMeshes) { M.Append(mesh); } M.Faces.ConvertQuadsToTriangles(); P = M.ToPlanktonMesh(); var FC = new List <Curve>(); foreach (BrepEdge E in SB.Edges) { if (!E.IsSmoothManifoldEdge(0.01)) { FC.Add(E.ToNurbsCurve()); } } var Corners = SB.Vertices; List <Point3d> FV = new List <Point3d>(); foreach (Point Pt in Corners) { FV.Add(Pt.Location); } //Mark any vertices or edges lying on features for (int i = 0; i < P.Vertices.Count; i++) { Point3d Pt = P.Vertices[i].ToPoint3d(); AnchorV.Add(-1); for (int j = 0; j < FV.Count; j++) { if (Pt.DistanceTo(FV[j]) < FixT) { AnchorV[AnchorV.Count - 1] = j; } } FeatureV.Add(-1); for (int j = 0; j < FC.Count; j++) { double param = new double(); FC[j].ClosestPoint(Pt, out param); if (Pt.DistanceTo(FC[j].PointAt(param)) < FixT) { FeatureV[FeatureV.Count - 1] = j; } } } int EdgeCount = P.Halfedges.Count / 2; for (int i = 0; i < EdgeCount; i++) { FeatureE.Add(-1); int vStart = P.Halfedges[2 * i].StartVertex; int vEnd = P.Halfedges[2 * i + 1].StartVertex; Point3d PStart = P.Vertices[vStart].ToPoint3d(); Point3d PEnd = P.Vertices[vEnd].ToPoint3d(); for (int j = 0; j < FC.Count; j++) { double paramS = new double(); double paramE = new double(); Curve thisFC = FC[j]; thisFC.ClosestPoint(PStart, out paramS); thisFC.ClosestPoint(PEnd, out paramE); if ((PStart.DistanceTo(thisFC.PointAt(paramS)) < FixT) && (PEnd.DistanceTo(thisFC.PointAt(paramE)) < FixT)) { FeatureE[FeatureE.Count - 1] = j; } } } for (int iter = 0; iter < 30; iter++) { EdgeCount = P.Halfedges.Count / 2; double[] EdgeLength = P.Halfedges.GetLengths(); List <bool> Visited = new List <bool>(); Vector3d[] Normals = new Vector3d[P.Vertices.Count]; for (int i = 0; i < P.Vertices.Count; i++) { Visited.Add(false); Normals[i] = Util.Normal(P, i); } double t = LengthTol; //a tolerance for when to split/collapse edges double smooth = SmoothStrength; //smoothing strength double pull = PullStrength; //pull to target mesh strength // Split the edges that are too long for (int i = 0; i < EdgeCount; i++) { if (P.Halfedges[2 * i].IsUnused == false) { int vStart = P.Halfedges[2 * i].StartVertex; int vEnd = P.Halfedges[2 * i + 1].StartVertex; if ((Visited[vStart] == false) && (Visited[vEnd] == false)) { double L2 = L; Point3d Mid = Util.MidPt(P, i); //if (CurvDep > 0) //{ // double NormDiff = Vector3d.VectorAngle(Normals[vStart], Normals[vEnd]); // L2 = Math.Min((1.0 / (3.0 * NormDiff) * L), 5 * L); // if (CurvDep != 1) // { // L2 = L2 * (CurvDep) + L * (1.0 - CurvDep); // } //} //if (BoundScale != 1.0) //{ // double MinDist = 99954; // for (int j = 0; j < FC.Count; j++) // { // double param = new double(); // FC[j].ClosestPoint(Mid, out param); // double ThisDist = Mid.DistanceTo(FC[j].PointAt(param)); // if (ThisDist < MinDist) // { MinDist = ThisDist; } // } // if (MinDist < BoundDist) // { // L2 = L2 * BoundScale + (MinDist / BoundDist) * (L2 * (1 - BoundScale)); // } //} //if (SizP.Count > 0) //{ // L2 = WeightedCombo(Mid, SizP, SizV, WExp, L2, BGW); // // L2 = (WL * (1.0 - BGW)) + (BGW * L2); //} if (EdgeLength[2 * i] > (1 + t) * (4f / 3f) * L2) { int SplitHEdge = P.Halfedges.TriangleSplitEdge(2 * i); if (SplitHEdge != -1) { int SplitCenter = P.Halfedges[SplitHEdge].StartVertex; P.Vertices.SetVertex(SplitCenter, Util.MidPt(P, i)); //update the feature information FeatureE.Add(FeatureE[i]); FeatureV.Add(FeatureE[i]); AnchorV.Add(-1); //2 additional new edges have also been created (or 1 if split was on a boundary) //mark these as non-features int CEdgeCount = P.Halfedges.Count / 2; while (FeatureE.Count < CEdgeCount) { FeatureE.Add(-1); } Visited.Add(true); int[] Neighbours = P.Vertices.GetVertexNeighbours(SplitCenter); foreach (int n in Neighbours) { Visited[n] = true; } } } } } } //Collapse the edges that are too short for (int i = 0; i < EdgeCount; i++) { if (P.Halfedges[2 * i].IsUnused == false) { int vStart = P.Halfedges[2 * i].StartVertex; int vEnd = P.Halfedges[2 * i + 1].StartVertex; if ((Visited[vStart] == false) && (Visited[vEnd] == false)) { if (!(AnchorV[vStart] != -1 && AnchorV[vEnd] != -1)) // if both ends are anchored, don't collapse { int Collapse_option = 0; //0 for none, 1 for collapse to midpt, 2 for towards start, 3 for towards end //if neither are anchorV if (AnchorV[vStart] == -1 && AnchorV[vEnd] == -1) { // if both on same feature (or neither on a feature) if (FeatureV[vStart] == FeatureV[vEnd]) { Collapse_option = 1; } // if start is on a feature and end isn't if ((FeatureV[vStart] != -1) && (FeatureV[vEnd] == -1)) { Collapse_option = 2; } // if end is on a feature and start isn't if ((FeatureV[vStart] == -1) && (FeatureV[vEnd] != -1)) { Collapse_option = 3; } } else // so one end must be an anchor { // if start is an anchor if (AnchorV[vStart] != -1) { // if both are on same feature, or if the end is not a feature if ((FeatureE[i] != -1) || (FeatureV[vEnd] == -1)) { Collapse_option = 2; } } // if end is an anchor if (AnchorV[vEnd] != -1) { // if both are on same feature, or if the start is not a feature if ((FeatureE[i] != -1) || (FeatureV[vStart] == -1)) { Collapse_option = 3; } } } double L2 = L; Point3d Mid = Util.MidPt(P, i); if (CurvDep > 0) { double NormDiff = Vector3d.VectorAngle(Normals[vStart], Normals[vEnd]); L2 = Math.Min((1.0 / (3.0 * NormDiff) * L), 5 * L); if (CurvDep != 1) { L2 = L2 * (CurvDep) + L * (1.0 - CurvDep); } } //if (BoundScale != 1.0) //{ // double MinDist = 99954; // for (int j = 0; j < FC.Count; j++) // { // double param = new double(); // FC[j].ClosestPoint(Mid, out param); // double ThisDist = Mid.DistanceTo(FC[j].PointAt(param)); // if (ThisDist < MinDist) // { MinDist = ThisDist; } // } // if (MinDist < BoundDist) // { // L2 = L2 * BoundScale + (MinDist / BoundDist) * (L2 * (1 - BoundScale)); // } //} //if (SizP.Count > 0) //{ // L2 = WeightedCombo(Mid, SizP, SizV, WExp, L2, BGW); // //double WL = WeightedCombo(Mid, SizP, SizV, WExp); // //L2 = (WL * (1.0 - BGW)) + (BGW * L2); //} if ((Collapse_option != 0) && (EdgeLength[2 * i] < (1 - t) * 4f / 5f * L2)) { int Collapsed = -1; int CollapseRtn = -1; if (Collapse_option == 1) { Collapsed = P.Halfedges[2 * i].StartVertex; P.Vertices.SetVertex(Collapsed, Util.MidPt(P, i)); CollapseRtn = P.Halfedges.CollapseEdge(2 * i); } if (Collapse_option == 2) { Collapsed = P.Halfedges[2 * i].StartVertex; CollapseRtn = P.Halfedges.CollapseEdge(2 * i); } if (Collapse_option == 3) { Collapsed = P.Halfedges[2 * i + 1].StartVertex; CollapseRtn = P.Halfedges.CollapseEdge(2 * i + 1); } if (CollapseRtn != -1) { int[] Neighbours = P.Vertices.GetVertexNeighbours(Collapsed); foreach (int n in Neighbours) { Visited[n] = true; } } } } } } } EdgeCount = P.Halfedges.Count / 2; if ((Flip == 0) && (PullStrength > 0)) { //Flip edges to reduce valence error for (int i = 0; i < EdgeCount; i++) { if (!P.Halfedges[2 * i].IsUnused && (P.Halfedges[2 * i].AdjacentFace != -1) && (P.Halfedges[2 * i + 1].AdjacentFace != -1) && (FeatureE[i] == -1) // don't flip feature edges ) { int Vert1 = P.Halfedges[2 * i].StartVertex; int Vert2 = P.Halfedges[2 * i + 1].StartVertex; int Vert3 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i].NextHalfedge].NextHalfedge].StartVertex; int Vert4 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i + 1].NextHalfedge].NextHalfedge].StartVertex; int Valence1 = P.Vertices.GetValence(Vert1); int Valence2 = P.Vertices.GetValence(Vert2); int Valence3 = P.Vertices.GetValence(Vert3); int Valence4 = P.Vertices.GetValence(Vert4); if (P.Vertices.NakedEdgeCount(Vert1) > 0) { Valence1 += 2; } if (P.Vertices.NakedEdgeCount(Vert2) > 0) { Valence2 += 2; } if (P.Vertices.NakedEdgeCount(Vert3) > 0) { Valence3 += 2; } if (P.Vertices.NakedEdgeCount(Vert4) > 0) { Valence4 += 2; } int CurrentError = Math.Abs(Valence1 - 6) + Math.Abs(Valence2 - 6) + Math.Abs(Valence3 - 6) + Math.Abs(Valence4 - 6); int FlippedError = Math.Abs(Valence1 - 7) + Math.Abs(Valence2 - 7) + Math.Abs(Valence3 - 5) + Math.Abs(Valence4 - 5); if (CurrentError > FlippedError) { P.Halfedges.FlipEdge(2 * i); } } } } else { //Flip edges based on angle for (int i = 0; i < EdgeCount; i++) { if (!P.Halfedges[2 * i].IsUnused && (P.Halfedges[2 * i].AdjacentFace != -1) && (P.Halfedges[2 * i + 1].AdjacentFace != -1) && (FeatureE[i] == -1) // don't flip feature edges ) { int Vert1 = P.Halfedges[2 * i].StartVertex; int Vert2 = P.Halfedges[2 * i + 1].StartVertex; int Vert3 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i].NextHalfedge].NextHalfedge].StartVertex; int Vert4 = P.Halfedges[P.Halfedges[P.Halfedges[2 * i + 1].NextHalfedge].NextHalfedge].StartVertex; Point3d P1 = P.Vertices[Vert1].ToPoint3d(); Point3d P2 = P.Vertices[Vert2].ToPoint3d(); Point3d P3 = P.Vertices[Vert3].ToPoint3d(); Point3d P4 = P.Vertices[Vert4].ToPoint3d(); double A1 = Vector3d.VectorAngle(new Vector3d(P3 - P1), new Vector3d(P4 - P1)) + Vector3d.VectorAngle(new Vector3d(P4 - P2), new Vector3d(P3 - P2)); double A2 = Vector3d.VectorAngle(new Vector3d(P1 - P4), new Vector3d(P2 - P4)) + Vector3d.VectorAngle(new Vector3d(P2 - P3), new Vector3d(P1 - P3)); if (A2 > A1) { P.Halfedges.FlipEdge(2 * i); } } } } //if (Minim) //{ // Vector3d[] SmoothC = LaplacianSmooth(P, 1, smooth); // for (int i = 0; i < P.Vertices.Count; i++) // { // if (AnchorV[i] == -1) // don't smooth feature vertices // { // P.Vertices.MoveVertex(i, 0.5 * SmoothC[i]); // } // } //} Vector3d[] Smooth = Util.LaplacianSmooth(P, 0, smooth); for (int i = 0; i < P.Vertices.Count; i++) { if (AnchorV[i] == -1) // don't smooth feature vertices { // make it tangential only Vector3d VNormal = Util.Normal(P, i); double ProjLength = Smooth[i] * VNormal; Smooth[i] = Smooth[i] - (VNormal * ProjLength); P.Vertices.MoveVertex(i, Smooth[i]); if (P.Vertices.NakedEdgeCount(i) != 0)//special smoothing for feature edges { int[] Neighbours = P.Vertices.GetVertexNeighbours(i); int ncount = 0; Point3d Avg = new Point3d(); for (int j = 0; j < Neighbours.Length; j++) { if (P.Vertices.NakedEdgeCount(Neighbours[j]) != 0) { ncount++; Avg = Avg + P.Vertices[Neighbours[j]].ToPoint3d(); } } Avg = Avg * (1.0 / ncount); Vector3d move = Avg - P.Vertices[i].ToPoint3d(); move = move * smooth; P.Vertices.MoveVertex(i, move); } if (FeatureV[i] != -1)//special smoothing for feature edges { int[] Neighbours = P.Vertices.GetVertexNeighbours(i); int ncount = 0; Point3d Avg = new Point3d(); for (int j = 0; j < Neighbours.Length; j++) { if ((FeatureV[Neighbours[j]] == FeatureV[i]) || (AnchorV[Neighbours[j]] != -1)) { ncount++; Avg = Avg + P.Vertices[Neighbours[j]].ToPoint3d(); } } Avg = Avg * (1.0 / ncount); Vector3d move = Avg - P.Vertices[i].ToPoint3d(); move = move * smooth; P.Vertices.MoveVertex(i, move); } //projecting points onto the target along their normals if (pull > 0) { Point3d Point = P.Vertices[i].ToPoint3d(); Vector3d normal = Util.Normal(P, i); Ray3d Ray1 = new Ray3d(Point, normal); Ray3d Ray2 = new Ray3d(Point, -normal); double RayPt1 = Rhino.Geometry.Intersect.Intersection.MeshRay(M, Ray1); double RayPt2 = Rhino.Geometry.Intersect.Intersection.MeshRay(M, Ray2); Point3d ProjectedPt; if ((RayPt1 < RayPt2) && (RayPt1 > 0) && (RayPt1 < 1.0)) { ProjectedPt = Point * (1 - pull) + pull * Ray1.PointAt(RayPt1); } else if ((RayPt2 < RayPt1) && (RayPt2 > 0) && (RayPt2 < 1.0)) { ProjectedPt = Point * (1 - pull) + pull * Ray2.PointAt(RayPt2); } else { ProjectedPt = Point * (1 - pull) + pull * M.ClosestPoint(Point); } P.Vertices.SetVertex(i, ProjectedPt); } if (FeatureV[i] != -1) //pull feature vertices onto feature curves { Point3d Point = P.Vertices[i].ToPoint3d(); Curve CF = FC[FeatureV[i]]; double param1 = 0.0; Point3d onFeature = new Point3d(); CF.ClosestPoint(Point, out param1); onFeature = CF.PointAt(param1); P.Vertices.SetVertex(i, onFeature); } } else { P.Vertices.SetVertex(i, FV[AnchorV[i]]); //pull anchor vertices onto their points } } AnchorV = Util.CompactByVertex(P, AnchorV); //compact the fixed points along with the vertices FeatureV = Util.CompactByVertex(P, FeatureV); FeatureE = Util.CompactByEdge(P, FeatureE); P.Compact(); //this cleans the mesh data structure of unused elements } Mesh MR = P.ToRhinoMesh(); MR.Unweld(0.4, true); doc.Objects.AddMesh(MR); doc.Views.Redraw(); RhinoApp.WriteLine("The {0} command added one mesh to the document.", EnglishName); // --- return(Result.Success); }
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.Annotation; go.SetCommandPrompt("Select Text to append Metrix M01:"); GetResult result = go.GetMultiple(1, -1); if (go.CommandResult() != Rhino.Commands.Result.Success) { return(go.CommandResult()); } RhinoApp.WriteLine("Object selection counter = {0}", go.ObjectCount); List <TextEntity> textEntityList = new List <TextEntity>(); List <RhinoObject> rhinoObjectList = new List <RhinoObject>(); // 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 textEntity = rhinoObject.Geometry as TextEntity; if (textEntity != null) { rhinoObjectList.Add(rhinoObject); textEntityList.Add(textEntity); } } } // Sort the text Entity list IEnumerable <TextEntity> query = textEntityList.OrderByDescending(t => t.Plane.OriginY); //.ThenBy(t => t.Plane.OriginX); IEnumerable <TextEntity> xSortedList = textEntityList.OrderBy(t => t.Plane.OriginX); //.ThenBy(t => t.Plane.OriginY); IEnumerable <TextEntity> newList = null; List <TextEntity> toSort = new List <TextEntity>(); List <TextEntity> toRemove = new List <TextEntity>(); double y; Point3d previous = new Point3d(0, 0, 0); int maxDigit = (int)Math.Floor(Math.Log10(textEntityList.Count) + 1); int j = 1; Boolean found = false; foreach (TextEntity yText in query) { found = false; if (toRemove.Count > 0) { foreach (TextEntity deletedElement in toRemove) { if (deletedElement.Equals(yText)) { found = true; break; } } } if (found == false) { y = yText.Plane.OriginY; toSort = new List <TextEntity>(); newList = null; // p = textE; foreach (TextEntity t in xSortedList) { if (t.Plane.OriginY == y || t.Plane.OriginY >= y && t.Plane.OriginY <= (y + 200) || t.Plane.OriginY <= y && t.Plane.OriginY >= (y - 1000)) //Check if y is same { toSort.Add(t); } } if (toSort.Count > 0) //If the list is more than 0, sort it by X { //toSort.Add(yText); newList = toSort.OrderBy(t => t.Plane.OriginX); toRemove.AddRange(newList); } foreach (TextEntity textE in newList) { // Test if there is a M_- in front of the text, if yes, remove it if (textE.Text.Count() > 2) { if (textE.Text[0] == 'M') { if (Char.IsNumber(textE.Text[1])) { if (textE.Text.IndexOf('-') != -1) { // This means M0 exist textE.Text = textE.Text.Substring(textE.Text.IndexOf('-') + 1); } } } } textE.Text = "M" + j.ToString().PadLeft(maxDigit, '0') + "-" + textE.Text; j++; } // toRemove.AddRange(newList); } else { continue; } } // Commit the changes for all updated labels for (int k = 0; k < rhinoObjectList.Count; k++) { rhinoObjectList[k].CommitChanges(); } doc.Views.Redraw(); return(Result.Success); }
public void OnDeclareInputs() { RhinoApp.WriteLine("Good!"); }
/// <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, PerforationPanel panel, PanelParameters panelParas) { if (panelParas == null) { panelParas = new PanelParameters(); } if (panel == null) { panel = new PerforationPanel(); } // 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); }
public Rhino.Commands.Result IntersectSurfaces(Rhino.RhinoDoc doc) { // Input interval var input = new Rhino.Input.Custom.GetNumber(); input.SetCommandPrompt("Input slicing interval"); input.Get(); if (input.CommandResult() != Rhino.Commands.Result.Success) { RhinoApp.WriteLine("Can't obtain interval number"); return(input.CommandResult()); } double SlicingInterval = input.Number(); // Select two curves to intersect var go = new Rhino.Input.Custom.GetObject(); go.SetCommandPrompt("Select surface"); go.GeometryFilter = Rhino.DocObjects.ObjectType.Surface; go.GetMultiple(2, 2); Rhino.Geometry.Surface surfaceA = go.Object(0).Surface(); Rhino.Geometry.Surface surfaceB = go.Object(1).Surface(); // Calculate the intersection RhinoApp.WriteLine("Executing the intersection between surfaces"); const double intersection_tolerance = 0.001; Rhino.Geometry.Curve[] intersectionCurves = null; Rhino.Geometry.Point3d[] intersectionPoints = null; bool ret = Rhino.Geometry.Intersect.Intersection.SurfaceSurface(surfaceA, surfaceB, intersection_tolerance, out intersectionCurves, out intersectionPoints); if (ret) { List <PlanePoint> PlanePoints = new List <PlanePoint>(); RhinoApp.WriteLine("Success - {0} curves", intersectionCurves.Length); for (int i = 0; i < intersectionCurves.Length; i++) { Rhino.Geometry.Curve curve = intersectionCurves[i]; doc.Objects.AddCurve(curve); RhinoApp.WriteLine("Curve is added"); Utility.CreateSections(doc, surfaceA, surfaceB, curve, SlicingInterval, ref PlanePoints); } RhinoApp.WriteLine("Success - {0} points", intersectionPoints.Length); for (int i = 0; i < intersectionPoints.Length; i++) { Rhino.Geometry.Point3d point = intersectionPoints[i]; doc.Objects.AddPoint(point); RhinoApp.WriteLine("Point is added"); } if (Utility.SavePlanePoints(@"c:\SlicerPlanePoints.csv", PlanePoints)) { RhinoApp.WriteLine("Saved SlicerPlanePoints.csv"); } } return(Rhino.Commands.Result.Success); }
protected override Rhino.Commands.Result RunCommand(RhinoDoc doc, Rhino.Commands.RunMode mode) { RhinoApp.WriteLine("The {0} command is under construction", EnglishName); IntersectSurfaces(doc); return(Rhino.Commands.Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { int i = 0; double level = 0; while (true) { Plane pl = (i > 0) ? new Plane(new Point3d(0, 0, level), Vector3d.ZAxis) :new Plane(); Result getResult; Point3d pt0 = Point3d.Unset; getResult = GetFirstPoint(ref pt0, pl, (i == 0)); //Debug.WriteLine(pt0, "Point"); if (getResult != Result.Success) { RhinoApp.WriteLine("Failed to get the first point. Ending Command."); Debug.WriteLine(getResult, "Result"); return(getResult); } Point3d pt1 = Point3d.Unset; getResult = GetSecondPoint(pt0, ref pt1, (i == 0)); //Debug.WriteLine(pt1,"Point"); if (getResult != Result.Success) { RhinoApp.WriteLine("Failed to get the second point. Run not created."); Debug.WriteLine(getResult, "Result"); return(getResult); } Point3d pt2 = Point3d.Unset; getResult = GetThirdPoint(pt0, pt1, ref pt2, (i == 0)); if (getResult != Result.Success) { RhinoApp.WriteLine("Failed to get the third point. Run Not created."); return(getResult); } curRun = new Run(pt0, pt2, this.width.CurrentValue); updateRunOptions(ref curRun); //adding the new run surface doc.Objects.AddSurface(curRun.getStepSurface()); List <Guid> rail_ids = AddLines(ref doc, curRun.getRails()); List <Guid> bal_ids = AddLines(ref doc, curRun.getBalusters()); int groupNum = doc.Groups.Add(); doc.Groups.AddToGroup(groupNum, rail_ids); doc.Groups.AddToGroup(groupNum, bal_ids); //adding landing if valid and user wants it if (i > 0 && this.LandingToggle.CurrentValue) { Landing land = new Landing(prevRun, curRun); if (land.IsValid) { doc.Objects.AddBrep(land.LandingSurface); List <Curve> railing = land.getRailings(this.leftRail.CurrentValue, this.rightRail.CurrentValue); foreach (Curve rail in railing) { doc.Objects.AddCurve(rail); } } else { RhinoApp.WriteLine("The relationship between the runs is ambiguous, Creation of landing will be skipped."); } } i++; level = pt2.Z; //updating the run for the next time prevRun = curRun; doc.Views.Redraw(); } }
/// <summary> /// Starts the service. /// </summary> public bool Start() { // Try creating the service host try { //m_service_host = new ServiceHost( // typeof(RockfishService), // new Uri("net.pipe://localhost/mcneel/rockfishserver/5/server")); m_service_host = new ServiceHost( typeof(RockfishService), new Uri("http://localhost:8000/mcneel/rockfish/5/server")); } catch { RhinoApp.WriteLine("Failed to create Rockfish service host."); Stop(); return(false); } // Try creating the binding and add a servic endpoint try { //var binding = new NetNamedPipeBinding //{ // MaxBufferSize = MAX_BUFFER, // MaxReceivedMessageSize = MAX_BUFFER //}; // //m_service_host.AddServiceEndpoint(typeof(IRockfishService), binding, "pipe"); var binding = new BasicHttpBinding { MaxBufferSize = MAX_BUFFER, MaxReceivedMessageSize = MAX_BUFFER }; m_service_host.AddServiceEndpoint(typeof(IRockfishService), binding, "basic"); } catch { RhinoApp.WriteLine("Failed to create Rockfish service end point."); Stop(); return(false); } // Try creating the service debug behavior try { var debug_behavior = m_service_host.Description.Behaviors.Find <ServiceDebugBehavior>(); if (null == debug_behavior) { debug_behavior = new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }; m_service_host.Description.Behaviors.Add(debug_behavior); } else { debug_behavior.IncludeExceptionDetailInFaults = true; } } catch { RhinoApp.WriteLine("Failed to create Rockfish service debug behavior."); Stop(); return(false); } // Try opening the service try { m_service_host.Open(); } catch { RhinoApp.WriteLine("Failed to open Rockfish service."); Stop(); return(false); } RhinoApp.WriteLine("Rockfish service started."); return(true); }
public void CalculateStrains(double force, double moment, Axis axis) { //ColorRGB c = Utils.HSL2RGB(0.5, 0.5, 0.5); //Calculate crossSectionBB Updatebb(getAllBBs()); //Divide the geometry larges into smaller segments for numerical integration CutWithReinforcement(); //Initial test Tuple <double, double> temp = CalculateLoading(_concreteMaterial.Epsc2, _concreteMaterial.Epsc2, axis); if (temp.Item1 > force) { RhinoApp.WriteLine("Cross section cannot bear that large load."); return; } temp = CalculateLoading(0.01, 0.01, axis); if (temp.Item1 < force) { RhinoApp.WriteLine("Cross section cannot bear that large load."); return; } int i = 0; int tressHould = 200; double testForce = 0; double testMoment = 0; double strainBot = 0; double strainTop = 0; double HigherLimitTop = 0.01; double HigherLimitBot = 0.01; double LowerLimitTop = _concreteMaterial.Epsc2; double LowerLimitBot = _concreteMaterial.Epsc2; //Iteration while (Math.Abs((testForce - force) / force) > 0.001 && Math.Abs((testMoment - moment) / moment) > 0.001 && i < tressHould) { while (Math.Abs((testForce - force) / force) > 0.001 && i < tressHould) { if (testForce < force) { LowerLimitTop = strainTop; LowerLimitBot = strainBot; strainTop += (HigherLimitTop - strainTop) / 2; strainBot += (HigherLimitBot - strainBot) / 2; } else { HigherLimitTop = strainTop; HigherLimitBot = strainBot; strainTop += (LowerLimitTop - strainTop) / 2; strainBot += (LowerLimitBot - strainBot) / 2; } i += 1; temp = CalculateLoading(strainTop, strainBot, axis); testForce = temp.Item1; RhinoApp.WriteLine($"Force: {testForce}, Moment: {testMoment}"); } HigherLimitTop = -_concreteMaterial.Epsc2; HigherLimitBot = -_concreteMaterial.Epsc2; LowerLimitTop = _concreteMaterial.Epsc2; LowerLimitBot = _concreteMaterial.Epsc2; while (Math.Abs((testMoment - moment) / moment) > 0.01 && i < tressHould) { if (testMoment < moment) { HigherLimitTop = strainTop; LowerLimitBot = strainBot; strainTop += (LowerLimitTop - strainTop) / 2; strainBot += (HigherLimitBot - strainBot) / 2; } else { LowerLimitTop = strainTop; HigherLimitBot = strainBot; strainTop += (HigherLimitTop - strainTop) / 2; strainBot += (LowerLimitBot - strainBot) / 2; } i += 1; temp = CalculateLoading(strainTop, strainBot, axis); testMoment = temp.Item2; RhinoApp.WriteLine($"Force: {testForce}, Moment: {testMoment}"); } } if (i < tressHould) { saveStresses(strainTop, strainBot, axis); } RhinoApp.WriteLine(i < tressHould ? "Success" : "Failure"); }
/// <summary> /// Command.RunCommand override /// </summary> protected override Result RunCommand(RhinoDoc doc, RunMode mode) { Potrace.Clear(); // Prompt the user for the name of the image file to vectorize. string path = GetImageFileName(mode); if (string.IsNullOrEmpty(path)) { return(Result.Cancel); } // Creates a bitmap from the specified file. var bitmap = Image.FromFile(path) as Bitmap; if (null == bitmap) { RhinoApp.WriteLine("The specified file cannot be identifed as a supported type."); return(Result.Failure); } // Verify bitmap size if (0 == bitmap.Width || 0 == bitmap.Height) { RhinoApp.WriteLine("Error reading the specified file."); return(Result.Failure); } // Calculate scale factor so curves of a reasonable size are added to Rhino var unit_scale = (doc.ModelUnitSystem != UnitSystem.Inches) ? RhinoMath.UnitScale(UnitSystem.Inches, doc.ModelUnitSystem) : 1.0; var scale = (double)(1.0 / bitmap.HorizontalResolution * unit_scale); // I'm not convinced this is useful... if (true) { var format = $"F{doc.DistanceDisplayPrecision}"; // Print image size in pixels RhinoApp.WriteLine("Image size in pixels: {0} x {1}", bitmap.Width, bitmap.Height ); // Print image size in inches var width = (double)(bitmap.Width / bitmap.HorizontalResolution); var height = (double)(bitmap.Height / bitmap.VerticalResolution); RhinoApp.WriteLine("Image size in inches: {0} x {1}", width.ToString(format, CultureInfo.InvariantCulture), height.ToString(format, CultureInfo.InvariantCulture) ); // Image size in in model units, if needed if (doc.ModelUnitSystem != UnitSystem.Inches) { width = (double)(bitmap.Width / bitmap.HorizontalResolution * unit_scale); height = (double)(bitmap.Height / bitmap.VerticalResolution * unit_scale); RhinoApp.WriteLine("Image size in {0}: {1} x {2}", doc.ModelUnitSystem.ToString().ToLower(), width.ToString(format, CultureInfo.InvariantCulture), height.ToString(format, CultureInfo.InvariantCulture) ); } } // Convert the bitmap to an Eto bitmap var eto_bitmap = ConvertBitmapToEto(bitmap); if (null == eto_bitmap) { RhinoApp.WriteLine("Unable to convert image to Eto bitmap."); return(Result.Failure); } // 12-Jan-2021 Dale Fugier // This should prevent Eto.Drawing.BitmapData.GetPixels() from throwing an exception if (!IsCompatibleBitmap(eto_bitmap)) { RhinoApp.WriteLine("The image has an incompatible pixel format. Please select an image with 24 or 32 bits per pixel, or 8 bit indexed."); return(Result.Failure); } // This bitmap is not needed anymore, so dispose of it bitmap.Dispose(); // Gets the Potrace settings from the plug-in settings file GetPotraceSettings(); // Create the conduit, which does most of the work var conduit = new VectorizeConduit( eto_bitmap, scale, doc.ModelAbsoluteTolerance, m_select_output ? Rhino.ApplicationSettings.AppearanceSettings.SelectedObjectColor : doc.Layers.CurrentLayer.Color ) { Enabled = true, IncludeBorder = m_include_border }; if (mode == RunMode.Interactive) { // Show the interactive dialog box var dialog = new VectorizeDialog(doc, conduit); dialog.RestorePosition(); var result = dialog.ShowSemiModal(doc, RhinoEtoApp.MainWindow); dialog.SavePosition(); if (result != Result.Success) { conduit.Enabled = false; Potrace.Clear(); doc.Views.Redraw(); return(Result.Cancel); } m_include_border = conduit.IncludeBorder; } else { // Show the command line options var go = new GetOption(); go.SetCommandPrompt("Vectorization options. Press Enter when done"); go.AcceptNothing(true); while (true) { conduit.IncludeBorder = m_include_border; conduit.TraceBitmap(); doc.Views.Redraw(); go.ClearCommandOptions(); // Threshold var threshold_opt = new OptionDouble(Potrace.Treshold, 0.0, 100.0); var threshold_idx = go.AddOptionDouble("Threshold", ref threshold_opt, "Threshold"); // TurnPolicy var turnpolicy_idx = go.AddOptionEnumList("TurnPolicy", Potrace.turnpolicy); // IgnoreArea var turdsize_opt = new OptionInteger(Potrace.turdsize, 2, 100); var turdsize_idx = go.AddOptionInteger("FilterSize", ref turdsize_opt, "Filter speckles of up to this size in pixels"); // CornerThreshold var alphamax_opt = new OptionDouble(Potrace.alphamax, 0.0, 100.0); var alphamax_idx = go.AddOptionDouble("CornerRounding", ref alphamax_opt, "Corner rounding threshold"); // IncludeBorder var include_border_opt = new OptionToggle(m_include_border, "No", "Yes"); var include_border_idx = go.AddOptionToggle("IncludeBorder", ref include_border_opt); // Optimizing var curveoptimizing_opt = new OptionToggle(Potrace.curveoptimizing, "No", "Yes"); var curveoptimizing_idx = go.AddOptionToggle("Optimizing", ref curveoptimizing_opt); // Tolerance var opttolerance_opt = new OptionDouble(Potrace.opttolerance, 0.0, 1.0); var opttolerance_idx = go.AddOptionDouble("Tolerance", ref opttolerance_opt, "Optimizing tolerance"); // RestoreDefaults var defaults_idx = go.AddOption("RestoreDefaults"); var res = go.Get(); if (res == GetResult.Option) { var option = go.Option(); if (null != option) { if (turdsize_idx == option.Index) { Potrace.turdsize = turdsize_opt.CurrentValue; } if (turnpolicy_idx == option.Index) { var list = Enum.GetValues(typeof(TurnPolicy)).Cast <TurnPolicy>().ToList(); Potrace.turnpolicy = list[option.CurrentListOptionIndex]; } if (curveoptimizing_idx == option.Index) { Potrace.curveoptimizing = curveoptimizing_opt.CurrentValue; } if (opttolerance_idx == option.Index) { Potrace.opttolerance = opttolerance_opt.CurrentValue; } if (alphamax_idx == option.Index) { Potrace.alphamax = alphamax_opt.CurrentValue; } if (threshold_idx == option.Index) { Potrace.Treshold = threshold_opt.CurrentValue; } if (include_border_idx == option.Index) { m_include_border = include_border_opt.CurrentValue; } if (defaults_idx == option.Index) { Potrace.RestoreDefaults(); m_include_border = true; } } continue; } if (res != GetResult.Nothing) { conduit.Enabled = false; doc.Views.Redraw(); Potrace.Clear(); return(Result.Cancel); } break; } } // Group curves var attributes = doc.CreateDefaultAttributes(); attributes.AddToGroup(doc.Groups.Add()); for (var i = 0; i < conduit.OutlineCurves.Count; i++) { if (i == 0 && !m_include_border) // skip border { continue; } var rhobj_id = doc.Objects.AddCurve(conduit.OutlineCurves[i], attributes); if (m_select_output) { var rhobj = doc.Objects.Find(rhobj_id); if (null != rhobj) { rhobj.Select(true); } } } conduit.Enabled = false; Potrace.Clear(); doc.Views.Redraw(); // Set the Potrace settings to the plug-in settings file. SetPotraceSettings(); return(Result.Success); }
public virtual void Setup() { RhinoApp.WriteLine("-- setup --"); }
public override bool OnApply() { RhinoApp.WriteLine("SampleCsDocPropertiesPage.OnApply"); return(true); }
private void Socket_OnMessage(object sender, MessageEventArgs e) { RhinoApp.WriteLine(e.Data); try { ClientEventArgs eve = JsonConvert.DeserializeObject <ClientEventArgs>(e.Data); switch (eve.route) { case ClientEventType.TaskGetInput: { string type = eve.data["geoType"].ToString(); string pick = null; switch (type) { case "Point": { pick = "pt"; break; } case "Curve": { pick = "crv"; break; } case "Surface": { pick = "srf"; break; } case "Brep": { pick = "brp"; break; } case "ID": { pick = "id"; break; } } RhinoApp.InvokeOnUiThread(new Action(() => { var res = GH_Utils.PickFunction(pick); var data = JsonConvert.SerializeObject(new JObject { ["route"] = "TaskSetInput", ["id"] = eve.data["paramId"], ["data"] = "" }); Client.Send(data); })); break; } case ClientEventType.TaskProcess: { if (!vm.Enabled) { vm.Enabled = true; } vm.Geometries.Clear(); string file = eve.data["file"].ToString(); if (string.IsNullOrEmpty(file)) { throw new Exception("没有指定程序文件"); } if (!System.IO.File.Exists(file)) { throw new Exception("指定程序文件不存在"); } var ext = System.IO.Path.GetExtension(file); var dataGroup = new Dictionary <string, string>(); foreach (var data in eve.data["data"]) { if (!(data is JProperty prop)) { continue; } dataGroup.Add(prop.Name, prop.Value.ToString()); } // 参数类型转换 var param = eve.data["params"].ToString(); JArray paramArray = JArray.Parse(param); var parameters = new List <List <object> >(); foreach (var p in paramArray) { if (!p.HasValues) { continue; } string type = p["type"].ToString(); JArray valueArray = JArray.Parse(p["value"].ToString()); var values = new List <object>(); foreach (var val in valueArray) { var obj = IO.DecodeCommonObjectFromBase64(val.ToString()); if (obj == null) { continue; } vm.Geometries.Add(obj as GeometryBase); values.Add(obj as object); } if (values.Count < 1) { continue; } parameters.Add(values); } switch (ext) { case ".dll": { string name = System.IO.Path.GetFileNameWithoutExtension(file); Assembly assem = Assembly.LoadFrom(file); var type = assem.GetType($"{name}.Program", true, true); var res = type.GetMethod("Main").Invoke(null, new object[] { new object[] { parameters, dataGroup } }); if (!(res is object[] results)) { RhinoApp.WriteLine("回收输出的时候失败!"); break; } foreach (var obj in results) { if (!(obj is CommonObject common) || !(common is GeometryBase geo)) { continue; } vm.Geometries.Add(geo); } // TODO 回收结果 break; } case ".gh": { GH_Utils.RunHeadless(); // TODO 1 GH_Utils.ComputeGHFile(file); // TODO 回收输出 break; } case ".py": { var python = Rhino.Runtime.PythonScript.Create(); python.SetVariable("params", parameters); python.SetVariable("data", dataGroup); python.ExecuteFile(file); var output = python.GetVariable("output"); // TODO 回收输出 break; } case ".yml": { Actions actions = null; if (ext == ".ga") { //actions = DeserializeFromGAFile(filename); } else if (ext == ".yml") { actions = ParseActionsFromYamlFile(file); } else { throw new Exception($"{ext}格式不支持GA"); } //actions.SetInput(dialog.Results); actions.Solve(); break; } default: { throw new Exception($"不支持的程序类型{ext}"); } } RhinoDoc.ActiveDoc.Views.Redraw(); break; } default: break; } } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); RhinoApp.WriteLine(ex.StackTrace); RhinoApp.WriteLine(ex.Source); } }
public override void OnCancel() { RhinoApp.WriteLine("SampleCsDocPropertiesPage.OnCancel"); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { // TODO: complete command. MyRhino5rs11project8PlugIn p = MyRhino5rs11project8PlugIn.Instance; if (p.if_painted_object_set_ == false) { RhinoApp.WriteLine("No mesh"); return(Result.Failure); } Mesh my_mesh = p.painted_object_; DijkstraGraph my_graph = p.graph; GetObject gbrep1 = new GetObject(); gbrep1.SetCommandPrompt("get the brep"); gbrep1.GeometryFilter = Rhino.DocObjects.ObjectType.Brep; gbrep1.SubObjectSelect = false; gbrep1.Get(); if (gbrep1.CommandResult() != Rhino.Commands.Result.Success) { return(gbrep1.CommandResult()); } Rhino.DocObjects.ObjRef my_objref1 = gbrep1.Object(0); Rhino.DocObjects.RhinoObject my_obj1 = my_objref1.Object(); if (my_obj1 == null) { return(Rhino.Commands.Result.Failure); } Brep brep1 = my_objref1.Brep(); if (brep1 == null) { return(Result.Failure); } my_obj1.Select(false); for (int i = 0; i < p.my_objects_list.Count; i++) { Guid brep1_id = My_object_functions.GetComponentID(brep1); Guid my_object_id = My_object_functions.GetComponentID(p.my_objects_list[i]); if (brep1_id == my_object_id) { p.my_objects_list.RemoveAt(i); } } IEnumerable <RhinoObject> path_objref = doc.Objects.GetObjectList(ObjectType.Curve); foreach (RhinoObject path in path_objref) { doc.Objects.Delete(path, true); } List <NurbsCurve> new_path_list = new List <NurbsCurve>(); int pin_number = My_object_functions.GetPinQuantity(brep1); for (int i = 0; i < pin_number; i++) { Guid pin_id = My_object_functions.GetPinGuid(brep1, i); new_path_list = p.graph.DijkstraPath_DeletePin(pin_id); } ObjectAttributes my_attributes = new ObjectAttributes(); my_attributes.ObjectColor = Color.Yellow; my_attributes.ColorSource = ObjectColorSource.ColorFromObject; my_attributes.PlotWeightSource = ObjectPlotWeightSource.PlotWeightFromObject; my_attributes.PlotWeight = 2.0; doc.Objects.Delete(my_objref1, true); for (int i = 0; i < new_path_list.Count; i++) { Guid path_id = new_path_list[i].UserDictionary.GetGuid("PathID"); my_attributes.ObjectId = path_id; doc.Objects.Add(new_path_list[i], my_attributes); } doc.Views.Redraw(); return(Result.Success); }
public static Result ExtendSurface(RhinoDoc doc) { var go = new Rhino.Input.Custom.GetObject(); go.SetCommandPrompt("Select edge of surface to extend"); go.GeometryFilter = ObjectType.EdgeFilter; go.GeometryAttributeFilter = GeometryAttributeFilter.EdgeCurve; go.Get(); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var obj_ref = go.Object(0); var surface = obj_ref.Surface(); if (surface == null) { RhinoApp.WriteLine("Unable to extend polysurfaces."); return(Result.Failure); } var brep = obj_ref.Brep(); var face = obj_ref.Face(); if (brep == null || face == null) { return(Result.Failure); } if (face.FaceIndex < 0) { return(Result.Failure); } if (!brep.IsSurface) { RhinoApp.WriteLine("Unable to extend trimmed surfaces."); return(Result.Nothing); } var curve = obj_ref.Curve(); var trim = obj_ref.Trim(); if (trim == null) { return(Result.Failure); } if (trim.TrimType == BrepTrimType.Seam) { RhinoApp.WriteLine("Unable to extend surface at seam."); return(Result.Nothing); } var extended_surface = surface.Extend(trim.IsoStatus, 5.0, true); if (extended_surface != null) { var mybrep = Brep.CreateFromSurface(extended_surface); doc.Objects.Replace(obj_ref.ObjectId, mybrep); doc.Views.Redraw(); } return(Result.Success); }
/// <since>5.0</since> public virtual Commands.Result RunScript(RhinoDoc doc, Commands.RunMode mode) { RhinoApp.WriteLine(Localization.LocalizeString("Scripting not supported for this option", 33)); Dialogs.ShowMessage(Localization.LocalizeString("Scripting not supported for this option", 34), Localization.LocalizeString("Unsupported Option", 35)); return(Commands.Result.Success); }
private static Result GetTolerance(ref double tolerance) { var gp = new GetPoint(); gp.SetCommandPrompt("Tolerance"); gp.SetDefaultNumber(tolerance); gp.AcceptNumber(true, false); for (;;) { var res = gp.Get(); if (res == GetResult.Number) { var d = gp.Number(); if (d < 0.0) { RhinoApp.WriteLine("Tolerance must be greater than 0."); } else { tolerance = d; return(Result.Success); } } if (res != GetResult.Point) { return(Result.Cancel); } break; } var base_point = gp.Point(); gp.SetBasePoint(base_point, true); gp.DrawLineFromPoint(base_point, true); gp.DynamicDrawColor = Rhino.ApplicationSettings.AppearanceSettings.TrackingColor; for (;;) { var res = gp.Get(); if (res == GetResult.Number) { var d = gp.Number(); if (d < 0.0) { RhinoApp.WriteLine("Tolerance must be greater than 0."); } else { tolerance = d; return(Result.Success); } } if (res != GetResult.Point) { return(Result.Cancel); } break; } tolerance = base_point.DistanceTo(gp.Point()); 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 go = new GetObject(); go.SetCommandPrompt("Select points for polyline creation"); go.GeometryFilter = ObjectType.Point; go.SubObjectSelect = false; go.GetMultiple(2, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } var in_points = new List <RockfishPoint>(go.ObjectCount); foreach (var obj_ref in go.Objects()) { var point = obj_ref.Point(); if (null != point) { in_points.Add(new RockfishPoint(point.Location)); } } if (in_points.Count < 2) { return(Result.Cancel); } RockfishGeometry out_curve; try { RockfishClientPlugIn.ServerHostName(); using (var channel = new RockfishClientChannel()) { channel.Create(); out_curve = channel.PolylineFromPoints(in_points.ToArray(), doc.ModelAbsoluteTolerance); } } catch (Exception ex) { RhinoApp.WriteLine(ex.Message); return(Result.Failure); } if (null != out_curve?.Curve) { doc.Objects.AddCurve(out_curve.Curve); doc.Views.Redraw(); } return(Result.Success); }
protected override Result RunCommand(RhinoDoc doc, RunMode mode) { var go = new GetObject(); go.SetCommandPrompt("Select curves to fair"); go.GeometryFilter = ObjectType.Curve; go.GroupSelect = true; go.ReferenceObjectSelect = false; go.GetMultiple(1, 0); if (go.CommandResult() != Result.Success) { return(go.CommandResult()); } foreach (var objref in go.Objects()) { var curve = objref.Curve(); var nurb = curve?.ToNurbsCurve(); if (nurb == null) { return(Result.Failure); } if (1 == nurb.Degree) { RhinoApp.WriteLine("Cannot fair degree 1 curves."); var obj = objref.Object(); if (null != obj) { obj.Select(false); obj.Highlight(false); doc.Views.Redraw(); } return(Result.Cancel); } } var rc = GetTolerance(ref m_dist_tol); if (rc != Result.Success) { return(rc); } // Divide tolerance by 4 as part of getting Fair to stay within stated tolerance var dist_tol = m_dist_tol * 0.25; var faired_count = 0; var degree3_count = 0; foreach (var objref in go.Objects()) { var curve = objref.Curve(); var nurb = curve?.ToNurbsCurve(); if (nurb == null) { return(Result.Failure); } var curve_degree = nurb.Degree; Curve fair = null; if (nurb.IsPeriodic) { nurb.Knots.ClampEnd(CurveEnd.Start); nurb.Knots.ClampEnd(CurveEnd.End); var new_curve = nurb.Fair(dist_tol, m_ang_tol, (int)FairClamp.Tangency, (int)FairClamp.Tangency, m_iterations); if (null != new_curve) { fair = Curve.CreatePeriodicCurve(new_curve, true); } } else { fair = nurb.Fair(dist_tol, m_ang_tol, (int)FairClamp.None, (int)FairClamp.None, m_iterations); } if (null != fair && fair.IsValid) { if (curve_degree != fair.Degree) { degree3_count++; } if (doc.Objects.Replace(objref, fair)) { faired_count++; } } } if (0 == faired_count) { RhinoApp.WriteLine("No curves were faired."); } else if (1 == faired_count) { RhinoApp.WriteLine("1 curve was faired."); } else { RhinoApp.WriteLine("{0} curves were faired.", faired_count); } if (degree3_count > 0) { if (1 == degree3_count) { RhinoApp.WriteLine("1 curve was changed to degree 3 during fairing."); } else { RhinoApp.WriteLine("{0} curves were changed to degree 3 during fairing.", degree3_count); } } doc.Views.Redraw(); return(Result.Success); }
public virtual Commands.Result RunScript(RhinoDoc doc, RhinoObject[] objectList) { RhinoApp.WriteLine(Localization.LocalizeString("Scripting not supported for this option", 30)); Dialogs.ShowMessage(Localization.LocalizeString("Scripting not supported for this option", 31), Localization.LocalizeString("Unsupported Option", 32)); return(Commands.Result.Success); }
private void RhinoDoc_SelectObjects(object sender, RhinoObjectSelectionEventArgs e) { var selectedObjs = e.RhinoObjects.Select(_ => _); if (this._mergedCounts > 0) { //Get all pasted in objects one by one. while (this._mergedCounts > _rhinoObjectsMergedIn.Count + 1) { this._rhinoObjectsMergedIn.AddRange(selectedObjs); return; } //Get the last one this._rhinoObjectsMergedIn.AddRange(selectedObjs); //All pasted objects selectedObjs = this._rhinoObjectsMergedIn.GetRange(0, this._mergedCounts); //reset the counts. this._mergedCounts = 0; this._rhinoObjectsMergedIn.Clear(); } //var selectedGroupEntities = selectedObjs.Select(_ => GroupEntity.TryGet(_)); var selectedRooms = selectedObjs.Where(_ => _.Geometry.IsRoom()).Select(_ => new ObjRef(_.Id)); var selectedApertures = selectedObjs.Where(_ => _.Geometry.IsAperture()).Select(_ => new ObjRef(_.Id)); var selectedDoors = selectedObjs.Where(_ => _.Geometry.IsDoor()).Select(_ => new ObjRef(_.Id)); //TODO: work on this later //var selectedShds = selectedObjs.Where(_ => _.IsShade()); if (this._isObjectCopied) { CheckCopiedObjs(selectedRooms, selectedApertures, selectedDoors); //reset the flag. this._isObjectCopied = false; } //currently there is one object is double clicked, //it is under editing, and no need to select the entire groupEntity. if (this.m_mc.IsEditingRoom) { return; } //Subobject is selected var subs = selectedObjs.ElementAt(0).GetSelectedSubObjects(); if (subs != null) { return; } //Only make the room obj as the entry point for selecting the entire group entity. var roomCounts = selectedRooms.Count(); SelectHighlightObj(selectedRooms, selectedApertures, selectedDoors); if (roomCounts > 1) { RhinoApp.WriteLine($"Honeybee Rhino Plugin: {selectedRooms.Count()} Honeybee rooms are selected"); } //local method void CheckCopiedObjs(IEnumerable <ObjRef> rooms, IEnumerable <ObjRef> apertures, IEnumerable <ObjRef> doors) { //Dictionary<OldRoomID, (newRoomID, newApertureList)>(); Dictionary <Guid, (Guid newRoomId, List <(ObjRef newApt, Guid oldAptID)> apertures, List <(ObjRef newDoor, Guid olddoorID)> doors)> roomAptDoorMatch = rooms.ToDictionary( _ => _.Geometry().TryGetRoomEntity().HostObjRef.ObjectId, _ => (_.ObjectId, new List <(ObjRef, Guid)>(), new List <(ObjRef, Guid)>()) ); //update Apertures foreach (var newAperture in apertures) { //TODO: refactor this later var ent = newAperture.TryGetApertureEntity(); var oldHost = ent.HostObjRef; var oldHostRoom = ent.HostRoomObjRef; if (oldHostRoom != null) { //keep tracking of new aperture with its host room var newMatch = roomAptDoorMatch[oldHostRoom.ObjectId]; newMatch.apertures.Add((newAperture, oldHost.ObjectId)); //attach aperture to new host room ent.HostRoomObjRef = new ObjRef(newMatch.newRoomId); } //update host brep ent.UpdateHostFrom(newAperture); //TODO: update hostRoomObjRef to new obj } //update Doors foreach (var newDoor in doors) { var ent = newDoor.TryGetDoorEntity(); var oldHost = ent.HostObjRef; var oldHostRoom = ent.HostRoomObjRef; if (oldHostRoom != null) { //keep tracking of new aperture with its host room var newMatch = roomAptDoorMatch[oldHostRoom.ObjectId]; newMatch.doors.Add((newDoor, oldHost.ObjectId)); //attach aperture to new host room ent.HostRoomObjRef = new ObjRef(newMatch.newRoomId); } //update host brep ent.UpdateHostFrom(newDoor); } //update room foreach (var newRoom in rooms) { var roomEnt = newRoom.Brep().TryGetRoomEntity(); var oldHostId = roomEnt.HostObjRef.ObjectId; var matchDic = roomAptDoorMatch[oldHostId]; //update aperture on faces var matchApts = matchDic.apertures; if (matchApts.Any()) { //update sub face entities //Figure out all new copied windows' ownership var brepFaces = newRoom.Brep().Faces; foreach (var bface in brepFaces) { var ent = bface.TryGetFaceEntity(); ent.UpdateApertures(matchApts); } } //update aperture on faces var matchDoors = matchDic.doors; if (matchDoors.Any()) { //update sub face entities //Figure out all new copied matchDoors' ownership var brepFaces = newRoom.Brep().Faces; foreach (var bface in brepFaces) { var ent = bface.TryGetFaceEntity(); ent.UpdateDoors(matchDoors); } } roomEnt.UpdateHost(newRoom); //Add to HB Model var model = HoneybeeRhinoPlugIn.Instance.ModelEntityTable.First().Value; model.Rooms.Add(new ObjRef(newRoom.ObjectId)); } } void SelectHighlightObj(IEnumerable <ObjRef> rooms, IEnumerable <ObjRef> apertures, IEnumerable <ObjRef> doors) { foreach (var room in rooms) { var entity = room.Geometry().TryGetRoomEntity(); if (!entity.IsValid) { continue; } entity.SelectAndHighlight(); if (roomCounts == 1) { RhinoApp.WriteLine($"Honeybee Rhino Plugin: {entity.Name}; Window: {entity.ApertureCount}"); } } foreach (var apt in apertures) { var entity = apt.Geometry().TryGetApertureEntity(); if (!entity.IsValid) { continue; } entity.SelectAndHighlightRoom(); } foreach (var door in doors) { var entity = door.Geometry().TryGetDoorEntity(); if (!entity.IsValid) { continue; } entity.SelectAndHighlightRoom(); } } }