Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
130 changes: 130 additions & 0 deletions src/RevitUnmodelingMep/ViewModels/CategoryAssignmentBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

using Autodesk.Revit.DB;

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(GetElementIdValue(type.Id)))
.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(GetElementIdValue(typeId));
}

return result;
}

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

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

return new SystemTypeItem {
Name = elementType.Name,
Id = typeId,
Configs = configAssignments
};
}

/// <summary>
/// Возвращает числовое значение ElementId с учетом различий API Revit до и после 2024 версии.
/// </summary>
private static int GetElementIdValue(ElementId elementId) {
long value;
#if REVIT_2024_OR_GREATER
value = elementId?.Value ?? 0;
#else
value = elementId?.IntegerValue ?? 0;
#endif
return unchecked((int) value);
}
Comment thread
vlastroG marked this conversation as resolved.
Outdated
}
98 changes: 98 additions & 0 deletions src/RevitUnmodelingMep/ViewModels/CategoryOptionsProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;

using Autodesk.Revit.DB;

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;
#if REVIT_2024_OR_GREATER
idValue = category?.Id.Value ?? (long) (int) builtInCategory;
#else
idValue = category?.Id.IntegerValue ?? (int) builtInCategory;
#endif
int id = unchecked((int) idValue);
Comment thread
vlastroG marked this conversation as resolved.
Outdated

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