RoomToSpaceUtils.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. using Autodesk.Revit.DB;
  2. using Autodesk.Revit.DB.Architecture;
  3. using Autodesk.Revit.DB.Mechanical;
  4. using FWindSoft.Revit;
  5. using FWindSoft.Revit.Extension;
  6. using FWindSoft.SystemExtensions;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace LRH.Tool
  13. {
  14. public static class RoomToSpaceUtils
  15. {
  16. /// <summary>
  17. /// 获取指定的元素信息
  18. /// </summary>
  19. /// <param name="view"></param>
  20. /// <param name="filter"></param>
  21. /// <returns></returns>
  22. public static List<Element> GetElements(View view, ElementFilter filter)
  23. {
  24. //删除当前视图下的所有空间和空间分割
  25. var doc = view.Document;
  26. var elements = doc.GetElements(filter);
  27. return elements.Where(e => e.LevelId == view.GenLevel.Id).ToList();
  28. }
  29. /// <summary>
  30. /// 房间转换成空间
  31. /// </summary>
  32. /// <param name="view"></param>
  33. /// <param name="option"></param>
  34. /// <returns></returns>
  35. public static List<RoomRelationItem> RoomToSpace(View view, RoomToSpaceTransOption option,Transaction tran)
  36. {
  37. //删除当前视图下的所有空间和空间分割
  38. var doc = view.Document;
  39. var spaces = GetElements(view, new SpaceFilter());
  40. if (option.DeleteOriginalSpace)
  41. {
  42. try
  43. {
  44. tran.Start();
  45. doc.Delete(spaces.Select(e => e.Id).ToList());
  46. tran.Commit();
  47. }
  48. catch (Exception)
  49. {
  50. tran.RollBack();
  51. }
  52. }
  53. var spaceSeps = GetElements(view, new ElementCategoryFilter(BuiltInCategory.OST_MEPSpaceSeparationLines)).OfType<ModelLine>().ToList();
  54. if (option.DeleteOriginalSpaceSq)
  55. {
  56. try
  57. {
  58. tran.Start();
  59. doc.Delete(spaceSeps.Select(e => e.Id).ToList());
  60. tran.Commit();
  61. }
  62. catch (Exception)
  63. {
  64. tran.RollBack();
  65. }
  66. }
  67. CreateSpaces(view, tran);
  68. List<RoomRelationItem> relationItems = new List<RoomRelationItem>();
  69. try
  70. {
  71. tran.Start();
  72. #region 根据房间分割创建空间分割
  73. if (option.RoomSqToSpaceSq)
  74. {
  75. var roomSeps = GetElements(view, new ElementCategoryFilter(BuiltInCategory.OST_RoomSeparationLines))
  76. .OfType<ModelLine>().ToList();
  77. CurveArray curveArray = new CurveArray();
  78. foreach (var roomSep in roomSeps)
  79. {
  80. curveArray.Append(roomSep.GeometryCurve);
  81. }
  82. if (!curveArray.IsEmpty)
  83. {
  84. Plane p = Plane.CreateByNormalAndOrigin(view.ViewDirection, view.Origin);
  85. var sp = SketchPlane.Create(doc, p);
  86. doc.Create.NewSpaceBoundaryLines(sp, curveArray, view);
  87. }
  88. }
  89. #endregion
  90. relationItems = RoomDataToSpace(view);
  91. tran.Commit();
  92. }
  93. catch (Exception)
  94. {
  95. tran.RollBack();
  96. }
  97. return relationItems;
  98. }
  99. /// <summary>
  100. /// 房间数据转移到空间数据
  101. /// </summary>
  102. /// <param name="view"></param>
  103. /// <returns></returns>
  104. public static List<RoomRelationItem> RoomDataToSpace(View view)
  105. {
  106. var doc = view.Document;
  107. var rooms = GetElements(view, new RoomFilter()).OfType<Room>();
  108. var offset = XYZ.BasisZ * 0.1;
  109. HashSet<int> handledSpaces = new HashSet<int>();
  110. List<RoomRelationItem> relations = new List<RoomRelationItem>();
  111. foreach (Room room in rooms)
  112. {
  113. var relationItem = new RoomRelationItem() { RoomId = room.Id.ToString() };
  114. relations.Add(relationItem);
  115. using (SubTransaction subTran = new SubTransaction(doc))
  116. {
  117. Space useSpcae = null;
  118. try
  119. {
  120. subTran.Start();
  121. var location = room.Location.ConvertToPoint();
  122. if (location == null )
  123. {
  124. //|| room.Area.IsEqual(0)
  125. relationItem.Messages.Add("房间信息无效");
  126. continue;
  127. }
  128. useSpcae = doc.GetSpaceAtPoint(location.Add(offset));
  129. if (useSpcae == null)
  130. {
  131. relationItem.Messages.Add("未找到对应空间");
  132. continue;
  133. }
  134. InfoTrans(room, useSpcae, handledSpaces.Contains(useSpcae.Id.IntegerValue));
  135. subTran.Commit();
  136. //成功
  137. handledSpaces.Add(useSpcae.Id.IntegerValue);
  138. relationItem.SpaceId = useSpcae.Id.ToString();
  139. relationItem.IsSuccess = true;
  140. }
  141. catch (Exception ex)
  142. {
  143. relationItem.Messages.Add("赋值异常"+ex.Message);
  144. subTran.RollBack();
  145. }
  146. }
  147. }
  148. return relations;
  149. }
  150. public static List<Space> CreateSpaces(View view)
  151. {
  152. List<Space> spaces = new List<Space>();
  153. Document doc = view.Document;
  154. var level = view.GenLevel;
  155. Parameter para = view.GetParameter(BuiltInParameter.VIEW_PHASE);
  156. ElementId phaseId = para.AsElementId();
  157. var phase = doc.GetElement(phaseId) as Phase;
  158. var points = GetSpacesPoints(view);
  159. foreach (var point in points)
  160. {
  161. var oldSpace = doc.GetSpaceAtPoint(point, phase);
  162. if (oldSpace == null)
  163. {
  164. var tempSapce = doc.Create.NewSpace(level, phase, new UV(point.X, point.Y));
  165. spaces.Add(tempSapce);
  166. }
  167. }
  168. return spaces;
  169. }
  170. public static void CreateSpaces(View view,Transaction tran)
  171. {
  172. Document doc = view.Document;
  173. FailuresPreprocessor preprocessor = new FailuresPreprocessor(true);
  174. {
  175. try
  176. {
  177. FailureHandlingOptions fho = tran.GetFailureHandlingOptions();
  178. fho.SetFailuresPreprocessor(preprocessor);
  179. tran.SetFailureHandlingOptions(fho);
  180. #region 创建空间
  181. tran.Start();
  182. var spaces=CreateSpaces(view);
  183. tran.Commit(); //提交获取冲突代码
  184. #endregion
  185. #region 冲突处理代码
  186. FailureHandlingOptions failureOptions = tran.GetFailureHandlingOptions();
  187. failureOptions.SetFailuresPreprocessor(new FailuresPreprocessor(false));
  188. tran.SetFailureHandlingOptions(failureOptions);
  189. tran.Start();
  190. //返回值临时使用
  191. var failItems = preprocessor.Items;
  192. foreach (var failuresItem in failItems)
  193. {
  194. var firstId = failuresItem.Items.FirstOrDefault();
  195. if (firstId == null)
  196. {
  197. continue;
  198. }
  199. for (int i = 1; i < failuresItem.Items.Count; i++)
  200. {
  201. var currentId = failuresItem.Items[i];
  202. if (firstId.IntegerValue > currentId.IntegerValue)
  203. {
  204. doc.Delete(new List<ElementId>() { firstId });
  205. firstId = currentId;
  206. }
  207. } // doc.GetElement(failuresItem.Items.FirstOrDefault());
  208. }
  209. tran.Commit();
  210. #endregion
  211. }
  212. catch (Exception ex)
  213. {
  214. tran.RollBack();
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// 获取视图中创建空间的点的信息
  220. /// </summary>
  221. /// <param name="view"></param>
  222. /// <returns></returns>
  223. public static List<XYZ> GetSpacesPoints(View view)
  224. {
  225. Document doc = view.Document;
  226. var level = view.GenLevel;
  227. Parameter para = view.GetParameter(BuiltInParameter.VIEW_PHASE);
  228. ElementId phaseId = para.AsElementId();
  229. var phase = doc.GetElement(phaseId) as Phase;
  230. #region 创建新的节点
  231. List<XYZ> points = new List<XYZ>();
  232. using (SubTransaction sub = new SubTransaction(doc))
  233. {
  234. try
  235. {
  236. sub.Start();
  237. var spaceSeps = GetElements(view, new ElementCategoryFilter(BuiltInCategory.OST_MEPSpaceSeparationLines)).OfType<ModelLine>().ToList();
  238. CurveArray curveArray = new CurveArray();
  239. foreach (var modelLine in spaceSeps)
  240. {
  241. curveArray.Append(modelLine.GeometryCurve);
  242. }
  243. #region 创建房间分割
  244. Plane p = Plane.CreateByNormalAndOrigin(view.ViewDirection, view.Origin);
  245. var sp = SketchPlane.Create(doc, p);
  246. if (!curveArray.IsEmpty)
  247. {
  248. doc.Create.NewRoomBoundaryLines(sp, curveArray, view);
  249. }
  250. #endregion
  251. #region 获取封闭区域
  252. var topology = doc.get_PlanTopology(level, phase);
  253. foreach (PlanCircuit topologyCircuit in topology.Circuits)
  254. {
  255. var point = topologyCircuit.GetPointInside();
  256. var xyz = new XYZ(point.U, point.V, level.ProjectElevation + 1); //适当升高一些
  257. points.Add(xyz);
  258. }
  259. #endregion
  260. }
  261. catch (Exception e)
  262. {
  263. }
  264. finally
  265. {
  266. sub.RollBack();
  267. }
  268. }
  269. #endregion
  270. return points;
  271. }
  272. public static void InfoTrans(Room room,Space space,bool isAppend)
  273. {
  274. var name = room.GetParameterString(BuiltInParameter.ROOM_NAME) ?? string.Empty;
  275. if (isAppend)
  276. {
  277. var oldName = space.GetParameterString(BuiltInParameter.ROOM_NAME)??string.Empty;
  278. if (!string.IsNullOrWhiteSpace(name)&& !oldName.Contains(name))
  279. {
  280. name = oldName + "," + name;
  281. }
  282. }
  283. space.SetParameter(BuiltInParameter.ROOM_NAME, name);
  284. }
  285. public static StringBuilder CreateResult(List<RoomRelationItem> items)
  286. {
  287. StringBuilder builder = new StringBuilder();
  288. int errorCount = 0;
  289. foreach (var item in items)
  290. {
  291. if (item.IsSuccess)
  292. {
  293. continue;
  294. }
  295. builder.AppendLine(item.ToString());
  296. errorCount++;
  297. }
  298. builder.AppendLine($"总共{items.Count}房间,转换过程出现问题{errorCount}个");
  299. return builder;
  300. }
  301. }
  302. #region 扩展选项类
  303. public class RoomRelationItem
  304. {
  305. public string RoomId { get; set; }
  306. public string SpaceId { get; set; }
  307. /// <summary>
  308. /// 是否成功
  309. /// </summary>
  310. public bool IsSuccess { get; set; }
  311. /// <summary>
  312. /// 错误消息
  313. /// </summary>
  314. public List<string> Messages { get; private set; } = new List<string>();
  315. public override string ToString()
  316. {
  317. var message = string.Join(";", Messages);
  318. return $"RoomId:{RoomId} SpaceId:{SpaceId} Result:{message}";
  319. }
  320. }
  321. /// <summary>
  322. /// 导出控制选项
  323. /// </summary>
  324. public class RoomToSpaceTransOption
  325. {
  326. /// <summary>
  327. /// 是否删除原始空间
  328. /// </summary>
  329. public bool DeleteOriginalSpace { get; set; } = true;
  330. /// <summary>
  331. /// 是否删除原始空间分割
  332. /// </summary>
  333. public bool DeleteOriginalSpaceSq { get; set; }
  334. /// <summary>
  335. /// 是否将房间分割转换成空间分割
  336. /// </summary>
  337. public bool RoomSqToSpaceSq { get; set; }
  338. }
  339. public class FailuresItem
  340. {
  341. public FailuresItem()
  342. {
  343. }
  344. public FailuresItem(IEnumerable<ElementId> ids)
  345. {
  346. Items.AddRange(ids);
  347. }
  348. public List<ElementId> Items { get; private set; } = new List<ElementId>();
  349. }
  350. /// <summary>
  351. /// 空间错误机制
  352. /// </summary>
  353. public class FailuresPreprocessor : IFailuresPreprocessor
  354. {
  355. /*
  356. * 创建警告时,如果一个区域已经存在多个空间,创建警告时会把所有警告空间进行捕获
  357. */
  358. #region 构造函数
  359. public FailuresPreprocessor()
  360. {
  361. Items = new List<FailuresItem>();
  362. }
  363. public FailuresPreprocessor(bool append) : this()
  364. {
  365. Append = append;
  366. }
  367. #endregion
  368. #region 相关操纵选项
  369. /// <summary>
  370. /// 是否追加捕获信息
  371. /// </summary>
  372. private bool Append { get; set; }
  373. public void SetOperate(bool continueAdd)
  374. {
  375. Append = continueAdd;
  376. }
  377. public List<FailuresItem> Items { get; private set; }
  378. #endregion
  379. public FailureProcessingResult PreprocessFailures(FailuresAccessor failuresAccessor)
  380. {
  381. IList<FailureMessageAccessor> messages = failuresAccessor.GetFailureMessages();
  382. if (messages.Count == 0)
  383. return FailureProcessingResult.Continue;
  384. foreach (FailureMessageAccessor message in messages)
  385. {
  386. var currentSeverity = message.GetSeverity();
  387. switch (currentSeverity)
  388. {
  389. case FailureSeverity.Error:
  390. {
  391. if (message.HasResolutions())
  392. failuresAccessor.ResolveFailure(message);
  393. break;
  394. }
  395. case FailureSeverity.Warning:
  396. {
  397. if (Append)
  398. {
  399. var elementIds = message.GetFailingElementIds();
  400. if (elementIds.Any())
  401. {
  402. Items.Add(new FailuresItem(elementIds.ToList()));
  403. }
  404. }
  405. failuresAccessor.DeleteWarning(message);
  406. break;
  407. }
  408. }
  409. }
  410. return FailureProcessingResult.ProceedWithCommit;
  411. }
  412. }
  413. #endregion
  414. }