using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
// 使用别名解决Exception冲突
using AcadException = Autodesk.AutoCAD.Runtime.Exception;
using SysException = System.Exception;
namespace ScaffoldPlugin
{
public class ScaffoldGenerator
{
// 图块尺寸映射
private static readonly Dictionary<string, int> BlockSizes = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
// 立杆
{“ScaffoldPole立杆200mm”, 200},
{“ScaffoldPole立杆350mm”, 350},
{“ScaffoldPole立杆500mm”, 500},
{“ScaffoldPole立杆1000mm”, 1000},
{“ScaffoldPole立杆1500mm”, 1500},
{“ScaffoldPole立杆2000mm”, 2000},
{“ScaffoldPole立杆2500mm”, 2500},
// 横杆 {"ScaffoldPole立横杆300mm", 300}, {"ScaffoldPole立横杆600mm", 600}, {"ScaffoldPole立横杆900mm", 900}, {"ScaffoldPole立横杆1200mm", 1200}, {"ScaffoldPole立横杆1500mm", 1500}, {"ScaffoldPole立横杆1800mm", 1800}, // 附件 {"ScaffoldPole顶托", 0}, // 顶托高度 {"ScaffoldPole顶托螺母", 0}, // 螺母高度 {"ScaffoldPole连接盘", 0} // 连接盘高度 }; // 常量定义 private const double FirstBarHeight = 250.0; // 第一道横杆高度 private const double HorizontalBarSpacing = 1500.0; // 横杆步距 private const double StandardDiskOffset = 250.0; // 标准立杆第一个盘距根部高度 private const double Tolerance = 5.0; // 位置容差 private const double NutOffset = 75.0; // 螺母相对于立杆顶部的偏移量 private const double MinTopGap = 200.0; // 最小顶部间隙 private const double MaxTopGap = 400.0; // 最大顶部间隙 private const double RelaxedTolerance = 25.0; // 放大的容差用于连接盘检测 private const double MaxBarDistance = 2000.0; // 最大横杆跨度 private Editor _ed; private string _blocksFolderPath; private Curve _topControlLine; private bool _isAscending; // 立杆高度是否递增 // 存储所有连接盘位置 [X坐标 -> 连接盘Y坐标列表] private readonly Dictionary<double, List<double>> _diskPositions = new Dictionary<double, List<double>>(); // 存储顶托位置 [X坐标 -> 顶托Y坐标] private readonly Dictionary<double, double> _adjusterPositions = new Dictionary<double, double>(); // 存储最后一根立杆信息 [X坐标 -> 最后一根立杆尺寸] private readonly Dictionary<double, int> _lastPoleSizes = new Dictionary<double, int>(); // 存储立杆底部位置 [X坐标 -> 底部Y坐标] private readonly Dictionary<double, double> _poleBasePositions = new Dictionary<double, double>(); [CommandMethod("GS", CommandFlags.Modal)] public void GenerateScaffold() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; _ed = doc.Editor; try { // 初始化图块文件夹路径 _blocksFolderPath = GetBlocksFolderPath(); if (string.IsNullOrEmpty(_blocksFolderPath)) { _ed.WriteMessage("\n错误: 图块文件夹路径无效"); return; } // 加载所有图块定义 LoadAllBlockDefinitions(db); // 框选图块 var blockRefs = SelectBlocks(); if (blockRefs == null || blockRefs.Count == 0) return; // 选择控制线 _ed.WriteMessage("\n选择底标高水平控制线"); var baseLine = SelectControlLine(); if (baseLine == null) return; _ed.WriteMessage("\n选择顶部控制线"); _topControlLine = SelectControlLine(); if (_topControlLine == null) return; // 获取控制线高度 double baseElev = GetLineElevation(baseLine); using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite); // 清空位置记录 _diskPositions.Clear(); _adjusterPositions.Clear(); _lastPoleSizes.Clear(); _poleBasePositions.Clear(); // 立杆布置 int poleCount = LayoutVerticalPoles(tr, bt, btr, blockRefs, baseElev); _ed.WriteMessage($"\n已布置 {poleCount} 根立杆。"); // 横杆布置 int barCount = LayoutHorizontalBars(tr, bt, btr, blockRefs, baseElev); _ed.WriteMessage($"\n已布置 {barCount} 根横杆。"); tr.Commit(); } _ed.WriteMessage("\n盘扣支模架生成完成!"); } catch (AcadException acadEx) // AutoCAD特有异常 { HandleAcadException(acadEx); } catch (SysException sysEx) // 系统异常 { _ed.WriteMessage($"\n系统错误: {sysEx.Message}"); } } // 处理AutoCAD特有异常 private void HandleAcadException(AcadException acadEx) { if (acadEx.ErrorStatus == ErrorStatus.UserBreak) { _ed.WriteMessage("\n操作已取消"); } else { _ed.WriteMessage($"\nAutoCAD错误: {acadEx.ErrorStatus} - {acadEx.Message}"); } } // 获取图块文件夹路径 private string GetBlocksFolderPath() { try { string assemblyPath = Assembly.GetExecutingAssembly().Location; string pluginDir = Path.GetDirectoryName(assemblyPath); return Path.Combine(pluginDir, "ScaffoldBlocks"); } catch { return null; } } // 加载所有图块定义 private void LoadAllBlockDefinitions(Database db) { if (string.IsNullOrEmpty(_blocksFolderPath)) return; try { string[] blockFiles = Directory.GetFiles(_blocksFolderPath, "*.dwg"); if (blockFiles.Length == 0) return; using (Transaction tr = db.TransactionManager.StartTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (string filePath in blockFiles) { string fileName = Path.GetFileNameWithoutExtension(filePath); if (!BlockSizes.ContainsKey(fileName) || bt.Has(fileName)) continue; using (Database sourceDb = new Database(false, true)) { sourceDb.ReadDwgFile(filePath, FileShare.Read, true, null); db.Insert(fileName, sourceDb, true); } } tr.Commit(); } } catch (SysException ex) { _ed.WriteMessage($"\n加载图块错误: {ex.Message}"); } } // 选择控制线 private Curve SelectControlLine() { try { var opts = new PromptEntityOptions("\n选择控制线: ") { AllowNone = false, AllowObjectOnLockedLayer = true }; opts.SetRejectMessage("\n必须选择直线或多段线"); opts.AddAllowedClass(typeof(Line), true); opts.AddAllowedClass(typeof(Polyline), true); PromptEntityResult result = _ed.GetEntity(opts); if (result.Status != PromptStatus.OK) return null; using (Transaction tr = _ed.Document.TransactionManager.StartTransaction()) { Curve curve = tr.GetObject(result.ObjectId, OpenMode.ForRead) as Curve; tr.Commit(); return curve; } } catch (AcadException acadEx) { HandleAcadException(acadEx); return null; } } // 获取直线/多段线的Y坐标 private double GetLineElevation(Curve curve) { if (curve == null) return 0; try { if (curve is Line line) return line.StartPoint.Y; if (curve is Polyline pline) return pline.GetPoint3dAt(0).Y; return 0; } catch (SysException ex) { _ed.WriteMessage($"\n获取标高错误: {ex.Message}"); return 0; } } // 选择图块 private List<BlockReference> SelectBlocks() { try { var filter = new SelectionFilter(new[] { new TypedValue(0, "INSERT"), new TypedValue(2, "ScaffoldPole*") }); var selOptions = new PromptSelectionOptions { MessageForAdding = "\n框选脚手架图块: ", AllowDuplicates = false }; PromptSelectionResult selResult = _ed.GetSelection(selOptions, filter); if (selResult.Status != PromptStatus.OK) return null; var references = new List<BlockReference>(); using (var resBuf = selResult.Value) { Database db = _ed.Document.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { foreach (ObjectId objId in resBuf.GetObjectIds()) { var bref = tr.GetObject(objId, OpenMode.ForRead) as BlockReference; if (bref != null) references.Add(bref); } tr.Commit(); } } return references; } catch (AcadException acadEx) { HandleAcadException(acadEx); return null; } } // 立杆布置 - 严格保证顶部间隙200-400mm private int LayoutVerticalPoles( Transaction tr, BlockTable bt, BlockTableRecord btr, List<BlockReference> blocks, double baseElev) { int poleCount = 0; try { // 获取所有立杆位置 var polePositions = blocks .Where(b => b.Name.Contains("立杆") && !b.Name.Contains("横杆")) .Select(b => b.Position.X) .Distinct() .OrderBy(x => x) .ToList(); if (polePositions.Count == 0) return 0; // 确定整体方向 double minY = polePositions.Min(x => GetElevationAtX(x)); double maxY = polePositions.Max(x => GetElevationAtX(x)); _isAscending = maxY > minY; // 存储整体方向 // 标准杆件尺寸 int[] standardSizes = { 2500, 2000, 1500, 1000, 500, 350, 200 }; foreach (var xPos in polePositions) { // 记录立杆底部位置 _poleBasePositions[xPos] = baseElev; // 获取该位置精确的顶部高度 double topElev = GetElevationAtX(xPos); double totalHeight = Math.Abs(topElev - baseElev); double currentY = baseElev; List<int> usedSizes = new List<int>(); // 精确配杆算法 double remaining = totalHeight; // 1. 先配标准杆(保留顶部间隙空间) while (remaining > MinTopGap + 350) // 保留至少350mm+200mm间隙 { // 计算最大可用尺寸(考虑最小间隙200mm) double maxUsableSize = remaining - MinTopGap; // 选择不超过最大可用尺寸的最大标准杆 int bestSize = standardSizes .Where(s => s <= maxUsableSize) .OrderByDescending(s => s) .FirstOrDefault(); if (bestSize <= 0) break; usedSizes.Add(bestSize); remaining -= bestSize; currentY += _isAscending ? bestSize : -bestSize; } // 2. 顶部配杆算法(关键:确保间隙在200-400mm) int lastPoleSize = 0; double gap = 0; // 计算理想顶部间隙(200-400mm) double minGap = MinTopGap; double maxGap = MaxTopGap; // 可选的最后一根杆尺寸(考虑间隙要求) var validLastSizes = standardSizes .Where(s => s <= remaining - minGap && s >= remaining - maxGap) .OrderByDescending(s => s) .ToList(); if (validLastSizes.Any()) { // 优先选择满足间隙要求的最大杆 lastPoleSize = validLastSizes.First(); gap = remaining - lastPoleSize; } else { // 次选:最接近300mm间隙的杆 lastPoleSize = standardSizes .OrderBy(s => Math.Abs((remaining - s) - 300)) // 300是理想间隙 .First(); gap = remaining - lastPoleSize; // 确保间隙至少200mm if (gap < minGap) { // 减少一根标准杆来增加空间 if (usedSizes.Count > 0) { int lastStandard = usedSizes.Last(); usedSizes.RemoveAt(usedSizes.Count - 1); remaining += lastStandard; currentY += _isAscending ? -lastStandard : lastStandard; // 重新计算最后一根杆 lastPoleSize = standardSizes .Where(s => s <= remaining - minGap) .OrderByDescending(s => s) .First(); gap = remaining - lastPoleSize; } else { // 无法调整时使用350mm杆 lastPoleSize = 350; gap = remaining - lastPoleSize; } } } // 添加最后一根立杆 usedSizes.Add(lastPoleSize); gap = remaining - lastPoleSize; // 记录最后一根立杆尺寸 _lastPoleSizes[xPos] = lastPoleSize; // 3. 布置所有立杆 currentY = baseElev; // 重置当前高度 foreach (int size in usedSizes) { string blockName = $"ScaffoldPole立杆{size}mm"; if (bt.Has(blockName)) { InsertBlock(tr, btr, bt, blockName, xPos, currentY); poleCount++; // 记录连接盘位置(关键:包括顶部连接盘) RecordDiskPositions(xPos, currentY, size); currentY += _isAscending ? size : -size; } } // 4. 布置顶托和螺母 if (bt.Has("ScaffoldPole顶托")) { // 顶托顶部精确对齐控制线 double topPosition = topElev; InsertBlock(tr, btr, bt, "ScaffoldPole顶托", xPos, topPosition); _adjusterPositions[xPos] = topPosition; // 螺母位置(在最后一根立杆顶部上方75mm) double nutPosition = _isAscending ? (currentY + NutOffset) : (currentY - NutOffset); if (bt.Has("ScaffoldPole顶托螺母")) { InsertBlock(tr, btr, bt, "ScaffoldPole顶托螺母", xPos, nutPosition); } } // 5. 验证顶部间隙 if (gap < minGap || gap > maxGap) { _ed.WriteMessage($"\n警告: 位置 {xPos} 顶部间隙为 {gap:F1}mm (要求200-400mm)"); } } } catch (SysException ex) { _ed.WriteMessage($"\n布置立杆错误: {ex.Message}"); } return poleCount; } // 记录立杆上的连接盘位置(包括顶部连接盘) private void RecordDiskPositions(double x, double startY, int poleSize) { try { if (!_diskPositions.ContainsKey(x)) _diskPositions[x] = new List<double>(); double direction = _isAscending ? 1 : -1; double poleHeight = poleSize; // 1. 添加250mm处的连接盘(第一道横杆位置) double firstDiskY = startY + FirstBarHeight * direction; if (!_diskPositions[x].Contains(firstDiskY)) _diskPositions[x].Add(firstDiskY); // 2. 添加1500mm步距连接盘 double currentHeight = firstDiskY; double step = HorizontalBarSpacing * direction; // 添加后续连接盘(1500mm步距) while (_isAscending ? (currentHeight + step <= startY + poleHeight * direction) : (currentHeight + step >= startY - poleHeight)) { currentHeight += step; if (!_diskPositions[x].Contains(currentHeight)) _diskPositions[x].Add(currentHeight); } // 3. 添加顶部连接盘(立杆顶部连接盘位置) double topDiskY = startY + poleHeight * direction; if (!_diskPositions[x].Contains(topDiskY)) _diskPositions[x].Add(topDiskY); } catch (SysException ex) { _ed.WriteMessage($"\n记录连接盘错误: {ex.Message}"); } } // 横杆布置 - 严格按250mm起始和1500mm步距 private int LayoutHorizontalBars( Transaction tr, BlockTable bt, BlockTableRecord btr, List<BlockReference> blocks, double baseElev) { int barCount = 0; try { // 获取所有立杆位置 var poleXPositions = _poleBasePositions.Keys .OrderBy(x => x) .ToList(); if (poleXPositions.Count < 2) return 0; // 计算横杆布置高度序列(250mm起始,1500mm步距) List<double> barHeights = CalculateBarHeights(poleXPositions, baseElev); // 为每个横杆高度布置横杆 foreach (var height in barHeights) { barCount += PlaceBarsAtHeight(tr, bt, btr, poleXPositions, height); } // 在顶部立杆圆盘处布置横杆(强制) barCount += PlaceTopDiskBars(tr, bt, btr, poleXPositions, barHeights); } catch (SysException ex) { _ed.WriteMessage($"\n布置横杆错误: {ex.Message}"); } return barCount; } // 计算横杆布置高度序列(250mm起始,1500mm步距) private List<double> CalculateBarHeights(List<double> polePositions, double baseElev) { var barHeights = new List<double>(); try { // 1. 添加第一道横杆(250mm高度) double firstBarHeight = baseElev + (_isAscending ? FirstBarHeight : -FirstBarHeight); barHeights.Add(firstBarHeight); // 2. 确定最高点(顶部立杆圆盘位置) double maxHeight = polePositions.Max(x => _adjusterPositions.ContainsKey(x) ? _adjusterPositions[x] : baseElev ); // 3. 计算1500mm步距序列 double currentHeight = firstBarHeight; double step = _isAscending ? HorizontalBarSpacing : -HorizontalBarSpacing; // 添加中间横杆(直到接近顶部) while (_isAscending ? (currentHeight + step <= maxHeight - MinTopGap) : (currentHeight + step >= maxHeight + MinTopGap)) { currentHeight += step; barHeights.Add(currentHeight); } } catch (SysException ex) { _ed.WriteMessage($"\n计算横杆高度错误: {ex.Message}"); } return barHeights; } // 在指定高度布置横杆 private int PlaceBarsAtHeight( Transaction tr, BlockTable bt, BlockTableRecord btr, List<double> poleXPositions, double height) { int barCount = 0; try { for (int i = 0; i < poleXPositions.Count - 1; i++) { double x1 = poleXPositions[i]; double x2 = poleXPositions[i + 1]; double distance = Math.Abs(x2 - x1); // 跳过过大的跨度 if (distance > MaxBarDistance) continue; // 选择最匹配的横杆尺寸 int bestSize = GetBestBarSize(distance); if (bestSize <= 0) continue; string blockName = $"ScaffoldPole立横杆{bestSize}mm"; if (!bt.Has(blockName)) continue; // 检查两端是否都有连接盘(使用放宽的容差) bool hasDisk1 = HasDiskAtHeight(x1, height, RelaxedTolerance); bool hasDisk2 = HasDiskAtHeight(x2, height, RelaxedTolerance); if (hasDisk1 && hasDisk2) { double midX = (x1 + x2) / 2; InsertBlock(tr, btr, bt, blockName, midX, height); barCount++; } else { // 记录缺失连接盘的警告 _ed.WriteMessage($"\n警告: 位置 {x1}-{x2} 高度 {height} 缺少连接盘,但仍布置横杆"); double midX = (x1 + x2) / 2; InsertBlock(tr, btr, bt, blockName, midX, height); barCount++; } } } catch (SysException ex) { _ed.WriteMessage($"\n在高度 {height} 布置横杆错误: {ex.Message}"); } return barCount; } // 在顶部立杆圆盘处布置横杆(精确对齐连接盘) private int PlaceTopDiskBars( Transaction tr, BlockTable bt, BlockTableRecord btr, List<double> poleXPositions, List<double> existingBarHeights) // 已布置高度列表 { int barCount = 0; try { // 1. 收集所有顶部连接盘位置 [X坐标, 连接盘Y坐标] var topDiskPositions = new Dictionary<double, double>(); foreach (var x in poleXPositions) { } // 2. 按高度分组(相同高度的立杆) var heightGroups = topDiskPositions .GroupBy(kv => kv.Value) .Select(g => new { Height = g.Key, XPositions = g.Select(kv => kv.Key).OrderBy(x => x).ToList() }); // 3. 为每个高度组布置横杆 foreach (var group in heightGroups) { double height = group.Height; var xPositions = group.XPositions; // 跳过已布置的高度(防重叠) if (existingBarHeights.Any(h => Math.Abs(h - height) <= Tolerance)) continue; // 仅当有2根以上立杆时才布置 if (xPositions.Count < 2) continue; // 布置相邻立杆间的横杆 for (int i = 0; i < xPositions.Count - 1; i++) { double x1 = xPositions[i]; double x2 = xPositions[i + 1]; double distance = Math.Abs(x2 - x1); // 跳过过大的跨度 if (distance > MaxBarDistance) continue; // 选择最佳横杆尺寸 int bestSize = GetBestBarSize(distance); if (bestSize <= 0) continue; string blockName = $"ScaffoldPole立横杆{bestSize}mm"; if (!bt.Has(blockName)) continue; // 布置横杆(精确对齐连接盘高度) double midX = (x1 + x2) / 2; InsertBlock(tr, btr, bt, blockName, midX, height); barCount++; _ed.WriteMessage($"\n已布置顶部横杆: {x1}-{x2} @ {height}mm"); } } } catch (SysException ex) { _ed.WriteMessage($"\n布置顶部横杆错误: {ex.Message}"); } return barCount; } // 检查指定位置是否有连接盘 private bool HasDiskAtHeight(double x, double height, double tolerance = Tolerance) { try { if (!_diskPositions.ContainsKey(x)) return false; return _diskPositions[x].Any(y => Math.Abs(y - height) <= tolerance); } catch { return false; } } // 获取最佳横杆尺寸 private int GetBestBarSize(double distance) { if (distance <= 0) return 0; int[] validSizes = { 300, 600, 900, 1200, 1500, 1800 }; return validSizes .Where(s => s >= distance * 0.8 && s <= distance * 1.2) // 允许20%误差 .OrderBy(s => Math.Abs(s - distance)) .FirstOrDefault(); } // 获取指定X坐标在控制线上的Y值 private double GetElevationAtX(double x) { if (_topControlLine == null) return 0; try { if (_topControlLine is Line line) { Vector3d direction = line.EndPoint - line.StartPoint; if (Math.Abs(direction.X) < 0.001) return line.StartPoint.Y; double t = (x - line.StartPoint.X) / direction.X; return line.StartPoint.Y + t * direction.Y; } if (_topControlLine is Polyline pline) { for (int i = 0; i < pline.NumberOfVertices - 1; i++) { Point3d start = pline.GetPoint3dAt(i); Point3d end = pline.GetPoint3dAt(i + 1); if ((x >= start.X && x <= end.X) || (x <= start.X && x >= end.X)) { if (Math.Abs(end.X - start.X) < 0.001) return start.Y; double t = (x - start.X) / (end.X - start.X); return start.Y + t * (end.Y - start.Y); } } return pline.GetPoint3dAt(0).Y; } } catch (SysException ex) { _ed.WriteMessage($"\n计算标高错误: {ex.Message}"); } return 0; } // 插入图块 private void InsertBlock(Transaction tr, BlockTableRecord btr, BlockTable bt, string blockName, double x, double y) { if (!bt.Has(blockName)) return; try { BlockReference bref = new BlockReference(new Point3d(x, y, 0), bt[blockName]); btr.AppendEntity(bref); tr.AddNewlyCreatedDBObject(bref, true); } catch (SysException ex) { _ed.WriteMessage($"\n插入图块错误: {ex.Message}"); } } }
}
顶控制线低跨处立杆顶部横杆未布置在顶立杆盘上,如低跨立杆顶部配的立杆350mm那横杆就布置在125mm位置的盘上。
顶控制线高跨立杆顶部立杆缺一道横杆