using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using UnityEditor; using UnityEngine; namespace Gyvr.Mythril2D { public class ScriptableObjectPostprocessor : AssetPostprocessor { private static readonly List _cachedScriptableObjects = new(); private static bool _cacheDirty = true; public static List cachedScriptableObjects { get { if (_cacheDirty) { _cacheDirty = false; RebuildScriptableObjectCache(); } return _cachedScriptableObjects; } } private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { _cacheDirty = true; } private static void RebuildScriptableObjectCache() { _cachedScriptableObjects.Clear(); foreach (string guid in AssetDatabase.FindAssets("t:ScriptableObject")) { ScriptableObject instance = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)); if (instance != null) { _cachedScriptableObjects.Add(instance); } } } } public class DatabaseWindow : EditorWindow { private static readonly Type[] BuiltInTabs = { typeof(HeroSheet), typeof(MonsterSheet), typeof(NPCSheet), typeof(AbilitySheet), typeof(Item), typeof(Shop), typeof(Recipe), typeof(CraftingStation), typeof(Inn), typeof(Quest), typeof(QuestTask), typeof(DialogueSequence), typeof(AudioClipResolver), typeof(SaveFile), typeof(PrefabReference), typeof(CommandHandler), typeof(NavigationCursorStyle), typeof(GameConfig), typeof(DatabaseRegistry) }; private static readonly List Tabs = new(BuiltInTabs); private const string LegacyPrefsPrefix = "Gyvr.Mythril2D.DatabaseWindow."; private const string TabOrderPrefsName = "TabOrder"; private const string TabColumnWidthPrefsName = "TabColumnWidth"; private const string ItemColumnsPrefsName = "ItemColumns"; private const string ItemColumnOrderPrefsName = "ItemColumnOrder"; private const string ItemColumnWidthsPrefsName = "ItemColumnWidths"; private const string CustomTabsPrefsName = "CustomTabs"; private const float TabColumnDefaultWidth = 150f; private const float TabColumnMinWidth = 100f; private const float TabColumnMaxWidth = 400f; private const float TabColumnResizeHandleWidth = 5f; private const float TabRowHeight = 22f; private const float ItemRowHeight = 24f; private const float ItemIconColumnWidth = 32f; private const float ItemNameColumnWidth = 200f; private const float ItemPriceColumnWidth = 70f; private const float ItemCategoryColumnWidth = 100f; private const float ItemDescriptionMinWidth = 250f; private const string IconColumnKey = "Icon"; private const string NameColumnKey = "Name"; private const string DescriptionColumnKey = "Description"; private const string PriceColumnKey = "Price"; private const string CategoryColumnKey = "Category"; private const string NoValueFilterOption = "(None)"; private const string CustomFieldsTooltip = "Serialized fields found on Item subclasses outside the Mythril2D core"; private const string ErrorCellText = "(error)"; private const float ColumnMinWidth = 40f; private const float ColumnMaxWidth = 1000f; private const float ColumnResizeHandleWidth = 6f; private static string _prefsPrefix; private static string PrefsPrefix => _prefsPrefix ??= $"{LegacyPrefsPrefix}{PlayerSettings.productGUID:N}."; private static bool HasPrefs(string name) { return EditorPrefs.HasKey(PrefsPrefix + name) || EditorPrefs.HasKey(LegacyPrefsPrefix + name); } private static string GetPrefsString(string name, string defaultValue) { return EditorPrefs.HasKey(PrefsPrefix + name) ? EditorPrefs.GetString(PrefsPrefix + name, defaultValue) : EditorPrefs.GetString(LegacyPrefsPrefix + name, defaultValue); } private static float GetPrefsFloat(string name, float defaultValue) { return EditorPrefs.HasKey(PrefsPrefix + name) ? EditorPrefs.GetFloat(PrefsPrefix + name, defaultValue) : EditorPrefs.GetFloat(LegacyPrefsPrefix + name, defaultValue); } private static void SetPrefsString(string name, string value) { EditorPrefs.SetString(PrefsPrefix + name, value); } private static void SetPrefsFloat(string name, float value) { EditorPrefs.SetFloat(PrefsPrefix + name, value); } private static readonly string[] DefaultItemColumnOrder = { IconColumnKey, NameColumnKey, PriceColumnKey, CategoryColumnKey }; private enum ColumnFilterKind { None, Contains, Ticklist } private class ItemColumnDefinition { public string Key; public string Label; public string HeaderLabel; public float Width; public bool Flexible; public bool Wrap; public bool Sortable = true; public float DefaultWidth; public ColumnFilterKind FilterKind; public Func GetDisplayValue; public Func> GetFilterValues; public Func> GetTicklistOptions; public Func GetSortValue; public Action DrawCell; public string[] CoversFields; public string Group; public string Tooltip; } private static List _itemColumns; private static List ItemColumns => _itemColumns ??= BuildItemColumns(); private static List BuildItemColumns() { List columns = BuildBaseItemColumns(); var coveredFields = columns.Where(c => c.CoversFields != null).SelectMany(c => c.CoversFields).ToHashSet(); columns.AddRange(BuildDetectedItemColumns(coveredFields, columns.Select(c => c.Label).ToHashSet())); foreach (ItemColumnDefinition column in columns) { column.DefaultWidth = column.Width; } return columns; } private static List BuildBaseItemColumns() { return new List { new() { Key = IconColumnKey, Label = "Icon", HeaderLabel = string.Empty, Width = ItemIconColumnWidth, Sortable = false, FilterKind = ColumnFilterKind.None, GetDisplayValue = item => item.icon != null ? item.icon.name : string.Empty, DrawCell = (rect, item) => DrawSpriteIcon(rect, item.icon), CoversFields = new[] { "Item.m_icon" } }, new() { Key = NameColumnKey, Label = "Item Name", Width = ItemNameColumnWidth, Flexible = true, FilterKind = ColumnFilterKind.Contains, GetDisplayValue = item => item.displayName, GetSortValue = item => item.displayName, CoversFields = new[] { "Item.m_displayName" } }, new() { Key = DescriptionColumnKey, Label = "Description", Width = ItemDescriptionMinWidth, Flexible = true, Wrap = true, Sortable = false, FilterKind = ColumnFilterKind.Contains, GetDisplayValue = item => ItemDescriptionField?.GetValue(item) as string ?? string.Empty, CoversFields = new[] { "Item.m_description" } }, new() { Key = PriceColumnKey, Label = "Price", Width = ItemPriceColumnWidth, FilterKind = ColumnFilterKind.Contains, GetDisplayValue = item => item.price.ToString(), GetSortValue = item => item.price, CoversFields = new[] { "Item.m_price" } }, new() { Key = CategoryColumnKey, Label = "Category", Width = ItemCategoryColumnWidth, FilterKind = ColumnFilterKind.Ticklist, GetDisplayValue = item => item.category.ToString(), GetFilterValues = item => new[] { item.category.ToString() }, GetTicklistOptions = () => Enum.GetNames(typeof(EItemCategory)).ToList(), GetSortValue = item => item.category.ToString(), CoversFields = new[] { "Item.m_category" } }, new() { Key = "EquipmentType", Label = "Equipment Type", Width = 110f, FilterKind = ColumnFilterKind.Ticklist, GetDisplayValue = item => item is Equipment equipment ? equipment.type.ToString() : string.Empty, GetFilterValues = item => item is Equipment equipment ? new[] { equipment.type.ToString() } : Array.Empty(), GetTicklistOptions = () => Enum.GetNames(typeof(EEquipmentType)).ToList(), GetSortValue = item => item is Equipment equipment ? (int)equipment.type : null, CoversFields = new[] { "Equipment.m_type" } }, new() { Key = "BonusStats", Label = "Bonus Stats", Width = 180f, FilterKind = ColumnFilterKind.Contains, GetDisplayValue = item => FormatBonusStats(item as Equipment), GetSortValue = item => GetTotalBonusStats(item as Equipment), CoversFields = new[] { "Equipment.m_bonusStats" } } }; } private static IEnumerable BuildDetectedItemColumns(HashSet coveredFields, HashSet reservedLabels) { var types = new[] { typeof(Item) } .Concat(TypeCache.GetTypesDerivedFrom()) .Where(t => !t.ContainsGenericParameters) .Distinct() .OrderBy(t => IsBaseMythril2DType(t) ? 0 : 1) .ThenBy(GetInheritanceDepth) .ThenBy(t => t.Name); var fields = types .SelectMany(t => t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) .Where(f => IsSerializedField(f) && !coveredFields.Contains($"{f.DeclaringType.Name}.{f.Name}")) .ToList(); var duplicateLabels = fields .GroupBy(GetFieldLabel) .Where(g => g.Count() > 1 || reservedLabels.Contains(g.Key)) .Select(g => g.Key) .ToHashSet(); return fields.Select(f => CreateDetectedColumn(f, duplicateLabels.Contains(GetFieldLabel(f)))); } private static bool IsBaseMythril2DType(Type type) { return type.Assembly == typeof(Item).Assembly; } private static ItemColumnDefinition CreateDetectedColumn(FieldInfo field, bool disambiguate) { Type declaringType = field.DeclaringType; bool polymorphic = field.IsDefined(typeof(SerializeReference), true); Type elementType = GetCollectionElementType(field.FieldType); Type valueType = elementType ?? field.FieldType; bool isSequence = field.FieldType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(field.FieldType); bool useTicklist = polymorphic || valueType.IsEnum || valueType == typeof(bool) || typeof(UnityEngine.Object).IsAssignableFrom(valueType); string label = disambiguate ? $"{GetFieldLabel(field)} ({declaringType.Name})" : GetFieldLabel(field); object GetValue(Item item) => declaringType.IsInstanceOfType(item) ? field.GetValue(item) : null; var column = new ItemColumnDefinition { Key = $"Field:{declaringType.FullName}.{field.Name}", Label = label, Group = IsBaseMythril2DType(declaringType) ? null : declaringType.Name, Tooltip = $"{field.FieldType.Name} {field.Name} on {declaringType.Name}", Width = GetDetectedColumnWidth(valueType, isSequence, label), FilterKind = useTicklist ? ColumnFilterKind.Ticklist : ColumnFilterKind.Contains, GetDisplayValue = item => FormatFieldValue(GetValue(item), polymorphic), GetSortValue = item => GetFieldSortValue(GetValue(item), polymorphic) }; if (useTicklist) { column.GetFilterValues = item => GetFieldFilterValues(GetValue(item), isSequence, polymorphic); column.GetTicklistOptions = () => { if (valueType.IsEnum) { return Enum.GetNames(valueType).ToList(); } if (valueType == typeof(bool)) { return new List { "Yes", "No" }; } if (polymorphic) { return TypeCache.GetTypesDerivedFrom(valueType) .Where(t => !t.IsAbstract && !t.IsInterface && !t.ContainsGenericParameters && t.IsSerializable) .Select(t => ObjectNames.NicifyVariableName(t.Name)) .Distinct() .OrderBy(v => v) .ToList(); } return ScriptableObjectPostprocessor.cachedScriptableObjects .OfType() .SelectMany(column.GetFilterValues) .Distinct() .OrderBy(v => v) .ToList(); }; } return column; } private static int GetInheritanceDepth(Type type) { int depth = 0; for (Type current = type; current != null && current != typeof(Item); current = current.BaseType) { depth++; } return depth; } private static bool IsSerializedField(FieldInfo field) { if (field.IsStatic || field.IsInitOnly || field.IsLiteral || field.IsNotSerialized || field.IsDefined(typeof(HideInInspector), true)) { return false; } if (field.IsDefined(typeof(SerializeReference), true)) { return true; } if (!field.IsPublic && !field.IsDefined(typeof(SerializeField), true)) { return false; } return IsSerializableValueType(GetCollectionElementType(field.FieldType) ?? field.FieldType); } private static bool IsSerializableValueType(Type type) { if (type.IsPrimitive || type.IsEnum || type == typeof(string) || typeof(UnityEngine.Object).IsAssignableFrom(type)) { return true; } if (type.IsAbstract || type.IsInterface || type.ContainsGenericParameters || typeof(Delegate).IsAssignableFrom(type)) { return false; } return type.IsSerializable || (type.IsValueType && type.Namespace != null && type.Namespace.StartsWith("UnityEngine")); } private static Type GetCollectionElementType(Type type) { if (type.IsArray && type.GetArrayRank() == 1) { return type.GetElementType(); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { return type.GetGenericArguments()[0]; } return null; } private static string GetFieldLabel(FieldInfo field) { string name = field.Name; if (name.StartsWith("<") && name.Contains(">")) { name = name.Substring(1, name.IndexOf('>') - 1); } return ObjectNames.NicifyVariableName(name); } private static float GetDetectedColumnWidth(Type valueType, bool isSequence, string label) { float width = isSequence ? 180f : valueType == typeof(bool) ? 60f : valueType.IsPrimitive ? 80f : valueType.IsEnum ? 110f : 140f; return Mathf.Max(width, label.Length * 7f + 24f); } private static string FormatFieldValue(object value, bool polymorphic, int depth = 0) { switch (value) { case null: return string.Empty; case UnityEngine.Object unityObject: return unityObject ? (unityObject is INameable nameable ? nameable.displayName : unityObject.name) : string.Empty; case string text: return text; case bool flag: return flag ? "Yes" : "No"; case float number: return number.ToString("0.###"); case double number: return number.ToString("0.###"); case Enum enumValue: return enumValue.ToString(); case IDictionary dictionary: return string.Join(", ", dictionary.Keys.Cast() .Select(key => $"{FormatFieldValue(key, polymorphic, depth + 1)}: {FormatFieldValue(dictionary[key], polymorphic, depth + 1)}")); case IEnumerable sequence: return string.Join(", ", sequence.Cast() .Select(element => FormatFieldValue(element, polymorphic, depth + 1)) .Where(text => text.Length > 0)); } Type type = value.GetType(); if (polymorphic) { string typeName = FormatPolymorphicTypeName(value); string details = depth > 0 ? string.Empty : FormatSerializedFields(value, type, depth); return details.Length > 0 ? $"{typeName} ({details})" : typeName; } if (type.IsPrimitive || depth > 0 || HasCustomToString(type)) { return value.ToString(); } return FormatSerializedFields(value, type, depth); } private static string FormatPolymorphicTypeName(object value) { return value == null ? string.Empty : ObjectNames.NicifyVariableName(value.GetType().Name); } private static string FormatSerializedFields(object value, Type type, int depth) { return string.Join(", ", GetSerializedFields(type) .Select(f => $"{GetFieldLabel(f)}: {FormatFieldValue(f.GetValue(value), f.IsDefined(typeof(SerializeReference), true), depth + 1)}") .Where(text => !text.EndsWith(": "))); } private static IEnumerable GetSerializedFields(Type type) { var hierarchy = new List(); for (Type current = type; current != null && current != typeof(object); current = current.BaseType) { hierarchy.Add(current); } hierarchy.Reverse(); return hierarchy .SelectMany(t => t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) .Where(IsSerializedField); } private static bool HasCustomToString(Type type) { Type declaringType = type.GetMethod(nameof(ToString), Type.EmptyTypes)?.DeclaringType; return declaringType != typeof(object) && declaringType != typeof(ValueType); } private static IComparable GetFieldSortValue(object value, bool polymorphic) { return value switch { null => null, bool flag => flag ? 1 : 0, Enum enumValue => Convert.ToInt64(enumValue), sbyte or byte or short or ushort or int or uint or long or ulong or float or double or decimal => Convert.ToDouble(value), _ => FormatFieldValue(value, polymorphic) }; } private static IEnumerable GetFieldFilterValues(object value, bool isSequence, bool polymorphic) { IEnumerable values = isSequence && value is IEnumerable sequence ? sequence.Cast() : new[] { value }; return values.Select(v => polymorphic ? FormatPolymorphicTypeName(v) : FormatFieldValue(v, false)).Where(text => text.Length > 0); } private static IComparable GetTotalBonusStats(Equipment equipment) { if (equipment == null || equipment.bonusStats == null) { return null; } int total = 0; for (int i = 0; i < Stats.StatCount; i++) { total += equipment.bonusStats[(EStat)i]; } return total; } private static string FormatBonusStats(Equipment equipment) { if (equipment == null || equipment.bonusStats == null) { return string.Empty; } var parts = new List(); for (int i = 0; i < Stats.StatCount; i++) { int value = equipment.bonusStats[(EStat)i]; if (value != 0) { parts.Add($"{(EStat)i}+{value}"); } } return string.Join(", ", parts); } private static int _selectedTab = 0; private static List _tabOrder; private static Vector2 _tabScrollPos; private static float _tabColumnWidth = TabColumnDefaultWidth; private static bool _resizingTabColumn = false; private static int _draggedTabRow = -1; private static int _tabDropRow = -1; private static bool _isDraggingTab = false; private static float _tabDragStartY; private static int _selectedIndex = -1; private static Vector2 _scrollPos; private static string _searchString = string.Empty; private static bool _showItemListView = false; private static bool _showRecipeGridView = false; private static bool _showItemFilterPanel = false; private static bool _showRecipeFilterPanel = false; private static bool _showItemColumnsPanel = false; private static string _recipeNameFilter = string.Empty; private static readonly List _itemColumnOrder = new(); private static readonly Dictionary _columnContainsFilters = new(); private static readonly Dictionary> _columnTicklistExclusions = new(); private static bool _itemColumnsLoaded = false; private static readonly Dictionary _customFieldFoldouts = new(); private static readonly Dictionary _filterFoldouts = new(); private static string _itemSortKey = NameColumnKey; private static bool _itemSortAscending = true; private enum RecipeSortColumn { Name, Station, Cost, None } private static RecipeSortColumn _recipeSortColumn = RecipeSortColumn.Name; private static bool _recipeSortAscending = true; private static Item _selectionAnchor; private static Item _pendingSingleSelection; private static Item _scrollToItem; private static Vector2 _itemDragStart; private static GUIStyle _cellStyle; private static GUIStyle _wrappedCellStyle; private static GUIStyle _headerCellStyle; private static GUIStyle _addTabStyle; private static GUIStyle _itemRowStyle; private static readonly Dictionary _wrappedColumnWidths = new(); private static readonly Dictionary _measuredWrappedColumnWidths = new(); private static readonly HashSet _reportedColumnErrors = new(); private static int _pressedHeaderColumn = -1; private static Vector2 _headerPressPosition; private static bool _isDraggingColumn = false; private static int _columnDropIndex = -1; private static int _resizingColumn = -1; private static readonly System.Reflection.FieldInfo ItemDescriptionField = typeof(Item).GetField("m_description", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); private static Dictionary _taskToQuestMap = new(); private static Dictionary _questGroupFoldouts = new(); private static Dictionary> _groupedTasks = new(); private static int _lastTabForTaskGrouping = -1; private static Dictionary _recipeToStationMap = new(); private static Dictionary _dialogueToSourceMap = new(); private static Dictionary _dialogueGroupFoldouts = new(); private static Dictionary> _groupedDialogues = new(); private static int _lastTabForDialogueGrouping = -1; [MenuItem("Window/Mythril2D/Database")] public static void ShowWindow() { EditorWindow window = GetWindow(); window.titleContent = new GUIContent("Database"); window.Show(); } private static void EnsureTabStateInitialized() { if (_tabOrder != null) { return; } _tabColumnWidth = Mathf.Clamp(GetPrefsFloat(TabColumnWidthPrefsName, TabColumnDefaultWidth), TabColumnMinWidth, TabColumnMaxWidth); if (!_itemColumnsLoaded) { _itemColumnsLoaded = true; LoadItemColumnOrder(); LoadItemColumnWidths(); } LoadCustomTabs(); _tabOrder = LoadTabOrder(); } private static void LoadCustomTabs() { foreach (string typeName in GetPrefsString(CustomTabsPrefsName, string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { Type type = Type.GetType(typeName); if (type != null && typeof(ScriptableObject).IsAssignableFrom(type) && !Tabs.Contains(type)) { Tabs.Add(type); } } } private static void SaveCustomTabs() { SetPrefsString(CustomTabsPrefsName, string.Join("|", Tabs.Except(BuiltInTabs).Select(t => $"{t.FullName}, {t.Assembly.GetName().Name}"))); } private static bool IsCustomTab(Type type) { return !BuiltInTabs.Contains(type); } private static void AddCustomTab(Type type, int insertRow) { Tabs.Add(type); SaveCustomTabs(); int tab = Tabs.Count - 1; _tabOrder.Insert(Mathf.Clamp(insertRow, 0, _tabOrder.Count), tab); SaveTabOrder(); _selectedTab = tab; } private static void RemoveCustomTab(Type type) { Type selectedType = Tabs[_selectedTab]; var visibleTypes = _tabOrder.Select(i => Tabs[i]).Where(t => t != type).ToList(); Tabs.Remove(type); SaveCustomTabs(); _tabOrder.Clear(); _tabOrder.AddRange(visibleTypes.Count > 0 ? visibleTypes.Select(t => Tabs.IndexOf(t)) : Enumerable.Range(0, Tabs.Count)); SaveTabOrder(); _selectedTab = selectedType == type ? _tabOrder[0] : Tabs.IndexOf(selectedType); } private static List GetAddableTabTypes() { var types = new HashSet(); foreach (ScriptableObject asset in ScriptableObjectPostprocessor.cachedScriptableObjects) { for (Type type = asset.GetType(); type != null && type != typeof(ScriptableObject); type = type.BaseType) { types.Add(type); } } return types .Where(t => !Tabs.Contains(t) && !t.IsGenericType && !IsUnityType(t)) .OrderBy(t => t.Name) .ToList(); } private static bool IsUnityType(Type type) { string ns = type.Namespace ?? string.Empty; return ns.StartsWith("UnityEngine") || ns.StartsWith("UnityEditor"); } private static List LoadTabOrder() { string saved = GetPrefsString(TabOrderPrefsName, string.Empty); if (string.IsNullOrEmpty(saved)) { return Enumerable.Range(0, Tabs.Count).ToList(); } var order = new List(); foreach (string typeName in saved.Split(',')) { int index = Tabs.FindIndex(t => t.FullName == typeName); if (index >= 0 && !order.Contains(index)) { order.Add(index); } } return order.Count > 0 ? order : Enumerable.Range(0, Tabs.Count).ToList(); } private static void SaveTabOrder() { SetPrefsString(TabOrderPrefsName, string.Join(",", _tabOrder.Select(i => Tabs[i].FullName))); } private static void SaveTabColumnWidth() { SetPrefsFloat(TabColumnWidthPrefsName, _tabColumnWidth); } private static void LoadItemColumnOrder() { _itemColumnOrder.Clear(); IEnumerable savedKeys = HasPrefs(ItemColumnOrderPrefsName) ? GetPrefsString(ItemColumnOrderPrefsName, string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) : DefaultItemColumnOrder.Concat(GetPrefsString(ItemColumnsPrefsName, string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); foreach (string key in savedKeys) { if (ItemColumns.Any(c => c.Key == key) && !_itemColumnOrder.Contains(key)) { _itemColumnOrder.Add(key); } } } private static void SaveItemColumnOrder() { SetPrefsString(ItemColumnOrderPrefsName, string.Join(",", _itemColumnOrder)); } private static void LoadItemColumnWidths() { foreach (string entry in GetPrefsString(ItemColumnWidthsPrefsName, string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) { int separator = entry.LastIndexOf('='); ItemColumnDefinition column = separator > 0 ? ItemColumns.FirstOrDefault(c => c.Key == entry.Substring(0, separator)) : null; if (column != null && float.TryParse(entry.Substring(separator + 1), NumberStyles.Float, CultureInfo.InvariantCulture, out float width)) { column.Width = Mathf.Clamp(width, ColumnMinWidth, ColumnMaxWidth); } } } private static void SaveItemColumnWidths() { SetPrefsString(ItemColumnWidthsPrefsName, string.Join("|", ItemColumns .Where(c => !Mathf.Approximately(c.Width, c.DefaultWidth)) .Select(c => $"{c.Key}={c.Width.ToString(CultureInfo.InvariantCulture)}"))); } private static List GetShownItemColumns() { return _itemColumnOrder.Select(key => ItemColumns.FirstOrDefault(c => c.Key == key)).Where(c => c != null).ToList(); } private static bool IsItemColumnShown(string key) { return _itemColumnOrder.Contains(key); } private static void SetItemColumnShown(string key, bool shown) { if (shown == _itemColumnOrder.Contains(key)) { return; } if (shown) { _itemColumnOrder.Add(key); } else { _itemColumnOrder.Remove(key); } SaveItemColumnOrder(); } private static void MoveItemColumn(int fromIndex, int dropIndex) { if (fromIndex < 0 || fromIndex >= _itemColumnOrder.Count || dropIndex < 0) { return; } string key = _itemColumnOrder[fromIndex]; _itemColumnOrder.RemoveAt(fromIndex); if (dropIndex > fromIndex) { dropIndex--; } _itemColumnOrder.Insert(Mathf.Clamp(dropIndex, 0, _itemColumnOrder.Count), key); SaveItemColumnOrder(); } private static void ResetItemColumns() { _itemColumnOrder.Clear(); _itemColumnOrder.AddRange(DefaultItemColumnOrder); SaveItemColumnOrder(); foreach (ItemColumnDefinition column in ItemColumns) { column.Width = column.DefaultWidth; } SaveItemColumnWidths(); } private static void MoveTab(int fromRow, int toRow) { if (fromRow < 0 || fromRow >= _tabOrder.Count) { return; } int tab = _tabOrder[fromRow]; _tabOrder.RemoveAt(fromRow); if (toRow > fromRow) { toRow--; } _tabOrder.Insert(Mathf.Clamp(toRow, 0, _tabOrder.Count), tab); SaveTabOrder(); } private static void HideTab(int row) { if (_tabOrder.Count <= 1) { return; } int hiddenTab = _tabOrder[row]; _tabOrder.RemoveAt(row); SaveTabOrder(); if (_selectedTab == hiddenTab) { _selectedTab = _tabOrder[Mathf.Min(row, _tabOrder.Count - 1)]; } } private void ShowTabContextMenu(int row) { var menu = new GenericMenu(); Type tabType = Tabs[_tabOrder[row]]; AddMenuItem(menu, "Move Up", row > 0, () => MoveTab(row, row - 1)); AddMenuItem(menu, "Move Down", row < _tabOrder.Count - 1, () => MoveTab(row, row + 2)); menu.AddSeparator(string.Empty); AddMenuItem(menu, $"Hide {tabType.Name}", _tabOrder.Count > 1, () => HideTab(row)); if (IsCustomTab(tabType)) { AddMenuItem(menu, $"Remove {tabType.Name}", true, () => RemoveCustomTab(tabType)); } menu.AddSeparator(string.Empty); AppendAddTabItems(menu, "Add Tab/", "Show Hidden/", row + 1); menu.AddSeparator(string.Empty); AddMenuItem(menu, "Reset Tabs", true, () => { _tabOrder.Clear(); _tabOrder.AddRange(Enumerable.Range(0, Tabs.Count)); SaveTabOrder(); }); menu.ShowAsContext(); } private void ShowAddTabMenu(Rect buttonRect) { var menu = new GenericMenu(); AppendAddTabItems(menu, string.Empty, "Show Hidden/", _tabOrder.Count); menu.DropDown(buttonRect); } private void AppendAddTabItems(GenericMenu menu, string addPrefix, string hiddenPrefix, int insertRow) { List addableTypes = GetAddableTabTypes(); if (addableTypes.Count == 0) { menu.AddDisabledItem(new GUIContent($"{addPrefix}No other asset types found")); } foreach (Type type in addableTypes) { string group = string.IsNullOrEmpty(type.Namespace) ? "Other" : type.Namespace; AddMenuItem(menu, $"{addPrefix}{group}/{type.Name}", true, () => AddCustomTab(type, insertRow)); } var hiddenTabs = Enumerable.Range(0, Tabs.Count).Where(i => !_tabOrder.Contains(i)).ToList(); if (hiddenTabs.Count == 0) { menu.AddDisabledItem(new GUIContent($"{hiddenPrefix}No hidden tabs")); } foreach (int hiddenTab in hiddenTabs) { AddMenuItem(menu, $"{hiddenPrefix}{Tabs[hiddenTab].Name}", true, () => { _tabOrder.Insert(Mathf.Clamp(insertRow, 0, _tabOrder.Count), hiddenTab); SaveTabOrder(); _selectedTab = hiddenTab; }); } } private void AddMenuItem(GenericMenu menu, string path, bool enabled, Action action) { if (enabled) { menu.AddItem(new GUIContent(path), false, () => { action(); Repaint(); }); } else { menu.AddDisabledItem(new GUIContent(path)); } } private static Color SelectionColor(bool focused) { if (!focused) { return EditorGUIUtility.isProSkin ? new Color(0.3f, 0.3f, 0.3f) : new Color(0.72f, 0.72f, 0.72f); } return EditorGUIUtility.isProSkin ? new Color(0.17f, 0.36f, 0.53f) : new Color(0.6f, 0.74f, 0.92f); } private static Color HoverColor => EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.06f) : new Color(0f, 0f, 0f, 0.06f); private static Color StripeColor => EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.025f) : new Color(0f, 0f, 0f, 0.035f); private static Color DividerColor => EditorGUIUtility.isProSkin ? new Color(0f, 0f, 0f, 0.35f) : new Color(0f, 0f, 0f, 0.15f); private static GUIStyle CellStyle => _cellStyle ??= new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft, clipping = TextClipping.Clip, padding = new RectOffset(4, 4, 0, 0), margin = new RectOffset(0, 0, 0, 0) }; private static GUIStyle WrappedCellStyle => _wrappedCellStyle ??= new GUIStyle(CellStyle) { alignment = TextAnchor.UpperLeft, wordWrap = true, padding = new RectOffset(4, 4, 4, 4) }; private static GUIStyle HeaderCellStyle => _headerCellStyle ??= new GUIStyle(EditorStyles.toolbarButton) { alignment = TextAnchor.MiddleLeft, clipping = TextClipping.Clip, padding = new RectOffset(4, 4, 0, 0), margin = new RectOffset(0, 0, 0, 0), fixedHeight = 0 }; private static string TruncateForWidth(string text, float maxWidth, GUIStyle style) { if (style.CalcSize(new GUIContent(text)).x <= maxWidth) { return text; } for (int length = text.Length - 1; length > 0; length--) { string candidate = text.Substring(0, length) + "…"; if (style.CalcSize(new GUIContent(candidate)).x <= maxWidth) { return candidate; } } return text; } private static bool MatchesNameFilter(ScriptableObject so) { if (string.IsNullOrEmpty(_searchString)) { return true; } if (so.name.IndexOf(_searchString, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } string displayName = so switch { Item item => item.displayName, Recipe recipe => recipe.displayName, _ => null }; return displayName != null && displayName.IndexOf(_searchString, StringComparison.OrdinalIgnoreCase) >= 0; } private static bool HasActiveFilter(ItemColumnDefinition column) { return column.FilterKind switch { ColumnFilterKind.Contains => _columnContainsFilters.TryGetValue(column.Key, out string text) && !string.IsNullOrWhiteSpace(text), ColumnFilterKind.Ticklist => _columnTicklistExclusions.TryGetValue(column.Key, out HashSet exclusions) && exclusions.Count > 0, _ => false }; } private static int CountActiveItemFilters() { return ItemColumns.Count(HasActiveFilter); } private static bool HasActiveFilterOnHiddenColumn() { return ItemColumns.Any(c => HasActiveFilter(c) && !IsItemColumnShown(c.Key)); } private static void ClearItemFilters() { _columnContainsFilters.Clear(); _columnTicklistExclusions.Clear(); GUI.FocusControl(null); } private static bool DrawFilterToggle(bool isOpen, int activeCount) { string label = activeCount > 0 ? $"Filter ({activeCount})" : "Filter"; return GUILayout.Toggle(isOpen, label, GUI.skin.button, GUILayout.Width(75)); } private static T EvaluateColumn(ItemColumnDefinition column, Func evaluate, T fallback) { try { return evaluate(); } catch (Exception exception) { if (_reportedColumnErrors.Add(column.Key)) { Debug.LogWarning($"Database window could not read column '{column.Label}': {exception.GetType().Name}: {exception.Message}"); } return fallback; } } private static string GetColumnDisplayValue(ItemColumnDefinition column, Item item) { return EvaluateColumn(column, () => column.GetDisplayValue(item) ?? string.Empty, ErrorCellText); } private static List GetColumnFilterValues(ItemColumnDefinition column, Item item) { return EvaluateColumn(column, () => column.GetFilterValues(item).ToList(), new List()); } private static IComparable GetColumnSortValue(ItemColumnDefinition column, Item item) { return EvaluateColumn(column, () => column.GetSortValue != null ? column.GetSortValue(item) : column.GetDisplayValue(item), (IComparable)null); } private static List GetColumnTicklistOptions(ItemColumnDefinition column) { return EvaluateColumn(column, column.GetTicklistOptions, new List()); } private static List GetTicklistValues(ItemColumnDefinition column, Item item) { List values = GetColumnFilterValues(column, item); if (values.Count == 0) { values.Add(NoValueFilterOption); } return values; } private static List GetTicklistOptions(ItemColumnDefinition column) { List options = GetColumnTicklistOptions(column); bool anyWithoutValue = ScriptableObjectPostprocessor.cachedScriptableObjects.OfType().Any(item => GetColumnFilterValues(column, item).Count == 0); if (anyWithoutValue && !options.Contains(NoValueFilterOption)) { options.Add(NoValueFilterOption); } return options; } private static bool MatchesColumnFilters(Item item) { foreach (ItemColumnDefinition column in ItemColumns) { if (!HasActiveFilter(column)) { continue; } if (column.FilterKind == ColumnFilterKind.Contains) { if (GetColumnDisplayValue(column, item).IndexOf(_columnContainsFilters[column.Key], StringComparison.OrdinalIgnoreCase) < 0) { return false; } } else if (column.FilterKind == ColumnFilterKind.Ticklist) { HashSet exclusions = _columnTicklistExclusions[column.Key]; if (GetTicklistValues(column, item).All(exclusions.Contains)) { return false; } } } return true; } private static void DrawItemFilterPanel() { EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Filters", EditorStyles.miniBoldLabel); using (new EditorGUI.DisabledScope(CountActiveItemFilters() == 0)) { if (GUILayout.Button("Clear All", EditorStyles.miniButton, GUILayout.Width(65))) { ClearItemFilters(); } } EditorGUILayout.EndHorizontal(); if (HasActiveFilterOnHiddenColumn()) { EditorGUILayout.LabelField("Some active filters are on columns that are not shown.", EditorStyles.miniLabel); } foreach (ItemColumnDefinition column in ItemColumns.Where(c => c.Group == null && c.FilterKind != ColumnFilterKind.None)) { DrawColumnFilter(column); } var customGroups = ItemColumns.Where(c => c.Group != null && c.FilterKind != ColumnFilterKind.None).GroupBy(c => c.Group).ToList(); if (customGroups.Count > 0) { GUILayout.Space(4); EditorGUILayout.LabelField(new GUIContent("Custom Fields", CustomFieldsTooltip), EditorStyles.miniBoldLabel); foreach (var group in customGroups) { int activeCount = group.Count(HasActiveFilter); string foldoutKey = $"Group:{group.Key}"; bool isOpen = _filterFoldouts.TryGetValue(foldoutKey, out bool open) ? open : activeCount > 0; isOpen = EditorGUILayout.Foldout(isOpen, activeCount > 0 ? $"{group.Key} ({activeCount} active)" : group.Key, true); _filterFoldouts[foldoutKey] = isOpen; if (isOpen) { EditorGUI.indentLevel++; foreach (ItemColumnDefinition column in group) { DrawColumnFilter(column); } EditorGUI.indentLevel--; } } } EditorGUILayout.EndVertical(); } private static void DrawColumnFilter(ItemColumnDefinition column) { bool isActive = HasActiveFilter(column); bool isOpen = _filterFoldouts.TryGetValue(column.Key, out bool open) ? open : isActive || column.Key == NameColumnKey || column.Key == CategoryColumnKey; isOpen = EditorGUILayout.Foldout(isOpen, new GUIContent(GetFilterFoldoutLabel(column, isActive), column.Tooltip), true); _filterFoldouts[column.Key] = isOpen; if (!isOpen) { return; } EditorGUI.indentLevel++; if (column.FilterKind == ColumnFilterKind.Contains) { string current = _columnContainsFilters.TryGetValue(column.Key, out string text) ? text : string.Empty; string updated = EditorGUILayout.TextField(current); if (updated != current) { if (string.IsNullOrEmpty(updated)) { _columnContainsFilters.Remove(column.Key); } else { _columnContainsFilters[column.Key] = updated; } } } else if (column.FilterKind == ColumnFilterKind.Ticklist) { if (!_columnTicklistExclusions.TryGetValue(column.Key, out HashSet exclusions)) { exclusions = new HashSet(); _columnTicklistExclusions[column.Key] = exclusions; } List options = GetTicklistOptions(column); if (options.Count == 0) { EditorGUILayout.LabelField("No values found in project", EditorStyles.miniLabel); } foreach (string option in options) { bool isShown = !exclusions.Contains(option); bool newIsShown = EditorGUILayout.ToggleLeft(option, isShown); if (newIsShown != isShown) { if (newIsShown) { exclusions.Remove(option); } else { exclusions.Add(option); } } } } EditorGUI.indentLevel--; } private static string GetFilterFoldoutLabel(ItemColumnDefinition column, bool isActive) { if (!isActive) { return column.Label; } bool shown = IsItemColumnShown(column.Key); if (column.FilterKind == ColumnFilterKind.Ticklist) { int hiddenCount = _columnTicklistExclusions[column.Key].Count; return shown ? $"{column.Label} ({hiddenCount} hidden)" : $"{column.Label} ({hiddenCount} hidden, column not shown)"; } string filterText = _columnContainsFilters[column.Key]; return shown ? $"{column.Label}: \"{filterText}\"" : $"{column.Label}: \"{filterText}\" (column not shown)"; } private static void DrawItemColumnsPanel() { EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Base M2D Features", EditorStyles.miniBoldLabel); if (GUILayout.Button(new GUIContent("Reset", "Restore the default columns, order and widths"), EditorStyles.miniButton, GUILayout.Width(65))) { ResetItemColumns(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.LabelField("Drag column headers to reorder, drag their edges to resize.", EditorStyles.miniLabel); foreach (ItemColumnDefinition column in ItemColumns.Where(c => c.Group == null)) { DrawColumnToggle(column); } var customGroups = ItemColumns.Where(c => c.Group != null).GroupBy(c => c.Group).ToList(); if (customGroups.Count > 0) { GUILayout.Space(4); EditorGUILayout.LabelField(new GUIContent("Custom Fields", CustomFieldsTooltip), EditorStyles.miniBoldLabel); foreach (var group in customGroups) { int shownCount = group.Count(c => IsItemColumnShown(c.Key)); bool isOpen = _customFieldFoldouts.TryGetValue(group.Key, out bool open) ? open : shownCount > 0; isOpen = EditorGUILayout.Foldout(isOpen, $"{group.Key} ({shownCount}/{group.Count()} shown)", true); _customFieldFoldouts[group.Key] = isOpen; if (isOpen) { EditorGUI.indentLevel++; foreach (ItemColumnDefinition column in group) { DrawColumnToggle(column); } EditorGUI.indentLevel--; } } } EditorGUILayout.EndVertical(); } private static void DrawColumnToggle(ItemColumnDefinition column) { bool isShown = IsItemColumnShown(column.Key); bool newIsShown = EditorGUILayout.ToggleLeft(new GUIContent(column.Label, column.Tooltip), isShown); if (newIsShown != isShown) { SetItemColumnShown(column.Key, newIsShown); } } private static void DrawRecipeFilterPanel() { EditorGUILayout.BeginVertical(GUI.skin.box); EditorGUILayout.LabelField("Name Contains", EditorStyles.miniBoldLabel); _recipeNameFilter = EditorGUILayout.TextField(_recipeNameFilter); EditorGUILayout.EndVertical(); } private void DrawTabColumnResizeHandle() { Rect handleRect = GUILayoutUtility.GetRect(TabColumnResizeHandleWidth, TabColumnResizeHandleWidth, GUILayout.ExpandHeight(true), GUILayout.Width(TabColumnResizeHandleWidth)); EditorGUIUtility.AddCursorRect(handleRect, MouseCursor.ResizeHorizontal); EditorGUI.DrawRect(handleRect, EditorGUIUtility.isProSkin ? new Color(0f, 0f, 0f, 0.3f) : new Color(0f, 0f, 0f, 0.15f)); Event evt = Event.current; if (evt.type == EventType.MouseDown && handleRect.Contains(evt.mousePosition)) { _resizingTabColumn = true; evt.Use(); } else if (evt.type == EventType.MouseDrag && _resizingTabColumn) { float maxWidth = Mathf.Min(TabColumnMaxWidth, position.width - TabColumnMinWidth); _tabColumnWidth = Mathf.Clamp(_tabColumnWidth + evt.delta.x, TabColumnMinWidth, maxWidth); SaveTabColumnWidth(); Repaint(); evt.Use(); } else if (evt.type == EventType.MouseUp && _resizingTabColumn) { _resizingTabColumn = false; evt.Use(); } } private void OnEnable() { wantsMouseMove = true; } private void OnSelectionChange() { Repaint(); } private void DrawTabList() { Rect listRect = GUILayoutUtility.GetRect(0f, _tabOrder.Count * TabRowHeight, GUILayout.ExpandWidth(true)); int controlId = GUIUtility.GetControlID(FocusType.Passive); Event evt = Event.current; int hoveredRow = listRect.Contains(evt.mousePosition) ? Mathf.Clamp((int)((evt.mousePosition.y - listRect.y) / TabRowHeight), 0, _tabOrder.Count - 1) : -1; switch (evt.GetTypeForControl(controlId)) { case EventType.MouseDown when hoveredRow >= 0 && evt.button == 0: _selectedTab = _tabOrder[hoveredRow]; _draggedTabRow = hoveredRow; _tabDragStartY = evt.mousePosition.y; _isDraggingTab = false; GUIUtility.hotControl = controlId; evt.Use(); break; case EventType.MouseDown when hoveredRow >= 0 && evt.button == 1: ShowTabContextMenu(hoveredRow); evt.Use(); break; case EventType.MouseDrag when GUIUtility.hotControl == controlId: _isDraggingTab |= Mathf.Abs(evt.mousePosition.y - _tabDragStartY) > 4f; _tabDropRow = Mathf.Clamp(Mathf.RoundToInt((evt.mousePosition.y - listRect.y) / TabRowHeight), 0, _tabOrder.Count); evt.Use(); break; case EventType.MouseUp when GUIUtility.hotControl == controlId: GUIUtility.hotControl = 0; if (_isDraggingTab) { MoveTab(_draggedTabRow, _tabDropRow); } _isDraggingTab = false; _draggedTabRow = -1; evt.Use(); break; case EventType.Repaint: bool focused = focusedWindow == this; for (int row = 0; row < _tabOrder.Count; row++) { Rect rowRect = new(listRect.x, listRect.y + row * TabRowHeight, listRect.width, TabRowHeight); int tab = _tabOrder[row]; if (tab == _selectedTab) { EditorGUI.DrawRect(rowRect, SelectionColor(focused)); } else if (row == hoveredRow && GUIUtility.hotControl == 0) { EditorGUI.DrawRect(rowRect, HoverColor); } string tabName = Tabs[tab].Name; var style = tab == _selectedTab ? EditorStyles.boldLabel : EditorStyles.label; Rect labelRect = new(rowRect.x + 6f, rowRect.y, rowRect.width - 8f, rowRect.height); GUI.Label(labelRect, TruncateForWidth(tabName, labelRect.width, style), style); } if (_isDraggingTab) { EditorGUI.DrawRect(new Rect(listRect.x, listRect.y + _tabDropRow * TabRowHeight - 1f, listRect.width, 2f), SelectionColor(true)); } break; } Rect addRect = GUILayoutUtility.GetRect(0f, TabRowHeight, GUILayout.ExpandWidth(true)); bool addHovered = addRect.Contains(evt.mousePosition); if (evt.type == EventType.Repaint && addHovered && GUIUtility.hotControl == 0) { EditorGUI.DrawRect(addRect, HoverColor); } if (GUI.Button(new Rect(addRect.x + 6f, addRect.y, addRect.width - 8f, addRect.height), "+ Add Tab", AddTabStyle)) { ShowAddTabMenu(addRect); } } private static GUIStyle AddTabStyle => _addTabStyle ??= new GUIStyle(EditorStyles.label) { normal = { textColor = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.45f) : new Color(0f, 0f, 0f, 0.45f) }, hover = { textColor = EditorStyles.label.normal.textColor } }; private void OnGUI() { EnsureTabStateInitialized(); if (Event.current.type == EventType.MouseMove) { Repaint(); } _tabColumnWidth = Mathf.Min(_tabColumnWidth, Mathf.Max(TabColumnMinWidth, position.width - TabColumnMinWidth)); if (!_tabOrder.Contains(_selectedTab) && _tabOrder.Count > 0) { _selectedTab = _tabOrder[0]; } EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(GUILayout.Width(_tabColumnWidth)); var previousSelectedTab = _selectedTab; _tabScrollPos = EditorGUILayout.BeginScrollView(_tabScrollPos); DrawTabList(); EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); DrawTabColumnResizeHandle(); EditorGUILayout.BeginVertical(); _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos); var previousSearchString = _searchString; _searchString = GUILayout.TextField(_searchString, EditorStyles.toolbarSearchField); if (Tabs[_selectedTab] == typeof(Item)) { EditorGUILayout.BeginHorizontal(); _showItemListView = EditorGUILayout.ToggleLeft("List View", _showItemListView, GUILayout.Width(70)); if (!_showItemListView) { _showItemFilterPanel = DrawFilterToggle(_showItemFilterPanel, CountActiveItemFilters()); _showItemColumnsPanel = GUILayout.Toggle(_showItemColumnsPanel, "Columns", GUI.skin.button, GUILayout.Width(70)); } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); if (!_showItemListView && _showItemColumnsPanel) { DrawItemColumnsPanel(); } if (!_showItemListView && _showItemFilterPanel) { DrawItemFilterPanel(); } } else if (Tabs[_selectedTab] == typeof(Recipe)) { EditorGUILayout.BeginHorizontal(); _showRecipeGridView = EditorGUILayout.ToggleLeft("Grid View", _showRecipeGridView, GUILayout.Width(80)); if (_showRecipeGridView) { _showRecipeFilterPanel = DrawFilterToggle(_showRecipeFilterPanel, string.IsNullOrEmpty(_recipeNameFilter) ? 0 : 1); } EditorGUILayout.EndHorizontal(); if (_showRecipeGridView && _showRecipeFilterPanel) { DrawRecipeFilterPanel(); } } else { _showItemListView = false; } if (previousSearchString != _searchString || _selectedTab != previousSelectedTab) { _selectedIndex = -1; _selectionAnchor = null; } var visibleScriptableObjects = ScriptableObjectPostprocessor.cachedScriptableObjects .Where(so => Tabs[_selectedTab].IsAssignableFrom(so.GetType()) && MatchesNameFilter(so)) .OrderBy(so => so.name) .ToList(); var names = visibleScriptableObjects.Select(so => so.name).ToArray(); if (!_showItemListView && Tabs[_selectedTab] == typeof(Item)) { DrawItemGridView(visibleScriptableObjects); } else if (Tabs[_selectedTab] == typeof(QuestTask)) { DrawGroupedQuestTasks(visibleScriptableObjects); } else if (Tabs[_selectedTab] == typeof(DialogueSequence)) { DrawGroupedDialogueSequences(visibleScriptableObjects); } else if (Tabs[_selectedTab] == typeof(Recipe)) { if (_showRecipeGridView) { DrawRecipeGridView(visibleScriptableObjects); } else { DrawRecipeListView(visibleScriptableObjects, names); } } else if (Tabs[_selectedTab] == typeof(Quest)) { DrawQuestListWithTaskCount(visibleScriptableObjects); } else { DrawListView(visibleScriptableObjects, names); } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } private void DrawListView(List visibleScriptableObjects, string[] names) { var previouslySelectedIndex = _selectedIndex; _selectedIndex = GUILayout.SelectionGrid(_selectedIndex, names, 1, EditorStyles.objectField); if (_selectedIndex >= 0 && previouslySelectedIndex != _selectedIndex) { var selectedObject = visibleScriptableObjects.First(so => so.name == names[_selectedIndex]); Selection.activeObject = selectedObject; RevealInProjectWindow(selectedObject); } } private void DrawItemGridView(List visibleScriptableObjects) { var items = new List(); foreach (var obj in visibleScriptableObjects) { if (obj is Item item && MatchesColumnFilters(item)) { items.Add(item); } } List columns = GetShownItemColumns(); if (!columns.Any(c => c.Sortable && c.Key == _itemSortKey)) { _itemSortKey = NameColumnKey; _itemSortAscending = true; } items = ApplyItemSorting(items); HandleItemKeyboard(items); DrawItemHeader(columns); for (int i = 0; i < items.Count; i++) { DrawItemRow(items[i], i, items, columns); } if (Event.current.type == EventType.Repaint && items.Count > 0 && SyncWrappedColumnWidths(columns)) { Repaint(); } if (items.Count == 0) { string message = HasActiveFilterOnHiddenColumn() ? "No items match the current search and filters. Some active filters are on columns that are not shown." : "No items match the current search and filters."; EditorGUILayout.LabelField(message, EditorStyles.centeredGreyMiniLabel, GUILayout.Height(ItemRowHeight)); } } private static bool SyncWrappedColumnWidths(List columns) { bool changed = false; foreach (ItemColumnDefinition column in columns) { if (column.Wrap && _measuredWrappedColumnWidths.TryGetValue(column.Key, out float measured) && !Mathf.Approximately(measured, GetWrappedColumnWidth(column))) { _wrappedColumnWidths[column.Key] = measured; changed = true; } } return changed; } private static float GetWrappedColumnWidth(ItemColumnDefinition column) { return _wrappedColumnWidths.TryGetValue(column.Key, out float width) ? width : column.Width; } private static GUIStyle ItemRowStyle => _itemRowStyle ??= new GUIStyle { padding = new RectOffset(EditorStyles.toolbar.padding.left, EditorStyles.toolbar.padding.right, 0, 0) }; private static Rect ItemCell(float width, float height) { return GUILayoutUtility.GetRect(width, width, height, height, GUIStyle.none); } private static Rect ItemFlexCell(float minWidth, float height) { return GUILayoutUtility.GetRect(minWidth, 100000f, height, height, GUIStyle.none, GUILayout.ExpandWidth(true)); } private static string GetExpandingColumnKey(List columns) { return columns.LastOrDefault(c => c.Flexible)?.Key; } private static Rect ItemColumnCell(ItemColumnDefinition column, float height, bool expand) { return expand ? ItemFlexCell(column.Width, height) : ItemCell(column.Width, height); } private static Rect GetResizeHandleRect(Rect cell) { return new Rect(cell.xMax - ColumnResizeHandleWidth * 0.5f, cell.y, ColumnResizeHandleWidth, cell.height); } private static int GetColumnDropIndex(List rects, float x) { for (int i = 0; i < rects.Count; i++) { if (x < rects[i].center.x) { return i; } } return rects.Count; } private static void ToggleItemSort(string key) { if (_itemSortKey == key) { _itemSortAscending = !_itemSortAscending; } else { _itemSortKey = key; _itemSortAscending = true; } } private void DrawItemHeader(List columns) { float height = Mathf.Max(18f, EditorStyles.toolbar.fixedHeight); string expandingKey = GetExpandingColumnKey(columns); Rect headerRect = EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); var rects = new List(columns.Count); foreach (ItemColumnDefinition column in columns) { rects.Add(ItemColumnCell(column, height, column.Key == expandingKey)); } EditorGUILayout.EndHorizontal(); int controlId = GUIUtility.GetControlID(FocusType.Passive); Event evt = Event.current; int hoveredHandle = -1; int hoveredColumn = -1; for (int i = 0; i < columns.Count; i++) { if (columns[i].Key != expandingKey) { Rect handleRect = GetResizeHandleRect(rects[i]); if (evt.type == EventType.Repaint) { EditorGUIUtility.AddCursorRect(handleRect, MouseCursor.ResizeHorizontal); } if (handleRect.Contains(evt.mousePosition)) { hoveredHandle = i; } } if (rects[i].Contains(evt.mousePosition)) { hoveredColumn = i; } } switch (evt.GetTypeForControl(controlId)) { case EventType.MouseDown when evt.button == 0 && hoveredHandle >= 0: _resizingColumn = hoveredHandle; GUIUtility.hotControl = controlId; evt.Use(); break; case EventType.MouseDown when evt.button == 0 && hoveredColumn >= 0: _pressedHeaderColumn = hoveredColumn; _headerPressPosition = evt.mousePosition; _isDraggingColumn = false; _columnDropIndex = -1; GUIUtility.hotControl = controlId; evt.Use(); break; case EventType.MouseDrag when GUIUtility.hotControl == controlId && _resizingColumn >= 0 && _resizingColumn < columns.Count: columns[_resizingColumn].Width = Mathf.Clamp(columns[_resizingColumn].Width + evt.delta.x, ColumnMinWidth, ColumnMaxWidth); evt.Use(); break; case EventType.MouseDrag when GUIUtility.hotControl == controlId && _pressedHeaderColumn >= 0: _isDraggingColumn |= Mathf.Abs(evt.mousePosition.x - _headerPressPosition.x) > 4f; _columnDropIndex = GetColumnDropIndex(rects, evt.mousePosition.x); evt.Use(); break; case EventType.MouseUp when GUIUtility.hotControl == controlId: GUIUtility.hotControl = 0; if (_resizingColumn >= 0) { SaveItemColumnWidths(); } else if (_isDraggingColumn) { MoveItemColumn(_pressedHeaderColumn, _columnDropIndex); } else if (_pressedHeaderColumn >= 0 && hoveredColumn == _pressedHeaderColumn && columns[hoveredColumn].Sortable) { ToggleItemSort(columns[hoveredColumn].Key); } _resizingColumn = -1; _pressedHeaderColumn = -1; _isDraggingColumn = false; _columnDropIndex = -1; evt.Use(); break; case EventType.Repaint: for (int i = 0; i < columns.Count; i++) { ItemColumnDefinition column = columns[i]; string label = column.HeaderLabel ?? column.Label; string text = column.Sortable && _itemSortKey == column.Key ? $"{label} {(_itemSortAscending ? "▲" : "▼")}" : label; bool hover = column.Sortable && i == hoveredColumn && hoveredHandle < 0 && GUIUtility.hotControl == 0; bool active = i == _pressedHeaderColumn && !_isDraggingColumn; HeaderCellStyle.Draw(rects[i], new GUIContent(text, column.Sortable ? $"Sort by {column.Label}" : column.Label), hover, active, false, false); } if (_isDraggingColumn && _columnDropIndex >= 0 && rects.Count > 0) { float x = _columnDropIndex < rects.Count ? rects[_columnDropIndex].x : rects[rects.Count - 1].xMax; EditorGUI.DrawRect(new Rect(x - 1f, headerRect.y, 2f, headerRect.height), SelectionColor(true)); } break; } } private static List ApplyItemSorting(List items) { Func selector = GetItemSortSelector(_itemSortKey); var keyed = items.Select(item => (item, value: selector(item))).ToList(); var withValue = keyed.Where(k => !IsEmptySortValue(k.value)); var ordered = _itemSortAscending ? withValue.OrderBy(k => k.value) : withValue.OrderByDescending(k => k.value); return ordered .ThenBy(k => k.item.displayName) .Select(k => k.item) .Concat(keyed.Where(k => IsEmptySortValue(k.value)).Select(k => k.item).OrderBy(i => i.displayName)) .ToList(); } private static Func GetItemSortSelector(string sortKey) { ItemColumnDefinition column = ItemColumns.FirstOrDefault(c => c.Key == sortKey); if (column == null || !column.Sortable) { return item => item.displayName; } return item => GetColumnSortValue(column, item); } private static bool IsEmptySortValue(IComparable value) { return value == null || value is string text && string.IsNullOrEmpty(text); } private void DrawItemRow(Item item, int index, List items, List columns) { string expandingKey = GetExpandingColumnKey(columns); float height = ItemRowHeight; foreach (ItemColumnDefinition column in columns) { if (column.Wrap) { height = Mathf.Max(height, WrappedCellStyle.CalcHeight(new GUIContent(GetColumnDisplayValue(column, item)), GetWrappedColumnWidth(column))); } } Rect rowRect = EditorGUILayout.BeginHorizontal(ItemRowStyle, GUILayout.Height(height)); if (Event.current.type == EventType.Repaint) { DrawItemRowBackground(rowRect, item, index); } foreach (ItemColumnDefinition column in columns) { Rect cell = ItemColumnCell(column, height, column.Key == expandingKey); if (column.DrawCell != null) { column.DrawCell(cell, item); } else if (column.Wrap) { GUI.Label(cell, GetColumnDisplayValue(column, item), WrappedCellStyle); if (Event.current.type == EventType.Repaint) { _measuredWrappedColumnWidths[column.Key] = cell.width; } } else { DrawCell(cell, GetColumnDisplayValue(column, item)); } } EditorGUILayout.EndHorizontal(); if (Event.current.type == EventType.Repaint && _scrollToItem == item) { _scrollToItem = null; GUI.ScrollTo(rowRect); Repaint(); } HandleItemRowEvents(rowRect, item, items); } private static void DrawCell(Rect rect, string text) { GUI.Label(rect, new GUIContent(text, text), CellStyle); } private void DrawItemRowBackground(Rect rowRect, Item item, int index) { if (Selection.Contains(item)) { EditorGUI.DrawRect(rowRect, SelectionColor(focusedWindow == this)); return; } if (index % 2 == 1) { EditorGUI.DrawRect(rowRect, StripeColor); } if (GUIUtility.hotControl == 0 && rowRect.Contains(Event.current.mousePosition)) { EditorGUI.DrawRect(rowRect, HoverColor); } } private static void DrawSpriteIcon(Rect cell, Sprite sprite) { if (Event.current.type != EventType.Repaint) { return; } if (sprite == null || sprite.texture == null) { GUI.Label(cell, "—", CellStyle); return; } Texture2D texture = sprite.texture; Rect spriteRect = sprite.rect; float size = Mathf.Min(cell.width, ItemRowHeight) - 4f; float aspect = spriteRect.width / spriteRect.height; Vector2 drawSize = aspect >= 1f ? new Vector2(size, size / aspect) : new Vector2(size * aspect, size); Rect drawRect = new(cell.center.x - drawSize.x * 0.5f, cell.center.y - drawSize.y * 0.5f, drawSize.x, drawSize.y); Rect texCoords = new(spriteRect.x / texture.width, spriteRect.y / texture.height, spriteRect.width / texture.width, spriteRect.height / texture.height); GUI.DrawTextureWithTexCoords(drawRect, texture, texCoords); } private void HandleItemRowEvents(Rect rowRect, Item item, List items) { int controlId = GUIUtility.GetControlID(FocusType.Passive); Event evt = Event.current; switch (evt.GetTypeForControl(controlId)) { case EventType.MouseDown when rowRect.Contains(evt.mousePosition) && evt.button == 0: GUIUtility.keyboardControl = 0; if (evt.clickCount == 2) { EditorGUIUtility.PingObject(item); } else { ClickItem(item, items, evt); } _itemDragStart = evt.mousePosition; GUIUtility.hotControl = controlId; evt.Use(); break; case EventType.MouseDown when rowRect.Contains(evt.mousePosition) && evt.button == 1: GUIUtility.keyboardControl = 0; if (!Selection.Contains(item)) { SelectItem(item); } ShowItemContextMenu(item); evt.Use(); break; case EventType.MouseDrag when GUIUtility.hotControl == controlId: if ((evt.mousePosition - _itemDragStart).sqrMagnitude > 16f) { GUIUtility.hotControl = 0; _pendingSingleSelection = null; DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = Selection.Contains(item) ? Selection.objects : new UnityEngine.Object[] { item }; DragAndDrop.StartDrag(item.displayName); } evt.Use(); break; case EventType.MouseUp when GUIUtility.hotControl == controlId: GUIUtility.hotControl = 0; if (_pendingSingleSelection == item) { SelectItem(item); } _pendingSingleSelection = null; evt.Use(); break; } } private static void ClickItem(Item item, List items, Event evt) { if (evt.shift && _selectionAnchor != null && items.Contains(_selectionAnchor)) { int from = items.IndexOf(_selectionAnchor); int to = items.IndexOf(item); Selection.objects = items.GetRange(Mathf.Min(from, to), Mathf.Abs(to - from) + 1).Cast().ToArray(); } else if (EditorGUI.actionKey) { var selected = Selection.objects.ToList(); if (!selected.Remove(item)) { selected.Add(item); } Selection.objects = selected.ToArray(); _selectionAnchor = item; } else if (Selection.Contains(item) && Selection.objects.Length > 1) { _pendingSingleSelection = item; } else { SelectItem(item); } } private static void SelectItem(Item item) { Selection.activeObject = item; _selectionAnchor = item; } private void HandleItemKeyboard(List items) { Event evt = Event.current; if (evt.type != EventType.KeyDown || items.Count == 0 || EditorGUIUtility.editingTextField) { return; } int current = items.IndexOf(Selection.activeObject as Item); if ((evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter) && current >= 0) { EditorGUIUtility.PingObject(items[current]); evt.Use(); return; } int next = evt.keyCode switch { KeyCode.UpArrow => Mathf.Max(current - 1, 0), KeyCode.DownArrow => Mathf.Min(current + 1, items.Count - 1), KeyCode.Home => 0, KeyCode.End => items.Count - 1, _ => -1 }; if (next < 0) { return; } SelectItem(items[next]); _scrollToItem = items[next]; evt.Use(); } private static void ShowItemContextMenu(Item item) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Show in Project"), false, () => EditorGUIUtility.PingObject(item)); menu.AddItem(new GUIContent("Open in New Inspector"), false, () => EditorUtility.OpenPropertyEditor(item)); menu.AddSeparator(string.Empty); menu.AddItem(new GUIContent("Copy Name"), false, () => EditorGUIUtility.systemCopyBuffer = item.displayName); menu.ShowAsContext(); } private void BuildQuestTaskGroups(List visibleScriptableObjects) { if (_lastTabForTaskGrouping != _selectedTab) { _taskToQuestMap.Clear(); _groupedTasks.Clear(); _questGroupFoldouts.Clear(); _lastTabForTaskGrouping = _selectedTab; var allQuests = ScriptableObjectPostprocessor.cachedScriptableObjects .OfType() .ToList(); foreach (var quest in allQuests) { if (quest.tasks != null) { foreach (var task in quest.tasks) { if (task != null) { _taskToQuestMap[task] = quest; } } } } } _groupedTasks.Clear(); var unassignedTasks = new List(); foreach (var obj in visibleScriptableObjects) { var task = obj as QuestTask; if (task != null) { if (_taskToQuestMap.TryGetValue(task, out var quest)) { string groupKey = $"Quest: {quest.title ?? quest.name}"; if (!_groupedTasks.ContainsKey(groupKey)) { _groupedTasks[groupKey] = new List(); if (!_questGroupFoldouts.ContainsKey(groupKey)) { _questGroupFoldouts[groupKey] = true; } } _groupedTasks[groupKey].Add(task); } else { unassignedTasks.Add(task); } } } if (unassignedTasks.Count > 0) { _groupedTasks["[Unassigned]"] = unassignedTasks; if (!_questGroupFoldouts.ContainsKey("[Unassigned]")) { _questGroupFoldouts["[Unassigned]"] = true; } } } private void DrawGroupedQuestTasks(List visibleScriptableObjects) { BuildQuestTaskGroups(visibleScriptableObjects); var sortedGroups = _groupedTasks.Keys .OrderBy(key => key == "[Unassigned]" ? 0 : 1) .ThenBy(key => key) .ToList(); foreach (var groupKey in sortedGroups) { var tasksInGroup = _groupedTasks[groupKey]; EditorGUILayout.BeginHorizontal(); _questGroupFoldouts[groupKey] = EditorGUILayout.Foldout(_questGroupFoldouts[groupKey], $"{groupKey} ({tasksInGroup.Count})", true); EditorGUILayout.EndHorizontal(); if (_questGroupFoldouts[groupKey]) { EditorGUI.indentLevel++; foreach (var task in tasksInGroup) { EditorGUILayout.BeginHorizontal(EditorStyles.objectField); if (GUILayout.Button(task.name, EditorStyles.label)) { Selection.activeObject = task; EditorGUIUtility.PingObject(task); } EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } } } private void DrawQuestListWithTaskCount(List visibleScriptableObjects) { foreach (var obj in visibleScriptableObjects) { var quest = obj as Quest; if (quest == null) continue; EditorGUILayout.BeginHorizontal(EditorStyles.objectField); int taskCount = quest.tasks?.Length ?? 0; string displayText = $"{quest.title} ({taskCount} Tasks)"; if (GUILayout.Button(displayText, EditorStyles.label)) { Selection.activeObject = quest; EditorGUIUtility.PingObject(quest); } EditorGUILayout.EndHorizontal(); } } private void RevealInProjectWindow(ScriptableObject obj) { if (obj == null) return; string assetPath = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(assetPath)) { EditorGUIUtility.PingObject(obj); } } private void BuildRecipeStationMap() { _recipeToStationMap.Clear(); var allStations = ScriptableObjectPostprocessor.cachedScriptableObjects .OfType() .ToList(); foreach (var station in allStations) { if (station.recipes != null) { foreach (var recipe in station.recipes) { if (recipe != null) { _recipeToStationMap[recipe] = station; } } } } } private void DrawRecipeGridView(List visibleScriptableObjects) { BuildRecipeStationMap(); var sortedRecipes = new List(); foreach (var obj in visibleScriptableObjects) { if (obj is Recipe recipe && (string.IsNullOrEmpty(_recipeNameFilter) || recipe.displayName.IndexOf(_recipeNameFilter, StringComparison.OrdinalIgnoreCase) >= 0)) { sortedRecipes.Add(recipe); } } sortedRecipes = ApplyRecipeSorting(sortedRecipes); EditorGUILayout.LabelField("Recipes", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(GUI.skin.box); if (GUILayout.Button(GetRecipeSortIndicator("Recipe Name", RecipeSortColumn.Name), GUILayout.Width(200))) { ToggleRecipeSort(RecipeSortColumn.Name); } if (GUILayout.Button(GetRecipeSortIndicator("Station", RecipeSortColumn.Station), GUILayout.Width(150))) { ToggleRecipeSort(RecipeSortColumn.Station); } if (GUILayout.Button(GetRecipeSortIndicator("Cost", RecipeSortColumn.Cost), GUILayout.Width(70))) { ToggleRecipeSort(RecipeSortColumn.Cost); } EditorGUILayout.LabelField("Input", GUILayout.Width(150)); EditorGUILayout.LabelField("Output", GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); for (int i = 0; i < sortedRecipes.Count; i++) { DrawRecipeGridRow(sortedRecipes[i]); } } private void DrawRecipeListView(List visibleScriptableObjects, string[] names) { BuildRecipeStationMap(); var recipes = new List(); foreach (var obj in visibleScriptableObjects) { if (obj is Recipe recipe) { recipes.Add(recipe); } } EditorGUILayout.LabelField("Recipes", EditorStyles.boldLabel); var recipeNames = recipes.Select(r => r.displayName).ToArray(); var previouslySelectedIndex = _selectedIndex; _selectedIndex = GUILayout.SelectionGrid(_selectedIndex, recipeNames, 1, EditorStyles.objectField); if (_selectedIndex >= 0 && _selectedIndex < recipes.Count && previouslySelectedIndex != _selectedIndex) { Selection.activeObject = recipes[_selectedIndex]; EditorGUIUtility.PingObject(recipes[_selectedIndex]); } } private List ApplyRecipeSorting(List recipes) { return _recipeSortColumn switch { RecipeSortColumn.Name => _recipeSortAscending ? recipes.OrderBy(r => r.displayName).ToList() : recipes.OrderByDescending(r => r.displayName).ToList(), RecipeSortColumn.Station => _recipeSortAscending ? recipes.OrderBy(r => _recipeToStationMap.TryGetValue(r, out var s) ? s.name : "[Unassigned]").ToList() : recipes.OrderByDescending(r => _recipeToStationMap.TryGetValue(r, out var s) ? s.name : "[Unassigned]").ToList(), RecipeSortColumn.Cost => _recipeSortAscending ? recipes.OrderBy(r => CalculateRecipeCost(r)).ToList() : recipes.OrderByDescending(r => CalculateRecipeCost(r)).ToList(), _ => recipes }; } private void ToggleRecipeSort(RecipeSortColumn column) { if (_recipeSortColumn == column) { _recipeSortAscending = !_recipeSortAscending; } else { _recipeSortColumn = column; _recipeSortAscending = true; } } private string GetRecipeSortIndicator(string columnName, RecipeSortColumn column) { if (_recipeSortColumn != column) { return columnName; } return _recipeSortAscending ? $"{columnName} ▲" : $"{columnName} ▼"; } private int CalculateRecipeCost(Recipe recipe) { if (_recipeToStationMap.TryGetValue(recipe, out var station)) { return recipe.CalculateCraftCost(station.flatPrice, station.priceMultiplier); } return 0; } private void DrawRecipeGridRow(Recipe recipe) { int ingredientCount = recipe.ingredients != null ? recipe.ingredients.Count : 0; float lineHeight = 16f; float rowHeight = Mathf.Max(24f, (ingredientCount + 1) * lineHeight + 8f); var normalColor = GUI.backgroundColor; var isSelected = Selection.activeObject == recipe; if (isSelected) { GUI.backgroundColor = new Color(0.3f, 0.6f, 1f, 1f); } Rect rowRect = EditorGUILayout.BeginHorizontal(GUI.skin.box, GUILayout.Height(rowHeight)); if (GUI.Button(rowRect, GUIContent.none, GUIStyle.none)) { Selection.activeObject = recipe; EditorGUIUtility.PingObject(recipe); Repaint(); } GUI.backgroundColor = normalColor; EditorGUILayout.BeginVertical(GUILayout.Width(200)); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField(recipe.displayName, EditorStyles.label, GUILayout.Width(200)); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.Width(150)); GUILayout.FlexibleSpace(); string stationName = "[Unassigned]"; if (_recipeToStationMap.TryGetValue(recipe, out var station)) { stationName = station.name; } EditorGUILayout.LabelField(stationName, GUILayout.Width(150)); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.Width(70)); GUILayout.FlexibleSpace(); int cost = CalculateRecipeCost(recipe); EditorGUILayout.LabelField(cost.ToString(), GUILayout.Width(70)); GUILayout.FlexibleSpace(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.Width(150)); if (recipe.ingredients != null && recipe.ingredients.Count > 0) { foreach (var ingredient in recipe.ingredients) { EditorGUILayout.LabelField($"{ingredient.Value}x {(ingredient.Key != null ? ingredient.Key.displayName : "[None]")}", EditorStyles.label, GUILayout.Width(150)); } } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayout.ExpandWidth(true)); if (recipe.item != null) { string outputText = recipe.quantity > 1 ? $"{recipe.quantity}x {recipe.item.displayName}" : recipe.item.displayName; EditorGUILayout.LabelField(outputText, EditorStyles.label); if (recipe.additionalOutput != null && recipe.additionalOutput.Count > 0) { foreach (var kvp in recipe.additionalOutput) { string additionalText = kvp.Value > 1 ? $"{kvp.Value}x {kvp.Key.displayName}" : kvp.Key.displayName; EditorGUILayout.LabelField(additionalText, EditorStyles.label); } } } EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } private void BuildDialogueSequenceGroups(List visibleScriptableObjects) { if (_lastTabForDialogueGrouping != _selectedTab) { _dialogueToSourceMap.Clear(); _groupedDialogues.Clear(); _dialogueGroupFoldouts.Clear(); _lastTabForDialogueGrouping = _selectedTab; var allQuests = ScriptableObjectPostprocessor.cachedScriptableObjects .OfType() .ToList(); foreach (var quest in allQuests) { string speakerName = null; if (quest.offeredBy != null) { speakerName = quest.offeredBy.displayName; } else if (quest.reportTo != null) { speakerName = quest.reportTo.displayName; } if (speakerName != null) { if (quest.questOfferDialogue != null) { _dialogueToSourceMap[quest.questOfferDialogue] = speakerName; } if (quest.questHintDialogue != null) { _dialogueToSourceMap[quest.questHintDialogue] = speakerName; } if (quest.questCompletedDialogue != null) { _dialogueToSourceMap[quest.questCompletedDialogue] = speakerName; } } } var allQuestTasks = ScriptableObjectPostprocessor.cachedScriptableObjects .OfType() .ToList(); foreach (var task in allQuestTasks) { if (task.dialogue != null && task.target != null) { _dialogueToSourceMap[task.dialogue] = task.target.displayName; } } } _groupedDialogues.Clear(); foreach (var obj in visibleScriptableObjects) { var dialogue = obj as DialogueSequence; if (dialogue == null) continue; string groupKey = "[Unassigned]"; if (_dialogueToSourceMap.TryGetValue(dialogue, out var source)) { groupKey = source; } if (!_groupedDialogues.ContainsKey(groupKey)) { _groupedDialogues[groupKey] = new List(); if (!_dialogueGroupFoldouts.ContainsKey(groupKey)) { _dialogueGroupFoldouts[groupKey] = true; } } _groupedDialogues[groupKey].Add(dialogue); } } private void DrawGroupedDialogueSequences(List visibleScriptableObjects) { BuildDialogueSequenceGroups(visibleScriptableObjects); var sortedGroups = _groupedDialogues.Keys .OrderBy(key => key == "[Unassigned]" ? 0 : 1) .ThenBy(key => key) .ToList(); foreach (var groupKey in sortedGroups) { var dialoguesInGroup = _groupedDialogues[groupKey]; EditorGUILayout.BeginHorizontal(); _dialogueGroupFoldouts[groupKey] = EditorGUILayout.Foldout(_dialogueGroupFoldouts[groupKey], $"{groupKey} ({dialoguesInGroup.Count})", true); EditorGUILayout.EndHorizontal(); if (_dialogueGroupFoldouts[groupKey]) { EditorGUI.indentLevel++; foreach (var dialogue in dialoguesInGroup) { EditorGUILayout.BeginHorizontal(EditorStyles.objectField); if (GUILayout.Button(dialogue.name, EditorStyles.label)) { Selection.activeObject = dialogue; EditorGUIUtility.PingObject(dialogue); } EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; } } } } }