Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/RevitUnmodelingMep/ViewModels/CategoryAssignmentBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

using Autodesk.Revit.DB;

using dosymep.Revit;

using RevitUnmodelingMep.Models;

namespace RevitUnmodelingMep.ViewModels;

internal sealed class CategoryAssignmentBuilder {
private readonly RevitRepository _revitRepository;

public CategoryAssignmentBuilder(RevitRepository revitRepository) {
_revitRepository = revitRepository;
}

/// <summary>
/// Строит дерево назначений: категории Revit, типы систем и доступные для них конфигурации расходников.
/// </summary>
public ObservableCollection<CategoryAssignmentItem> Build(
IReadOnlyList<CategoryOption> categoryOptions,
IEnumerable<ConsumableTypeItem> consumableTypes,
bool onlyPlacedInProject,
Func<ConsumableTypeItem, int?> resolveCategoryId) {
List<BuiltInCategory> categories = new List<BuiltInCategory> {
BuiltInCategory.OST_PipeCurves,
BuiltInCategory.OST_DuctCurves,
BuiltInCategory.OST_PipeInsulations,
BuiltInCategory.OST_DuctInsulations,
BuiltInCategory.OST_DuctSystem,
BuiltInCategory.OST_PipingSystem
};

var assignments = new List<CategoryAssignmentItem>();

foreach(BuiltInCategory builtInCategory in categories) {
CategoryOption option = categoryOptions.FirstOrDefault(o => o.BuiltInCategory == builtInCategory);
int optionCategoryId = option?.Id ?? (int) builtInCategory;
string categoryName = option?.Name ?? builtInCategory.ToString();

List<Element> types = CollectionGenerator.GetElementTypesByCategory(_revitRepository.Doc, builtInCategory)
?? new List<Element>();
if(types.Count == 0) {
continue;
}

List<ConsumableTypeItem> configsForCategory = consumableTypes?
.Where(c => resolveCategoryId(c) == optionCategoryId)
.OrderBy(c => c?.ConsumableTypeName ?? string.Empty, StringComparer.CurrentCultureIgnoreCase)
.ToList() ?? new List<ConsumableTypeItem>();

HashSet<int> placedTypeIds = onlyPlacedInProject ? GetPlacedTypeIds(builtInCategory) : null;

ObservableCollection<SystemTypeItem> systemTypes =
new ObservableCollection<SystemTypeItem>(
types
.OfType<ElementType>()
.Where(type => placedTypeIds == null || placedTypeIds.Contains(unchecked((int) type.Id.GetIdValue())))
.OrderBy(type => type?.Name ?? string.Empty, StringComparer.CurrentCultureIgnoreCase)
.Select(type => CreateSystemTypeItem(type, configsForCategory)));

if(systemTypes.Count == 0) {
continue;
}

assignments.Add(new CategoryAssignmentItem {
Name = categoryName,
Category = builtInCategory,
SystemTypes = systemTypes
});
}

return new ObservableCollection<CategoryAssignmentItem>(
assignments.OrderBy(a => a?.Name ?? string.Empty, StringComparer.CurrentCultureIgnoreCase));
}

/// <summary>
/// Возвращает идентификаторы типов, которые реально размещены в проекте для указанной категории.
/// </summary>
private HashSet<int> GetPlacedTypeIds(BuiltInCategory builtInCategory) {
var result = new HashSet<int>();

var collector = new FilteredElementCollector(_revitRepository.Doc)
.OfCategory(builtInCategory)
.WhereElementIsNotElementType();

foreach(Element element in collector) {
ElementId typeId = element.GetTypeId();
if(typeId == null || typeId == ElementId.InvalidElementId) {
continue;
}

result.Add(unchecked((int) typeId.GetIdValue()));
}

return result;
}

/// <summary>
/// Создает элемент типа системы с назначениями всех расходников, подходящих для его категории.
/// </summary>
private static SystemTypeItem CreateSystemTypeItem(ElementType elementType, List<ConsumableTypeItem> configs) {
int typeId = unchecked((int) elementType.Id.GetIdValue());

ObservableCollection<ConfigAssignmentItem> configAssignments =
new ObservableCollection<ConfigAssignmentItem>(
configs.Select(config => new ConfigAssignmentItem(config, typeId)));

return new SystemTypeItem {
Name = elementType.Name,
Id = typeId,
Configs = configAssignments
};
}
}
93 changes: 93 additions & 0 deletions src/RevitUnmodelingMep/ViewModels/CategoryOptionsProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;

using Autodesk.Revit.DB;

using dosymep.Revit;
using dosymep.SimpleServices;

namespace RevitUnmodelingMep.ViewModels;

internal sealed class CategoryOptionsProvider {
private readonly Document _document;
private readonly ILocalizationService _localizationService;

/// <summary>
/// Создает поставщик доступных MEP-категорий для настроек расходников.
/// </summary>
public CategoryOptionsProvider(Document document, ILocalizationService localizationService) {
_document = document;
_localizationService = localizationService;
}

/// <summary>
/// Создает справочник категорий, доступных для выбора в настройках расходников.
/// </summary>
public IReadOnlyList<CategoryOption> CreateCategoryOptions() {
return new List<CategoryOption> {
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.DuctsName"),
BuiltInCategory.OST_DuctCurves),
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.PipesName"),
BuiltInCategory.OST_PipeCurves),
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.PipeInsName"),
BuiltInCategory.OST_PipeInsulations),
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.DuctInsName"),
BuiltInCategory.OST_DuctInsulations),
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.DuctSysName"),
BuiltInCategory.OST_DuctSystem),
CreateCategoryOption(
_localizationService.GetLocalizedString("MainViewModel.PipeSysName"),
BuiltInCategory.OST_PipingSystem)
};
}

/// <summary>
/// Преобразует сохраненное значение категории в один из доступных вариантов выбора.
/// </summary>
public CategoryOption ResolveCategoryOption(
IReadOnlyList<CategoryOption> categoryOptions,
string categoryValue) {
if(string.IsNullOrWhiteSpace(categoryValue)) {
return categoryOptions.FirstOrDefault();
}

if(int.TryParse(categoryValue, out int id)) {
return categoryOptions.FirstOrDefault(o => o.Id == id);
}

string trimmed = categoryValue.Trim();
if(trimmed.StartsWith("BuiltInCategory.", StringComparison.OrdinalIgnoreCase)) {
string enumName = trimmed.Substring("BuiltInCategory.".Length);
CategoryOption byEnumName = categoryOptions.FirstOrDefault(o =>
string.Equals(o.BuiltInCategory.ToString(), enumName, StringComparison.OrdinalIgnoreCase));
if(byEnumName != null) {
return byEnumName;
}
}

return categoryOptions.FirstOrDefault(o =>
string.Equals(o.Name, categoryValue, StringComparison.OrdinalIgnoreCase))
?? categoryOptions.FirstOrDefault();
}

/// <summary>
/// Создает один вариант категории с локализованным именем, BuiltInCategory и фактическим id категории в документе.
/// </summary>
private CategoryOption CreateCategoryOption(string name, BuiltInCategory builtInCategory) {
Category category = Category.GetCategory(_document, builtInCategory);
long idValue = category?.Id?.GetIdValue() ?? (int) builtInCategory;
int id = unchecked((int) idValue);

return new CategoryOption {
Name = name,
BuiltInCategory = builtInCategory,
Id = id
};
}
}
Loading
Loading