/// <summary> /// Adds the predefined hatch. /// </summary> /// <param name="trans">The trans.</param> /// <param name="points">The points.</param> /// <param name="layername">The layername.</param> /// <param name="isClosed">if set to <c>true</c> [is closed].</param> /// <param name="patternName">Name of the pattern.</param> /// <returns></returns> public static ObjectId AddPredefinedHatch(Transaction trans, Point2dCollection points, string layername, bool isClosed, string patternName) { //_logger.Debug("Start AddPredefinedHatch"); ObjectId id = ObjectId.Null; Autodesk.AutoCAD.DatabaseServices.Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database; Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager; using (Hatch hatch = new Hatch()) { hatch.SetDatabaseDefaults(); hatch.Layer = layername; id = AddToDatabase(db, hatch, trans); hatch.UpgradeOpen(); //hatch.HatchStyle = HatchStyle.Outer; hatch.Associative = true; hatch.PatternScale = 100.0; hatch.SetHatchPattern(HatchPatternType.PreDefined, patternName); double buldge = 0.0; HatchLoop loop = new HatchLoop(HatchLoopTypes.Polyline); foreach (Point2d pt in points) { BulgeVertex bv = new BulgeVertex(pt, buldge); loop.Polyline.Add(bv); } hatch.AppendLoop(loop); hatch.EvaluateHatch(true); } //_logger.Debug("End AddPredefinedHatch"); return(id); }
Hatch CloneHatch(Hatch oldEnt) { try { Hatch newEnt = new Hatch(); for (int hi = 0; hi < oldEnt.NumberOfLoops; hi++) { HatchLoop hl = oldEnt.GetLoopAt(hi); newEnt.AppendLoop(hl); } newEnt.Associative = oldEnt.Associative; newEnt.BackgroundColor = oldEnt.BackgroundColor; newEnt.Elevation = oldEnt.Elevation; //newEnt.GradientAngle = oldEnt.GradientAngle; //newEnt.GradientOneColorMode = oldEnt.GradientOneColorMode; //newEnt.GradientShift = oldEnt.GradientShift; newEnt.HatchObjectType = oldEnt.HatchObjectType; newEnt.HatchStyle = oldEnt.HatchStyle; newEnt.Normal = oldEnt.Normal; newEnt.Origin = oldEnt.Origin; newEnt.PatternAngle = oldEnt.PatternAngle; newEnt.PatternDouble = oldEnt.PatternDouble; newEnt.PatternScale = oldEnt.PatternScale; newEnt.PatternSpace = oldEnt.PatternSpace; //newEnt.ShadeTintValue = oldEnt.ShadeTintValue; return(newEnt); } catch (Exception ex) { Logger.log("CloneHatch", ex.Message); } return(null); }
/// <summary> /// 创建填充。 /// </summary> /// <param name="pattern"></param> /// <param name="loops"></param> /// <param name="type"></param> /// <param name="scale"></param> /// <param name="otherSetting"></param> /// <param name="db"></param> /// <param name="space"></param> /// <returns></returns> public static ObjectId CreateHatch(string pattern, Polyline[] loops, HatchPatternType type = HatchPatternType.PreDefined, double scale = 1, Action <Hatch> otherSetting = null, Database db = null, string space = null) { var hatch = new Hatch(); var id = hatch.ToSpace(db, space); using (var trans = id.Database.TransactionManager.StartTransaction()) { hatch = trans.GetObject(id, OpenMode.ForWrite) as Hatch; hatch.PatternScale = scale; hatch.SetHatchPattern(type, pattern); foreach (var loop in loops) { var hatchLoop = new HatchLoop(HatchLoopTypes.Polyline); for (var i = 0; i < loop.NumberOfVertices; i++) { hatchLoop.Polyline.Add( new BulgeVertex(loop.GetPoint2dAt(i), loop.GetBulgeAt(i))); } hatch.AppendLoop(hatchLoop); } otherSetting?.Invoke(hatch); trans.Commit(); } return(id); }
/// <summary> /// Adds the predefined hatch. /// </summary> /// <param name="trans">The trans.</param> /// <param name="points">The points.</param> /// <param name="layername">The layername.</param> /// <param name="isClosed">if set to <c>true</c> [is closed].</param> /// <param name="patternName">Name of the pattern.</param> /// <returns></returns> public static ObjectId AddPredefinedHatch(Transaction trans, Point2dCollection points, string layername, bool isClosed, string patternName) { PGA.MessengerManager.MessengerManager.AddLog("Start AddPredefinedHatch"); var id = ObjectId.Null; var db = Application.DocumentManager.MdiActiveDocument.Database; var tm = db.TransactionManager; using (var hatch = new Hatch()) { hatch.SetDatabaseDefaults(); hatch.Layer = layername; id = AddToDatabase(db, hatch, trans); hatch.UpgradeOpen(); //hatch.HatchStyle = HatchStyle.Outer; hatch.Associative = true; hatch.PatternScale = 100.0; hatch.SetHatchPattern(HatchPatternType.PreDefined, patternName); var buldge = 0.0; var loop = new HatchLoop(HatchLoopTypes.Polyline); foreach (var pt in points) { var bv = new BulgeVertex(pt, buldge); loop.Polyline.Add(bv); } hatch.AppendLoop(loop); hatch.EvaluateHatch(true); } PGA.MessengerManager.MessengerManager.AddLog("End AddPredefinedHatch"); return(id); }
/// <summary> /// Encode the content using the encoding scheme given. /// Replace the base.Encode method /// </summary> /// <param name="content"></param> /// <param name="encoding"></param> /// <returns></returns> public Hatch HatchEncode(String content, Encoding encoding) { Hatch h = new Hatch(); // This for/for/if is the same used at the original // ThoughtWorks.Code sample bool[][] matrix = calQrcode(encoding.GetBytes(content)); for (int i = 0; i < matrix.Length; i++) { for (int j = 0; j < matrix.Length; j++) { if (matrix[j][i]) { HatchLoop loop = new HatchLoop(HatchLoopTypes.Polyline); Point2d[] points = new Point2d[] { new Point2d(j * QRCodeScale, i * QRCodeScale), new Point2d((j + 1) * QRCodeScale, i * QRCodeScale), new Point2d((j + 1) * QRCodeScale, (i + 1) * QRCodeScale), new Point2d(j * QRCodeScale, (i + 1) * QRCodeScale) }; loop.Polyline.Add(new BulgeVertex(points[0], 0)); loop.Polyline.Add(new BulgeVertex(points[1], 0)); loop.Polyline.Add(new BulgeVertex(points[2], 0)); loop.Polyline.Add(new BulgeVertex(points[3], 0)); loop.Polyline.Add(new BulgeVertex(points[0], 0)); h.AppendLoop(loop); } } } // Mirror the hatch as the original code use Windows // coordinates (from upper left corner) double halfSize = (h.GeometricExtents.MaxPoint.X - h.GeometricExtents.MinPoint.X) / 2; h.TransformBy( Matrix3d.Mirroring( new Line3d( new Point3d(halfSize, 0, 0), new Point3d(halfSize, halfSize, 0) ) ) ); return(h); }
public override bool WorldDraw(AcGi.Drawable drawable, AcGi.WorldDraw wd) { var wall = drawable as Line; if (wall != null) { var data = DBHelper.GetNODData(CommandJson.AppName, wall.Id.ToString())?.Data?.AsArray(); var wallParam = JsonConvert.DeserializeObject <Wall>( data[1].Value.ToString() ); var dir = new Vector2d(wallParam.Dir.X, wallParam.Dir.Y) .GetNormal() * wallParam.Size.H; var vertDir = dir.RotateBy(Math.PI / 2) .GetNormal() * wallParam.Size.W * 0.5; var startPt = new Point2d(wallParam.Pos.X, wallParam.Pos.Y); var endPt = startPt + dir; var poly = new Polyline(4); poly.AddVertexAt(poly.NumberOfVertices, startPt + vertDir, 0, 0, 0); poly.AddVertexAt(poly.NumberOfVertices, startPt - vertDir, 0, 0, 0); poly.AddVertexAt(poly.NumberOfVertices, endPt - vertDir, 0, 0, 0); poly.AddVertexAt(poly.NumberOfVertices, endPt + vertDir, 0, 0, 0); poly.Closed = true; var hatch = new Hatch(); hatch.SetHatchPattern(HatchPatternType.PreDefined, wallParam.Hatch); hatch.PatternAngle = dir.Angle - Math.PI / 2; var loop = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly.NumberOfVertices; i++) { loop.Polyline.Add(new BulgeVertex(poly.GetPoint2dAt(i), poly.GetBulgeAt(i))); } hatch.AppendLoop(loop); poly.WorldDraw(wd); hatch.WorldDraw(wd); } //return base.WorldDraw(drawable, wd); return(true); }
/// <summary> /// Функция преобразования координат контура штриховки. Последовательно пробегает по каждому из контуров штриховки и преобразует их в полилинии /// </summary> /// <param name="hatchId">ObjectId штриховки Hatch</param> /// <returns>Список crawlAcDbPolyline - перечень контуров штриховки</returns> private List <crawlAcDbPolyline> HatchToPolylines(ObjectId hatchId) { List <crawlAcDbPolyline> result = new List <crawlAcDbPolyline>(); //Исходный код для AutoCAD .Net //http://forums.autodesk.com/t5/NET/Restore-hatch-boundaries-if-they-have-been-lost-with-NET/m-p/3779514#M33429 try { Hatch hatch = (Hatch)hatchId.GetObject(OpenMode.ForRead); if (hatch != null) { int nLoops = hatch.NumberOfLoops; for (int i = 0; i < nLoops; i++) {//Цикл по каждому из контуров штриховки //Проверяем что контур является полилинией HatchLoop loop = hatch.GetLoopAt(i); if (loop.IsPolyline) { using (Polyline poly = new Polyline()) { //Создаем полилинию из точек контура int iVertex = 0; foreach (BulgeVertex bv in loop.Polyline) { poly.AddVertexAt(iVertex++, bv.Vertex, bv.Bulge, 0.0, 0.0); } result.Add(new crawlAcDbPolyline(poly)); } } else {//Если не удалось преобразовать контур к полилинии //Выводим сообщение в командную строку Crawl.cDebug.WriteLine("Ошибка обработки: Контур штриховки - не полилиния"); //Не будем брать исходный код для штриховок, контур который не сводится к полилинии } } } } catch (Exception e) { Crawl.cDebug.WriteLine("Ошибка обработки штриховки: {0}", e.Message); } return(result); }
/// <summary> /// Единообразное представление границы штриховки в виде набора некомпозитных кривых /// </summary> /// <param name="hl"></param> /// <returns></returns> public static List <Curve2d> GetHatchLoopCurves(HatchLoop hl) { BulgeVertexCollection bvc = hl.Polyline; Curve2dCollection cc = hl.Curves; //Перевод в общий набор Curve2d List <Curve2d> curves = new List <Curve2d>(); if (bvc != null && bvc.Count > 0) { Point2d?prevPt = null; double prevBulge = 0; Action <BulgeVertex> action = new Action <BulgeVertex>(bv => { if (prevPt != null) { Curve2d c = (prevBulge == 0 ? (Curve2d)(new LineSegment2d(prevPt.Value, bv.Vertex)) : (Curve2d)(new CircularArc2d(prevPt.Value, bv.Vertex, prevBulge, false))); curves.Add(c); } prevPt = bv.Vertex; prevBulge = bv.Bulge; }); foreach (BulgeVertex bv in bvc) { action(bv); } foreach (BulgeVertex bv in bvc)//добавление замыкающего сегмента полилинии { action(bv); break; } } else if (cc != null && cc.Count > 0) { foreach (Curve2d c in cc) { curves.Add(c); } } return(curves); }
public static HatchModel Hatch2Model(Hatch dbText, AttributeModel atModel) { HatchModel dbModel = new HatchModel(); try { dbModel.Area = dbText.Area; } catch { } int cont = dbText.NumberOfLoops; string color = ""; for (int i = 0; i < cont; i++) { dbModel.loopPoints.Add(i, new ColorAndPointItemModel()); HatchLoop loop = dbText.GetLoopAt(i); ColorAndPointItemModel cpModel = new ColorAndPointItemModel(); if (i == 0) { color = cpModel.Color = dbText.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(dbText.LayerId) : System.Drawing.ColorTranslator.ToHtml(dbText.Color.ColorValue); } else { cpModel.Color = "#FFFFFF"; // cpModel.ZIndex = "1"; } if (loop.IsPolyline) { for (int j = 0; j < loop.Polyline.Count - 1; j++) { BulgeVertex vertex = loop.Polyline[j]; BulgeVertex vertex1 = loop.Polyline[j + 1]; if (vertex.Bulge != 0) { cpModel.loopPoints.AddRange(MethodCommand.GetArcPointsByBulge(vertex.Vertex, vertex1.Vertex, vertex.Bulge)); } else { cpModel.loopPoints.Add(Point2d2Pointf(vertex.Vertex)); } } if (dbText.NumberOfHatchLines > 0) { Line2dCollection cl = dbText.GetHatchLinesData(); } //foreach (Line2d itemi in ) //{ //} } else { Curve2dCollection col_cur2d = loop.Curves; foreach (Curve2d item in col_cur2d) { Point2d[] M_point2d = item.GetSamplePoints(20); foreach (Point2d point in M_point2d) { cpModel.loopPoints.Add(Point2d2Pointf(point)); } } } if (cpModel.loopPoints[0] != cpModel.loopPoints[cpModel.loopPoints.Count - 1]) { cpModel.loopPoints.Add(cpModel.loopPoints[0]); } cpModel.attItemList = new List <AttributeItemModel>(); foreach (AttributeItemModel item in atModel.attributeItems) { string attValue = ""; switch (item.AtItemType) { case AttributeItemType.Area: attValue = dbModel.Area.ToString(); break; case AttributeItemType.TxtHeight: break; case AttributeItemType.Color: attValue = color; break; case AttributeItemType.Content: break; case AttributeItemType.LayerName: attValue = dbText.Layer; break; case AttributeItemType.LineScale: attValue = dbText.LinetypeScale.ToString(); break; case AttributeItemType.LineType: attValue = GetLayerLineTypeByID(dbText); break; case AttributeItemType.Overallwidth: break; case AttributeItemType.TotalArea: attValue = dbModel.Area.ToString(); break; } if (!string.IsNullOrEmpty(attValue)) { item.AtValue = attValue; cpModel.attItemList.Add(item); } else { } } dbModel.loopPoints[i] = cpModel; } for (int i = 0; i < dbModel.loopPoints.Count; i++) { for (int j = 0; j < dbModel.loopPoints.Count; j++) { if (i != j) { if (MethodCommand.PointsAllInPoints(dbModel.loopPoints[j].loopPoints, dbModel.loopPoints[i].loopPoints)) { dbModel.loopPoints[j].ZIndex = "2"; } } } } // dbModel.Color = return(dbModel); }
public void JsCmd() { var doc = Application.DocumentManager.MdiActiveDocument; var basePt = doc.Editor.GetPoint("\n请输入起始点:"); if (basePt.Status == PromptStatus.OK) { var jigOpt = new JigPromptPointOptions(); var line = new Line(basePt.Value, basePt.Value); var polyLine = new Polyline(4) { Closed = true }; var hatch = new Hatch(); hatch.SetHatchPattern(HatchPatternType.PreDefined, "BOX"); var wall = new JigHelper(); wall.PrapareForNextInput(jigOpt, "\n请输入墙顶中心坐标:"); wall.SetEntities(new Entity[] { line }); wall.SetUpdate(jig => { line.EndPoint = jig.Point; }); if (wall.Drag() != PromptStatus.OK) { return; } wall.PrapareForNextInput(jigOpt, "\n请输入墙面宽度:"); wall.SetEntities(new Entity[] { polyLine, hatch }); wall.SetUpdate(jig => { var edgePt = jig.Point; var centerToEdgeLength = (line.StartPoint - line.EndPoint) .CrossProduct(edgePt - line.EndPoint) .Length / line.Length; var centerToEdge = (line.StartPoint - line.EndPoint) .RotateBy(Math.PI / 2, Vector3d.ZAxis) .GetNormal() * centerToEdgeLength; Point3d pt; pt = line.StartPoint - centerToEdge; polyLine.SetPointAt(0, new Point2d(pt.X, pt.Y)); pt = line.StartPoint + centerToEdge; polyLine.SetPointAt(1, new Point2d(pt.X, pt.Y)); pt = line.EndPoint + centerToEdge; polyLine.SetPointAt(2, new Point2d(pt.X, pt.Y)); pt = line.EndPoint - centerToEdge; polyLine.SetPointAt(3, new Point2d(pt.X, pt.Y)); var loop = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < polyLine.NumberOfVertices; i++) { loop.Polyline.Add(new BulgeVertex(polyLine.GetPoint2dAt(i), polyLine.GetBulgeAt(i))); } if (hatch.NumberOfLoops > 0) { hatch.RemoveLoopAt(0); } hatch.AppendLoop(loop); }); if (wall.Drag() != PromptStatus.OK) { return; } } }
public Tuple <Line, Wall> JigWall(string name, string hatchPattern) { var doc = Application.DocumentManager.MdiActiveDocument; var basePt = doc.Editor.GetPoint("\n请输入起始点:"); if (basePt.Status == PromptStatus.OK) { var jigOpt = new JigPromptPointOptions(); var line = new Line(basePt.Value, basePt.Value); var polyLine = new Polyline(4) { Closed = true }; polyLine.AddVertexAt(0, Point2d.Origin, 0, 0, 0); polyLine.AddVertexAt(0, Point2d.Origin, 0, 0, 0); polyLine.AddVertexAt(0, Point2d.Origin, 0, 0, 0); polyLine.AddVertexAt(0, Point2d.Origin, 0, 0, 0); var hatch = new Hatch(); hatch.SetHatchPattern(HatchPatternType.PreDefined, hatchPattern); var wall = new JigHelper(); wall.PrapareForNextInput(jigOpt, "\n请输入墙顶中心坐标:"); wall.SetEntities(new Entity[] { line }); wall.SetUpdate(jig => { line.EndPoint = jig.Point; }); if (wall.Drag() != PromptStatus.OK) { return(null); } wall.PrapareForNextInput(jigOpt, "\n请输入墙面宽度:"); wall.SetEntities(new Entity[] { polyLine, hatch }); wall.SetUpdate(jig => { var edgePt = jig.Point; var centerToEdgeLength = (line.StartPoint - line.EndPoint) .CrossProduct(edgePt - line.EndPoint) .Length / line.Length; var centerToEdge = (line.StartPoint - line.EndPoint) .RotateBy(Math.PI / 2, Vector3d.ZAxis) .GetNormal() * centerToEdgeLength; Point3d pt; pt = line.StartPoint - centerToEdge; polyLine.SetPointAt(0, new Point2d(pt.X, pt.Y)); pt = line.StartPoint + centerToEdge; polyLine.SetPointAt(1, new Point2d(pt.X, pt.Y)); pt = line.EndPoint + centerToEdge; polyLine.SetPointAt(2, new Point2d(pt.X, pt.Y)); pt = line.EndPoint - centerToEdge; polyLine.SetPointAt(3, new Point2d(pt.X, pt.Y)); var loop = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < polyLine.NumberOfVertices; i++) { loop.Polyline.Add(new BulgeVertex(polyLine.GetPoint2dAt(i), polyLine.GetBulgeAt(i))); } if (hatch.NumberOfLoops > 0) { hatch.RemoveLoopAt(0); } hatch.AppendLoop(loop); }); if (wall.Drag() != PromptStatus.OK) { return(null); } return(Tuple.Create(line, new Wall { Name = name, Pos = new Point { X = line.StartPoint.X, Y = line.StartPoint.Y }, Dir = new Point { X = line.EndPoint.X - line.StartPoint.X, Y = line.EndPoint.Y - line.StartPoint.Y, }, Size = new Size { W = (polyLine.GetPoint2dAt(0) - polyLine.GetPoint2dAt(1)).Length, H = (polyLine.GetPoint2dAt(1) - polyLine.GetPoint2dAt(2)).Length, }, Hatch = hatchPattern, })); } return(null); }
public static void DrawBorder(ArrayList hats, Transaction trans, BlockTableRecord btr, int numSample, Editor ed) { ArrayList two = new ArrayList(); System.Collections.Generic.Dictionary <string, string> result = new System.Collections.Generic.Dictionary <string, string>(); ArrayList attrlist = new ArrayList(); foreach (Hatch hat in hats) { ArrayList one = new ArrayList(); //取得边界数 int loopNum = hat.NumberOfLoops; Point2dCollection col_point2d = new Point2dCollection(); BulgeVertexCollection col_ver = new BulgeVertexCollection(); Curve2dCollection col_cur2d = new Curve2dCollection(); for (int i = 0; i < loopNum; i++) { col_point2d.Clear(); HatchLoop hatLoop = null; try { hatLoop = hat.GetLoopAt(i); } catch (System.Exception) { continue; } //如果HatchLoop为PolyLine if (hatLoop.IsPolyline) { col_ver = hatLoop.Polyline; foreach (BulgeVertex vertex in col_ver) { col_point2d.Add(vertex.Vertex); } } //如果HatchLoop为Curves else { col_cur2d = hatLoop.Curves; foreach (Curve2d item in col_cur2d) { Point2d[] M_point2d = item.GetSamplePoints(numSample); foreach (Point2d point in M_point2d) { if (!col_point2d.Contains(point)) { col_point2d.Add(point); } } } } //根据获得的Point2d点集创建闭合Polyline //Polyline pl = new Polyline(); //pl.Closed = true; //pl.Color = hat.Color; //PolylineTools.CreatePolyline(pl, col_point2d); //btr.AppendEntity(pl); //trans.AddNewlyCreatedDBObject(pl, true); double[] one_0 = new double[2]; foreach (Point2d point in col_point2d) { double X = Math.Round(point.X, 7) + 4000000; double Y = Math.Round(point.Y, 7) + 38500000; //double X = 60146 + 4000000; //double Y = 34953 + 38500000; // 由高斯投影坐标反算成经纬度 int ProjNo; int ZoneWide; ////带宽 double[] output = new double[2]; double longitude1, latitude1, longitude0, X0, Y0, xval, yval; //latitude0, double e1, e2, f, a, ee, NN, T, C, M, D, R, u, fai, iPI; iPI = 0.0174532925199433; ////3.1415926535898/180.0; a = 6378245.0; f = 1.0 / 298.3; //54年北京坐标系参数 //a = 6378140.0; f = 1 / 298.257; //80年西安坐标系参数 ZoneWide = 6; ////6度带宽 ProjNo = (int)(X / 1000000L); //查找带号 longitude0 = (ProjNo - 1) * ZoneWide + ZoneWide / 2; longitude0 = longitude0 * iPI; //中央经线 X0 = ProjNo * 1000000L + 500000L; Y0 = 0; xval = X - X0; yval = Y - Y0; //带内大地坐标 e2 = 2 * f - f * f; e1 = (1.0 - Math.Sqrt(1 - e2)) / (1.0 + Math.Sqrt(1 - e2)); ee = e2 / (1 - e2); M = yval; u = M / (a * (1 - e2 / 4 - 3 * e2 * e2 / 64 - 5 * e2 * e2 * e2 / 256)); fai = u + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.Sin(2 * u) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.Sin(4 * u) + (151 * e1 * e1 * e1 / 96) * Math.Sin(6 * u) + (1097 * e1 * e1 * e1 * e1 / 512) * Math.Sin(8 * u); C = ee * Math.Cos(fai) * Math.Cos(fai); T = Math.Tan(fai) * Math.Tan(fai); NN = a / Math.Sqrt(1.0 - e2 * Math.Sin(fai) * Math.Sin(fai)); R = a * (1 - e2) / Math.Sqrt((1 - e2 * Math.Sin(fai) * Math.Sin(fai)) * (1 - e2 * Math.Sin(fai) * Math.Sin(fai)) * (1 - e2 * Math.Sin (fai) * Math.Sin(fai))); D = xval / NN; //计算经度(Longitude) 纬度(Latitude) longitude1 = longitude0 + (D - (1 + 2 * T + C) * D * D * D / 6 + (5 - 2 * C + 28 * T - 3 * C * C + 8 * ee + 24 * T * T) * D * D * D * D * D / 120) / Math.Cos(fai); latitude1 = fai - (NN * Math.Tan(fai) / R) * (D * D / 2 - (5 + 3 * T + 10 * C - 4 * C * C - 9 * ee) * D * D * D * D / 24 + (61 + 90 * T + 298 * C + 45 * T * T - 256 * ee - 3 * C * C) * D * D * D * D * D * D / 720); //转换为度 DD // 现状图 output[0] = longitude1 / iPI + 108.7271360867638 + 0.0002173 - 11 + 0.00061422; output[1] = latitude1 / iPI - 310.2659499330605 + 0.0009752 - 0.0002805; //output[0] = Math.Round(point.X, 7); //output[1] = Math.Round(point.Y, 7); one_0 = new double[2] { output[0], output[1] }; one.Add(one_0); } } // 单个hatch边界顶点循环结束 two.Add(one); LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(hat.LayerId, OpenMode.ForRead); string hatchColor = "hatchColor:" + ltr.Color; attrlist.Add(hatchColor); } // 所有的Hatch循环结束 Hashtable geom = new Hashtable(); geom.Add("rings", two); string geomString = string.Empty; geomString = JsonConvert.SerializeObject(geom); result.Add("geom", geomString); //string[] attrlist = new string[] { "componentcategoryType:61" }; string[] factorid = new string[] { "b73e3fce-8314-4d5b-8e2b-0a3e8844b28b" }; string type = "polygon"; string name = "456"; string srid = "4214"; string attrlistString = string.Empty; attrlistString = JsonConvert.SerializeObject(attrlist); string factoridString = string.Empty; factoridString = JsonConvert.SerializeObject(factorid); result.Add("attrlist", attrlistString); result.Add("factorid", factoridString); result.Add("type", type); result.Add("srid", srid); result.Add("name", name); string JSONString = string.Empty; JSONString = JsonConvert.SerializeObject(result); MessageBox.Show(JSONString); using (StreamWriter file = new StreamWriter(@"C:\Users\Public\Documents\WriteLines2.json", false)) { file.WriteLine(JSONString); } ed.WriteMessage("\nFound X:{0} ", JSONString); // 发送 开始 var baseAddress = "http://172.18.84.192:8080/CIM/cim/geom!addCadGeomByType.action"; var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress)); http.ContentType = "application/x-www-form-urlencoded"; http.Method = "POST"; StringBuilder builder = new StringBuilder(); int h = 0; foreach (var item in result) { if (h > 0) { builder.Append("&"); } builder.AppendFormat("{0}={1}", item.Key, item.Value); h++; } //string parsedContent = "srid=4326&attrlist=[\"chColor:51\"]&factorid=[\"b73e3fce-8314-4d5b-8e2b-0a3e8844b28b\"]&type=polygon&geom={\"rings\":[[[60145.4546169,33387.5339155],[59895.3137297,33437.8260557],[59885.7661656,33285.0286724],[59885.4849623,33280.5283488],[59902.1499232,33259.5545569],[59906.5973667,33258.8114325],[60127.4437563,33221.9101578],[60145.4546169,33387.5339155]]]}&name=123"; ASCIIEncoding encoding = new ASCIIEncoding(); Byte[] bytes = encoding.GetBytes(builder.ToString()); Stream newStream = http.GetRequestStream(); newStream.Write(bytes, 0, bytes.Length); newStream.Close(); try { var response = http.GetResponse(); var stream = response.GetResponseStream(); var sr = new StreamReader(stream, Encoding.UTF8); var content = sr.ReadToEnd(); MessageBox.Show(content); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null) { MessageBox.Show(ex.Message); } } } // 发送 结束 } // 发送方法结束
public string AjouteSurface(double upperx, double uppery, double lowerx, double lowery, double angle, double echelle, byte R, byte G, byte B, string legende, string hachuretype, string hachfilepath) { //db = HostApplicationServices.WorkingDatabase; //doc = Application.DocumentManager.GetDocument(db); doc = Application.DocumentManager.MdiActiveDocument; db = doc.Database; try { DocumentLock loc = doc.LockDocument(); using (loc) { using (Transaction transaction = db.TransactionManager.StartTransaction()) { Hatch hatch = new Hatch { Color = Autodesk.AutoCAD.Colors.Color.FromRgb(R, G, B) }; hatch.SetHatchPattern(HatchPatternType.PreDefined, hachuretype); hatch.HatchObjectType = HatchObjectType.HatchObject; hatch.PatternAngle = angle; hatch.PatternScale = echelle; //hatch.BlockName = "legende"; //hatch. //} //{ ajoute la définition de la hachure au modelspace BlockTable bt = (BlockTable)transaction.GetObject(doc.Database.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)transaction.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); ObjectId hatId = btr.AppendEntity(hatch); transaction.AddNewlyCreatedDBObject(hatch, true); //} //{ ajoute la boucle de hachure hatch.Associative = true; HatchLoop loop = new HatchLoop(HatchLoopTypes.Polyline); loop.Polyline.Add(new BulgeVertex(new Point2d(upperx, lowery), 0)); loop.Polyline.Add(new BulgeVertex(new Point2d(upperx, uppery), 0)); loop.Polyline.Add(new BulgeVertex(new Point2d(lowerx, uppery), 0)); loop.Polyline.Add(new BulgeVertex(new Point2d(lowerx, lowery), 0)); //pour fermer la polyline, on rajoute le premier point loop.Polyline.Add(new BulgeVertex(new Point2d(upperx, lowery), 0)); hatch.AppendLoop(loop); hatch.EvaluateHatch(true); transaction.Commit(); return("c bon"); //} } } } catch (Exception excp) { return("c pas bon /" + excp.Message + "/" + excp.ErrorStatus.ToString()); } }
public void Fill() { Document acDoc = Application.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Polyline poly0 = new Polyline(); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.5 + Vector2d.YAxis, Math.Tan(0.25 * -1 * Math.PI), 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.5 + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -1 + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -1, 0, 0, 0); poly0.Closed = true; ObjectId poly0Id = acBlkTblRec.AppendEntity(poly0); acTrans.AddNewlyCreatedDBObject(poly0, true); Polyline poly1 = new Polyline(); poly1.AddVertexAt(poly1.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.4 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly1.AddVertexAt(poly1.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.6 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly1.Closed = true; ObjectId poly1Id = acBlkTblRec.AppendEntity(poly1); acTrans.AddNewlyCreatedDBObject(poly1, true); Polyline poly2 = new Polyline(); poly2.AddVertexAt(poly2.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.4 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly2.AddVertexAt(poly2.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.6 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly2.Closed = true; ObjectId poly2Id = acBlkTblRec.AppendEntity(poly2); acTrans.AddNewlyCreatedDBObject(poly2, true); Hatch acHatch = new Hatch(); acBlkTblRec.AppendEntity(acHatch); acTrans.AddNewlyCreatedDBObject(acHatch, true); acHatch.PatternScale = 0.01; acHatch.SetHatchPattern(HatchPatternType.PreDefined, "BOX"); acHatch.Associative = true; //acHatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { poly0Id }); //acHatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { poly1Id }); //acHatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { poly2Id }); HatchLoop hatchLoop = new HatchLoop(HatchLoopTypes.Polyline); foreach (var i in Enumerable.Range(0, poly0.NumberOfVertices)) { hatchLoop.Polyline.Add(new BulgeVertex(poly0.GetPoint2dAt(i), poly0.GetBulgeAt(i))); } hatchLoop.Polyline.Add(new BulgeVertex(poly0.GetPoint2dAt(0), poly0.GetBulgeAt(0))); HatchLoop hatchLoop1 = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly1.NumberOfVertices; i++) { hatchLoop1.Polyline.Add(new BulgeVertex(poly1.GetPoint2dAt(i), poly1.GetBulgeAt(i))); } hatchLoop1.Polyline.Add(new BulgeVertex(poly1.GetPoint2dAt(0), poly1.GetBulgeAt(0))); HatchLoop hatchLoop2 = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly2.NumberOfVertices; i++) { hatchLoop2.Polyline.Add(new BulgeVertex(poly2.GetPoint2dAt(i), poly2.GetBulgeAt(i))); } hatchLoop2.Polyline.Add(new BulgeVertex(poly2.GetPoint2dAt(0), poly2.GetBulgeAt(0))); acHatch.AppendLoop(hatchLoop); acHatch.AppendLoop(hatchLoop1); acHatch.AppendLoop(hatchLoop2); acTrans.Commit(); } }
private void Create3dProfile(object arg) { try { if (doc != null) { List <ObjectId> toHighlight = new List <ObjectId>(); using (doc.LockDocument()) { Editor ed = doc.Editor; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { //найти координату X начала профиля (крайнюю левую) double minx = double.PositiveInfinity; List <ObjectId> allSelected = new List <ObjectId>(soilHatchIds); foreach (ObjectId id in allSelected) { Entity ent = null; try { ent = (Entity)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } Extents3d?ext = ent.Bounds; if (ext != null) { Point3d minPt = ext.Value.MinPoint; if (minx > minPt.X) { minx = minPt.X; } } } //Штриховки должны быть заранее раскиданы по слоям в соответствии с ИГЭ! //пересчет всех точек штриховок в координаты: //X - положение отностиельно начала профиля с учетом горизонтального масштаба профиля, //Y - отметка расчитанная согласно базовой отметке с учетом вертикального масштаба профиля Matrix2d transform = new Matrix2d(new double[] { HorScaling, 0, 0, 0, VertScaling, 0, 0, 0, 1 }) * Matrix2d.Displacement(new Vector2d(-minx, -ElevBasePoint.Value.Y + ElevationInput / VertScaling)); C5.IntervalHeap <HatchEvent> eventQueue = new C5.IntervalHeap <HatchEvent>(); List <HatchData> allHatchData = new List <HatchData>(); List <Point2dCollection> selfintersectingLoops = new List <Point2dCollection>(); foreach (ObjectId id in soilHatchIds) { //получить все точки штриховок с учетом возможных дуг, сплайнов и проч //Для каждой штриховки создается набор композитных кривых, состоящих из линейных сегментов Hatch hatch = null; try { hatch = (Hatch)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } List <CompositeCurve2d> boundaries = new List <CompositeCurve2d>(); List <Extents2d> extends = new List <Extents2d>(); List <Point2dCollection> ptsCollList = new List <Point2dCollection>(); List <List <double> > ptParamsList = new List <List <double> >(); for (int i = 0; i < hatch.NumberOfLoops; i++) { HatchLoop hl = hatch.GetLoopAt(i); if (!hl.LoopType.HasFlag(HatchLoopTypes.SelfIntersecting) && !hl.LoopType.HasFlag(HatchLoopTypes.Textbox) && !hl.LoopType.HasFlag(HatchLoopTypes.TextIsland) && !hl.LoopType.HasFlag(HatchLoopTypes.NotClosed)) { List <Curve2d> curves = Utils.GetHatchLoopCurves(hl); List <Curve2d> compositeCurveElems = new List <Curve2d>(); double _minx = double.PositiveInfinity; double _miny = double.PositiveInfinity; double _maxx = double.NegativeInfinity; double _maxy = double.NegativeInfinity; Action <Point2d> updateExtends = new Action <Point2d>(p => { _minx = p.X < _minx ? p.X : _minx; _miny = p.Y < _miny ? p.Y : _miny; _maxx = p.X > _maxx ? p.X : _maxx; _maxy = p.Y > _maxy ? p.Y : _maxy; }); Point2dCollection ptsColl = new Point2dCollection(); List <double> ptParams = new List <double>(); double currParam = 0; foreach (Curve2d c in curves) { if (!(c is LineSegment2d)) { Interval interval = c.GetInterval(); PointOnCurve2d[] samplePts = c.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.02); Point2d[] pts = samplePts.Select(p => transform * p.Point).ToArray(); for (int n = 0; n < pts.Length - 1; n++) { LineSegment2d lineSeg = new LineSegment2d(pts[n], pts[n + 1]); compositeCurveElems.Add(lineSeg); ptsColl.Add(pts[n]); ptParams.Add(currParam); updateExtends(pts[n]); currParam += lineSeg.Length; } } else { LineSegment2d lineSeg = (LineSegment2d)c; lineSeg.TransformBy(transform); compositeCurveElems.Add(lineSeg); ptsColl.Add(lineSeg.StartPoint); ptParams.Add(currParam); updateExtends(lineSeg.StartPoint); currParam += lineSeg.Length; } } CompositeCurve2d boundary = new CompositeCurve2d(compositeCurveElems.ToArray()); Extents2d ext = new Extents2d(_minx, _miny, _maxx, _maxy); boundaries.Add(boundary); ptsCollList.Add(ptsColl); ptParamsList.Add(ptParams); extends.Add(ext); } } //контуры штриховок не могут иметь самопересечений! #region Проверка на пересечения //проверка на самопересечения //bool badBoundaries = false; HashSet <int> badBoundaries = new HashSet <int>(); HashSet <int> splitBoundaries = new HashSet <int>();//Если 2 контура в одной штриховке пересекаются, то разносить их по разным штриховкам //List<HatchData> decomposeHatchData = new List<HatchData>();//TODO: самопересекающиеся полигоны нужно разбить на отдельные по количеству самопересечний. for (int i = 0; i < boundaries.Count; i++) { CompositeCurve2d b = boundaries[i]; CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(b, b); if (intersector.NumberOfIntersectionPoints > 0) { //если происходит только наложение??? badBoundaries.Add(i); selfintersectingLoops.Add(ptsCollList[i]); } } if (boundaries.Count > 1) { //проверка на взаимные пересечения. //Исп RBush для того чтобы избежать проверки на пересечение каждого с каждым и квадратичной сложности //(работает только если контуры разнесены) //Не брать в расчет пересечения по касательной RBush <Spatial> boundariesRBush = new RBush <Spatial>(); List <Spatial> spatialData = new List <Spatial>(); for (int i = 0; i < extends.Count; i++) { spatialData.Add(new Spatial(extends[i], i)); } boundariesRBush.BulkLoad(spatialData); foreach (Spatial s in spatialData) { IReadOnlyList <Spatial> nearestNeighbors = boundariesRBush.Search(s.Envelope); if (nearestNeighbors.Count > 1) { CompositeCurve2d thisCurve = boundaries[(int)s.Obj]; foreach (Spatial n in nearestNeighbors) { if (!s.Equals(n)) { CompositeCurve2d otherCurve = boundaries[(int)n.Obj]; CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(thisCurve, otherCurve); if (intersector.NumberOfIntersectionPoints > 0 || intersector.OverlapCount > 0) { bool matches = false; //Проверить, что кривые не накладываются друг на друга по всей длине (то есть полностью совпадают) if (intersector.OverlapCount > 0) { //сумма длин всех интервалов перекрытия равна общей длине кривой double thisCurveOverlapLength = 0; double otherCurveOverlapLength = 0; for (int i = 0; i < intersector.OverlapCount; i++) { Interval[] intervals = intersector.GetOverlapRanges(i); Interval thisOverlapInterval = intervals[0]; thisCurveOverlapLength += thisOverlapInterval.Length; Interval otherOverlapInterval = intervals[1]; otherCurveOverlapLength += otherOverlapInterval.Length; } Interval thisCurveInterval = thisCurve.GetInterval(); Interval otherCurveInterval = otherCurve.GetInterval(); if (Utils.LengthIsEquals(thisCurveOverlapLength, thisCurveInterval.Length) && Utils.LengthIsEquals(otherCurveOverlapLength, otherCurveInterval.Length)) { matches = true; } } if (!matches) { splitBoundaries.Add((int)s.Obj); splitBoundaries.Add((int)n.Obj); } else { badBoundaries.Add((int)s.Obj); badBoundaries.Add((int)n.Obj); } } } } } } } splitBoundaries.ExceptWith(badBoundaries); List <HatchData> splitHatchData = new List <HatchData>(); if (badBoundaries.Count > 0 || splitBoundaries.Count > 0) { List <CompositeCurve2d> boundariesClear = new List <CompositeCurve2d>(); List <Extents2d> extendsClear = new List <Extents2d>(); List <Point2dCollection> ptsCollListClear = new List <Point2dCollection>(); List <List <double> > ptParamsListClear = new List <List <double> >(); for (int i = 0; i < boundaries.Count; i++) { if (!badBoundaries.Contains(i) && !splitBoundaries.Contains(i)) { boundariesClear.Add(boundaries[i]); extendsClear.Add(extends[i]); ptsCollListClear.Add(ptsCollList[i]); ptParamsListClear.Add(ptParamsList[i]); } } foreach (int index in splitBoundaries) { splitHatchData.Add(new HatchData( new HatchNestingNode( boundaries[index], extends[index], ptsCollList[index], ptParamsList[index], hatch))); } boundaries = boundariesClear; extends = extendsClear; ptsCollList = ptsCollListClear; ptParamsList = ptParamsListClear; } #endregion //определяется вложенность контуров штриховки //ЕСЛИ ШТРИХОВКА СОСТОИТ ИЗ 2 И БОЛЕЕ КОНТУРОВ, КОТОРЫЕ НЕ ВЛОЖЕНЫ ДРУГ В ДРУГА, //ТО ЭТИ КОНТУРЫ ДОЛЖНЫ РАССМАТРИВАТЬСЯ КАК ОТДЕЛЬНЫЕ ШТРИХОВКИ!!! HatchNestingTree hatchNestingTree = new HatchNestingTree(boundaries, extends, ptsCollList, ptParamsList, hatch); List <HatchData> currHatchData = hatchNestingTree.GetHatchData(); currHatchData.AddRange(splitHatchData);//добавить контуры, полученные из взаимно пересекающихся контуров //currHatchData.AddRange(decomposeHatchData); allHatchData.AddRange(currHatchData); //Каждая штриховка имеет диапазон по X от начала до конца по оси. //В общую очередь событий сохраняются события начала и конца штриховки foreach (HatchData hd in currHatchData) { hd.AddEventsToQueue(eventQueue); } } //Трассу разбить на отрезки, на которых будут вставлены прямолинейные сегменты штриховок Polyline alignmentPoly = null; try { alignmentPoly = (Polyline)tr.GetObject(AlignmentPolyId, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { return; } int segments = alignmentPoly.NumberOfVertices - 1; List <AlignmentSegment> alignmentSegments = new List <AlignmentSegment>(); Action <Point2d, Point2d> addAlignmentSegment = new Action <Point2d, Point2d>((p0, p1) => { double start = alignmentPoly.GetDistAtPoint(new Point3d(p0.X, p0.Y, 0)); double end = alignmentPoly.GetDistAtPoint(new Point3d(p1.X, p1.Y, 0)); if (Math.Abs(start - end) > Tolerance.Global.EqualPoint)//TODO: Это спорный момент - ведь может быть большое множество очень коротких участков подряд! { Vector2d startDir = p1 - p0; alignmentSegments.Add(new AlignmentSegment(start, end, p0, startDir)); } }); for (int i = 0; i < segments; i++) { SegmentType segmentType = alignmentPoly.GetSegmentType(i); Point2d startLoc = alignmentPoly.GetPoint2dAt(i); Point2d endLoc = alignmentPoly.GetPoint2dAt(i + 1); switch (segmentType) { case SegmentType.Line: addAlignmentSegment(startLoc, endLoc); break; case SegmentType.Arc: CircularArc2d arc = new CircularArc2d(startLoc, endLoc, alignmentPoly.GetBulgeAt(i), false); Interval interval = arc.GetInterval(); PointOnCurve2d[] samplePts = arc.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.1); for (int n = 0; n < samplePts.Length - 1; n++) { addAlignmentSegment(samplePts[n].Point, samplePts[n + 1].Point); } break; } } //проход по каждому отрезку трассы (диапазон отрезка - диапазон длины полилинии) HashSet <HatchData> currentHatchData = new HashSet <HatchData>(); foreach (AlignmentSegment alignmentSegment in alignmentSegments) { if (eventQueue.Count == 0) { break; //штриховки закончились } //Получить те штриховки, диапазон по X которых пересекается с диапазоном текущего отрезка //(СКАНИРУЮЩАЯ ЛИНИЯ: события - начало, конец штриховки) HashSet <HatchData> intervalHatchData = new HashSet <HatchData>(currentHatchData);//штриховки пришедшие из предыдущего участка остаются все //Собрать все события до конца сегмента //Если при проходе от начала до конца сегмента какая-то штриховка проходится полностью от начала до конца, то //все ее контуры без изменений должны быть переданы для создания М-полигона!!! (для них обход графа не нужен!) HashSet <HatchData> startedInsideInterval = new HashSet <HatchData>(); List <HatchData> hatchesCompletelyInsideInterval = new List <HatchData>(); while (eventQueue.Count > 0) { HatchEvent nextEvent = eventQueue.FindMin(); if (nextEvent.Position > alignmentSegment.End) { break; } else if (nextEvent.Start) { //добавить штриховку в текущий набор HatchData hd = eventQueue.DeleteMin().HatchData; currentHatchData.Add(hd); //добавлять в набор текущего интервла только в том случае, //если сканирующая линия еще не дошла до конца интервала if (nextEvent.Position < alignmentSegment.End && !Utils.LengthIsEquals(nextEvent.Position, alignmentSegment.End)) //Допуск нужен { startedInsideInterval.Add(hd); intervalHatchData.Add(hd); } } else { //убрать штриховку из текущего набора HatchData hd = eventQueue.DeleteMin().HatchData; currentHatchData.Remove(hd); if (startedInsideInterval.Contains(hd)) { hatchesCompletelyInsideInterval.Add(hd); } } } foreach (HatchData hd in hatchesCompletelyInsideInterval) { HatchSegmentData hsd = new HatchSegmentData(hd); alignmentSegment.HatchSegmentData.Add(hsd); hsd.Polygons = hd.GetAllBoundaries(); } intervalHatchData.ExceptWith(hatchesCompletelyInsideInterval); foreach (HatchData hd in intervalHatchData) { HatchSegmentData hsd = new HatchSegmentData(hd); alignmentSegment.HatchSegmentData.Add(hsd); //для каждой штриховки выполнить построение и обход графа сегмента штриховки HatchSegmentGraph graph = new HatchSegmentGraph(alignmentSegment.Start, alignmentSegment.End, hd, doc.Editor); //сохранить наборы полигонов для текущего диапазона hsd.Polygons = graph.Result; } } //для каждого диапазона создать полученные полигоны в 3d BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockTableRecord btr = new BlockTableRecord();//Каждый профиль в отдельный блок btr.Name = Guid.NewGuid().ToString(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); foreach (AlignmentSegment alignmentSegment in alignmentSegments) { List <Entity> flatObjs = new List <Entity>(); foreach (HatchSegmentData hsd in alignmentSegment.HatchSegmentData) { //PlaneSurface hsd.GetNesting(); Dictionary <Point2dCollection, List <Point2dCollection> > bwhs = hsd.GetBoundariesWithHoles(); foreach (KeyValuePair <Point2dCollection, List <Point2dCollection> > bwh in bwhs) { //создать Region Region region = null; using (Polyline poly = new Polyline()) { for (int i = 0; i < bwh.Key.Count; i++) { poly.AddVertexAt(i, bwh.Key[i], 0, 0, 0); } poly.Closed = true; DBObjectCollection coll = new DBObjectCollection(); coll.Add(poly); try { DBObjectCollection regionColl = Region.CreateFromCurves(coll); foreach (DBObject dbo in regionColl) { region = (Region)dbo; break; } } catch { } } //из Region создать PlaneSurface if (region != null) { using (PlaneSurface planeSurface = new PlaneSurface()) { planeSurface.CreateFromRegion(region); planeSurface.LayerId = hsd.Hatch.LayerId; planeSurface.ColorIndex = 256; ObjectId planeSurfaceId = ms.AppendEntity(planeSurface); tr.AddNewlyCreatedDBObject(planeSurface, true); //вырезать отверстия в PlaneSurface foreach (Point2dCollection holePts2d in bwh.Value) { if (holePts2d.Count < 3) { continue; } using (Polyline poly = new Polyline()) { for (int i = 0; i < holePts2d.Count; i++) { poly.AddVertexAt(i, holePts2d[i], 0, 0, 0); } poly.Closed = true; ObjectIdCollection trimPolyColl = new ObjectIdCollection(); trimPolyColl.Add(ms.AppendEntity(poly)); tr.AddNewlyCreatedDBObject(poly, true); List <Point2d> ptsList = new List <Point2d>(holePts2d.ToArray()); Point2d pickPt2d = Utils.GetAnyPointInsidePoligon(ptsList, Utils.DirectionIsClockwise(ptsList)); try { AcadDB.Surface.TrimSurface(planeSurfaceId, new ObjectIdCollection(), trimPolyColl, new Vector3dCollection() { Vector3d.ZAxis }, new Point3d(pickPt2d.X, pickPt2d.Y, 0), -Vector3d.ZAxis, false, false); } catch /*(Exception ex)*/ { //Вывод в командную строку Utils.ErrorToCommandLine(doc.Editor, "Ошибка при попытке вырезания отверстия в поверхности" /*, ex*/); } //Удалить все объекты, добавленные в чертеж! poly.Erase(); } } flatObjs.Add((Entity)planeSurface.Clone()); //Удалить все объекты, добавленные в чертеж! planeSurface.Erase(); } region.Dispose(); } } } foreach (Entity ent in flatObjs) { ent.TransformBy(alignmentSegment.Transform); /*ms*/ btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); ent.Dispose(); } } BlockReference br = new BlockReference(Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); if (selfintersectingLoops.Count > 0) { Utils.ErrorToCommandLine(doc.Editor, "Отбраковано самопересекающихся контуров штриховок - " + selfintersectingLoops.Count + " (отмечены на профиле)"); ObjectId layerId = Utils.CreateLayerIfNotExists("САМОПЕРЕСЕКАЮЩИЙСЯ КОНТУР ШТРИХОВКИ", db, tr, color: Color.FromColorIndex(ColorMethod.ByAci, 1), lineWeight: LineWeight.LineWeight200); Matrix2d returnTransform = transform.Inverse(); foreach (Point2dCollection pts in selfintersectingLoops) { using (Polyline selfIntersectingPoly = new Polyline()) { selfIntersectingPoly.LayerId = layerId; selfIntersectingPoly.ColorIndex = 256; for (int i = 0; i < pts.Count; i++) { Point2d pt = pts[i].TransformBy(returnTransform); selfIntersectingPoly.AddVertexAt(i, pt, 0, 0, 0); } toHighlight.Add(ms.AppendEntity(selfIntersectingPoly)); tr.AddNewlyCreatedDBObject(selfIntersectingPoly, true); //selfIntersectingPoly.Highlight(); } } } tr.Commit(); } } ps.Visible = false; if (toHighlight.Count > 0) { using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { foreach (ObjectId id in toHighlight) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); ent.Highlight(); } tr.Commit(); } } } } catch (System.Exception ex) { GeologyConvertationCommand.ClosePalette(null, null); CommonException(ex, "Ошибка при создании 3d профиля геологии"); } }
Entity[] GetComponenty() { Polyline poly0 = new Polyline(); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis + Vector2d.YAxis * 0.8, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.8 + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.5 + Vector2d.YAxis, Math.Tan(0.25 * -1 * Math.PI), 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.5 + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -1 + Vector2d.YAxis, 0, 0, 0); poly0.AddVertexAt(poly0.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -1, 0, 0, 0); poly0.Closed = true; Polyline poly1 = new Polyline(); poly1.AddVertexAt(poly1.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.4 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly1.AddVertexAt(poly1.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * 0.6 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly1.Closed = true; Polyline poly2 = new Polyline(); poly2.AddVertexAt(poly2.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.4 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly2.AddVertexAt(poly2.NumberOfVertices, Point2d.Origin + Vector2d.XAxis * -0.6 + Vector2d.YAxis * 0.25, Math.Tan(0.25 * Math.PI), 0, 0); poly2.Closed = true; Hatch acHatch = new Hatch(); acHatch.SetHatchPattern(HatchPatternType.PreDefined, "BOX"); HatchLoop hLoop0 = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly0.NumberOfVertices; i++) { hLoop0.Polyline.Add(new BulgeVertex(poly0.GetPoint2dAt(i), poly0.GetBulgeAt(i))); } hLoop0.Polyline.Add(new BulgeVertex(poly0.GetPoint2dAt(0), poly0.GetBulgeAt(0))); HatchLoop hLoop1 = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly1.NumberOfVertices; i++) { hLoop1.Polyline.Add(new BulgeVertex(poly1.GetPoint2dAt(i), poly1.GetBulgeAt(i))); } hLoop1.Polyline.Add(new BulgeVertex(poly1.GetPoint2dAt(0), poly1.GetBulgeAt(0))); HatchLoop hLoop2 = new HatchLoop(HatchLoopTypes.Polyline); for (int i = 0; i < poly2.NumberOfVertices; i++) { hLoop2.Polyline.Add(new BulgeVertex(poly2.GetPoint2dAt(i), poly2.GetBulgeAt(i))); } hLoop2.Polyline.Add(new BulgeVertex(poly2.GetPoint2dAt(0), poly2.GetBulgeAt(0))); acHatch.AppendLoop(hLoop0); acHatch.AppendLoop(hLoop1); acHatch.AppendLoop(hLoop2); return(new Entity[4] { poly0, poly1, poly2, acHatch }); }
public static HatchModel Hatch2Model(Hatch dbText) { HatchModel dbModel = new HatchModel(); int cont = dbText.NumberOfLoops; for (int i = 0; i < cont; i++) { dbModel.loopPoints.Add(i, new ColorAndPointItemModel()); HatchLoop loop = dbText.GetLoopAt(i); ColorAndPointItemModel cpModel = new ColorAndPointItemModel(); if (i == 0) { cpModel.Color = dbText.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(dbText.LayerId) : System.Drawing.ColorTranslator.ToHtml(dbText.Color.ColorValue); } else { cpModel.Color = "#FFFFFF"; // cpModel.ZIndex = "1"; } //if (loop.Polyline.Count == 3) //{ //} if (loop.IsPolyline && loop.Polyline.Count > 3) { for (int j = 0; j < loop.Polyline.Count - 1; j++) { BulgeVertex vertex = loop.Polyline[j]; BulgeVertex vertex1 = loop.Polyline[j + 1]; if (vertex.Bulge != 0) { cpModel.loopPoints.AddRange(MethodCommand.GetArcPointsByBulge(vertex.Vertex, vertex1.Vertex, vertex.Bulge)); } else { cpModel.loopPoints.Add(Point2d2Pointf(vertex.Vertex)); } } if (dbText.NumberOfHatchLines > 0) { Line2dCollection cl = dbText.GetHatchLinesData(); } //foreach (Line2d itemi in ) //{ //} } else { Curve2dCollection col_cur2d = loop.Curves; foreach (Curve2d item in col_cur2d) { Point2d[] M_point2d = item.GetSamplePoints(20); foreach (Point2d point in M_point2d) { cpModel.loopPoints.Add(Point2d2Pointf(point)); } } } if (cpModel.loopPoints[0] != cpModel.loopPoints[cpModel.loopPoints.Count - 1]) { cpModel.loopPoints.Add(cpModel.loopPoints[0]); } dbModel.loopPoints[i] = cpModel; } for (int i = 0; i < dbModel.loopPoints.Count; i++) { for (int j = 0; j < dbModel.loopPoints.Count; j++) { if (i != j) { if (MethodCommand.PointsAllInPoints(dbModel.loopPoints[j].loopPoints, dbModel.loopPoints[i].loopPoints)) { dbModel.loopPoints[j].ZIndex = "2"; } } } } try { dbModel.Area = dbText.Area; } catch { } // dbModel.Color = return(dbModel); }
Entity[] MakeGouJian(Param param) { Point2d[] p2ds = new Point2d[] { Point2d.Origin, Point2d.Origin + Vector2d.YAxis * param.A, Point2d.Origin + Vector2d.YAxis * param.A - Vector2d.XAxis * param.D, Point2d.Origin + Vector2d.YAxis * param.B - Vector2d.XAxis * (param.C - param.E), Point2d.Origin + Vector2d.YAxis * param.B - Vector2d.XAxis * param.C, Point2d.Origin - Vector2d.XAxis * param.C }; Vector2d vec1 = p2ds[1] - p2ds[2]; Vector2d vec2 = p2ds[3] - p2ds[2]; //倒角 Point2d[] AnglePoint = GetAnglePoint(p2ds[2], vec1, vec2, 0.1); Vector2d vec3 = p2ds[0] - p2ds[1]; Vector2d vec4 = p2ds[2] - p2ds[1]; Point2d[] AnglePoint0 = GetAnglePoint(p2ds[1], vec3, vec4, 0.1); Polyline pline0 = EntityHelper.CreatePolygon( new double[] { p2ds[0].X, p2ds[0].Y, AnglePoint0[1].X, AnglePoint0[1].Y, AnglePoint0[0].X, AnglePoint0[0].Y, p2ds[1].X - param.D * 0.5, p2ds[1].Y, AnglePoint[1].X, AnglePoint[1].Y, AnglePoint[0].X, AnglePoint[0].Y, p2ds[3].X, p2ds[3].Y, p2ds[4].X, p2ds[4].Y, p2ds[5].X, p2ds[5].Y, }, new Tuple <int, double>[] { Tuple.Create(4, Math.Tan((Math.PI - vec2.GetAngleTo(vec1)) / 4)), Tuple.Create(1, Math.Tan((Math.PI - vec4.GetAngleTo(vec3)) / 4)) }, null, null ); AlignedDimension alignDim1 = new AlignedDimension(Point3d.Origin, Point3d.Origin + Vector3d.YAxis * param.A, Point3d.Origin + Vector3d.XAxis * 0.5, null, ObjectId.Null); AlignedDimension alignDim2 = new AlignedDimension(Point3d.Origin + Vector3d.YAxis * param.A, Point3d.Origin + Vector3d.YAxis * param.A - Vector3d.XAxis * param.D, Point3d.Origin + Vector3d.YAxis * 3.5, null, ObjectId.Null); AlignedDimension alignDim3 = new AlignedDimension(Point3d.Origin + Vector3d.YAxis * param.B - Vector3d.XAxis * (param.C - param.E), Point3d.Origin + Vector3d.YAxis * param.B - Vector3d.XAxis * param.C, Point3d.Origin + Vector3d.YAxis * (param.B + 0.5), null, ObjectId.Null); AlignedDimension alignDim4 = new AlignedDimension(Point3d.Origin + Vector3d.YAxis * param.B - Vector3d.XAxis * param.C, Point3d.Origin - Vector3d.XAxis * param.C, Point3d.Origin - Vector3d.XAxis * (param.C + 0.5), null, ObjectId.Null); AlignedDimension alignDim5 = new AlignedDimension(Point3d.Origin - Vector3d.XAxis * param.C, Point3d.Origin, Point3d.Origin - Vector3d.YAxis * 0.5, null, ObjectId.Null); LineAngularDimension2 langularDim = new LineAngularDimension2(new Point3d(p2ds[3].X, p2ds[3].Y, 0), new Point3d(p2ds[2].X, p2ds[2].Y, 0), new Point3d(p2ds[3].X, p2ds[3].Y, 0), new Point3d(p2ds[4].X, p2ds[4].Y, 0), new Point3d(p2ds[3].X - 0.8, p2ds[3].Y + 0.8, 0), null, ObjectId.Null ); Xline xline = new Xline() { BasePoint = new Point3d(0, param.A * 0.5, 0), UnitDir = Vector3d.XAxis }; DBText d1 = new DBText() { TextString = "A", Position = new Point3d(-0.15, param.A * 0.5, 0) }; HatchLoop hLoop = new HatchLoop(HatchLoopTypes.Polyline); foreach (var i in Enumerable.Range(0, pline0.NumberOfVertices)) { hLoop.Polyline.Add(new BulgeVertex(pline0.GetPoint2dAt(i), pline0.GetBulgeAt(i))); } Hatch hatch = new Hatch(); hatch.SetHatchPattern(HatchPatternType.PreDefined, "BOX"); hatch.AppendLoop(hLoop); return(new Entity[] { pline0, alignDim1, alignDim2, alignDim3, alignDim4, alignDim5, d1, hatch, langularDim, xline }); }
private void CreateProfile(object arg) { try { if (doc != null) { using (doc.LockDocument()) { Editor ed = doc.Editor; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { //выбрать базовую точку снизу слева double minx = double.PositiveInfinity; double miny = double.PositiveInfinity; List <ObjectId> allSelected = new List <ObjectId>(soilHatchIds); allSelected.Add(groundSurfPolyId); foreach (ObjectId id in allSelected) { Entity ent = null; try { ent = (Entity)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } Extents3d?ext = ent.Bounds; if (ext != null) { Point3d minPt = ext.Value.MinPoint; if (minx > minPt.X) { minx = minPt.X; } if (miny > minPt.Y) { miny = minPt.Y; } } } Point2d basePt = new Point2d(minx, miny); //для трансформации координат //Vector2d baseVector = new Vector2d(minx, miny); Matrix2d transform = new Matrix2d(new double[] { StartHorScaling, 0, 0, 0, StartVertScaling, 0, 0, 0, 1 }) * Matrix2d.Displacement(new Vector2d(-minx, -miny)); //полилиния поверхности земли //???????координаты точек полилинии расчитываются относительно базовой точки (и пересчитываются в метры согласно введенным коэффициентам?) //отсортировать список сточек по координате X. //ПОИСК ПО ДИАПАЗОНУ: //Использовать бинарный поиск (https://www.baeldung.com/java-binary-search) для нахождения хотябы одной точки в заданном диапазоне //затем проверять соседние точки на нахождение в диапазоне Polyline poly = null; try { poly = (Polyline)tr.GetObject(groundSurfPolyId, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { return; } ObjectId groundSurfLayerId = poly.LayerId; List <Point2d> polyPts = new List <Point2d>(); for (int i = 0; i < poly.NumberOfVertices; i++) { Point2d pt = poly.GetPoint2dAt(i); pt = transform * pt; //pt = pt - baseVector; //pt = new Point2d(pt.X * StartHorScaling, pt.Y * StartVertScaling); polyPts.Add(pt); } polyPts.Sort((a, b) => { return(a.X.CompareTo(b.X)); }); double depthMultipier = StartVertSoilScaling / StartVertScaling; //для каждой штриховки получить все контуры //любые контуры должны быть переведены в полигоны без кривизны //???????координаты точек полигонов расчитываются относительно базовой точки (и пересчитываются в метры согласно введенным коэффициентам?) //для каждой точки полигона должно быть расчитано заглубление относительно поверхности земли //если между двумя точками полигона по гоизонтали есть точки перелома поверхности земли, //то для этих точек должны быть добавлены соответствующие точки полигона List <HatchData> hatchData = new List <HatchData>(); foreach (ObjectId id in soilHatchIds) { Hatch hatch = null; try { hatch = (Hatch)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } HatchData hd = new HatchData(hatch); hatchData.Add(hd); for (int i = 0; i < hatch.NumberOfLoops; i++) { HatchLoop hl = hatch.GetLoopAt(i); if (!hl.LoopType.HasFlag(HatchLoopTypes.SelfIntersecting) && !hl.LoopType.HasFlag(HatchLoopTypes.Textbox) && !hl.LoopType.HasFlag(HatchLoopTypes.TextIsland) && !hl.LoopType.HasFlag(HatchLoopTypes.NotClosed)) { List <Point2d> polygon = new List <Point2d>(); hd.Polygons.Add(polygon); List <Curve2d> curves = Utils.GetHatchLoopCurves(hl); foreach (Curve2d c in curves) { if (!(c is LineSegment2d)) { Interval interval = c.GetInterval(); PointOnCurve2d[] samplePts = c.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.02); for (int n = 0; n < samplePts.Length - 1; n++) { ProcessLineSegmentOfHatch(samplePts[n].Point, samplePts[n + 1].Point, polygon, polyPts, transform, /*baseVector, StartHorScaling, StartVertScaling,*/ depthMultipier); } } else { ProcessLineSegmentOfHatch(c.StartPoint, c.EndPoint, polygon, polyPts, transform, /*baseVector, StartHorScaling, StartVertScaling,*/ depthMultipier); } } } } } //указание пользователем точки вставки нового профиля //создание полилиний //координаты точек пересчитываются заданным масштабным коэффициентам // PromptPointOptions pPtOpts = new PromptPointOptions("\nУкажите точку вставки"); PromptPointResult pPtRes = doc.Editor.GetPoint(pPtOpts); if (pPtRes.Status == PromptStatus.OK) { BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); DrawOrderTable drawOrder = tr.GetObject(ms.DrawOrderTableId, OpenMode.ForWrite) as DrawOrderTable; ObjectId continLtId = Utils.GetContinuousLinetype(db); Point2d insertPt = Utils.Point2DBy3D(pPtRes.Value); //Vector2d insertVec = new Vector2d(insertPt.X, insertPt.Y); Matrix2d insertTransform = Matrix2d.Displacement(new Vector2d(insertPt.X, insertPt.Y)) * new Matrix2d(new double[] { 1 / EndHorScaling, 0, 0, 0, 1 / EndVertScaling, 0, 0, 0, 1 }); //полилиния поверхности земли using (Polyline surfGroundPoly = new Polyline()) { surfGroundPoly.LayerId = groundSurfLayerId; surfGroundPoly.ColorIndex = 256; surfGroundPoly.LinetypeId = continLtId; for (int i = 0; i < polyPts.Count; i++) { Point2d pt = polyPts[i]; //Point2d convertedPt = new Point2d(pt.X / EndHorScaling, pt.Y / EndVertScaling); //convertedPt = convertedPt + insertVec; Point2d convertedPt = insertTransform * pt; surfGroundPoly.AddVertexAt(i, convertedPt, 0, 0, 0); } ms.AppendEntity(surfGroundPoly); tr.AddNewlyCreatedDBObject(surfGroundPoly, true); } //полилинии штриховок //HashSet<ObjectId> createdLayers = new HashSet<ObjectId>(); ObjectIdCollection hatchIds = new ObjectIdCollection(); foreach (HatchData hd in hatchData) { /* * double patternScale = hd.Hatch.PatternScale; * * string layerName = patternScale != 1 ? hd.Hatch.PatternName + "_" + patternScale.ToString("f2") : hd.Hatch.PatternName; * * ObjectId hatchLayerId = Utils.CreateLayerIfNotExists(layerName, db, tr, * lineWeight: LineWeight.LineWeight030); * createdLayers.Add(hatchLayerId); */ ObjectIdCollection polyIds = new ObjectIdCollection(); foreach (List <Point2d> polygon in hd.Polygons) { if (polygon.Count > 0) { using (Polyline geologPoly = new Polyline()) { geologPoly.LayerId = hd.Hatch.LayerId; //hatchLayerId; geologPoly.ColorIndex = 256; geologPoly.LinetypeId = continLtId; for (int i = 0; i < polygon.Count; i++) { Point2d pt = polygon[i]; //Point2d convertedPt = new Point2d(pt.X / EndHorScaling, pt.Y / EndVertScaling); //convertedPt = convertedPt + insertVec; Point2d convertedPt = insertTransform * pt; geologPoly.AddVertexAt(i, convertedPt, 0, 0, 0); } geologPoly.Closed = true; ObjectId id = ms.AppendEntity(geologPoly); tr.AddNewlyCreatedDBObject(geologPoly, true); if (!id.IsNull && id.IsValid) { polyIds.Add(id); } } } } if (polyIds.Count > 0) { try { using (Hatch oHatch = /*(Hatch)hd.Hatch.Clone()*/ new Hatch()) { oHatch.LayerId = hd.Hatch.LayerId; //hatchLayerId; Vector3d normal = new Vector3d(0.0, 0.0, 1.0); oHatch.Normal = normal; oHatch.Elevation = 0.0; oHatch.PatternScale = hd.Hatch.PatternScale; //oHatch.SetHatchPattern(hd.Hatch.PatternType, hd.Hatch.PatternName); oHatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID"); oHatch.ColorIndex = 256; //while (oHatch.NumberOfLoops>0) //{ // oHatch.RemoveLoopAt(0); //} ObjectId hatchId = ms.AppendEntity(oHatch); tr.AddNewlyCreatedDBObject(oHatch, true); oHatch.Associative = true; foreach (ObjectId polyId in polyIds) { oHatch.AppendLoop(HatchLoopTypes.Default, new ObjectIdCollection() { polyId }); } oHatch.EvaluateHatch(true); if (!hatchId.IsNull && hatchId.IsValid) { hatchIds.Add(hatchId); } } } catch { } } } /* * short colorIndex = 1; * foreach (ObjectId layerId in createdLayers) * { * LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForWrite); * ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, colorIndex); * * colorIndex = Convert.ToByte((colorIndex + 1) % 256); * } */ drawOrder.MoveToBottom(hatchIds); //GeologyConvertationCommand.ClosePalette(null, null); ps.Visible = false; } tr.Commit(); } } } } catch (System.Exception ex) { GeologyConvertationCommand.ClosePalette(null, null); CommonException(ex, "Ошибка при переводе масштаба профиля геологии"); } }
// 获取实体信息 public void GetEntitiesInfo(ArrayList entities, Transaction trans, BlockTableRecord btr, int numSample, Document doc, Editor ed) { ArrayList uuid = new ArrayList(); ArrayList geom = new ArrayList(); // 坐标点集合 ArrayList colorList = new ArrayList(); // 颜色集合 ArrayList type = new ArrayList(); // 类型集合 ArrayList layerName = new ArrayList(); ArrayList tableName = new ArrayList(); // 表名 System.Data.DataTable attributeList = new System.Data.DataTable(); // 属性集合 ArrayList attributeIndexList = new ArrayList(); //属性索引集合 ArrayList tuliList = new ArrayList(); //图例集合 string projectId = ""; //项目ID string chartName = ""; //表名称 ArrayList kgGuide = new ArrayList(); //控规引导 string srid = ""; //地理坐标系统编号 ArrayList parentId = new ArrayList(); //配套设施所在地块集合 ArrayList textContent = new ArrayList(); // 文字内容(GIS端展示) ArrayList blockContent = new ArrayList(); // 块内容(GIS端展示) Dictionary <string, string> result = new Dictionary <string, string>(); // 汇总 // 遍历所有实体 foreach (object entity in entities) { ArrayList singlePositionList = new ArrayList(); // 单个实体坐标点集合 //取得边界数 int loopNum = 1; if (entity is Hatch) { loopNum = (entity as Hatch).NumberOfLoops; type.Add("polygon"); } Point3dCollection col_point3d = new Point3dCollection(); BulgeVertexCollection col_ver = new BulgeVertexCollection(); Curve2dCollection col_cur2d = new Curve2dCollection(); for (int i = 0; i < loopNum; i++) { col_point3d.Clear(); HatchLoop hatLoop = null; if (entity is Hatch) { try { hatLoop = (entity as Hatch).GetLoopAt(i); } catch (System.Exception) { continue; } //如果HatchLoop为PolyLine if (hatLoop.IsPolyline) { col_ver = hatLoop.Polyline; foreach (BulgeVertex vertex in col_ver) { col_point3d.Add(new Point3d(vertex.Vertex.X, vertex.Vertex.Y, 0)); } } } // 如果实体为Polyline if (entity is Polyline) { // 类型 type.Add("polyline"); Polyline polyline = (Polyline)entity; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); } } //// 如果实体为Curve //if (entity is Curve) //{ // col_cur2d = hatLoop.Curves; // foreach (Curve2d item in col_cur2d) // { // Point2d[] M_point2d = item.GetSamplePoints(numSample); // foreach (Point2d pt in M_point2d) // { // if (!col_point3d.Contains(new Point3d(pt.X, pt.Y, 0))) // col_point3d.Add(new Point3d(pt.X, pt.Y, 0)); // } // } //} // 如果实体为Point2d if (entity is DBPoint) { type.Add("point"); DBPoint entity3 = (DBPoint)entity; col_point3d.Add(new Point3d(entity3.Position.X, entity3.Position.Y, 0)); } // 如果实体为Point if (entity is Point3d) { type.Add("point"); Point3d entity3 = (Point3d)entity; col_point3d.Add(entity3); } // 如果实体为文字 if (entity is MText) { type.Add("text"); col_point3d.Add(new Point3d((entity as MText).Location.X, (entity as MText).Location.Y, 0)); } // 如果实体为文字 if (entity is DBText) { type.Add("text"); col_point3d.Add(new Point3d((entity as DBText).Position.X, (entity as DBText).Position.Y, 0)); } // 块参照 if (entity is BlockReference) { type.Add("block"); col_point3d.Add(new Point3d((entity as BlockReference).Position.X, (entity as BlockReference).Position.Y, 0)); } double[] pointPositionList = new double[2]; //单个点的坐标点集合 // 经纬度转换 foreach (Point3d point in col_point3d) { pointPositionList = new double[2] { Transform(point)[0], Transform(point)[1] }; singlePositionList.Add(pointPositionList); } // 经纬度转换结束 } // 单个实体几何坐标数量循环结束 // UUID Entity entityLayer = (Entity)entity; Guid guid = new Guid(); guid = Guid.NewGuid(); string str = guid.ToString(); uuid.Add(str); // 坐标 geom.Add(singlePositionList); // 颜色 if (entity is Point3d) { colorList.Add(""); // 图层名 layerName.Add("无"); } else { LayerTableRecord ltr = (LayerTableRecord)trans.GetObject(entityLayer.LayerId, OpenMode.ForRead); string color; color = entityLayer.ColorIndex == 256 ? MethodCommand.GetLayerColorByID(entityLayer.LayerId) : ColorTranslator.ToHtml(entityLayer.Color.ColorValue); colorList.Add(color); // 图层名 layerName.Add(ltr.Name); } // 表名 tableName.Add("a"); // 属性索引 // 获取每个闭合多段线对应的个体编号和用地代号 ArrayList tagList = new ArrayList(); PromptSelectionResult psrss = ed.SelectCrossingPolygon(col_point3d); // 获取闭合区域内实体方法 if (psrss.Status == PromptStatus.OK) { tagList.Clear(); SelectionSet SS = psrss.Value; ObjectId[] idArray = SS.GetObjectIds(); // 如果读取的块参照数量大于1,取中心点在闭合多段线的块参照 if (idArray.Length > 1) { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { BlockReference ent2 = (BlockReference)ent1; if (IsInPolygon(ent2.Position, col_point3d)) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); //MessageBox.Show("Tag: " + acAttRef.Tag + "\n" + // "Value: " + acAttRef.TextString + "\n"); } } } } } // 如果读取的块参照数量等于1,取中心点在闭合多段线的块参照 else { for (int i = 0; i < idArray.Length; i++) { Entity ent1 = (Entity)idArray[i].GetObject(OpenMode.ForRead); if (ent1 is BlockReference) { foreach (ObjectId rt in ((BlockReference)ent1).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; tagList.Add(acAttRef.TextString); } } } } } // 如果地块编码属性只有两个属性值,attributeIndexList,如果少于2个或者多于2个都视为异常,添加空。 if (tagList.Count == 2) { attributeIndexList.Add(tagList[0] + "_" + tagList[1]); } else { attributeIndexList.Add(""); } // 属性 readAttributeList attributeListObj = new readAttributeList(); attributeList = attributeListObj.AttributeList(); // 配套设施所属的地块UUID // 获取块参照的属性值 ArrayList blockAttribute = new ArrayList(); // 是否是地块编码本身 string isBlockNum = ""; // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID if (entity is BlockReference) { // 清除原有内容 blockAttribute.Clear(); // 如果entity有两个属性值,可以判断这是一个地块编码 if (((BlockReference)entity).AttributeCollection.Count == 2) { isBlockNum = "Block"; } // 获取地块界限图层上的所有实体 ArrayList polylineEntities = new ArrayList(); // 找出地块界限里的所有闭合多段线,并判断当前块标注实体是否在某一个闭合多段线内,如果在,找出该闭合多段线内的块参照个体编号 TypedValue[] tvs = new TypedValue[1] { new TypedValue( (int)DxfCode.LayerName, "地块界限" ) }; SelectionFilter sf = new SelectionFilter(tvs); PromptSelectionResult psr = ed.SelectAll(sf); if (psr.Status == PromptStatus.OK) { SelectionSet SS = psr.Value; ObjectId[] idArray = SS.GetObjectIds(); //MessageBox.Show(idArray.Length.ToString()); Point3dCollection polylinePoint3d = new Point3dCollection(); for (int j = 0; j < idArray.Length; j++) { // 清除原有内容 polylinePoint3d.Clear(); Entity ent1 = trans.GetObject(idArray[j], OpenMode.ForWrite) as Entity; if (ent1 is Polyline && (ent1 as Polyline).Closed) { Polyline polyline = (Polyline)ent1; int vn = polyline.NumberOfVertices; for (int w = 0; w < vn; w++) { Point2d pt = polyline.GetPoint2dAt(w); polylinePoint3d.Add(new Point3d(pt.X, pt.Y, 0)); } // 获取闭合多段线(地块)内的所有实体 PromptSelectionResult psrss2 = ed.SelectCrossingPolygon(polylinePoint3d); if (psrss2.Status == PromptStatus.OK) { SelectionSet SS2 = psrss2.Value; ObjectId[] idArray2 = SS2.GetObjectIds(); // 如果读取的块参照数量大于1,且包含当前实体,找出当前块参照所在的闭合多段线 if (idArray2.Length > 1) { for (int i = 0; i < idArray2.Length; i++) { Entity ent2 = (Entity)idArray2[i].GetObject(OpenMode.ForRead); // 判断是否是配套设施开始 if (ent2 is BlockReference && (ent2 as BlockReference).Position.X == (entity as BlockReference).Position.X) { for (int k = 0; k < idArray2.Length; k++) { Entity ent3 = (Entity)idArray2[k].GetObject(OpenMode.ForRead); if (ent3 is BlockReference) { // 判断块参照中心点是否在闭合多段线内,只读取中心点在闭合多段线内的块参照 if (IsInPolygon((ent3 as BlockReference).Position, polylinePoint3d)) { foreach (ObjectId rt in ((BlockReference)ent3).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; blockAttribute.Add(acAttRef.TextString); } } } } } // 判断是否是配套设施结束 } } } // 获取闭合多段线(地块)内的所有实体结束 } } } } // 如果这个块标注是幼儿园、公厕等,找对对应的地块编号或UUID 结束 // 如果地块编码属性只有两个属性值,而且不是地块编码块参照,添加到parentId,如果少于2个或者多于2个都视为异常,添加空。 if (blockAttribute.Count == 2 && isBlockNum != "Block") { parentId.Add(blockAttribute[0] + "_" + blockAttribute[1]); } else { parentId.Add(""); } // 文字内容(GIS端展示) if (entity is DBText) { textContent.Add((entity as DBText).TextString); } else if (entity is MText) { textContent.Add((entity as MText).Text); } else if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = ""; if ((entity as BlockReference).AttributeCollection.Count > 0) { foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = text + acAttRef.TextString + "//"; } text = text.Substring(0, text.Length - 2); } textContent.Add(text); } else { textContent.Add(""); } // 块内容(GIS端展示) if (entity is BlockReference) { List <string> singleBlockContent = new List <string>(); string text = "//"; foreach (ObjectId rt in ((BlockReference)entity).AttributeCollection) { DBObject dbObj = trans.GetObject(rt, OpenMode.ForRead) as DBObject; AttributeReference acAttRef = dbObj as AttributeReference; text = acAttRef.TextString + text; //singleBlockContent.Add(acAttRef.TextString); } blockContent.Add(text); //blockContent.Add(singleBlockContent); } else { blockContent.Add(""); } } // 所有的实体循环结束 // 图例 readAttributeList attributeListObj3 = new readAttributeList(); //tuliList.Add(attributeListObj3.TuliList()); tuliList.Add(""); // 项目名 //string projectIdBaseAddress = "http://172.18.84.70:8081/PDD/pdd/individual-manage!findAllProject.action"; //var projectIdHttp = (HttpWebRequest)WebRequest.Create(new Uri(projectIdBaseAddress)); //var response = projectIdHttp.GetResponse(); //var stream = response.GetResponseStream(); //var sr = new StreamReader(stream, Encoding.UTF8); //var content = sr.ReadToEnd(); //MessageBox.Show(content); projectId = "D3DEC178-2C05-C5F1-F6D3-45729EB9436A"; // 图表名或者叫文件名 chartName = Path.GetFileName(ed.Document.Name); // 控规引导 readAttributeList attributeListObj2 = new readAttributeList(); kgGuide = attributeListObj2.KgGuide(); //地理坐标系统编号 srid = "4326"; // 发文字信息 RegulatoryPost.FenTuZe.FenTuZe.SendData(result, uuid, geom, colorList, type, layerName, tableName, attributeIndexList, attributeList, tuliList, projectId, chartName, kgGuide, srid, parentId, textContent, blockContent); }
private ObjectId ProcessEntity(Hatch hatch, BlockTable bt) { //Для создания контура штриховки //Hatch.NumberOfLoops //Hatch.GetLoopAt //HatchLoop.Polyline!!! //Получить полилинии List <Polyline> polylines = new List <Polyline>(); for (int i = 0; i < hatch.NumberOfLoops; i++) { HatchLoop hl = hatch.GetLoopAt(i); BulgeVertexCollection bvc = hl.Polyline; Curve2dCollection cc = hl.Curves; Polyline poly = null; if (bvc != null && bvc.Count > 0) { //сюда попадет если контур состоит из отрезков и круговых дуг poly = new Polyline(); int vertNum = 0; foreach (BulgeVertex bv in bvc) { poly.AddVertexAt(vertNum, bv.Vertex, bv.Bulge, 0, 0); vertNum++; } } else if (cc != null && cc.Count > 0) { //сюда попадет если контур состоит только из отрезков или включает сложные линии (сплайны, эллипсы) poly = new Polyline(); //добавить первую вершину //poly.AddVertexAt(0, cc[0].StartPoint, 0, 0, 0); int vertNum = 0; foreach (Curve2d c in cc) { if (c is LinearEntity2d) { //добавить сегмент без кривизны LinearEntity2d l2d = c as LinearEntity2d; poly.AddVertexAt(vertNum, l2d.EndPoint, 0, 0, 0); vertNum++; } else { //просто пропустить эту кривую (может это сплайн или еще чего) //throw new System.Exception("Неверный тип 2d кривой - " + c.GetType().ToString()); } } } if (poly != null && poly.NumberOfVertices > 1) { //присвоить слой штриховки poly.LayerId = hatch.LayerId; //замкнуть poly.Closed = true; polylines.Add(poly); } } //Создать новый блок и сохранить в него полилинии ObjectId createdBtrId = ObjectId.Null; Database db = bt.Database; if (polylines.Count > 0) { using (Transaction tr = db.TransactionManager.StartTransaction()) { //Создать новый блок для сохранения замкнутых контуров BlockTableRecord btr = new BlockTableRecord(); btr.Name = n.ToString(); n++; createdBtrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); if (createdBtrId != ObjectId.Null) { foreach (Polyline p in polylines) { btr.AppendEntity(p); tr.AddNewlyCreatedDBObject(p, true); } } tr.Commit(); } } return(createdBtrId); }
void HatchPerimeter(ObjectId entId) { Document activeDoc = Application.DocumentManager.MdiActiveDocument; Database db = activeDoc.Database; Editor ed = activeDoc.Editor; using (Transaction tr = db.TransactionManager.StartTransaction()) { Hatch hatch = tr.GetObject(entId, OpenMode.ForRead) as Hatch; int nLoops = hatch.NumberOfLoops; double totalExternalPerimeter = 0.0; double totalInternalPerimeter = 0.0; for (int i = 0; i < nLoops; i++) { double loopLength = 0.0; HatchLoopTypes hlt = hatch.LoopTypeAt(i); HatchLoop hatchLoop = hatch.GetLoopAt(i); if ((hatch.LoopTypeAt(i) & HatchLoopTypes.Polyline) == HatchLoopTypes.Polyline) { BulgeVertexCollection bulges = hatchLoop.Polyline; int nVertices = bulges.Count; Polyline testPoly = new Polyline(nVertices); for (int vx = 0; vx < bulges.Count; vx++) { BulgeVertex bv = bulges[vx]; testPoly.AddVertexAt(vx, bv.Vertex, bv.Bulge, 1.0, 1.0); } LineSegment3d ls = new LineSegment3d(); CircularArc3d cs = new CircularArc3d(); double d = 0.0, p1 = 0.0, p2 = 1.0; for (int ver = 0; ver < nVertices - 1; ver++) { d = testPoly.GetBulgeAt(ver); if (d <= 1e-5) { ls = testPoly.GetLineSegmentAt(ver); loopLength += ls.Length; } else { Point2d v1 = new Point2d(bulges[ver].Vertex.X, bulges[ver].Vertex.Y); Point2d v2 = new Point2d(bulges[ver + 1].Vertex.X, bulges[ver + 1].Vertex.Y); if (v1.IsEqualTo(v2) == false) { cs = testPoly.GetArcSegmentAt(ver); p1 = cs.GetParameterOf(cs.StartPoint); p2 = cs.GetParameterOf(cs.EndPoint); loopLength += cs.GetLength (p1, p2, Tolerance.Global.EqualPoint); } } } } else { Curve2dCollection curves = hatchLoop.Curves; if (curves != null) { foreach (Curve2d curve in curves) { if (hatchLoop.LoopType == HatchLoopTypes.External) { totalExternalPerimeter += curve.GetLength(0.0, 1.0); } else { totalInternalPerimeter += curve.GetLength(0.0, 1.0); } } } } if (nLoops > 1 && ((hlt & HatchLoopTypes.External) != HatchLoopTypes.External)) { totalInternalPerimeter += loopLength; } else { totalExternalPerimeter += loopLength; } } ed.WriteMessage(string.Format("\nExternal Perimeter : {0}", totalExternalPerimeter)); ed.WriteMessage(string.Format("\nInternal Perimeter : {0}", totalInternalPerimeter)); tr.Commit(); } }