From ea63ca82bf1d8c3af2dc5416eba3d18265c137e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lucas=20Vilas-B=C3=B4as?= Date: Fri, 15 Mar 2024 12:35:46 +0000 Subject: [PATCH] Adjustments (#53) --- Config/DefaultElementusInventory.ini | 32 +- ElementusInventory.uplugin | 78 +- .../ElementusInventory.Build.cs | 34 +- .../Actors/ElementusInventoryPackage.cpp | 109 +- .../ElementusInventoryComponent.cpp | 1268 ++++++++--------- .../Private/ElementusInventory.cpp | 2 +- .../Private/LogElementusInventory.cpp | 2 +- .../Management/ElementusInventoryData.cpp | 2 +- .../ElementusInventoryFunctions.cpp | 555 ++++---- .../Management/ElementusInventorySettings.cpp | 27 +- .../Public/Actors/ElementusInventoryPackage.h | 51 +- .../Components/ElementusInventoryComponent.h | 300 ++-- .../Public/ElementusInventory.h | 6 +- .../Public/LogElementusInventory.h | 3 +- .../Management/ElementusInventoryData.h | 206 +-- .../Management/ElementusInventoryFunctions.h | 169 +-- .../Management/ElementusInventorySettings.h | 45 +- .../ElementusInventoryEditor.Build.cs | 50 +- .../Private/ElementusInventoryEditor.cpp | 91 +- .../Private/SElementusDetailsPanel.cpp | 90 +- .../Private/SElementusDetailsPanel.h | 20 +- .../Private/SElementusFrame.cpp | 67 +- .../Private/SElementusFrame.h | 14 +- .../Private/SElementusItemCreator.cpp | 652 ++++----- .../Private/SElementusItemCreator.h | 56 +- .../Private/SElementusSearch.cpp | 184 ++- .../Private/SElementusSearch.h | 25 +- .../Private/SElementusTable.cpp | 492 ++++--- .../Private/SElementusTable.h | 108 +- .../Private/SElementusUtils.cpp | 140 +- .../Private/SElementusUtils.h | 18 +- .../Public/ElementusInventoryEditor.h | 10 +- 32 files changed, 2407 insertions(+), 2499 deletions(-) diff --git a/Config/DefaultElementusInventory.ini b/Config/DefaultElementusInventory.ini index c00ee41..fcaba87 100644 --- a/Config/DefaultElementusInventory.ini +++ b/Config/DefaultElementusInventory.ini @@ -1,21 +1,21 @@ [CoreRedirects] -+ClassRedirects=(OldName="/Script/ElementusInventory.InventoryItemData",NewName="/Script/ElementusInventory.ElementusItemData") ++ClassRedirects = (OldName="/Script/ElementusInventory.InventoryItemData",NewName="/Script/ElementusInventory.ElementusItemData") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareElementusItems",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareItemInfo") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareElementusItemDatas",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareItemData") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetElementusItemDataById",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetSingleItemDataById") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetElementusItemDataArrayById",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemDataArrayById") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.SearchElementusItemData",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.SearchItemData") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CanStackItem",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.IsItemStackable") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemTagsFromParent",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemTagsWithParentTag") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareElementusItems",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareItemInfo") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareElementusItemDatas",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.CompareItemData") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetElementusItemDataById",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetSingleItemDataById") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetElementusItemDataArrayById",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemDataArrayById") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.SearchElementusItemData",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.SearchItemData") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.CanStackItem",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.IsItemStackable") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemTagsFromParent",NewName="/Script/ElementusInventory.ElementusInventoryFunctions.GetItemTagsWithParentTag") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.GetItemStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.GetItemsArray") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.FindElementusItemInStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.FindFirstItemIndexWithInfo") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.FindElementusItemInStackWithTags",NewName="/Script/ElementusInventory.ElementusInventoryComponent.FindFirstItemIndexWithTags") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.ContainItemInStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.ContainsItem") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.DebugInventoryStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.DebugInventory") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.GetItemStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.GetItemsArray") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.FindElementusItemInStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.FindFirstItemIndexWithInfo") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.FindElementusItemInStackWithTags",NewName="/Script/ElementusInventory.ElementusInventoryComponent.FindFirstItemIndexWithTags") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.ContainItemInStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.ContainsItem") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.DebugInventoryStack",NewName="/Script/ElementusInventory.ElementusInventoryComponent.DebugInventory") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.AddElementusItem",NewName="/Script/ElementusInventory.ElementusInventoryComponent.AddElementusItems") -+FunctionRedirects=(OldName="/Script/ElementusInventory.ElementusInventoryComponent.RemoveElementusItem",NewName="/Script/ElementusInventory.ElementusInventoryComponent.RemoveElementusItems") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.AddElementusItem",NewName="/Script/ElementusInventory.ElementusInventoryComponent.AddElementusItems") ++FunctionRedirects = (OldName="/Script/ElementusInventory.ElementusInventoryComponent.RemoveElementusItem",NewName="/Script/ElementusInventory.ElementusInventoryComponent.RemoveElementusItems") -+FunctionRedirects=(OldName="/Script/ElementusInventory.UElementusInventoryFunctions.SearchItemData",NewName="/Script/ElementusInventory.UElementusInventoryFunctions.SearchElementusItemData") \ No newline at end of file ++FunctionRedirects = (OldName="/Script/ElementusInventory.UElementusInventoryFunctions.SearchItemData",NewName="/Script/ElementusInventory.UElementusInventoryFunctions.SearchElementusItemData") \ No newline at end of file diff --git a/ElementusInventory.uplugin b/ElementusInventory.uplugin index 379d39e..421bb3c 100644 --- a/ElementusInventory.uplugin +++ b/ElementusInventory.uplugin @@ -1,41 +1,41 @@ { - "FileVersion": 3, - "Version": 7, - "VersionName": "1.1.9", - "FriendlyName": "Elementus Inventory", - "Description": "Plugin that provides a Data-Driven Inventory & Items system based on FPrimaryAssetIds and the Asset Manager.", - "Category": "Game Features", - "CreatedBy": "Lucas Vilas-Boas", - "CreatedByURL": "https://github.com/lucoiso", - "DocsURL": "https://github.com/lucoiso/UEElementusInventory/wiki", - "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/ed47993a6b8a49bdb04dfe83939b6361", - "SupportURL": "https://github.com/lucoiso/UEElementusInventory/issues", - "CanContainContent": false, - "IsBetaVersion": true, - "IsExperimentalVersion": false, - "Installed": false, - "Modules": [ - { - "Name": "ElementusInventory", - "Type": "Runtime", - "LoadingPhase": "Default", - "WhitelistPlatforms": [ - "Win64", - "Mac", - "Linux", - "IOS", - "Android" - ] - }, - { - "Name": "ElementusInventoryEditor", - "Type": "Editor", - "LoadingPhase": "Default", - "PlatformAllowList": [ - "Win64", - "Mac", - "Linux" - ] - } - ] + "FileVersion": 3, + "Version": 8, + "VersionName": "1.1.10", + "FriendlyName": "Elementus Inventory", + "Description": "Plugin that provides a Data-Driven Inventory & Items system based on FPrimaryAssetIds and the Asset Manager.", + "Category": "Game Features", + "CreatedBy": "Lucas Vilas-Boas", + "CreatedByURL": "https://github.com/lucoiso", + "DocsURL": "https://github.com/lucoiso/UEElementusInventory/wiki", + "MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/ed47993a6b8a49bdb04dfe83939b6361", + "SupportURL": "https://github.com/lucoiso/UEElementusInventory/issues", + "CanContainContent": false, + "IsBetaVersion": true, + "IsExperimentalVersion": false, + "Installed": false, + "Modules": [ + { + "Name": "ElementusInventory", + "Type": "Runtime", + "LoadingPhase": "Default", + "WhitelistPlatforms": [ + "Win64", + "Mac", + "Linux", + "IOS", + "Android" + ] + }, + { + "Name": "ElementusInventoryEditor", + "Type": "Editor", + "LoadingPhase": "Default", + "PlatformAllowList": [ + "Win64", + "Mac", + "Linux" + ] + } + ] } \ No newline at end of file diff --git a/Source/ElementusInventory/ElementusInventory.Build.cs b/Source/ElementusInventory/ElementusInventory.Build.cs index e9105dd..4adb2f9 100644 --- a/Source/ElementusInventory/ElementusInventory.Build.cs +++ b/Source/ElementusInventory/ElementusInventory.Build.cs @@ -6,23 +6,23 @@ public class ElementusInventory : ModuleRules { - public ElementusInventory(ReadOnlyTargetRules Target) : base(Target) - { - PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; - CppStandard = CppStandardVersion.Cpp17; + public ElementusInventory(ReadOnlyTargetRules Target) : base(Target) + { + PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; + CppStandard = CppStandardVersion.Cpp17; - PublicDependencyModuleNames.AddRange(new[] - { - "Core" - }); + PublicDependencyModuleNames.AddRange(new[] + { + "Core" + }); - PrivateDependencyModuleNames.AddRange(new[] - { - "Engine", - "NetCore", - "CoreUObject", - "GameplayTags", - "DeveloperSettings" - }); - } + PrivateDependencyModuleNames.AddRange(new[] + { + "Engine", + "NetCore", + "CoreUObject", + "GameplayTags", + "DeveloperSettings" + }); + } } \ No newline at end of file diff --git a/Source/ElementusInventory/Private/Actors/ElementusInventoryPackage.cpp b/Source/ElementusInventory/Private/Actors/ElementusInventoryPackage.cpp index 8da7387..babdea2 100644 --- a/Source/ElementusInventory/Private/Actors/ElementusInventoryPackage.cpp +++ b/Source/ElementusInventory/Private/Actors/ElementusInventoryPackage.cpp @@ -17,92 +17,95 @@ AElementusInventoryPackage::AElementusInventoryPackage(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { - bNetStartup = false; - bNetLoadOnClient = false; - bReplicates = true; + bNetStartup = false; + bNetLoadOnClient = false; + bReplicates = true; - PrimaryActorTick.bCanEverTick = false; - PrimaryActorTick.bStartWithTickEnabled = false; + PrimaryActorTick.bCanEverTick = false; + PrimaryActorTick.bStartWithTickEnabled = false; - RootComponent = CreateDefaultSubobject(TEXT("RootComponent")); + RootComponent = CreateDefaultSubobject(TEXT("RootComponent")); - PackageInventory = CreateDefaultSubobject(TEXT("PackageInventory")); - PackageInventory->SetIsReplicated(true); + PackageInventory = CreateDefaultSubobject(TEXT("PackageInventory")); + PackageInventory->SetIsReplicated(true); - if (const UElementusInventorySettings* const Settings = UElementusInventorySettings::Get()) - { - bDestroyWhenInventoryIsEmpty = Settings->bDestroyWhenInventoryIsEmpty; - } + if (const UElementusInventorySettings* const Settings = UElementusInventorySettings::Get()) + { + bDestroyWhenInventoryIsEmpty = Settings->bDestroyWhenInventoryIsEmpty; + } } void AElementusInventoryPackage::BeginPlay() { - Super::BeginPlay(); + Super::BeginPlay(); - SetDestroyOnEmpty(bDestroyWhenInventoryIsEmpty); + SetDestroyOnEmpty(bDestroyWhenInventoryIsEmpty); - if (bDestroyWhenInventoryIsEmpty && UElementusInventoryFunctions::HasEmptyParam(PackageInventory->GetItemsArray())) - { - Destroy(); - } + if (bDestroyWhenInventoryIsEmpty && UElementusInventoryFunctions::HasEmptyParam(PackageInventory->GetItemsArray())) + { + Destroy(); + } } void AElementusInventoryPackage::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { - Super::GetLifetimeReplicatedProps(OutLifetimeProps); + Super::GetLifetimeReplicatedProps(OutLifetimeProps); - FDoRepLifetimeParams SharedParams; - SharedParams.bIsPushBased = true; + FDoRepLifetimeParams SharedParams; + SharedParams.bIsPushBased = true; - DOREPLIFETIME_WITH_PARAMS_FAST(AElementusInventoryPackage, PackageInventory, SharedParams); + DOREPLIFETIME_WITH_PARAMS_FAST(AElementusInventoryPackage, PackageInventory, SharedParams); } void AElementusInventoryPackage::PutItemIntoPackage(const TArray ItemInfo, UElementusInventoryComponent* FromInventory) { - UElementusInventoryFunctions::TradeElementusItem(ItemInfo, FromInventory, PackageInventory); - MARK_PROPERTY_DIRTY_FROM_NAME(AElementusInventoryPackage, PackageInventory, this); + UElementusInventoryFunctions::TradeElementusItem(ItemInfo, FromInventory, PackageInventory); + MARK_PROPERTY_DIRTY_FROM_NAME(AElementusInventoryPackage, PackageInventory, this); } void AElementusInventoryPackage::GetItemFromPackage(const TArray ItemInfo, UElementusInventoryComponent* ToInventory) { - UElementusInventoryFunctions::TradeElementusItem(ItemInfo, PackageInventory, ToInventory); - MARK_PROPERTY_DIRTY_FROM_NAME(AElementusInventoryPackage, PackageInventory, this); + UElementusInventoryFunctions::TradeElementusItem(ItemInfo, PackageInventory, ToInventory); + MARK_PROPERTY_DIRTY_FROM_NAME(AElementusInventoryPackage, PackageInventory, this); } void AElementusInventoryPackage::SetDestroyOnEmpty(const bool bDestroy) { - if (bDestroyWhenInventoryIsEmpty == bDestroy) - { - return; - } - - bDestroyWhenInventoryIsEmpty = bDestroy; - FElementusInventoryEmpty Delegate = PackageInventory->OnInventoryEmpty; - - if (const bool bIsAlreadyBound = Delegate.IsAlreadyBound(this, &AElementusInventoryPackage::BeginPackageDestruction); bDestroy && !bIsAlreadyBound) - { - Delegate.AddDynamic(this, &AElementusInventoryPackage::BeginPackageDestruction); - } - else if (!bDestroy && bIsAlreadyBound) - { - Delegate.RemoveDynamic(this, &AElementusInventoryPackage::BeginPackageDestruction); - } + if (bDestroyWhenInventoryIsEmpty == bDestroy) + { + return; + } + + bDestroyWhenInventoryIsEmpty = bDestroy; + FElementusInventoryEmpty Delegate = PackageInventory->OnInventoryEmpty; + + if (const bool bIsAlreadyBound = Delegate.IsAlreadyBound(this, &AElementusInventoryPackage::BeginPackageDestruction); bDestroy && ! + bIsAlreadyBound) + { + Delegate.AddDynamic(this, &AElementusInventoryPackage::BeginPackageDestruction); + } + else if (!bDestroy && bIsAlreadyBound) + { + Delegate.RemoveDynamic(this, &AElementusInventoryPackage::BeginPackageDestruction); + } } bool AElementusInventoryPackage::GetDestroyOnEmpty() const { - return bDestroyWhenInventoryIsEmpty; + return bDestroyWhenInventoryIsEmpty; } void AElementusInventoryPackage::BeginPackageDestruction_Implementation() { - // Check if this option is still active before the destruction - if (bDestroyWhenInventoryIsEmpty) - { - Destroy(); - } - else - { - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("ElementusInventory - %s: Package %s was not destroyed because the " "option 'bDestroyWhenInventoryIsEmpty' was disabled"), *FString(__func__), *GetName()); - } -} \ No newline at end of file + // Check if this option is still active before the destruction + if (bDestroyWhenInventoryIsEmpty) + { + Destroy(); + } + else + { + UE_LOG(LogElementusInventory_Internal, Warning, + TEXT("ElementusInventory - %s: Package %s was not destroyed because the " "option 'bDestroyWhenInventoryIsEmpty' was disabled"), + *FString(__func__), *GetName()); + } +} diff --git a/Source/ElementusInventory/Private/Components/ElementusInventoryComponent.cpp b/Source/ElementusInventory/Private/Components/ElementusInventoryComponent.cpp index d5e5b8b..4b3f5b6 100644 --- a/Source/ElementusInventory/Private/Components/ElementusInventoryComponent.cpp +++ b/Source/ElementusInventory/Private/Components/ElementusInventoryComponent.cpp @@ -16,832 +16,824 @@ #include UE_INLINE_GENERATED_CPP_BY_NAME(ElementusInventoryComponent) #endif -UElementusInventoryComponent::UElementusInventoryComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), CurrentWeight(0.f), MaxWeight(0.f), MaxNumItems(0) +UElementusInventoryComponent::UElementusInventoryComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), + CurrentWeight(0.f), MaxWeight(0.f), MaxNumItems(0) { - PrimaryComponentTick.bCanEverTick = false; - PrimaryComponentTick.bStartWithTickEnabled = false; + PrimaryComponentTick.bCanEverTick = false; + PrimaryComponentTick.bStartWithTickEnabled = false; - SetIsReplicatedByDefault(true); + SetIsReplicatedByDefault(true); - if (const UElementusInventorySettings* const Settings = UElementusInventorySettings::Get()) - { - bAllowEmptySlots = Settings->bAllowEmptySlots; - MaxWeight = Settings->MaxWeight; - MaxNumItems = Settings->MaxNumItems; - } + if (const UElementusInventorySettings* const Settings = UElementusInventorySettings::Get()) + { + bAllowEmptySlots = Settings->bAllowEmptySlots; + MaxWeight = Settings->MaxWeight; + MaxNumItems = Settings->MaxNumItems; + } } float UElementusInventoryComponent::GetCurrentWeight() const { - return CurrentWeight; + return CurrentWeight; } float UElementusInventoryComponent::GetMaxWeight() const { - return MaxWeight <= 0.f ? MAX_flt : MaxWeight; + return MaxWeight <= 0.f ? MAX_flt : MaxWeight; } int32 UElementusInventoryComponent::GetCurrentNumItems() const { - return ElementusItems.Num(); + return ElementusItems.Num(); } int32 UElementusInventoryComponent::GetMaxNumItems() const { - return MaxNumItems <= 0 ? MAX_int32 : MaxNumItems; + return MaxNumItems <= 0 ? MAX_int32 : MaxNumItems; } TArray UElementusInventoryComponent::GetItemsArray() const { - return ElementusItems; + return ElementusItems; } FElementusItemInfo& UElementusInventoryComponent::GetItemReferenceAt(const int32 Index) { - return ElementusItems[Index]; + return ElementusItems[Index]; } FElementusItemInfo UElementusInventoryComponent::GetItemCopyAt(const int32 Index) const { - return ElementusItems[Index]; + return ElementusItems[Index]; } bool UElementusInventoryComponent::CanReceiveItem(const FElementusItemInfo InItemInfo) const { - if (!UElementusInventoryFunctions::IsItemValid(InItemInfo)) - { - return false; - } + if (!UElementusInventoryFunctions::IsItemValid(InItemInfo)) + { + return false; + } - bool bOutput = ElementusItems.Num() <= GetMaxNumItems(); + bool bOutput = ElementusItems.Num() <= GetMaxNumItems(); - if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(InItemInfo.ItemId, { "Data" })) - { - bOutput = bOutput && ((GetCurrentWeight() + (ItemData->ItemWeight * InItemInfo.Quantity)) <= GetMaxWeight()); - } + if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(InItemInfo.ItemId, {"Data"})) + { + bOutput = bOutput && ((GetCurrentWeight() + (ItemData->ItemWeight * InItemInfo.Quantity)) <= GetMaxWeight()); + } - if (!bOutput) - { - UE_LOG(LogElementusInventory, Warning, TEXT("%s: Actor %s cannot receive %d item(s) with name '%s'"), *FString(__func__), *GetOwner()->GetName(), InItemInfo.Quantity, *InItemInfo.ItemId.ToString()); - } + if (!bOutput) + { + UE_LOG(LogElementusInventory, Warning, TEXT("%s: Actor %s cannot receive %d item(s) with name '%s'"), *FString(__func__), + *GetOwner()->GetName(), InItemInfo.Quantity, *InItemInfo.ItemId.ToString()); + } - return bOutput; + return bOutput; } bool UElementusInventoryComponent::CanGiveItem(const FElementusItemInfo InItemInfo) const { - if (!UElementusInventoryFunctions::IsItemValid(InItemInfo)) - { - return false; - } + if (!UElementusInventoryFunctions::IsItemValid(InItemInfo)) + { + return false; + } - if (TArray InIndex; FindAllItemIndexesWithInfo(InItemInfo, InIndex, FGameplayTagContainer::EmptyContainer)) - { - int32 Quantity = 0u; - for (const int32& Index : InIndex) - { - Quantity += ElementusItems[Index].Quantity; - } + if (TArray InIndex; FindAllItemIndexesWithInfo(InItemInfo, InIndex, FGameplayTagContainer::EmptyContainer)) + { + int32 Quantity = 0u; + for (const int32& Index : InIndex) + { + Quantity += ElementusItems[Index].Quantity; + } - return Quantity >= InItemInfo.Quantity; - } + return Quantity >= InItemInfo.Quantity; + } - UE_LOG(LogElementusInventory, Warning, TEXT("%s: Actor %s cannot give %d item(s) with name '%s'"), *FString(__func__), *GetOwner()->GetName(), InItemInfo.Quantity, *InItemInfo.ItemId.ToString()); + UE_LOG(LogElementusInventory, Warning, TEXT("%s: Actor %s cannot give %d item(s) with name '%s'"), *FString(__func__), *GetOwner()->GetName(), + InItemInfo.Quantity, *InItemInfo.ItemId.ToString()); - return false; + return false; } void UElementusInventoryComponent::SortInventory(const EElementusInventorySortingMode Mode, const EElementusInventorySortingOrientation Orientation) { - const auto SortByOrientation = [Orientation](const auto A, const auto B) { - switch (Orientation) - { - case EElementusInventorySortingOrientation::Ascending: - return A < B; - - case EElementusInventorySortingOrientation::Descending: - return A > B; - - default: - return false; - } - - return false; - }; - - switch (Mode) - { - case EElementusInventorySortingMode::ID: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.ItemId, B.ItemId); - } - ); - break; - - case EElementusInventorySortingMode::Name: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemName.ToString(), ItemDataB->ItemName.ToString()); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::Type: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemType, ItemDataB->ItemType); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::IndividualValue: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemValue, ItemDataB->ItemValue); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::StackValue: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemValue * A.Quantity, ItemDataB->ItemValue * B.Quantity); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::IndividualWeight: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemWeight, ItemDataB->ItemWeight); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::StackWeight: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - if (!UElementusInventoryFunctions::IsItemValid(A)) - { - return false; - } - - if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, { "Data" })) - { - if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, { "Data" })) - { - return SortByOrientation(ItemDataA->ItemWeight * A.Quantity, ItemDataB->ItemWeight * B.Quantity); - } - } - - return false; - } - ); - break; - - case EElementusInventorySortingMode::Quantity: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Quantity, B.Quantity); - } - ); - break; - - case EElementusInventorySortingMode::Level: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Level, B.Level); - } - ); - break; - - case EElementusInventorySortingMode::Tags: - ElementusItems.Sort( - [SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) - { - return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Tags.Num(), B.Tags.Num()); - } - ); - break; - - default: - break; - } + const auto SortByOrientation = [Orientation](const auto A, const auto B) + { + switch (Orientation) + { + case EElementusInventorySortingOrientation::Ascending: + return A < B; + + case EElementusInventorySortingOrientation::Descending: + return A > B; + + default: + return false; + } + + return false; + }; + + switch (Mode) + { + case EElementusInventorySortingMode::ID: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.ItemId, B.ItemId); + }); + break; + + case EElementusInventorySortingMode::Name: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemName.ToString(), ItemDataB->ItemName.ToString()); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::Type: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemType, ItemDataB->ItemType); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::IndividualValue: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemValue, ItemDataB->ItemValue); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::StackValue: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemValue * A.Quantity, ItemDataB->ItemValue * B.Quantity); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::IndividualWeight: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemWeight, ItemDataB->ItemWeight); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::StackWeight: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + if (!UElementusInventoryFunctions::IsItemValid(A)) + { + return false; + } + + if (const UElementusItemData* const ItemDataA = UElementusInventoryFunctions::GetSingleItemDataById(A.ItemId, {"Data"})) + { + if (const UElementusItemData* const ItemDataB = UElementusInventoryFunctions::GetSingleItemDataById(B.ItemId, {"Data"})) + { + return SortByOrientation(ItemDataA->ItemWeight * A.Quantity, ItemDataB->ItemWeight * B.Quantity); + } + } + + return false; + }); + break; + + case EElementusInventorySortingMode::Quantity: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Quantity, B.Quantity); + }); + break; + + case EElementusInventorySortingMode::Level: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Level, B.Level); + }); + break; + + case EElementusInventorySortingMode::Tags: + ElementusItems.Sort([SortByOrientation](const FElementusItemInfo& A, const FElementusItemInfo& B) + { + return UElementusInventoryFunctions::IsItemValid(A) && SortByOrientation(A.Tags.Num(), B.Tags.Num()); + }); + break; + + default: + break; + } } void UElementusInventoryComponent::BeginPlay() { - Super::BeginPlay(); + Super::BeginPlay(); - RefreshInventory(); + RefreshInventory(); } void UElementusInventoryComponent::GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const { - Super::GetLifetimeReplicatedProps(OutLifetimeProps); + Super::GetLifetimeReplicatedProps(OutLifetimeProps); - FDoRepLifetimeParams SharedParams; - SharedParams.bIsPushBased = true; + FDoRepLifetimeParams SharedParams; + SharedParams.bIsPushBased = true; - DOREPLIFETIME_WITH_PARAMS_FAST(UElementusInventoryComponent, ElementusItems, SharedParams); + DOREPLIFETIME_WITH_PARAMS_FAST(UElementusInventoryComponent, ElementusItems, SharedParams); } void UElementusInventoryComponent::RefreshInventory() { - ForceWeightUpdate(); - ForceInventoryValidation(); + ForceWeightUpdate(); + ForceInventoryValidation(); } void UElementusInventoryComponent::ForceWeightUpdate() { - float NewWeigth = 0.f; - for (const FElementusItemInfo& Iterator : ElementusItems) - { - if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(Iterator.ItemId, { "Data" })) - { - NewWeigth += ItemData->ItemWeight * Iterator.Quantity; - } - } + float NewWeigth = 0.f; + for (const FElementusItemInfo& Iterator : ElementusItems) + { + if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(Iterator.ItemId, {"Data"})) + { + NewWeigth += ItemData->ItemWeight * Iterator.Quantity; + } + } - CurrentWeight = NewWeigth; + CurrentWeight = NewWeigth; } void UElementusInventoryComponent::ForceInventoryValidation() { - TArray NewItems; - TArray IndexesToRemove; - - for (int32 i = 0; i < ElementusItems.Num(); ++i) - { - if (ElementusItems[i].Quantity <= 0) - { - IndexesToRemove.Add(i); - } - - else if (ElementusItems[i].Quantity > 1) - { - if (!UElementusInventoryFunctions::IsItemStackable(ElementusItems[i])) - { - for (int32 j = 0; j < ElementusItems[i].Quantity; ++j) - { - NewItems.Add(FElementusItemInfo(ElementusItems[i].ItemId, 1, ElementusItems[i].Tags)); - } - - IndexesToRemove.Add(i); - } - } - } - - if (!UElementusInventoryFunctions::HasEmptyParam(IndexesToRemove)) - { - for (const int32& Iterator : IndexesToRemove) - { - if (bAllowEmptySlots) - { - ElementusItems[Iterator] = FElementusItemInfo::EmptyItemInfo; - } - else - { - ElementusItems.RemoveAt(Iterator, 1, false); - } - } - } - if (!UElementusInventoryFunctions::HasEmptyParam(NewItems)) - { - ElementusItems.Append(NewItems); - } - - NotifyInventoryChange(); -} + TArray NewItems; + TArray IndexesToRemove; + + for (int32 i = 0; i < ElementusItems.Num(); ++i) + { + if (ElementusItems[i].Quantity <= 0) + { + IndexesToRemove.Add(i); + } + + else if (ElementusItems[i].Quantity > 1) + { + if (!UElementusInventoryFunctions::IsItemStackable(ElementusItems[i])) + { + for (int32 j = 0; j < ElementusItems[i].Quantity; ++j) + { + NewItems.Add(FElementusItemInfo(ElementusItems[i].ItemId, 1, ElementusItems[i].Tags)); + } + + IndexesToRemove.Add(i); + } + } + } + + if (!UElementusInventoryFunctions::HasEmptyParam(IndexesToRemove)) + { + for (const int32& Iterator : IndexesToRemove) + { + if (bAllowEmptySlots) + { + ElementusItems[Iterator] = FElementusItemInfo::EmptyItemInfo; + } + else + { + ElementusItems.RemoveAt(Iterator, 1, false); + } + } + } + if (!UElementusInventoryFunctions::HasEmptyParam(NewItems)) + { + ElementusItems.Append(NewItems); + } + + NotifyInventoryChange(); +} + +bool UElementusInventoryComponent::FindFirstItemIndexWithInfo(const FElementusItemInfo& InItemInfo, int32& OutIndex, + const FGameplayTagContainer& IgnoreTags, const int32 Offset) const +{ + for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) + { + FElementusItemInfo InParamCopy = InItemInfo; + InParamCopy.Tags.RemoveTags(IgnoreTags); + + FElementusItemInfo InExistingCopy = ElementusItems[Iterator]; + InExistingCopy.Tags.RemoveTags(IgnoreTags); + + if (InExistingCopy == InParamCopy) + { + OutIndex = Iterator; + return true; + } + } + + OutIndex = INDEX_NONE; + return false; +} + +bool UElementusInventoryComponent::FindFirstItemIndexWithTags(const FGameplayTagContainer& WithTags, int32& OutIndex, + const FGameplayTagContainer& IgnoreTags, const int32 Offset) const +{ + for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) + { + FElementusItemInfo InExistingCopy = ElementusItems[Iterator]; + InExistingCopy.Tags.RemoveTags(IgnoreTags); + + if (InExistingCopy.Tags.HasAllExact(WithTags)) + { + OutIndex = Iterator; + return true; + } + } + + OutIndex = INDEX_NONE; + return false; +} + +bool UElementusInventoryComponent::FindFirstItemIndexWithId(const FPrimaryElementusItemId& InId, int32& OutIndex, + const FGameplayTagContainer& IgnoreTags, const int32 Offset) const +{ + for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) + { + if (!ElementusItems[Iterator].Tags.HasAny(IgnoreTags) && ElementusItems[Iterator].ItemId == InId) + { + OutIndex = Iterator; + return true; + } + } + + OutIndex = INDEX_NONE; + return false; +} + +bool UElementusInventoryComponent::FindAllItemIndexesWithInfo(const FElementusItemInfo& InItemInfo, TArray& OutIndexes, + const FGameplayTagContainer& IgnoreTags) const +{ + for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) + { + if (IgnoreTags.IsEmpty() && *Iterator == InItemInfo) + { + OutIndexes.Add(Iterator.GetIndex()); + continue; + } -bool UElementusInventoryComponent::FindFirstItemIndexWithInfo(const FElementusItemInfo InItemInfo, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset) const -{ - for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) - { - FElementusItemInfo InParamCopy = InItemInfo; - InParamCopy.Tags.RemoveTags(IgnoreTags); - - FElementusItemInfo InExistingCopy = ElementusItems[Iterator]; - InExistingCopy.Tags.RemoveTags(IgnoreTags); - - if (InExistingCopy == InParamCopy) - { - OutIndex = Iterator; - return true; - } - } - - OutIndex = INDEX_NONE; - return false; -} - -bool UElementusInventoryComponent::FindFirstItemIndexWithTags(const FGameplayTagContainer WithTags, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset) const -{ - for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) - { - FElementusItemInfo InExistingCopy = ElementusItems[Iterator]; - InExistingCopy.Tags.RemoveTags(IgnoreTags); + FElementusItemInfo InItCopy(*Iterator); + InItCopy.Tags.RemoveTags(IgnoreTags); - if (InExistingCopy.Tags.HasAllExact(WithTags)) - { - OutIndex = Iterator; - return true; - } - } + FElementusItemInfo InParamCopy(InItemInfo); + InParamCopy.Tags.RemoveTags(IgnoreTags); - OutIndex = INDEX_NONE; - return false; -} - -bool UElementusInventoryComponent::FindFirstItemIndexWithId(const FPrimaryElementusItemId InId, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset) const -{ - for (int32 Iterator = Offset; Iterator < ElementusItems.Num(); ++Iterator) - { - if (!ElementusItems[Iterator].Tags.HasAny(IgnoreTags) && ElementusItems[Iterator].ItemId == InId) - { - OutIndex = Iterator; - return true; - } - } - - OutIndex = INDEX_NONE; - return false; -} - -bool UElementusInventoryComponent::FindAllItemIndexesWithInfo(const FElementusItemInfo InItemInfo, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const -{ - for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) - { - if (IgnoreTags.IsEmpty() && *Iterator == InItemInfo) - { - OutIndexes.Add(Iterator.GetIndex()); - continue; - } - - FElementusItemInfo InItCopy(*Iterator); - InItCopy.Tags.RemoveTags(IgnoreTags); - - FElementusItemInfo InParamCopy(InItemInfo); - InParamCopy.Tags.RemoveTags(IgnoreTags); + if (InItCopy == InParamCopy) + { + OutIndexes.Add(Iterator.GetIndex()); + } + } - if (InItCopy == InParamCopy) - { - OutIndexes.Add(Iterator.GetIndex()); - } - } - - return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); + return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); } -bool UElementusInventoryComponent::FindAllItemIndexesWithTags(const FGameplayTagContainer WithTags, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const +bool UElementusInventoryComponent::FindAllItemIndexesWithTags(const FGameplayTagContainer& WithTags, TArray& OutIndexes, + const FGameplayTagContainer& IgnoreTags) const { - for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) - { - FElementusItemInfo InCopy(*Iterator); - if (!IgnoreTags.IsEmpty()) - { - InCopy.Tags.RemoveTags(IgnoreTags); - } + for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) + { + FElementusItemInfo InCopy(*Iterator); + if (!IgnoreTags.IsEmpty()) + { + InCopy.Tags.RemoveTags(IgnoreTags); + } - if (InCopy.Tags.HasAll(WithTags)) - { - OutIndexes.Add(Iterator.GetIndex()); - } - } + if (InCopy.Tags.HasAll(WithTags)) + { + OutIndexes.Add(Iterator.GetIndex()); + } + } - return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); + return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); } -bool UElementusInventoryComponent::FindAllItemIndexesWithId(const FPrimaryElementusItemId InId, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const +bool UElementusInventoryComponent::FindAllItemIndexesWithId(const FPrimaryElementusItemId& InId, TArray& OutIndexes, + const FGameplayTagContainer& IgnoreTags) const { - for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) - { - if (!Iterator->Tags.HasAll(IgnoreTags) && Iterator->ItemId == InId) - { - OutIndexes.Add(Iterator.GetIndex()); - } - } + for (auto Iterator = ElementusItems.CreateConstIterator(); Iterator; ++Iterator) + { + if (!Iterator->Tags.HasAll(IgnoreTags) && Iterator->ItemId == InId) + { + OutIndexes.Add(Iterator.GetIndex()); + } + } - return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); + return !UElementusInventoryFunctions::HasEmptyParam(OutIndexes); } -bool UElementusInventoryComponent::ContainsItem(const FElementusItemInfo InItemInfo, const bool bIgnoreTags) const +bool UElementusInventoryComponent::ContainsItem(const FElementusItemInfo& InItemInfo, const bool bIgnoreTags) const { - return ElementusItems.FindByPredicate( - [&InItemInfo, &bIgnoreTags](const FElementusItemInfo& InInfo) - { - if (bIgnoreTags) - { - return InInfo.ItemId == InItemInfo.ItemId; - } + return ElementusItems.FindByPredicate([&InItemInfo, &bIgnoreTags](const FElementusItemInfo& InInfo) + { + if (bIgnoreTags) + { + return InInfo.ItemId == InItemInfo.ItemId; + } - return InInfo == InItemInfo; - } - ) != nullptr; + return InInfo == InItemInfo; + }) != nullptr; } bool UElementusInventoryComponent::IsInventoryEmpty() const { - bool bOutput = true; + bool bOutput = true; - for (const FElementusItemInfo& Iterator : ElementusItems) - { - if (Iterator.Quantity > 0) - { - bOutput = false; - break; - } - } + for (const FElementusItemInfo& Iterator : ElementusItems) + { + if (Iterator.Quantity > 0) + { + bOutput = false; + break; + } + } - return bOutput; + return bOutput; } void UElementusInventoryComponent::DebugInventory() { #if !UE_BUILD_SHIPPING - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("%s"), *FString(__func__)); - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Owning Actor: %s"), *GetOwner()->GetName()); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("%s"), *FString(__func__)); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Owning Actor: %s"), *GetOwner()->GetName()); - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Weight: %d"), CurrentWeight); - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Num: %d"), ElementusItems.Num()); - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Size: %d"), ElementusItems.GetAllocatedSize()); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Weight: %d"), CurrentWeight); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Num: %d"), ElementusItems.Num()); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Size: %d"), ElementusItems.GetAllocatedSize()); - for (const FElementusItemInfo& Iterator : ElementusItems) - { - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Item: %s"), *Iterator.ItemId.ToString()); - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Quantity: %d"), Iterator.Quantity); + for (const FElementusItemInfo& Iterator : ElementusItems) + { + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Item: %s"), *Iterator.ItemId.ToString()); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Quantity: %d"), Iterator.Quantity); - for (const FGameplayTag& Tag : Iterator.Tags) - { - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Tag: %s"), *Tag.ToString()); - } - } + for (const FGameplayTag& Tag : Iterator.Tags) + { + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Tag: %s"), *Tag.ToString()); + } + } - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Component Memory Size: %d"), GetResourceSizeBytes(EResourceSizeMode::EstimatedTotal)); + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("Component Memory Size: %d"), GetResourceSizeBytes(EResourceSizeMode::EstimatedTotal)); #endif } void UElementusInventoryComponent::ClearInventory_Implementation() { - UE_LOG(LogElementusInventory, Display, TEXT("%s: Cleaning %s's inventory"), *FString(__func__), *GetOwner()->GetName()); + UE_LOG(LogElementusInventory, Display, TEXT("%s: Cleaning %s's inventory"), *FString(__func__), *GetOwner()->GetName()); - ElementusItems.Empty(); - CurrentWeight = 0.f; + ElementusItems.Empty(); + CurrentWeight = 0.f; } void UElementusInventoryComponent::GetItemIndexesFrom_Implementation(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } + if (GetOwnerRole() != ROLE_Authority) + { + return; + } - TArray Modifiers; - for (const int32& Iterator : ItemIndexes) - { - if (OtherInventory->ElementusItems.IsValidIndex(Iterator)) - { - Modifiers.Add(OtherInventory->ElementusItems[Iterator]); - } - } + TArray Modifiers; + for (const int32& Iterator : ItemIndexes) + { + if (OtherInventory->ElementusItems.IsValidIndex(Iterator)) + { + Modifiers.Add(OtherInventory->ElementusItems[Iterator]); + } + } - GetItemsFrom_Implementation(OtherInventory, Modifiers); + GetItemsFrom_Implementation(OtherInventory, Modifiers); } void UElementusInventoryComponent::GiveItemIndexesTo_Implementation(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } + if (GetOwnerRole() != ROLE_Authority) + { + return; + } - TArray Modifiers; - for (const int32& Iterator : ItemIndexes) - { - if (OtherInventory->ElementusItems.IsValidIndex(Iterator)) - { - Modifiers.Add(ElementusItems[Iterator]); - } - } + TArray Modifiers; + for (const int32& Iterator : ItemIndexes) + { + if (OtherInventory->ElementusItems.IsValidIndex(Iterator)) + { + Modifiers.Add(ElementusItems[Iterator]); + } + } - GiveItemsTo_Implementation(OtherInventory, Modifiers); + GiveItemsTo_Implementation(OtherInventory, Modifiers); } void UElementusInventoryComponent::GetItemsFrom_Implementation(UElementusInventoryComponent* OtherInventory, const TArray& Items) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } + if (GetOwnerRole() != ROLE_Authority) + { + return; + } - if (!IsValid(OtherInventory)) - { - return; - } + if (!IsValid(OtherInventory)) + { + return; + } - const TArray TradeableItems = UElementusInventoryFunctions::FilterTradeableItems(OtherInventory, this, Items); + const TArray TradeableItems = UElementusInventoryFunctions::FilterTradeableItems(OtherInventory, this, Items); - OtherInventory->UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Remove); - UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Add); + OtherInventory->UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Remove); + UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Add); } void UElementusInventoryComponent::GiveItemsTo_Implementation(UElementusInventoryComponent* OtherInventory, const TArray& Items) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } + if (GetOwnerRole() != ROLE_Authority) + { + return; + } - if (!IsValid(OtherInventory)) - { - return; - } + if (!IsValid(OtherInventory)) + { + return; + } - const TArray TradeableItems = UElementusInventoryFunctions::FilterTradeableItems(this, OtherInventory, Items); + const TArray TradeableItems = UElementusInventoryFunctions::FilterTradeableItems(this, OtherInventory, Items); - UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Remove); - OtherInventory->UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Add); + UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Remove); + OtherInventory->UpdateElementusItems(TradeableItems, EElementusInventoryUpdateOperation::Add); } void UElementusInventoryComponent::DiscardItemIndexes_Implementation(const TArray& ItemIndexes) { - if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(ItemIndexes)) - { - return; - } + if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(ItemIndexes)) + { + return; + } - TArray Modifiers; - for (const int32& Iterator : ItemIndexes) - { - if (ElementusItems.IsValidIndex(Iterator)) - { - Modifiers.Add(ElementusItems[Iterator]); - } - } + TArray Modifiers; + for (const int32& Iterator : ItemIndexes) + { + if (ElementusItems.IsValidIndex(Iterator)) + { + Modifiers.Add(ElementusItems[Iterator]); + } + } - DiscardItems(Modifiers); + DiscardItems(Modifiers); } void UElementusInventoryComponent::DiscardItems_Implementation(const TArray& Items) { - if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(Items)) - { - return; - } + if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(Items)) + { + return; + } - UpdateElementusItems(Items, EElementusInventoryUpdateOperation::Remove); + UpdateElementusItems(Items, EElementusInventoryUpdateOperation::Remove); } void UElementusInventoryComponent::AddItems_Implementation(const TArray& Items) { - if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(Items)) - { - return; - } + if (GetOwnerRole() != ROLE_Authority || UElementusInventoryFunctions::HasEmptyParam(Items)) + { + return; + } - UpdateElementusItems(Items, EElementusInventoryUpdateOperation::Add); + UpdateElementusItems(Items, EElementusInventoryUpdateOperation::Add); } -void UElementusInventoryComponent::UpdateElementusItems(const TArray& Modifiers, const EElementusInventoryUpdateOperation Operation) +void UElementusInventoryComponent::UpdateElementusItems(const TArray& Modifiers, + const EElementusInventoryUpdateOperation Operation) { - TArray ModifierDataArr; + TArray ModifierDataArr; - const FString OpStr = Operation == EElementusInventoryUpdateOperation::Add ? "Add" : "Remove"; - const FString OpPred = Operation == EElementusInventoryUpdateOperation::Add ? "to" : "from"; + const FString OpStr = Operation == EElementusInventoryUpdateOperation::Add ? "Add" : "Remove"; + const FString OpPred = Operation == EElementusInventoryUpdateOperation::Add ? "to" : "from"; - uint32 SearchOffset = 0; - FElementusItemInfo LastCheckedItem; - for (const FElementusItemInfo& Iterator : Modifiers) - { - UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: %s %d item(s) with name '%s' %s inventory"), *FString(__func__), *OpStr, Iterator.Quantity, *Iterator.ItemId.ToString(), *OpPred); + uint32 SearchOffset = 0; + FElementusItemInfo LastCheckedItem; + for (const FElementusItemInfo& Iterator : Modifiers) + { + UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: %s %d item(s) with name '%s' %s inventory"), *FString(__func__), *OpStr, + Iterator.Quantity, *Iterator.ItemId.ToString(), *OpPred); - if (Iterator != LastCheckedItem) - { - SearchOffset = 0u; - } + if (Iterator != LastCheckedItem) + { + SearchOffset = 0u; + } - int32 Index; - if (FindFirstItemIndexWithInfo(Iterator, Index, FGameplayTagContainer::EmptyContainer, SearchOffset) && Operation == EElementusInventoryUpdateOperation::Remove) - { - SearchOffset = Index + 1u; - } + int32 Index; + if (FindFirstItemIndexWithInfo(Iterator, Index, FGameplayTagContainer::EmptyContainer, SearchOffset) && Operation == + EElementusInventoryUpdateOperation::Remove) + { + SearchOffset = Index + 1u; + } - ModifierDataArr.Add(FItemModifierData(Iterator, Index)); - LastCheckedItem = Iterator; - } + ModifierDataArr.Add(FItemModifierData(Iterator, Index)); + LastCheckedItem = Iterator; + } - switch (Operation) - { - case EElementusInventoryUpdateOperation::Add: - Server_ProcessInventoryAddition_Internal(ModifierDataArr); - break; + switch (Operation) + { + case EElementusInventoryUpdateOperation::Add: + Server_ProcessInventoryAddition_Internal(ModifierDataArr); + break; - case EElementusInventoryUpdateOperation::Remove: - Server_ProcessInventoryRemoval_Internal(ModifierDataArr); - break; + case EElementusInventoryUpdateOperation::Remove: + Server_ProcessInventoryRemoval_Internal(ModifierDataArr); + break; - default: - break; - } + default: + break; + } } void UElementusInventoryComponent::Server_ProcessInventoryAddition_Internal_Implementation(const TArray& Modifiers) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } - - for (const FItemModifierData& Iterator : Modifiers) - { - if (const bool bIsStackable = UElementusInventoryFunctions::IsItemStackable(Iterator.ItemInfo); - bIsStackable && Iterator.Index != INDEX_NONE) - { - ElementusItems[Iterator.Index].Quantity += Iterator.ItemInfo.Quantity; - } - else if (!bIsStackable) - { - for (int32 i = 0u; i < Iterator.ItemInfo.Quantity; ++i) - { - const FElementusItemInfo ItemInfo{ Iterator.ItemInfo.ItemId, 1, Iterator.ItemInfo.Tags }; - - ElementusItems.Add(ItemInfo); - } - } - else - { - ElementusItems.Add(Iterator.ItemInfo); - } - } - - NotifyInventoryChange(); + if (GetOwnerRole() != ROLE_Authority) + { + return; + } + + for (const FItemModifierData& Iterator : Modifiers) + { + if (const bool bIsStackable = UElementusInventoryFunctions::IsItemStackable(Iterator.ItemInfo); bIsStackable && Iterator.Index != INDEX_NONE) + { + ElementusItems[Iterator.Index].Quantity += Iterator.ItemInfo.Quantity; + } + else if (!bIsStackable) + { + for (int32 i = 0u; i < Iterator.ItemInfo.Quantity; ++i) + { + const FElementusItemInfo ItemInfo{Iterator.ItemInfo.ItemId, 1, Iterator.ItemInfo.Tags}; + + ElementusItems.Add(ItemInfo); + } + } + else + { + ElementusItems.Add(Iterator.ItemInfo); + } + } + + NotifyInventoryChange(); } void UElementusInventoryComponent::Server_ProcessInventoryRemoval_Internal_Implementation(const TArray& Modifiers) { - if (GetOwnerRole() != ROLE_Authority) - { - return; - } - - for (const FItemModifierData& Iterator : Modifiers) - { - if (Iterator.Index == INDEX_NONE || Iterator.Index > ElementusItems.Num()) - { - UE_LOG(LogElementusInventory_Internal, Warning, TEXT("%s: Item with name '%s' not found in inventory"), *FString(__func__), *Iterator.ItemInfo.ItemId.ToString()); - - continue; - } - - ElementusItems[Iterator.Index].Quantity -= Iterator.ItemInfo.Quantity; - } - - if (bAllowEmptySlots) - { - Algo::ForEach(ElementusItems, [](FElementusItemInfo& InInfo) - { - if (InInfo.Quantity <= 0) - { - InInfo = FElementusItemInfo::EmptyItemInfo; - } - }); - } - else - { - ElementusItems.RemoveAll( - [](const FElementusItemInfo& InInfo) - { - return InInfo.Quantity <= 0; - } - ); - } - - NotifyInventoryChange(); + if (GetOwnerRole() != ROLE_Authority) + { + return; + } + + for (const FItemModifierData& Iterator : Modifiers) + { + if (Iterator.Index == INDEX_NONE || Iterator.Index > ElementusItems.Num()) + { + UE_LOG(LogElementusInventory_Internal, Warning, TEXT("%s: Item with name '%s' not found in inventory"), *FString(__func__), + *Iterator.ItemInfo.ItemId.ToString()); + + continue; + } + + ElementusItems[Iterator.Index].Quantity -= Iterator.ItemInfo.Quantity; + } + + if (bAllowEmptySlots) + { + Algo::ForEach(ElementusItems, [](FElementusItemInfo& InInfo) + { + if (InInfo.Quantity <= 0) + { + InInfo = FElementusItemInfo::EmptyItemInfo; + } + }); + } + else + { + ElementusItems.RemoveAll([](const FElementusItemInfo& InInfo) + { + return InInfo.Quantity <= 0; + }); + } + + NotifyInventoryChange(); } void UElementusInventoryComponent::OnRep_ElementusItems() { - if (const int32 LastValidIndex = ElementusItems.FindLastByPredicate([](const FElementusItemInfo& Item) { return UElementusInventoryFunctions::IsItemValid(Item); }); LastValidIndex != INDEX_NONE && ElementusItems.IsValidIndex(LastValidIndex + 1)) - { - ElementusItems.RemoveAt(LastValidIndex + 1, ElementusItems.Num() - LastValidIndex - 1, false); - } - else if (LastValidIndex == INDEX_NONE && !UElementusInventoryFunctions::HasEmptyParam(ElementusItems)) - { - ElementusItems.Empty(); - } + if (const int32 LastValidIndex = ElementusItems.FindLastByPredicate([](const FElementusItemInfo& Item) + { + return UElementusInventoryFunctions::IsItemValid(Item); + }); LastValidIndex != INDEX_NONE && ElementusItems.IsValidIndex(LastValidIndex + 1)) + { + ElementusItems.RemoveAt(LastValidIndex + 1, ElementusItems.Num() - LastValidIndex - 1, false); + } + else if (LastValidIndex == INDEX_NONE && !UElementusInventoryFunctions::HasEmptyParam(ElementusItems)) + { + ElementusItems.Empty(); + } - ElementusItems.Shrink(); + ElementusItems.Shrink(); - if (IsInventoryEmpty()) - { - ElementusItems.Empty(); + if (IsInventoryEmpty()) + { + ElementusItems.Empty(); - CurrentWeight = 0.f; - OnInventoryEmpty.Broadcast(); - } - else - { - UpdateWeight(); - } + CurrentWeight = 0.f; + OnInventoryEmpty.Broadcast(); + } + else + { + UpdateWeight(); + } - OnInventoryUpdate.Broadcast(); + OnInventoryUpdate.Broadcast(); } void UElementusInventoryComponent::NotifyInventoryChange() { - if (GetOwnerRole() == ROLE_Authority) - { - OnRep_ElementusItems(); - } + if (GetOwnerRole() == ROLE_Authority) + { + OnRep_ElementusItems(); + } - MARK_PROPERTY_DIRTY_FROM_NAME(UElementusInventoryComponent, ElementusItems, this); + MARK_PROPERTY_DIRTY_FROM_NAME(UElementusInventoryComponent, ElementusItems, this); } void UElementusInventoryComponent::UpdateWeight_Implementation() { - float NewWeight = 0.f; - for (const FElementusItemInfo& Iterator : ElementusItems) - { - if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(Iterator.ItemId, { "Data" })) - { - NewWeight += ItemData->ItemWeight * Iterator.Quantity; - } - } - - CurrentWeight = FMath::Clamp(NewWeight, 0.f, MAX_FLT); -} \ No newline at end of file + float NewWeight = 0.f; + for (const FElementusItemInfo& Iterator : ElementusItems) + { + if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(Iterator.ItemId, {"Data"})) + { + NewWeight += ItemData->ItemWeight * Iterator.Quantity; + } + } + + CurrentWeight = FMath::Clamp(NewWeight, 0.f, MAX_FLT); +} diff --git a/Source/ElementusInventory/Private/ElementusInventory.cpp b/Source/ElementusInventory/Private/ElementusInventory.cpp index f431499..d1466f9 100644 --- a/Source/ElementusInventory/Private/ElementusInventory.cpp +++ b/Source/ElementusInventory/Private/ElementusInventory.cpp @@ -13,4 +13,4 @@ void FElementusInventoryModule::ShutdownModule() { } -IMPLEMENT_MODULE(FElementusInventoryModule, ElementusInventory) \ No newline at end of file +IMPLEMENT_MODULE(FElementusInventoryModule, ElementusInventory) diff --git a/Source/ElementusInventory/Private/LogElementusInventory.cpp b/Source/ElementusInventory/Private/LogElementusInventory.cpp index a3639b8..800b622 100644 --- a/Source/ElementusInventory/Private/LogElementusInventory.cpp +++ b/Source/ElementusInventory/Private/LogElementusInventory.cpp @@ -5,4 +5,4 @@ #include "LogElementusInventory.h" DEFINE_LOG_CATEGORY(LogElementusInventory); -DEFINE_LOG_CATEGORY(LogElementusInventory_Internal); \ No newline at end of file +DEFINE_LOG_CATEGORY(LogElementusInventory_Internal); diff --git a/Source/ElementusInventory/Private/Management/ElementusInventoryData.cpp b/Source/ElementusInventory/Private/Management/ElementusInventoryData.cpp index 895a733..d2dcb32 100644 --- a/Source/ElementusInventory/Private/Management/ElementusInventoryData.cpp +++ b/Source/ElementusInventory/Private/Management/ElementusInventoryData.cpp @@ -12,4 +12,4 @@ const FElementusItemInfo FElementusItemInfo::EmptyItemInfo(FPrimaryElementusItem UElementusItemData::UElementusItemData(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { -} \ No newline at end of file +} diff --git a/Source/ElementusInventory/Private/Management/ElementusInventoryFunctions.cpp b/Source/ElementusInventory/Private/Management/ElementusInventoryFunctions.cpp index 1a59b1e..a55e7dc 100644 --- a/Source/ElementusInventory/Private/Management/ElementusInventoryFunctions.cpp +++ b/Source/ElementusInventory/Private/Management/ElementusInventoryFunctions.cpp @@ -16,378 +16,385 @@ void UElementusInventoryFunctions::UnloadAllElementusItems() { #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - AssetManager->UnloadPrimaryAssetsWithType(FPrimaryAssetType(ElementusItemDataType)); - } + { + AssetManager->UnloadPrimaryAssetsWithType(FPrimaryAssetType(ElementusItemDataType)); + } } void UElementusInventoryFunctions::UnloadElementusItem(const FPrimaryElementusItemId& InItemId) { #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - AssetManager->UnloadPrimaryAsset(FPrimaryAssetId(InItemId)); - } + { + AssetManager->UnloadPrimaryAsset(FPrimaryAssetId(InItemId)); + } } bool UElementusInventoryFunctions::CompareItemInfo(const FElementusItemInfo& Info1, const FElementusItemInfo& Info2) { - return Info1 == Info2; + return Info1 == Info2; } bool UElementusInventoryFunctions::CompareItemData(const UElementusItemData* Data1, const UElementusItemData* Data2) { - return Data1->GetPrimaryAssetId() == Data2->GetPrimaryAssetId(); + return Data1->GetPrimaryAssetId() == Data2->GetPrimaryAssetId(); } -UElementusItemData* UElementusInventoryFunctions::GetSingleItemDataById(const FPrimaryElementusItemId& InID, const TArray& InBundles, const bool bAutoUnload) +UElementusItemData* UElementusInventoryFunctions::GetSingleItemDataById(const FPrimaryElementusItemId& InID, const TArray& InBundles, + const bool bAutoUnload) { - UElementusItemData* Output = nullptr; + UElementusItemData* Output = nullptr; #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - if (const TSharedPtr StreamableHandle = AssetManager->LoadPrimaryAsset(InID, InBundles); StreamableHandle.IsValid()) - { - StreamableHandle->WaitUntilComplete(5.f); - Output = Cast(StreamableHandle->GetLoadedAsset()); - } - else // The object is already loaded - { - Output = AssetManager->GetPrimaryAssetObject(InID); - } - - if (bAutoUnload) - { - AssetManager->UnloadPrimaryAsset(InID); - } - } - - return Output; + { + if (const TSharedPtr StreamableHandle = AssetManager->LoadPrimaryAsset(InID, InBundles); StreamableHandle.IsValid()) + { + StreamableHandle->WaitUntilComplete(5.f); + Output = Cast(StreamableHandle->GetLoadedAsset()); + } + else // The object is already loaded + { + Output = AssetManager->GetPrimaryAssetObject(InID); + } + + if (bAutoUnload) + { + AssetManager->UnloadPrimaryAsset(InID); + } + } + + return Output; } -TArray UElementusInventoryFunctions::GetItemDataArrayById(const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload) +TArray UElementusInventoryFunctions::GetItemDataArrayById(const TArray& InIDs, + const TArray& InBundles, const bool bAutoUnload) { - TArray Output; + TArray Output; #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - Output = LoadElementusItemDatas_Internal(AssetManager, InIDs, InBundles, bAutoUnload); - } - return Output; + { + Output = LoadElementusItemDatas_Internal(AssetManager, InIDs, InBundles, bAutoUnload); + } + return Output; } -TArray UElementusInventoryFunctions::SearchElementusItemData(const EElementusSearchType SearchType, const FString& SearchString, const TArray& InBundles, const bool bAutoUnload) +TArray UElementusInventoryFunctions::SearchElementusItemData(const EElementusSearchType SearchType, const FString& SearchString, + const TArray& InBundles, const bool bAutoUnload) { - TArray Output; + TArray Output; #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - TArray ReturnedValues = LoadElementusItemDatas_Internal(AssetManager, GetAllElementusItemIds(), InBundles, bAutoUnload); - - for (UElementusItemData* const& Iterator : ReturnedValues) - { - UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Filtering items. Current iteration: id %s and name %s"), *FString(__func__), *FString::FromInt(Iterator->ItemId), *Iterator->ItemName.ToString()); - - bool bAddItem = false; - switch (SearchType) - { - case EElementusSearchType::Name: - bAddItem = Iterator->ItemName.ToString().Contains(SearchString, ESearchCase::IgnoreCase); - break; - - case EElementusSearchType::ID: - bAddItem = FString::FromInt(Iterator->ItemId).Contains(SearchString, ESearchCase::IgnoreCase); - break; - - case EElementusSearchType::Type: - bAddItem = ElementusItemEnumTypeToString(Iterator->ItemType).Contains(SearchString, ESearchCase::IgnoreCase); - break; - - default: - break; - } - - if (bAddItem) - { - UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Item with id %s and name %s matches the search parameters"), *FString(__func__), *FString::FromInt(Iterator->ItemId), *Iterator->ItemName.ToString()); - - Output.Add(Iterator); - } - } - } - - return Output; + { + TArray ReturnedValues = LoadElementusItemDatas_Internal(AssetManager, GetAllElementusItemIds(), InBundles, bAutoUnload); + + for (UElementusItemData* const& Iterator : ReturnedValues) + { + UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Filtering items. Current iteration: id %s and name %s"), *FString(__func__), + *FString::FromInt(Iterator->ItemId), *Iterator->ItemName.ToString()); + + bool bAddItem = false; + switch (SearchType) + { + case EElementusSearchType::Name: + bAddItem = Iterator->ItemName.ToString().Contains(SearchString, ESearchCase::IgnoreCase); + break; + + case EElementusSearchType::ID: + bAddItem = FString::FromInt(Iterator->ItemId).Contains(SearchString, ESearchCase::IgnoreCase); + break; + + case EElementusSearchType::Type: + bAddItem = ElementusItemEnumTypeToString(Iterator->ItemType).Contains(SearchString, ESearchCase::IgnoreCase); + break; + + default: + break; + } + + if (bAddItem) + { + UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Item with id %s and name %s matches the search parameters"), + *FString(__func__), *FString::FromInt(Iterator->ItemId), *Iterator->ItemName.ToString()); + + Output.Add(Iterator); + } + } + } + + return Output; } -TMap UElementusInventoryFunctions::GetItemMetadatas(const FElementusItemInfo InItemInfo) +TMap UElementusInventoryFunctions::GetItemMetadatas(const FElementusItemInfo& InItemInfo) { - TMap Output; - if (UElementusItemData* const Data = GetSingleItemDataById(InItemInfo.ItemId, TArray { "Custom" })) - { - Output = Data->Metadatas; - UnloadElementusItem(InItemInfo.ItemId); - } - - return Output; + TMap Output; + if (const UElementusItemData* const Data = GetSingleItemDataById(InItemInfo.ItemId, TArray{"Custom"})) + { + Output = Data->Metadatas; + UnloadElementusItem(InItemInfo.ItemId); + } + + return Output; } -TMap UElementusInventoryFunctions::GetItemRelations(const FElementusItemInfo InItemInfo) +TMap UElementusInventoryFunctions::GetItemRelations(const FElementusItemInfo& InItemInfo) { - TMap Output; - if (UElementusItemData* const Data = GetSingleItemDataById(InItemInfo.ItemId, TArray { "Custom" })) - { - Output = Data->Relations; - UnloadElementusItem(InItemInfo.ItemId); - } - - return Output; + TMap Output; + if (const UElementusItemData* const Data = GetSingleItemDataById(InItemInfo.ItemId, TArray{"Custom"})) + { + Output = Data->Relations; + UnloadElementusItem(InItemInfo.ItemId); + } + + return Output; } -TArray UElementusInventoryFunctions::LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload) +TArray UElementusInventoryFunctions::LoadElementusItemDatas_Internal( + UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload) { - TArray Output; - - const auto CheckAssetValidity_Lambda = [FuncName = __func__](UObject* const& InAsset) -> bool - { - const bool bOutput = IsValid(InAsset); - if (bOutput) - { - UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Item data %s found and loaded"), *FString(FuncName), *InAsset->GetName()); - } - else - { - UE_LOG(LogElementusInventory_Internal, Error, TEXT("%s: Failed to load item data: Invalid Asset"), *FString(FuncName)); - } - - return bOutput; - }; - - const auto PassItemArr_Lambda = [&CheckAssetValidity_Lambda, &Output, FuncName = __func__](TArray& InArr) - { - if (UElementusInventoryFunctions::HasEmptyParam(InArr)) - { - UE_LOG(LogElementusInventory_Internal, Error, TEXT("%s: Failed to find items with the given parameters"), *FString(FuncName)); - } - - for (UObject* const& Iterator : InArr) - { - if (!CheckAssetValidity_Lambda(Iterator)) - { - continue; - } - - if (UElementusItemData* const CastedAsset = Cast(Iterator)) - { - Output.Add(CastedAsset); - } - } - }; - - if (const TSharedPtr StreamableHandle = InAssetManager->LoadPrimaryAssets(InIDs, InBundles); StreamableHandle.IsValid()) - { - StreamableHandle->WaitUntilComplete(5.f); - - TArray LoadedAssets; - StreamableHandle->GetLoadedAssets(LoadedAssets); - - PassItemArr_Lambda(LoadedAssets); - } - else // Objects already loaded - { - if (TArray LoadedAssets; - InAssetManager->GetPrimaryAssetObjectList(FPrimaryAssetType(ElementusItemDataType), LoadedAssets)) - { - PassItemArr_Lambda(LoadedAssets); - } - - if (!UElementusInventoryFunctions::HasEmptyParam(Output)) - { - for (int32 Iterator = 0; Iterator < InIDs.Num(); ++Iterator) - { - if (!InIDs.Contains(Output[Iterator]->GetPrimaryAssetId())) - { - Output.RemoveAt(Iterator); - --Iterator; - } - } - } - } - - if (bAutoUnload) - { - // Unload all elementus item assets - InAssetManager->UnloadPrimaryAssets(InIDs); - } - - return Output; + TArray Output; + + const auto CheckAssetValidity_Lambda = [FuncName = __func__](UObject* const& InAsset) -> bool + { + const bool bOutput = IsValid(InAsset); + if (bOutput) + { + UE_LOG(LogElementusInventory_Internal, Display, TEXT("%s: Item data %s found and loaded"), *FString(FuncName), *InAsset->GetName()); + } + else + { + UE_LOG(LogElementusInventory_Internal, Error, TEXT("%s: Failed to load item data: Invalid Asset"), *FString(FuncName)); + } + + return bOutput; + }; + + const auto PassItemArr_Lambda = [&CheckAssetValidity_Lambda, &Output, FuncName = __func__](TArray& InArr) + { + if (HasEmptyParam(InArr)) + { + UE_LOG(LogElementusInventory_Internal, Error, TEXT("%s: Failed to find items with the given parameters"), *FString(FuncName)); + } + + for (UObject* const& Iterator : InArr) + { + if (!CheckAssetValidity_Lambda(Iterator)) + { + continue; + } + + if (UElementusItemData* const CastedAsset = Cast(Iterator)) + { + Output.Add(CastedAsset); + } + } + }; + + if (const TSharedPtr StreamableHandle = InAssetManager->LoadPrimaryAssets(InIDs, InBundles); StreamableHandle.IsValid()) + { + StreamableHandle->WaitUntilComplete(5.f); + + TArray LoadedAssets; + StreamableHandle->GetLoadedAssets(LoadedAssets); + + PassItemArr_Lambda(LoadedAssets); + } + else // Objects already loaded + { + if (TArray LoadedAssets; InAssetManager->GetPrimaryAssetObjectList(FPrimaryAssetType(ElementusItemDataType), LoadedAssets)) + { + PassItemArr_Lambda(LoadedAssets); + } + + if (!HasEmptyParam(Output)) + { + for (int32 Iterator = 0; Iterator < InIDs.Num(); ++Iterator) + { + if (!InIDs.Contains(Output[Iterator]->GetPrimaryAssetId())) + { + Output.RemoveAt(Iterator); + --Iterator; + } + } + } + } + + if (bAutoUnload) + { + // Unload all elementus item assets + InAssetManager->UnloadPrimaryAssets(InIDs); + } + + return Output; } -TArray UElementusInventoryFunctions::LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload) +TArray UElementusInventoryFunctions::LoadElementusItemDatas_Internal( + UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload) { - const TArray PrimaryAssetIds(InIDs); - return LoadElementusItemDatas_Internal(InAssetManager, PrimaryAssetIds, InBundles, bAutoUnload); + const TArray PrimaryAssetIds(InIDs); + return LoadElementusItemDatas_Internal(InAssetManager, PrimaryAssetIds, InBundles, bAutoUnload); } -TArray UElementusInventoryFunctions::FilterTradeableItems(UElementusInventoryComponent* FromInventory, UElementusInventoryComponent* ToInventory, const TArray& Items) +TArray UElementusInventoryFunctions::FilterTradeableItems(UElementusInventoryComponent* FromInventory, + UElementusInventoryComponent* ToInventory, + const TArray& Items) { - TArray Output; - float VirtualWeight = ToInventory->GetCurrentWeight(); - - Algo::CopyIf(Items, Output, - [&](const FElementusItemInfo& Iterator) - { - if (VirtualWeight >= ToInventory->GetMaxWeight()) - { - return false; - } - - bool bCanTradeIterator = FromInventory->CanGiveItem(Iterator) && ToInventory->CanReceiveItem(Iterator); - - if (bCanTradeIterator) - { - if (const UElementusItemData* const ItemData = UElementusInventoryFunctions::GetSingleItemDataById(Iterator.ItemId, { "Data" })) - { - VirtualWeight += Iterator.Quantity * ItemData->ItemWeight; - bCanTradeIterator = bCanTradeIterator && VirtualWeight <= ToInventory->GetMaxWeight(); - } - else - { - return false; - } - } - - return bCanTradeIterator; - } - ); - - return Output; + TArray Output; + float VirtualWeight = ToInventory->GetCurrentWeight(); + + Algo::CopyIf(Items, Output, [&](const FElementusItemInfo& Iterator) + { + if (VirtualWeight >= ToInventory->GetMaxWeight()) + { + return false; + } + + bool bCanTradeIterator = FromInventory->CanGiveItem(Iterator) && ToInventory->CanReceiveItem(Iterator); + + if (bCanTradeIterator) + { + if (const UElementusItemData* const ItemData = GetSingleItemDataById(Iterator.ItemId, {"Data"})) + { + VirtualWeight += Iterator.Quantity * ItemData->ItemWeight; + bCanTradeIterator = bCanTradeIterator && VirtualWeight <= ToInventory->GetMaxWeight(); + } + else + { + return false; + } + } + + return bCanTradeIterator; + }); + + return Output; } TArray UElementusInventoryFunctions::GetAllElementusItemIds() { - TArray Output; + TArray Output; #if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) - if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) #else if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) #endif - { - AssetManager->GetPrimaryAssetIdList(FPrimaryAssetType(ElementusItemDataType), Output); - } + { + AssetManager->GetPrimaryAssetIdList(FPrimaryAssetType(ElementusItemDataType), Output); + } - return Output; + return Output; } -void UElementusInventoryFunctions::TradeElementusItem(TArray ItemsToTrade, UElementusInventoryComponent* FromInventory, UElementusInventoryComponent* ToInventory) +void UElementusInventoryFunctions::TradeElementusItem(const TArray& ItemsToTrade, UElementusInventoryComponent* FromInventory, + UElementusInventoryComponent* ToInventory) { - if (UElementusInventoryFunctions::HasEmptyParam(ItemsToTrade)) - { - return; - } + if (HasEmptyParam(ItemsToTrade)) + { + return; + } - FromInventory->GiveItemsTo(ToInventory, ItemsToTrade); + FromInventory->GiveItemsTo(ToInventory, ItemsToTrade); } -bool UElementusInventoryFunctions::IsItemValid(const FElementusItemInfo InItemInfo) +bool UElementusInventoryFunctions::IsItemValid(const FElementusItemInfo& InItemInfo) { - return InItemInfo.ItemId.IsValid() && InItemInfo != FElementusItemInfo::EmptyItemInfo && InItemInfo.Quantity > 0; + return InItemInfo.ItemId.IsValid() && InItemInfo != FElementusItemInfo::EmptyItemInfo && InItemInfo.Quantity > 0; } -bool UElementusInventoryFunctions::IsItemStackable(const FElementusItemInfo InItemInfo) +bool UElementusInventoryFunctions::IsItemStackable(const FElementusItemInfo& InItemInfo) { - if (!IsItemValid(InItemInfo)) - { - return false; - } + if (!IsItemValid(InItemInfo)) + { + return false; + } - if (const UElementusItemData* const ItemData = GetSingleItemDataById(InItemInfo.ItemId, { "Data" })) - { - return ItemData->bIsStackable; - } + if (const UElementusItemData* const ItemData = GetSingleItemDataById(InItemInfo.ItemId, {"Data"})) + { + return ItemData->bIsStackable; + } - return true; + return true; } -FGameplayTagContainer UElementusInventoryFunctions::GetItemTagsWithParentTag(const FElementusItemInfo InItemInfo, const FGameplayTag FromParentTag) +FGameplayTagContainer UElementusInventoryFunctions::GetItemTagsWithParentTag(const FElementusItemInfo& InItemInfo, const FGameplayTag FromParentTag) { - FGameplayTagContainer Output; - for (const FGameplayTag& Iterator : InItemInfo.Tags) - { - if (Iterator.MatchesTag(FromParentTag)) - { - Output.AddTag(Iterator); - } - } - - return Output; + FGameplayTagContainer Output; + for (const FGameplayTag& Iterator : InItemInfo.Tags) + { + if (Iterator.MatchesTag(FromParentTag)) + { + Output.AddTag(Iterator); + } + } + + return Output; } FString UElementusInventoryFunctions::ElementusItemEnumTypeToString(const EElementusItemType InEnumName) { - switch (InEnumName) - { - case EElementusItemType::None: - return "None"; + switch (InEnumName) + { + case EElementusItemType::None: + return "None"; - case EElementusItemType::Consumable: - return "Consumable"; + case EElementusItemType::Consumable: + return "Consumable"; - case EElementusItemType::Armor: - return "Armor"; + case EElementusItemType::Armor: + return "Armor"; - case EElementusItemType::Weapon: - return "Weapon"; + case EElementusItemType::Weapon: + return "Weapon"; - case EElementusItemType::Accessory: - return "Accessory"; + case EElementusItemType::Accessory: + return "Accessory"; - case EElementusItemType::Crafting: - return "Crafting"; + case EElementusItemType::Crafting: + return "Crafting"; - case EElementusItemType::Material: - return "Material"; + case EElementusItemType::Material: + return "Material"; - case EElementusItemType::Information: - return "Information"; + case EElementusItemType::Information: + return "Information"; - case EElementusItemType::Special: - return "Special"; + case EElementusItemType::Special: + return "Special"; - case EElementusItemType::Event: - return "Event"; + case EElementusItemType::Event: + return "Event"; - case EElementusItemType::Quest: - return "Quest"; + case EElementusItemType::Quest: + return "Quest"; - case EElementusItemType::Junk: - return "Junk"; + case EElementusItemType::Junk: + return "Junk"; - case EElementusItemType::Other: - return "Other"; + case EElementusItemType::Other: + return "Other"; - default: - break; - } + default: + break; + } - return FString(); -} \ No newline at end of file + return FString(); +} diff --git a/Source/ElementusInventory/Private/Management/ElementusInventorySettings.cpp b/Source/ElementusInventory/Private/Management/ElementusInventorySettings.cpp index 8053fa9..40d0f22 100644 --- a/Source/ElementusInventory/Private/Management/ElementusInventorySettings.cpp +++ b/Source/ElementusInventory/Private/Management/ElementusInventorySettings.cpp @@ -9,39 +9,40 @@ #include UE_INLINE_GENERATED_CPP_BY_NAME(ElementusInventorySettings) #endif -UElementusInventorySettings::UElementusInventorySettings(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), bEnableInternalLogs(false) +UElementusInventorySettings::UElementusInventorySettings(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), + bEnableInternalLogs(false) { - CategoryName = TEXT("Plugins"); + CategoryName = TEXT("Plugins"); } const UElementusInventorySettings* UElementusInventorySettings::Get() { - static const UElementusInventorySettings* const Instance = GetDefault(); - return Instance; + static const UElementusInventorySettings* const Instance = GetDefault(); + return Instance; } #if WITH_EDITOR void UElementusInventorySettings::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { - Super::PostEditChangeProperty(PropertyChangedEvent); + Super::PostEditChangeProperty(PropertyChangedEvent); - if (PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UElementusInventorySettings, bEnableInternalLogs)) - { - ToggleInternalLogs(); - } + if (PropertyChangedEvent.Property->GetFName() == GET_MEMBER_NAME_CHECKED(UElementusInventorySettings, bEnableInternalLogs)) + { + ToggleInternalLogs(); + } } #endif void UElementusInventorySettings::PostInitProperties() { - Super::PostInitProperties(); + Super::PostInitProperties(); - ToggleInternalLogs(); + ToggleInternalLogs(); } void UElementusInventorySettings::ToggleInternalLogs() { #if !UE_BUILD_SHIPPING - LogElementusInventory_Internal.SetVerbosity(bEnableInternalLogs ? ELogVerbosity::Display : ELogVerbosity::NoLogging); + LogElementusInventory_Internal.SetVerbosity(bEnableInternalLogs ? ELogVerbosity::Display : ELogVerbosity::NoLogging); #endif -} \ No newline at end of file +} diff --git a/Source/ElementusInventory/Public/Actors/ElementusInventoryPackage.h b/Source/ElementusInventory/Public/Actors/ElementusInventoryPackage.h index 8fd2810..36e6554 100644 --- a/Source/ElementusInventory/Public/Actors/ElementusInventoryPackage.h +++ b/Source/ElementusInventory/Public/Actors/ElementusInventoryPackage.h @@ -12,40 +12,41 @@ UCLASS(Category = "Elementus Inventory | Classes") class ELEMENTUSINVENTORY_API AElementusInventoryPackage : public AActor { - GENERATED_BODY() + GENERATED_BODY() public: - explicit AElementusInventoryPackage(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); + explicit AElementusInventoryPackage(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); - /* The inventory component of this package actor */ - UPROPERTY(Replicated, EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory") - UElementusInventoryComponent* PackageInventory; + /* The inventory component of this package actor */ + UPROPERTY(Replicated, EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory") + UElementusInventoryComponent* PackageInventory; - /* Put a item in this package */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - void PutItemIntoPackage(const TArray ItemInfo, UElementusInventoryComponent* FromInventory); + /* Put a item in this package */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + void PutItemIntoPackage(const TArray ItemInfo, UElementusInventoryComponent* FromInventory); - /* Get a item from this package */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - void GetItemFromPackage(const TArray ItemInfo, UElementusInventoryComponent* ToInventory); + /* Get a item from this package */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + void GetItemFromPackage(const TArray ItemInfo, UElementusInventoryComponent* ToInventory); - /* Set this package to auto destroy when its empty */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - void SetDestroyOnEmpty(const bool bDestroy); + /* Set this package to auto destroy when its empty */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + void SetDestroyOnEmpty(const bool bDestroy); - /* Will this package auto destroy when empty? */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - bool GetDestroyOnEmpty() const; + /* Will this package auto destroy when empty? */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + bool GetDestroyOnEmpty() const; protected: - virtual void BeginPlay() override; - virtual void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const override; + virtual void BeginPlay() override; + virtual void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const override; - /* Should this package auto destroy when empty? */ - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (Getter = "GetDestroyOnEmpty", Setter = "SetDestroyOnEmpty")) - bool bDestroyWhenInventoryIsEmpty; + /* Should this package auto destroy when empty? */ + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", + meta = (Getter = "GetDestroyOnEmpty", Setter = "SetDestroyOnEmpty")) + bool bDestroyWhenInventoryIsEmpty; - /* Destroy this package (Call Destroy()) */ - UFUNCTION(BlueprintNativeEvent, Category = "Elementus Inventory") - void BeginPackageDestruction(); + /* Destroy this package (Call Destroy()) */ + UFUNCTION(BlueprintNativeEvent, Category = "Elementus Inventory") + void BeginPackageDestruction(); }; diff --git a/Source/ElementusInventory/Public/Components/ElementusInventoryComponent.h b/Source/ElementusInventory/Public/Components/ElementusInventoryComponent.h index 8435e9f..ca4045c 100644 --- a/Source/ElementusInventory/Public/Components/ElementusInventoryComponent.h +++ b/Source/ElementusInventory/Public/Components/ElementusInventoryComponent.h @@ -13,50 +13,50 @@ UENUM(Category = "Elementus Inventory | Enumerations") enum class EElementusInventoryUpdateOperation : uint8 { - None, - Add, - Remove + None, + Add, + Remove }; UENUM(Category = "Elementus Inventory | Enumerations") enum class EElementusInventorySortingMode : uint8 { - ID, - Name, - Type, - IndividualValue, - StackValue, - IndividualWeight, - StackWeight, - Quantity, - Level, - Tags + ID, + Name, + Type, + IndividualValue, + StackValue, + IndividualWeight, + StackWeight, + Quantity, + Level, + Tags }; UENUM(Category = "Elementus Inventory | Enumerations") enum class EElementusInventorySortingOrientation : uint8 { - Ascending, - Descending + Ascending, + Descending }; USTRUCT(Category = "Elementus Inventory | Structures") struct FItemModifierData { - GENERATED_BODY() + GENERATED_BODY() - FItemModifierData() = default; + FItemModifierData() = default; - explicit FItemModifierData(const FElementusItemInfo& InItemInfo) : ItemInfo(InItemInfo) - { - } + explicit FItemModifierData(const FElementusItemInfo& InItemInfo) : ItemInfo(InItemInfo) + { + } - explicit FItemModifierData(const FElementusItemInfo& InItemInfo, const int32& InIndex) : ItemInfo(InItemInfo), Index(InIndex) - { - } + explicit FItemModifierData(const FElementusItemInfo& InItemInfo, const int32& InIndex) : ItemInfo(InItemInfo), Index(InIndex) + { + } - FElementusItemInfo ItemInfo = FElementusItemInfo(); - int32 Index = INDEX_NONE; + FElementusItemInfo ItemInfo = FElementusItemInfo(); + int32 Index = INDEX_NONE; }; DECLARE_DYNAMIC_MULTICAST_DELEGATE(FElementusInventoryUpdate); @@ -66,176 +66,182 @@ DECLARE_DYNAMIC_MULTICAST_DELEGATE(FElementusInventoryEmpty); UCLASS(Blueprintable, ClassGroup = (Custom), Category = "Elementus Inventory | Classes", EditInlineNew, meta = (BlueprintSpawnableComponent)) class ELEMENTUSINVENTORY_API UElementusInventoryComponent : public UActorComponent { - GENERATED_BODY() + GENERATED_BODY() public: - explicit UElementusInventoryComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); + explicit UElementusInventoryComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); - /* Experimental parameter to assist using empty slots in the inventory: If true, will replace empty slots with empty item info */ - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - bool bAllowEmptySlots; + /* Experimental parameter to assist using empty slots in the inventory: If true, will replace empty slots with empty item info */ + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + bool bAllowEmptySlots; - /* Get the current inventory weight */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - float GetCurrentWeight() const; + /* Get the current inventory weight */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + float GetCurrentWeight() const; - /* Get the max inventory weight */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - float GetMaxWeight() const; + /* Get the max inventory weight */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + float GetMaxWeight() const; - /* Get the current num of items in this inventory */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - int32 GetCurrentNumItems() const; + /* Get the current num of items in this inventory */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + int32 GetCurrentNumItems() const; - /* Get the current max num of items in this inventory */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - int32 GetMaxNumItems() const; + /* Get the current max num of items in this inventory */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + int32 GetMaxNumItems() const; - /* Called on every inventory update */ - UPROPERTY(BlueprintAssignable, Category = "Elementus Inventory") - FElementusInventoryUpdate OnInventoryUpdate; + /* Called on every inventory update */ + UPROPERTY(BlueprintAssignable, Category = "Elementus Inventory") + FElementusInventoryUpdate OnInventoryUpdate; - /* Called when the inventory is empty */ - UPROPERTY(BlueprintAssignable, Category = "Elementus Inventory") - FElementusInventoryEmpty OnInventoryEmpty; + /* Called when the inventory is empty */ + UPROPERTY(BlueprintAssignable, Category = "Elementus Inventory") + FElementusInventoryEmpty OnInventoryEmpty; - /* Get the items that this inventory have */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - TArray GetItemsArray() const; + /* Get the items that this inventory have */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + TArray GetItemsArray() const; - /* Get a reference of the item at given index */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - FElementusItemInfo& GetItemReferenceAt(const int32 Index); + /* Get a reference of the item at given index */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + FElementusItemInfo& GetItemReferenceAt(const int32 Index); - /* Get a copy of the item at given index */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - FElementusItemInfo GetItemCopyAt(const int32 Index) const; + /* Get a copy of the item at given index */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + FElementusItemInfo GetItemCopyAt(const int32 Index) const; - /* Check if this inventory can receive the item */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - virtual bool CanReceiveItem(const FElementusItemInfo InItemInfo) const; + /* Check if this inventory can receive the item */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + virtual bool CanReceiveItem(const FElementusItemInfo InItemInfo) const; - /* Check if this inventory can give the item */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - virtual bool CanGiveItem(const FElementusItemInfo InItemInfo) const; + /* Check if this inventory can give the item */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + virtual bool CanGiveItem(const FElementusItemInfo InItemInfo) const; - /* Find the first elementus item that matches the specified info */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindFirstItemIndexWithInfo(const FElementusItemInfo InItemInfo, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset = 0) const; + /* Find the first elementus item that matches the specified info */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindFirstItemIndexWithInfo(const FElementusItemInfo& InItemInfo, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, + const int32 Offset = 0) const; - /* Find the first elementus item that matches the specified tag container */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindFirstItemIndexWithTags(const FGameplayTagContainer WithTags, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset = 0) const; + /* Find the first elementus item that matches the specified tag container */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindFirstItemIndexWithTags(const FGameplayTagContainer& WithTags, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, + const int32 Offset = 0) const; - /* Find the first elementus item that matches the specified id */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindFirstItemIndexWithId(const FPrimaryElementusItemId InId, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, const int32 Offset = 0) const; + /* Find the first elementus item that matches the specified id */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindFirstItemIndexWithId(const FPrimaryElementusItemId& InId, int32& OutIndex, const FGameplayTagContainer& IgnoreTags, + const int32 Offset = 0) const; - /* Find the first elementus item that matches the specified info */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindAllItemIndexesWithInfo(const FElementusItemInfo InItemInfo, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; + /* Find the first elementus item that matches the specified info */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindAllItemIndexesWithInfo(const FElementusItemInfo& InItemInfo, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; - /* Find the first elementus item that matches the specified tag container */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindAllItemIndexesWithTags(const FGameplayTagContainer WithTags, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; + /* Find the first elementus item that matches the specified tag container */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindAllItemIndexesWithTags(const FGameplayTagContainer& WithTags, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; - /* Find the first elementus item that matches the specified id */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) - bool FindAllItemIndexesWithId(const FPrimaryElementusItemId InId, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; + /* Find the first elementus item that matches the specified id */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory", meta = (AutoCreateRefTerm = "IgnoreTags")) + bool FindAllItemIndexesWithId(const FPrimaryElementusItemId& InId, TArray& OutIndexes, const FGameplayTagContainer& IgnoreTags) const; - /* Check if the inventory stack contains a item that matches the specified info */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - bool ContainsItem(const FElementusItemInfo InItemInfo, const bool bIgnoreTags = false) const; + /* Check if the inventory stack contains a item that matches the specified info */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + bool ContainsItem(const FElementusItemInfo& InItemInfo, const bool bIgnoreTags = false) const; - /* Check if the inventory is empty */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - bool IsInventoryEmpty() const; + /* Check if the inventory is empty */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + bool IsInventoryEmpty() const; - /* Print debug informations in the log about this inventory */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - virtual void DebugInventory(); + /* Print debug informations in the log about this inventory */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + virtual void DebugInventory(); - /* Remove all items from this inventory */ - UFUNCTION(NetMulticast, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void ClearInventory(); + /* Remove all items from this inventory */ + UFUNCTION(NetMulticast, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void ClearInventory(); - /* Update the current weight of this inventory */ - UFUNCTION(Client, Unreliable, BlueprintCallable, Category = "Elementus Inventory") - void UpdateWeight(); + /* Update the current weight of this inventory */ + UFUNCTION(Client, Unreliable, BlueprintCallable, Category = "Elementus Inventory") + void UpdateWeight(); - /* Get items from another inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void GetItemIndexesFrom(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes); + /* Get items from another inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void GetItemIndexesFrom(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes); - /* Give items to another inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void GiveItemIndexesTo(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes); + /* Give items to another inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void GiveItemIndexesTo(UElementusInventoryComponent* OtherInventory, const TArray& ItemIndexes); - /* Get items from another inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void GetItemsFrom(UElementusInventoryComponent* OtherInventory, const TArray& Items); + /* Get items from another inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void GetItemsFrom(UElementusInventoryComponent* OtherInventory, const TArray& Items); - /* Give items to another inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void GiveItemsTo(UElementusInventoryComponent* OtherInventory, const TArray& Items); + /* Give items to another inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void GiveItemsTo(UElementusInventoryComponent* OtherInventory, const TArray& Items); - /* Discard items from this inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void DiscardItemIndexes(const TArray& ItemIndexes); + /* Discard items from this inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void DiscardItemIndexes(const TArray& ItemIndexes); - /* Discard items from this inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void DiscardItems(const TArray& Items); + /* Discard items from this inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void DiscardItems(const TArray& Items); - /* Add items to this inventory */ - UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") - void AddItems(const TArray& Items); + /* Add items to this inventory */ + UFUNCTION(Server, Reliable, BlueprintCallable, Category = "Elementus Inventory") + void AddItems(const TArray& Items); - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - void SortInventory(const EElementusInventorySortingMode Mode, const EElementusInventorySortingOrientation Orientation); + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + void SortInventory(const EElementusInventorySortingMode Mode, const EElementusInventorySortingOrientation Orientation); protected: - /* Items that this inventory have */ - UPROPERTY(ReplicatedUsing = OnRep_ElementusItems, EditAnywhere, BlueprintReadOnly, Category = "Elementus Inventory", meta = (Getter = "GetItemsArray", ArrayClamp = "MaxNumItems")) - TArray ElementusItems; + /* Items that this inventory have */ + UPROPERTY(ReplicatedUsing = OnRep_ElementusItems, EditAnywhere, BlueprintReadOnly, Category = "Elementus Inventory", + meta = (Getter = "GetItemsArray", ArrayClamp = "MaxNumItems")) + TArray ElementusItems; - /* Current weight of this inventory */ - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AllowPrivateAccess = "true")) - float CurrentWeight; + /* Current weight of this inventory */ + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AllowPrivateAccess = "true")) + float CurrentWeight; - virtual void BeginPlay() override; - virtual void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const override; + virtual void BeginPlay() override; + virtual void GetLifetimeReplicatedProps(TArray& OutLifetimeProps) const override; - virtual void RefreshInventory(); + virtual void RefreshInventory(); private: - /* Max weight allowed for this inventory */ - UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Elementus Inventory", meta = (AllowPrivateAccess = "true", ClampMin = "0", UIMin = "0")) - float MaxWeight; + /* Max weight allowed for this inventory */ + UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Elementus Inventory", + meta = (AllowPrivateAccess = "true", ClampMin = "0", UIMin = "0")) + float MaxWeight; - /* Max num of items allowed for this inventory */ - UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Elementus Inventory", meta = (AllowPrivateAccess = "true", ClampMin = "1", UIMin = "1")) - int32 MaxNumItems; + /* Max num of items allowed for this inventory */ + UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Elementus Inventory", + meta = (AllowPrivateAccess = "true", ClampMin = "1", UIMin = "1")) + int32 MaxNumItems; - void ForceWeightUpdate(); - void ForceInventoryValidation(); + void ForceWeightUpdate(); + void ForceInventoryValidation(); public: - /* Add a item to this inventory */ - void UpdateElementusItems(const TArray& Modifiers, const EElementusInventoryUpdateOperation Operation); + /* Add a item to this inventory */ + void UpdateElementusItems(const TArray& Modifiers, const EElementusInventoryUpdateOperation Operation); private: - UFUNCTION(Server, Reliable) - void Server_ProcessInventoryAddition_Internal(const TArray& Modifiers); + UFUNCTION(Server, Reliable) + void Server_ProcessInventoryAddition_Internal(const TArray& Modifiers); - UFUNCTION(Server, Reliable) - void Server_ProcessInventoryRemoval_Internal(const TArray& Modifiers); + UFUNCTION(Server, Reliable) + void Server_ProcessInventoryRemoval_Internal(const TArray& Modifiers); - UFUNCTION(Category = "Elementus Inventory") - void OnRep_ElementusItems(); + UFUNCTION(Category = "Elementus Inventory") + void OnRep_ElementusItems(); protected: - /* Mark the inventory as dirty to update the replicated data and broadcast the events */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - void NotifyInventoryChange(); + /* Mark the inventory as dirty to update the replicated data and broadcast the events */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + void NotifyInventoryChange(); }; diff --git a/Source/ElementusInventory/Public/ElementusInventory.h b/Source/ElementusInventory/Public/ElementusInventory.h index f884f62..c5a05b7 100644 --- a/Source/ElementusInventory/Public/ElementusInventory.h +++ b/Source/ElementusInventory/Public/ElementusInventory.h @@ -13,6 +13,6 @@ class FElementusInventoryModule : public IModuleInterface { public: - virtual void StartupModule() override; - virtual void ShutdownModule() override; -}; \ No newline at end of file + virtual void StartupModule() override; + virtual void ShutdownModule() override; +}; diff --git a/Source/ElementusInventory/Public/LogElementusInventory.h b/Source/ElementusInventory/Public/LogElementusInventory.h index 946d9b1..3463223 100644 --- a/Source/ElementusInventory/Public/LogElementusInventory.h +++ b/Source/ElementusInventory/Public/LogElementusInventory.h @@ -11,4 +11,5 @@ */ DECLARE_LOG_CATEGORY_EXTERN(LogElementusInventory, Display, All); -DECLARE_LOG_CATEGORY_EXTERN(LogElementusInventory_Internal, NoLogging, All); \ No newline at end of file + +DECLARE_LOG_CATEGORY_EXTERN(LogElementusInventory_Internal, NoLogging, All); diff --git a/Source/ElementusInventory/Public/Management/ElementusInventoryData.h b/Source/ElementusInventory/Public/Management/ElementusInventoryData.h index f324e4b..2150de6 100644 --- a/Source/ElementusInventory/Public/Management/ElementusInventoryData.h +++ b/Source/ElementusInventory/Public/Management/ElementusInventoryData.h @@ -16,160 +16,162 @@ constexpr auto ElementusItemDataType = TEXT("ElementusInventory_ItemData"); UENUM(BlueprintType, Category = "Elementus Inventory | Enumerations") enum class EElementusItemType : uint8 { - None, - Consumable, - Armor, - Weapon, - Accessory, - Crafting, - Material, - Information, - Special, - Event, - Quest, - Junk, - Other, - - MAX + None, + Consumable, + Armor, + Weapon, + Accessory, + Crafting, + Material, + Information, + Special, + Event, + Quest, + Junk, + Other, + + MAX }; USTRUCT(BlueprintType, Category = "Elementus Inventory | Structs") struct FPrimaryElementusItemId : public FPrimaryAssetId { - GENERATED_BODY() + GENERATED_BODY() - FPrimaryElementusItemId() : Super() - { - } + FPrimaryElementusItemId() : Super() + { + } - explicit FPrimaryElementusItemId(const FPrimaryAssetId& InId) : Super(InId.PrimaryAssetType, InId.PrimaryAssetName) - { - } + explicit FPrimaryElementusItemId(const FPrimaryAssetId& InId) : Super(InId.PrimaryAssetType, InId.PrimaryAssetName) + { + } - explicit FPrimaryElementusItemId(const FString& TypeAndName) : Super(TypeAndName) - { - } + explicit FPrimaryElementusItemId(const FString& TypeAndName) : Super(TypeAndName) + { + } - bool operator>(const FPrimaryElementusItemId& Other) const - { - return ToString() > Other.ToString(); - } + bool operator>(const FPrimaryElementusItemId& Other) const + { + return ToString() > Other.ToString(); + } - bool operator<(const FPrimaryElementusItemId& Other) const - { - return ToString() < Other.ToString(); - } + bool operator<(const FPrimaryElementusItemId& Other) const + { + return ToString() < Other.ToString(); + } }; USTRUCT(BlueprintType, Category = "Elementus Inventory | Structs") struct FPrimaryElementusItemIdContainer { - GENERATED_BODY() + GENERATED_BODY() - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - TArray Items; + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + TArray Items; }; USTRUCT(BlueprintType, Category = "Elementus Inventory | Structs") struct FElementusItemInfo { - GENERATED_BODY() + GENERATED_BODY() - static const FElementusItemInfo EmptyItemInfo; + static const FElementusItemInfo EmptyItemInfo; - FElementusItemInfo() = default; + FElementusItemInfo() = default; - explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId) : ItemId(InItemId) - { - } + explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId) : ItemId(InItemId) + { + } - explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId, const int32& InQuant) : ItemId(InItemId), Quantity(InQuant) - { - } + explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId, const int32& InQuant) : ItemId(InItemId), Quantity(InQuant) + { + } - explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId, const int32& InQuant, const FGameplayTagContainer& InTags) : ItemId(InItemId), Quantity(InQuant), Tags(InTags) - { - } + explicit FElementusItemInfo(const FPrimaryElementusItemId& InItemId, const int32& InQuant, + const FGameplayTagContainer& InTags) : ItemId(InItemId), Quantity(InQuant), Tags(InTags) + { + } - bool operator==(const FElementusItemInfo& Other) const - { - return ItemId == Other.ItemId && Tags == Other.Tags && Level == Other.Level; - } + bool operator==(const FElementusItemInfo& Other) const + { + return ItemId == Other.ItemId && Tags == Other.Tags && Level == Other.Level; + } - bool operator!=(const FElementusItemInfo& Other) const - { - return !(*this == Other); - } + bool operator!=(const FElementusItemInfo& Other) const + { + return !(*this == Other); + } - bool operator<(const FElementusItemInfo& Other) const - { - return ItemId.ToString() < Other.ItemId.ToString(); - } + bool operator<(const FElementusItemInfo& Other) const + { + return ItemId.ToString() < Other.ItemId.ToString(); + } - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - FPrimaryElementusItemId ItemId; + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + FPrimaryElementusItemId ItemId; - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - int32 Level = 1; + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + int32 Level = 1; - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - int32 Quantity = 1; + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + int32 Quantity = 1; - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") - FGameplayTagContainer Tags; + UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Elementus Inventory") + FGameplayTagContainer Tags; }; UCLASS(NotBlueprintable, NotPlaceable, Category = "Elementus Inventory | Classes | Data") class ELEMENTUSINVENTORY_API UElementusItemData final : public UPrimaryDataAsset { - GENERATED_BODY() + GENERATED_BODY() public: - explicit UElementusItemData(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); + explicit UElementusItemData(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); - FORCEINLINE virtual FPrimaryAssetId GetPrimaryAssetId() const override - { - return FPrimaryAssetId(TEXT("ElementusInventory_ItemData"), *("Item_" + FString::FromInt(ItemId))); - } + FORCEINLINE virtual FPrimaryAssetId GetPrimaryAssetId() const override + { + return FPrimaryAssetId(TEXT("ElementusInventory_ItemData"), *("Item_" + FString::FromInt(ItemId))); + } - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) - int32 ItemId; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) + int32 ItemId; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "SoftData")) - TSoftObjectPtr ItemObject; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "SoftData")) + TSoftObjectPtr ItemObject; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "SoftData")) - TSoftClassPtr ItemClass; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "SoftData")) + TSoftClassPtr ItemClass; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) - FName ItemName; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) + FName ItemName; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data", MultiLine = "true")) - FText ItemDescription; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data", MultiLine = "true")) + FText ItemDescription; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) - EElementusItemType ItemType; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) + EElementusItemType ItemType; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) - bool bIsStackable = true; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "Data")) + bool bIsStackable = true; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (UIMin = 0, ClampMin = 0, AssetBundles = "Data")) - float ItemValue; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (UIMin = 0, ClampMin = 0, AssetBundles = "Data")) + float ItemValue; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (UIMin = 0, ClampMin = 0, AssetBundles = "Data")) - float ItemWeight; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (UIMin = 0, ClampMin = 0, AssetBundles = "Data")) + float ItemWeight; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "UI")) - TSoftObjectPtr ItemIcon; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "UI")) + TSoftObjectPtr ItemIcon; - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "UI")) - TSoftObjectPtr ItemImage; + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (AssetBundles = "UI")) + TSoftObjectPtr ItemImage; - /* Allows to implement custom properties in this item data */ - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (DisplayName = "Custom Metadatas", AssetBundles = "Custom")) - TMap Metadatas; + /* Allows to implement custom properties in this item data */ + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", + meta = (DisplayName = "Custom Metadatas", AssetBundles = "Custom")) + TMap Metadatas; - /* Map containing a tag as key and a ID container as value to add relations to other items such as crafting requirements, etc. */ - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (DisplayName = "Item Relations", AssetBundles = "Custom")) - TMap Relations; + /* Map containing a tag as key and a ID container as value to add relations to other items such as crafting requirements, etc. */ + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Elementus Inventory", meta = (DisplayName = "Item Relations", AssetBundles = "Custom")) + TMap Relations; }; diff --git a/Source/ElementusInventory/Public/Management/ElementusInventoryFunctions.h b/Source/ElementusInventory/Public/Management/ElementusInventoryFunctions.h index c08df40..d2f2c60 100644 --- a/Source/ElementusInventory/Public/Management/ElementusInventoryFunctions.h +++ b/Source/ElementusInventory/Public/Management/ElementusInventoryFunctions.h @@ -12,9 +12,9 @@ UENUM(BlueprintType, Category = "Elementus Inventory | Enumerations") enum class EElementusSearchType : uint8 { - Name, - ID, - Type + Name, + ID, + Type }; class UElementusInventoryComponent; @@ -28,94 +28,101 @@ struct FPrimaryElementusItemId; UCLASS(Category = "Elementus Inventory | Functions") class ELEMENTUSINVENTORY_API UElementusInventoryFunctions final : public UBlueprintFunctionLibrary { - GENERATED_BODY() + GENERATED_BODY() public: - /* Unload all elementus items that were loaded by Asset Manager */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static void UnloadAllElementusItems(); - - /* Unload a elementus item that was loaded by Asset Manager */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static void UnloadElementusItem(const FPrimaryElementusItemId& InItemId); - - /* Check if the ids are equal */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static bool CompareItemInfo(const FElementusItemInfo& Info1, const FElementusItemInfo& Info2); - - /* Check if the ids of the given item datas are equal */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static bool CompareItemData(const UElementusItemData* Data1, const UElementusItemData* Data2); - - /* Return the item data related to the given id */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static UElementusItemData* GetSingleItemDataById(const FPrimaryElementusItemId& InID, const TArray& InBundles, const bool bAutoUnload = true); - - /* Return a array of data depending of the given ids */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static TArray GetItemDataArrayById(const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload = true); - - /* Search all registered elementus items and return a array of item data that match with the given parameters */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static TArray SearchElementusItemData(const EElementusSearchType SearchType, const FString& SearchString, const TArray& InBundles, const bool bAutoUnload = true); - - /* Get the primary asset ids of all registered elementus items */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static TArray GetAllElementusItemIds(); - - /* Trade items between two inventory components */ - UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") - static void TradeElementusItem(TArray ItemsToTrade, UElementusInventoryComponent* FromInventory, UElementusInventoryComponent* ToInventory); - - /* Check if the given item info have a valid id */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static bool IsItemValid(const FElementusItemInfo InItemInfo); - - /* Check if the given item info represents a stackable item */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static bool IsItemStackable(const FElementusItemInfo InItemInfo); - - /* Get item tags providing a parent tag */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static FGameplayTagContainer GetItemTagsWithParentTag(const FElementusItemInfo InItemInfo, const FGameplayTag FromParentTag); - - /* Convert an item type enum value to string */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static FString ElementusItemEnumTypeToString(const EElementusItemType InEnumName); - - template - constexpr static const bool HasEmptyParam(const Ty& Arg1) - { - if constexpr (std::is_base_of()) - { - return Arg1.IsEmpty(); - } - else if constexpr (std::is_base_of()) - { - return Arg1.IsNone(); - } - else - { + /* Unload all elementus items that were loaded by Asset Manager */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static void UnloadAllElementusItems(); + + /* Unload a elementus item that was loaded by Asset Manager */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static void UnloadElementusItem(const FPrimaryElementusItemId& InItemId); + + /* Check if the ids are equal */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static bool CompareItemInfo(const FElementusItemInfo& Info1, const FElementusItemInfo& Info2); + + /* Check if the ids of the given item datas are equal */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static bool CompareItemData(const UElementusItemData* Data1, const UElementusItemData* Data2); + + /* Return the item data related to the given id */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static UElementusItemData* GetSingleItemDataById(const FPrimaryElementusItemId& InID, const TArray& InBundles, + const bool bAutoUnload = true); + + /* Return a array of data depending of the given ids */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static TArray GetItemDataArrayById(const TArray& InIDs, const TArray& InBundles, + const bool bAutoUnload = true); + + /* Search all registered elementus items and return a array of item data that match with the given parameters */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static TArray SearchElementusItemData(const EElementusSearchType SearchType, const FString& SearchString, + const TArray& InBundles, const bool bAutoUnload = true); + + /* Get the primary asset ids of all registered elementus items */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static TArray GetAllElementusItemIds(); + + /* Trade items between two inventory components */ + UFUNCTION(BlueprintCallable, Category = "Elementus Inventory") + static void TradeElementusItem(const TArray& ItemsToTrade, UElementusInventoryComponent* FromInventory, + UElementusInventoryComponent* ToInventory); + + /* Check if the given item info have a valid id */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static bool IsItemValid(const FElementusItemInfo& InItemInfo); + + /* Check if the given item info represents a stackable item */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static bool IsItemStackable(const FElementusItemInfo& InItemInfo); + + /* Get item tags providing a parent tag */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static FGameplayTagContainer GetItemTagsWithParentTag(const FElementusItemInfo& InItemInfo, const FGameplayTag FromParentTag); + + /* Convert an item type enum value to string */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static FString ElementusItemEnumTypeToString(const EElementusItemType InEnumName); + + template + constexpr static const bool HasEmptyParam(const Ty& Arg1) + { + if constexpr (std::is_base_of()) + { + return Arg1.IsEmpty(); + } + else if constexpr (std::is_base_of()) + { + return Arg1.IsNone(); + } + else + { #if ENGINE_MAJOR_VERSION >= 5 - return Arg1.IsEmpty(); + return Arg1.IsEmpty(); #else return Arg1.Num() == 0; #endif - } - } + } + } - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static TMap GetItemMetadatas(const FElementusItemInfo InItemInfo); + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static TMap GetItemMetadatas(const FElementusItemInfo& InItemInfo); - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static TMap GetItemRelations(const FElementusItemInfo InItemInfo); + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static TMap GetItemRelations(const FElementusItemInfo& InItemInfo); private: - static TArray LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload); - static TArray LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, const TArray& InBundles, const bool bAutoUnload); + static TArray LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, + const TArray& InBundles, const bool bAutoUnload); + static TArray LoadElementusItemDatas_Internal(UAssetManager* InAssetManager, const TArray& InIDs, + const TArray& InBundles, const bool bAutoUnload); public: - /* Filter the container and return only items that can be traded at the current context */ - UFUNCTION(BlueprintPure, Category = "Elementus Inventory") - static TArray FilterTradeableItems(UElementusInventoryComponent* FromInventory, UElementusInventoryComponent* ToInventory, const TArray& Items); + /* Filter the container and return only items that can be traded at the current context */ + UFUNCTION(BlueprintPure, Category = "Elementus Inventory") + static TArray FilterTradeableItems(UElementusInventoryComponent* FromInventory, UElementusInventoryComponent* ToInventory, + const TArray& Items); }; diff --git a/Source/ElementusInventory/Public/Management/ElementusInventorySettings.h b/Source/ElementusInventory/Public/Management/ElementusInventorySettings.h index ee5ec02..1fae349 100644 --- a/Source/ElementusInventory/Public/Management/ElementusInventorySettings.h +++ b/Source/ElementusInventory/Public/Management/ElementusInventorySettings.h @@ -14,39 +14,42 @@ UCLASS(Config = Plugins, DefaultConfig, meta = (DisplayName = "Elementus Inventory")) class ELEMENTUSINVENTORY_API UElementusInventorySettings final : public UDeveloperSettings { - GENERATED_BODY() + GENERATED_BODY() public: - explicit UElementusInventorySettings(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); - static const UElementusInventorySettings* Get(); + explicit UElementusInventorySettings(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); + static const UElementusInventorySettings* Get(); - /* Will print extra internal informations in log - Useful for debugging */ - UPROPERTY(GlobalConfig, EditAnywhere, Category = "Settings", Meta = (DisplayName = "Enable Internal Logs")) - bool bEnableInternalLogs; + /* Will print extra internal informations in log - Useful for debugging */ + UPROPERTY(GlobalConfig, EditAnywhere, Category = "Settings", Meta = (DisplayName = "Enable Internal Logs")) + bool bEnableInternalLogs; - /* Experimental parameter to assist using empty slots in the inventory: If true, will replace empty slots with empty item info */ - UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", Meta = (DisplayName = "Allow Empty Slots")) - bool bAllowEmptySlots; + /* Experimental parameter to assist using empty slots in the inventory: If true, will replace empty slots with empty item info */ + UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", Meta = (DisplayName = "Allow Empty Slots")) + bool bAllowEmptySlots; - /* Max weight allowed for this inventory */ - UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", meta = (DisplayName = "Max Weight", ClampMin = "0", UIMin = "0")) - float MaxWeight; + /* Max weight allowed for this inventory */ + UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", + meta = (DisplayName = "Max Weight", ClampMin = "0", UIMin = "0")) + float MaxWeight; - /* Max num of items allowed for this inventory */ - UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", meta = (DisplayName = "Max Num Items", ClampMin = "1", UIMin = "1")) - int32 MaxNumItems; + /* Max num of items allowed for this inventory */ + UPROPERTY(GlobalConfig, EditAnywhere, Category = "Default Values | Inventory Component", + meta = (DisplayName = "Max Num Items", ClampMin = "1", UIMin = "1")) + int32 MaxNumItems; - /* Should the inventory package auto destroy when empty? */ - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Default Values | Inventory Package", meta = (DisplayName = "Destroy When Inventory Is Empty")) - bool bDestroyWhenInventoryIsEmpty; + /* Should the inventory package auto destroy when empty? */ + UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Default Values | Inventory Package", + meta = (DisplayName = "Destroy When Inventory Is Empty")) + bool bDestroyWhenInventoryIsEmpty; protected: #if WITH_EDITOR - virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; + virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif - virtual void PostInitProperties() override; + virtual void PostInitProperties() override; private: - void ToggleInternalLogs(); + void ToggleInternalLogs(); }; diff --git a/Source/ElementusInventoryEditor/ElementusInventoryEditor.Build.cs b/Source/ElementusInventoryEditor/ElementusInventoryEditor.Build.cs index 6b12e6a..a0308a2 100644 --- a/Source/ElementusInventoryEditor/ElementusInventoryEditor.Build.cs +++ b/Source/ElementusInventoryEditor/ElementusInventoryEditor.Build.cs @@ -6,31 +6,31 @@ public class ElementusInventoryEditor : ModuleRules { - public ElementusInventoryEditor(ReadOnlyTargetRules Target) : base(Target) - { - PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; - CppStandard = CppStandardVersion.Cpp17; + public ElementusInventoryEditor(ReadOnlyTargetRules Target) : base(Target) + { + PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; + CppStandard = CppStandardVersion.Cpp17; - PublicDependencyModuleNames.AddRange(new[] - { - "Core" - }); + PublicDependencyModuleNames.AddRange(new[] + { + "Core" + }); - PrivateDependencyModuleNames.AddRange(new[] - { - "ElementusInventory", - "InputCore", - "CoreUObject", - "UnrealEd", - "AssetTools", - "ToolMenus", - "Engine", - "Slate", - "SlateCore", - "EditorStyle", - "WorkspaceMenuStructure", - "PropertyEditor", - "GameplayTags" - }); - } + PrivateDependencyModuleNames.AddRange(new[] + { + "ElementusInventory", + "InputCore", + "CoreUObject", + "UnrealEd", + "AssetTools", + "ToolMenus", + "Engine", + "Slate", + "SlateCore", + "EditorStyle", + "WorkspaceMenuStructure", + "PropertyEditor", + "GameplayTags" + }); + } } \ No newline at end of file diff --git a/Source/ElementusInventoryEditor/Private/ElementusInventoryEditor.cpp b/Source/ElementusInventoryEditor/Private/ElementusInventoryEditor.cpp index 1eb80fe..ebab2a4 100644 --- a/Source/ElementusInventoryEditor/Private/ElementusInventoryEditor.cpp +++ b/Source/ElementusInventoryEditor/Private/ElementusInventoryEditor.cpp @@ -16,79 +16,78 @@ void FElementusInventoryEditorModule::StartupModule() { - const auto RegisterDelegate = FSimpleMulticastDelegate::FDelegate::CreateRaw(this, &FElementusInventoryEditorModule::RegisterMenus); + const auto RegisterDelegate = FSimpleMulticastDelegate::FDelegate::CreateRaw(this, &FElementusInventoryEditorModule::RegisterMenus); - UToolMenus::RegisterStartupCallback(RegisterDelegate); + UToolMenus::RegisterStartupCallback(RegisterDelegate); - const auto MakeInstanceDelegate = FOnGetPropertyTypeCustomizationInstance::CreateStatic(&SElementusDetailsPanel::MakeInstance); + const auto MakeInstanceDelegate = FOnGetPropertyTypeCustomizationInstance::CreateStatic(&SElementusDetailsPanel::MakeInstance); - PropertyEditorModule = &FModuleManager::LoadModuleChecked(TEXT("PropertyEditor")); - PropertyEditorModule->RegisterCustomPropertyTypeLayout(ItemStackPropertyId, MakeInstanceDelegate); + PropertyEditorModule = &FModuleManager::LoadModuleChecked(TEXT("PropertyEditor")); + PropertyEditorModule->RegisterCustomPropertyTypeLayout(ItemStackPropertyId, MakeInstanceDelegate); } void FElementusInventoryEditorModule::ShutdownModule() { - UToolMenus::UnRegisterStartupCallback(this); - UToolMenus::UnregisterOwner(this); + UToolMenus::UnRegisterStartupCallback(this); + UToolMenus::UnregisterOwner(this); - FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(ElementusEditorTabId); - FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(ItemCreatorTabId); + FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(ElementusEditorTabId); + FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(ItemCreatorTabId); - PropertyEditorModule->UnregisterCustomPropertyTypeLayout(ItemStackPropertyId); + PropertyEditorModule->UnregisterCustomPropertyTypeLayout(ItemStackPropertyId); } TSharedRef FElementusInventoryEditorModule::OnSpawnTab([[maybe_unused]] const FSpawnTabArgs&, const FName TabId) const { - TSharedPtr OutContent; - - if (TabId == ElementusEditorTabId) - { - OutContent = SNew(SElementusFrame); - } - else if (TabId == ItemCreatorTabId) - { - OutContent = SNew(SElementusItemCreator); - } - - if (OutContent.IsValid()) - { - return SNew(SDockTab) - .TabRole(NomadTab) - [ - OutContent.ToSharedRef() - ]; - } - - return SNew(SDockTab); + TSharedPtr OutContent; + + if (TabId == ElementusEditorTabId) + { + OutContent = SNew(SElementusFrame); + } + else if (TabId == ItemCreatorTabId) + { + OutContent = SNew(SElementusItemCreator); + } + + if (OutContent.IsValid()) + { + return SNew(SDockTab).TabRole(NomadTab) + [ + OutContent.ToSharedRef() + ]; + } + + return SNew(SDockTab); } void FElementusInventoryEditorModule::RegisterMenus() { - FToolMenuOwnerScoped OwnerScoped(this); + FToolMenuOwnerScoped OwnerScoped(this); #if ENGINE_MAJOR_VERSION < 5 const FName AppStyleName = FEditorStyle::GetStyleSetName(); #else - const FName AppStyleName = FAppStyle::GetAppStyleSetName(); + const FName AppStyleName = FAppStyle::GetAppStyleSetName(); #endif - const TSharedPtr Menu = WorkspaceMenu::GetMenuStructure().GetToolsCategory()->AddGroup(LOCTEXT("ElementusCategory", "Elementus"), LOCTEXT("ElementusCategoryTooltip", "Elementus Plugins Tabs"), FSlateIcon(AppStyleName, "InputBindingEditor.LevelViewport")); + const TSharedPtr Menu = WorkspaceMenu::GetMenuStructure().GetToolsCategory()->AddGroup( + LOCTEXT("ElementusCategory", "Elementus"), LOCTEXT("ElementusCategoryTooltip", "Elementus Plugins Tabs"), + FSlateIcon(AppStyleName, "InputBindingEditor.LevelViewport")); - const auto EditorTabSpawnerDelegate = FOnSpawnTab::CreateRaw(this, &FElementusInventoryEditorModule::OnSpawnTab, ElementusEditorTabId); + const auto EditorTabSpawnerDelegate = FOnSpawnTab::CreateRaw(this, &FElementusInventoryEditorModule::OnSpawnTab, ElementusEditorTabId); - FGlobalTabmanager::Get()->RegisterNomadTabSpawner(ElementusEditorTabId, EditorTabSpawnerDelegate) - .SetDisplayName(FText::FromString(TEXT("Elementus Inventory Management"))) - .SetTooltipText(FText::FromString(TEXT("Open Elementus Inventory Window"))) - .SetGroup(Menu.ToSharedRef()) - .SetIcon(FSlateIcon(AppStyleName, "Icons.Package")); + FGlobalTabmanager::Get()->RegisterNomadTabSpawner(ElementusEditorTabId, EditorTabSpawnerDelegate). + SetDisplayName(FText::FromString(TEXT("Elementus Inventory Management"))).SetTooltipText( + FText::FromString(TEXT("Open Elementus Inventory Window"))).SetGroup(Menu.ToSharedRef()).SetIcon( + FSlateIcon(AppStyleName, "Icons.Package")); - const auto ItemCreatorTabSpawnerDelegate = FOnSpawnTab::CreateRaw(this, &FElementusInventoryEditorModule::OnSpawnTab, ItemCreatorTabId); + const auto ItemCreatorTabSpawnerDelegate = FOnSpawnTab::CreateRaw(this, &FElementusInventoryEditorModule::OnSpawnTab, ItemCreatorTabId); - FGlobalTabmanager::Get()->RegisterNomadTabSpawner(ItemCreatorTabId, ItemCreatorTabSpawnerDelegate) - .SetDisplayName(FText::FromString(TEXT("Elementus Item Creator"))) - .SetGroup(Menu.ToSharedRef()) - .SetIcon(FSlateIcon(AppStyleName, "Icons.PlusCircle")); + FGlobalTabmanager::Get()->RegisterNomadTabSpawner(ItemCreatorTabId, ItemCreatorTabSpawnerDelegate). + SetDisplayName(FText::FromString(TEXT("Elementus Item Creator"))).SetGroup(Menu.ToSharedRef()).SetIcon( + FSlateIcon(AppStyleName, "Icons.PlusCircle")); } #undef LOCTEXT_NAMESPACE -IMPLEMENT_MODULE(FElementusInventoryEditorModule, ElementusInventoryEditor) \ No newline at end of file +IMPLEMENT_MODULE(FElementusInventoryEditorModule, ElementusInventoryEditor) diff --git a/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.cpp b/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.cpp index 8b8e466..d679e5f 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.cpp @@ -6,68 +6,68 @@ #include #include -void SElementusDetailsPanel::CustomizeHeader(const TSharedRef PropertyHandle, FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& CustomizationUtils) +void SElementusDetailsPanel::CustomizeHeader(const TSharedRef PropertyHandle, FDetailWidgetRow& HeaderRow, + IPropertyTypeCustomizationUtils& CustomizationUtils) { - PropertyHandlePtr = PropertyHandle; + PropertyHandlePtr = PropertyHandle; - HeaderRow - .NameContent() - [ - PropertyHandle->CreatePropertyNameWidget() - ] - .ValueContent() - [ - SNew(SObjectPropertyEntryBox) - .AllowedClass(UElementusItemData::StaticClass()) - .PropertyHandle(PropertyHandle) - .DisplayThumbnail(true) - .ThumbnailPool(CustomizationUtils.GetThumbnailPool()) - .ObjectPath(this, &SElementusDetailsPanel::GetObjPath) - .OnObjectChanged(this, &SElementusDetailsPanel::OnObjChanged) - .OnShouldFilterAsset_Lambda( - [](const FAssetData& AssetData) -> bool - { - return AssetData.GetPrimaryAssetId().PrimaryAssetType != FPrimaryAssetType(ElementusItemDataType); - } - ) - ]; + HeaderRow.NameContent()[PropertyHandle->CreatePropertyNameWidget()].ValueContent()[SNew(SObjectPropertyEntryBox) + .AllowedClass(UElementusItemData::StaticClass()) + .PropertyHandle(PropertyHandle) + .DisplayThumbnail(true) + .ThumbnailPool(CustomizationUtils.GetThumbnailPool()) + .ObjectPath(this, &SElementusDetailsPanel::GetObjPath) + .OnObjectChanged(this, &SElementusDetailsPanel::OnObjChanged) + .OnShouldFilterAsset_Lambda([](const FAssetData& AssetData) -> bool + { + return AssetData.GetPrimaryAssetId().PrimaryAssetType != FPrimaryAssetType(ElementusItemDataType); + })]; } -void SElementusDetailsPanel::CustomizeChildren(TSharedRef StructPropertyHandle, IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& CustomizationUtils) +void SElementusDetailsPanel::CustomizeChildren(TSharedRef StructPropertyHandle, IDetailChildrenBuilder& StructBuilder, + IPropertyTypeCustomizationUtils& CustomizationUtils) { } void SElementusDetailsPanel::OnObjChanged(const FAssetData& AssetData) const { - // (PrimaryAssetType="VALUE",PrimaryAssetName="VALUE") - const FString InValue(FString::Printf(TEXT("(PrimaryAssetType=\"%s\",PrimaryAssetName=\"%s\")"), *AssetData.GetPrimaryAssetId().PrimaryAssetType.ToString(), *AssetData.GetPrimaryAssetId().PrimaryAssetName.ToString())); + // (PrimaryAssetType="VALUE",PrimaryAssetName="VALUE") + const FString InValue(FString::Printf( + TEXT("(PrimaryAssetType=\"%s\",PrimaryAssetName=\"%s\")"), *AssetData.GetPrimaryAssetId().PrimaryAssetType.ToString(), + *AssetData.GetPrimaryAssetId().PrimaryAssetName.ToString())); - ensure(PropertyHandlePtr->SetValueFromFormattedString(InValue) == FPropertyAccess::Result::Success); + ensure(PropertyHandlePtr->SetValueFromFormattedString(InValue) == FPropertyAccess::Result::Success); } FString SElementusDetailsPanel::GetObjPath() const { - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid(); - AssetManager && PropertyHandlePtr.IsValid()) - { - FString AssetTypeValueStr; - PropertyHandlePtr->GetChildHandle(GET_MEMBER_NAME_CHECKED(FPrimaryAssetId, PrimaryAssetType))->GetValueAsDisplayString(AssetTypeValueStr); +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized(); +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid(); +#endif + AssetManager && PropertyHandlePtr.IsValid()) + { + FString AssetTypeValueStr; + PropertyHandlePtr->GetChildHandle(GET_MEMBER_NAME_CHECKED(FPrimaryAssetId, PrimaryAssetType))->GetValueAsDisplayString(AssetTypeValueStr); - FString AssetIdValueStr; - PropertyHandlePtr->GetChildHandle(GET_MEMBER_NAME_CHECKED(FPrimaryAssetId, PrimaryAssetName))->GetValueAsDisplayString(AssetIdValueStr); + FString AssetIdValueStr; + PropertyHandlePtr->GetChildHandle(GET_MEMBER_NAME_CHECKED(FPrimaryAssetId, PrimaryAssetName))->GetValueAsDisplayString(AssetIdValueStr); - const FPrimaryAssetId AssetId(*AssetTypeValueStr, *AssetIdValueStr); - const FString Output = AssetId.IsValid() ? AssetManager->GetPrimaryAssetPath(AssetId).ToString() : FString(); + const FPrimaryAssetId AssetId(*AssetTypeValueStr, *AssetIdValueStr); + const FString Output = AssetId.IsValid() ? AssetManager->GetPrimaryAssetPath(AssetId).ToString() : FString(); - if (AssetId.IsValid() && Output.IsEmpty()) - { - FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Asset Manager could not retrieve asset information: Check if you've added the path to the Asset Manager settings."))); + if (AssetId.IsValid() && Output.IsEmpty()) + { + FMessageDialog::Open(EAppMsgType::Ok, + FText::FromString(TEXT( + "Asset Manager could not retrieve asset information: Check if you've added the path to the Asset Manager settings."))); - PropertyHandlePtr->ResetToDefault(); - } + PropertyHandlePtr->ResetToDefault(); + } - return Output; - } + return Output; + } - return FString(); -} \ No newline at end of file + return FString(); +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.h b/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.h index bef55ed..44546d8 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.h +++ b/Source/ElementusInventoryEditor/Private/SElementusDetailsPanel.h @@ -10,19 +10,21 @@ class SElementusDetailsPanel final : public IPropertyTypeCustomization { public: - static TSharedRef MakeInstance() - { - return MakeShared(); - } + static TSharedRef MakeInstance() + { + return MakeShared(); + } protected: - virtual void CustomizeHeader(TSharedRef PropertyHandle, FDetailWidgetRow& HeaderRow, IPropertyTypeCustomizationUtils& CustomizationUtils) override; + virtual void CustomizeHeader(TSharedRef PropertyHandle, FDetailWidgetRow& HeaderRow, + IPropertyTypeCustomizationUtils& CustomizationUtils) override; - virtual void CustomizeChildren(TSharedRef StructPropertyHandle, IDetailChildrenBuilder& StructBuilder, IPropertyTypeCustomizationUtils& CustomizationUtils) override; + virtual void CustomizeChildren(TSharedRef StructPropertyHandle, IDetailChildrenBuilder& StructBuilder, + IPropertyTypeCustomizationUtils& CustomizationUtils) override; - FString GetObjPath() const; - void OnObjChanged(const FAssetData& AssetData) const; + FString GetObjPath() const; + void OnObjChanged(const FAssetData& AssetData) const; private: - TSharedPtr PropertyHandlePtr; + TSharedPtr PropertyHandlePtr; }; diff --git a/Source/ElementusInventoryEditor/Private/SElementusFrame.cpp b/Source/ElementusInventoryEditor/Private/SElementusFrame.cpp index 90cb476..6977bdd 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusFrame.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusFrame.cpp @@ -10,47 +10,38 @@ void SElementusFrame::Construct([[maybe_unused]] const FArguments& InArgs) { - ChildSlot - [ - ConstructContent() - ]; + ChildSlot + [ + ConstructContent() + ]; } TSharedRef SElementusFrame::ConstructContent() { - constexpr float SlotPadding = 4.f; + constexpr float SlotPadding = 4.f; - SAssignNew(Table, SElementusTable); + SAssignNew(Table, SElementusTable); - return SNew(SHorizontalBox) - + SHorizontalBox::Slot() - .AutoWidth() - .MaxWidth(300.f) - [ - SNew(SScrollBox) - + SScrollBox::Slot() - [ - SNew(SVerticalBox) - + SVerticalBox::Slot() - .Padding(SlotPadding) - .AutoHeight() - [ - SNew(SElementusSearch) - .OnSearchTextChanged(Table.ToSharedRef(), &SElementusTable::OnSearchTextModified) - .OnCheckboxStateChanged(Table.ToSharedRef(), &SElementusTable::OnSearchTypeModified) - ] - + SVerticalBox::Slot() - .Padding(SlotPadding) - .AutoHeight() - [ - SNew(SElementusUtils) - .TableSource(Table) - ] - ] - ] - + SHorizontalBox::Slot() - .FillWidth(1.f) - [ - Table.ToSharedRef() - ]; -} \ No newline at end of file + return SNew(SHorizontalBox) + + SHorizontalBox::Slot().AutoWidth().MaxWidth(300.f) + [ + SNew(SScrollBox) + + SScrollBox::Slot() + [ + SNew(SVerticalBox) + + SVerticalBox::Slot().Padding(SlotPadding).AutoHeight() + [ + SNew(SElementusSearch).OnSearchTextChanged(Table.ToSharedRef(), &SElementusTable::OnSearchTextModified).OnCheckboxStateChanged( + Table.ToSharedRef(), &SElementusTable::OnSearchTypeModified) + ] + + SVerticalBox::Slot().Padding(SlotPadding).AutoHeight() + [ + SNew(SElementusUtils).TableSource(Table) + ] + ] + ] + + SHorizontalBox::Slot().FillWidth(1.f) + [ + Table.ToSharedRef() + ]; +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusFrame.h b/Source/ElementusInventoryEditor/Private/SElementusFrame.h index d501b4f..fed1b1e 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusFrame.h +++ b/Source/ElementusInventoryEditor/Private/SElementusFrame.h @@ -9,16 +9,16 @@ class SElementusFrame final : public SCompoundWidget { public: - SLATE_USER_ARGS(SElementusFrame) - { - } + SLATE_USER_ARGS(SElementusFrame) + { + } - SLATE_END_ARGS() + SLATE_END_ARGS() - void Construct(const FArguments& InArgs); + void Construct(const FArguments& InArgs); private: - TSharedRef ConstructContent(); + TSharedRef ConstructContent(); - TSharedPtr Table; + TSharedPtr Table; }; diff --git a/Source/ElementusInventoryEditor/Private/SElementusItemCreator.cpp b/Source/ElementusInventoryEditor/Private/SElementusItemCreator.cpp index d790875..a341c7f 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusItemCreator.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusItemCreator.cpp @@ -23,433 +23,347 @@ void SElementusItemCreator::Construct([[maybe_unused]] const FArguments&) { - ItemTypesArr = GetEnumValuesAsStringArray(); - UpdateFolders(); + ItemTypesArr = GetEnumValuesAsStringArray(); + UpdateFolders(); - ChildSlot - [ - ConstructContent() - ]; + ChildSlot + [ + ConstructContent() + ]; } TSharedRef SElementusItemCreator::ConstructContent() { - constexpr float SlotPadding = 4.f; + constexpr float SlotPadding = 4.f; - ImageIcon_ThumbnailPool = MakeShared(1024u); + ImageIcon_ThumbnailPool = MakeShared(1024u); #if ENGINE_MAJOR_VERSION < 5 using FAppStyle = FEditorStyle; #endif - const auto ObjEntryBoxCreator_Lambda = [this](UClass* const ObjClass, const int32 ObjId) -> const TSharedRef - { - return SNew(SObjectPropertyEntryBox) - .IsEnabled(true) - .AllowedClass(ObjClass) - .AllowClear(true) - .DisplayUseSelected(true) - .DisplayBrowse(true) - .DisplayThumbnail(true) - .ThumbnailPool(ImageIcon_ThumbnailPool.ToSharedRef()) - .ObjectPath(this, &SElementusItemCreator::GetObjPath, ObjId) - .OnObjectChanged(this, &SElementusItemCreator::OnObjChanged, ObjId); - }; + const auto ObjEntryBoxCreator_Lambda = [this](UClass* const ObjClass, const int32 ObjId) -> const TSharedRef + { + return SNew(SObjectPropertyEntryBox) + .IsEnabled(true) + .AllowedClass(ObjClass) + .AllowClear(true) + .DisplayUseSelected(true) + .DisplayBrowse(true) + .DisplayThumbnail(true) + .ThumbnailPool(ImageIcon_ThumbnailPool.ToSharedRef()) + .ObjectPath(this, &SElementusItemCreator::GetObjPath, ObjId) + .OnObjectChanged(this, &SElementusItemCreator::OnObjChanged, ObjId); + }; - return SNew(SScrollBox) - + SScrollBox::Slot() - [ - SNew(SGridPanel) - .FillColumn(0, 0.3f) - .FillColumn(1, 0.7f) - + SGridPanel::Slot(0, 0) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("ID"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 0) - .Padding(SlotPadding) - [ - SNew(SNumericEntryBox) - .AllowSpin(false) - .MinValue(1) - .Value_Lambda([this] { return ItemId; }) - .OnValueChanged_Lambda( - [this](const int32 InValue) - { - ItemId = InValue; - } - ) - ] - + SGridPanel::Slot(0, 1) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Object"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 1) - .Padding(SlotPadding) - [ - ObjEntryBoxCreator_Lambda(UObject::StaticClass(), 0) - ] - + SGridPanel::Slot(0, 2) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Class"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 2) - .Padding(SlotPadding) - [ - SNew(SClassPropertyEntryBox) - .AllowAbstract(true) - .SelectedClass(this, &SElementusItemCreator::GetSelectedEntryClass) - .OnSetClass(this, &SElementusItemCreator::HandleNewEntryClassSelected) - ] - + SGridPanel::Slot(0, 3) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Name"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 3) - .Padding(SlotPadding) - [ - SNew(SEditableTextBox) - .OnTextChanged_Lambda( - [this](const FText& InText) - { - ItemName = *InText.ToString(); - } - ) - ] - + SGridPanel::Slot(0, 4) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Description"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 4) - .Padding(SlotPadding) - [ - SNew(SMultiLineEditableTextBox) - .OnTextChanged_Lambda( - [this](const FText& InText) - { - ItemDescription = InText; - } - ) - ] - + SGridPanel::Slot(0, 5) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Type"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 5) - .Padding(SlotPadding) - [ - SNew(STextComboBox) - .OptionsSource(&ItemTypesArr) - .OnSelectionChanged_Lambda( - [this](const FTextDisplayStringPtr& InStr, [[maybe_unused]] ESelectInfo::Type) - { - ItemType = ItemTypesArr.Find(InStr); - } - ) - ] - + SGridPanel::Slot(0, 6) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Is Stackable"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 6) - .Padding(SlotPadding) - [ - SNew(SCheckBox) - .IsChecked(ECheckBoxState::Checked) - .OnCheckStateChanged_Lambda( - [this](const ECheckBoxState InState) - { - bIsStackable = InState == ECheckBoxState::Checked; - } - ) - ] - + SGridPanel::Slot(0, 7) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Value"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 7) - .Padding(SlotPadding) - [ - SNew(SNumericEntryBox) - .AllowSpin(false) - .MinValue(0.0f) - .Value_Lambda([this] { return ItemValue; }) - .OnValueChanged_Lambda( - [this](const float InValue) - { - ItemValue = InValue; - } - ) - ] - + SGridPanel::Slot(0, 8) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Weight"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 8) - .Padding(SlotPadding) - [ - SNew(SNumericEntryBox) - .AllowSpin(false) - .MinValue(0.0f) - .Value_Lambda([this] { return ItemWeight; }) - .OnValueChanged_Lambda( - [this](const float InValue) - { - ItemWeight = InValue; - } - ) - ] - + SGridPanel::Slot(0, 9) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Icon"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 9) - .Padding(SlotPadding) - [ - ObjEntryBoxCreator_Lambda(UTexture2D::StaticClass(), 1) - ] - + SGridPanel::Slot(0, 10) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Image"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 10) - .Padding(SlotPadding) - [ - ObjEntryBoxCreator_Lambda(UTexture2D::StaticClass(), 2) - ] - + SGridPanel::Slot(0, 11) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Asset Name"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 11) - .Padding(SlotPadding) - [ - SNew(SEditableTextBox) - .OnTextChanged_Lambda( - [this](const FText& InText) - { - AssetName = *InText.ToString(); - } - ) - ] - + SGridPanel::Slot(0, 12) - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Asset Folder"))) - .TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass") - .Font(FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) - ] - + SGridPanel::Slot(1, 12) - .Padding(SlotPadding) - [ - SNew(SHorizontalBox) - + SHorizontalBox::Slot() - [ - SNew(STextComboBox) - .OptionsSource(&AssetFoldersArr) - .OnSelectionChanged_Lambda( - [this](const FTextDisplayStringPtr& InStr, [[maybe_unused]] ESelectInfo::Type) - { - AssetFolder = FName(*InStr.Get()); - } - ) - ] - + SHorizontalBox::Slot() - .AutoWidth() - [ - SNew(SButton) - .OnClicked_Lambda( - [this]() -> FReply - { - UpdateFolders(); - return FReply::Handled(); - } - ) - .Content() - [ - SNew(SImage) - .Image(FAppStyle::Get().GetBrush("Icons.Refresh")) - ] - ] - ] - + SGridPanel::Slot(1, 13) - .Padding(SlotPadding * 2.f) - .HAlign(HAlign_Left) - [ - SNew(SButton) - .Text(FText::FromString(TEXT("Create Item"))) - .OnClicked(this, &SElementusItemCreator::HandleCreateItemButtonClicked) - .IsEnabled(this, &SElementusItemCreator::IsCreateEnabled) - .ToolTip( - SNew(SToolTip) - .Text(FText::FromString(TEXT("Already exists a item with this Id."))) - .Visibility_Lambda( - [this]() -> EVisibility - { - return IsCreateEnabled() ? EVisibility::Collapsed : EVisibility::Visible; - } - ) - ) - ] - ]; + return SNew(SScrollBox) + + SScrollBox::Slot() + [ + SNew(SGridPanel).FillColumn(0, 0.3f).FillColumn(1, 0.7f) + + SGridPanel::Slot(0, 0).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("ID"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 0).Padding(SlotPadding) + [ + SNew(SNumericEntryBox).AllowSpin(false).MinValue(1).Value_Lambda([this] { return ItemId; }).OnValueChanged_Lambda( + [this](const int32 InValue) + { + ItemId = InValue; + }) + ] + + SGridPanel::Slot(0, 1).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Object"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 1).Padding(SlotPadding) + [ + ObjEntryBoxCreator_Lambda(UObject::StaticClass(), 0) + ] + + SGridPanel::Slot(0, 2).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Class"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 2).Padding(SlotPadding) + [ + SNew(SClassPropertyEntryBox).AllowAbstract(true).SelectedClass(this, &SElementusItemCreator::GetSelectedEntryClass).OnSetClass( + this, &SElementusItemCreator::HandleNewEntryClassSelected) + ] + + SGridPanel::Slot(0, 3).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Name"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 3).Padding(SlotPadding) + [ + SNew(SEditableTextBox).OnTextChanged_Lambda([this](const FText& InText) + { + ItemName = *InText.ToString(); + }) + ] + + SGridPanel::Slot(0, 4).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Description"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 4).Padding(SlotPadding) + [ + SNew(SMultiLineEditableTextBox).OnTextChanged_Lambda([this](const FText& InText) + { + ItemDescription = InText; + }) + ] + + SGridPanel::Slot(0, 5).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Type"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 5).Padding(SlotPadding) + [ + SNew(STextComboBox).OptionsSource(&ItemTypesArr).OnSelectionChanged_Lambda( + [this](const FTextDisplayStringPtr& InStr, [[maybe_unused]] ESelectInfo::Type) + { + ItemType = ItemTypesArr.Find(InStr); + }) + ] + + SGridPanel::Slot(0, 6).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Is Stackable"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 6).Padding(SlotPadding) + [ + SNew(SCheckBox).IsChecked(ECheckBoxState::Checked).OnCheckStateChanged_Lambda([this](const ECheckBoxState InState) + { + bIsStackable = InState == ECheckBoxState::Checked; + }) + ] + + SGridPanel::Slot(0, 7).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Value"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 7).Padding(SlotPadding) + [ + SNew(SNumericEntryBox).AllowSpin(false).MinValue(0.0f).Value_Lambda([this] { return ItemValue; }).OnValueChanged_Lambda( + [this](const float InValue) + { + ItemValue = InValue; + }) + ] + + SGridPanel::Slot(0, 8).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Weight"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 8).Padding(SlotPadding) + [ + SNew(SNumericEntryBox).AllowSpin(false).MinValue(0.0f).Value_Lambda([this] { return ItemWeight; }).OnValueChanged_Lambda( + [this](const float InValue) + { + ItemWeight = InValue; + }) + ] + + SGridPanel::Slot(0, 9).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Icon"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 9).Padding(SlotPadding) + [ + ObjEntryBoxCreator_Lambda(UTexture2D::StaticClass(), 1) + ] + + SGridPanel::Slot(0, 10).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Image"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 10).Padding(SlotPadding) + [ + ObjEntryBoxCreator_Lambda(UTexture2D::StaticClass(), 2) + ] + + SGridPanel::Slot(0, 11).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Asset Name"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 11).Padding(SlotPadding) + [ + SNew(SEditableTextBox).OnTextChanged_Lambda([this](const FText& InText) + { + AssetName = *InText.ToString(); + }) + ] + + SGridPanel::Slot(0, 12).Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Asset Folder"))).TextStyle(FAppStyle::Get(), "PropertyEditor.AssetClass").Font( + FAppStyle::Get().GetFontStyle("PropertyWindow.NormalFont")) + ] + + SGridPanel::Slot(1, 12).Padding(SlotPadding) + [ + SNew(SHorizontalBox) + + SHorizontalBox::Slot() + [ + SNew(STextComboBox).OptionsSource(&AssetFoldersArr).OnSelectionChanged_Lambda( + [this](const FTextDisplayStringPtr& InStr, [[maybe_unused]] ESelectInfo::Type) + { + AssetFolder = FName(*InStr.Get()); + }) + ] + + SHorizontalBox::Slot().AutoWidth() + [ + SNew(SButton) + .OnClicked_Lambda([this]() -> FReply + { + UpdateFolders(); + return FReply::Handled(); + }) + .Content() + [ + SNew(SImage).Image(FAppStyle::Get().GetBrush("Icons.Refresh")) + ] + ] + ] + + SGridPanel::Slot(1, 13).Padding(SlotPadding * 2.f).HAlign(HAlign_Left) + [ + SNew(SButton) + .Text(FText::FromString(TEXT("Create Item"))) + .OnClicked(this, &SElementusItemCreator::HandleCreateItemButtonClicked) + .IsEnabled(this, &SElementusItemCreator::IsCreateEnabled) + .ToolTip(SNew(SToolTip).Text(FText::FromString(TEXT("Already exists a item with this Id."))).Visibility_Lambda([this]() -> EVisibility + { + return IsCreateEnabled() ? EVisibility::Collapsed : EVisibility::Visible; + })) + ] + ]; } void SElementusItemCreator::OnObjChanged(const FAssetData& AssetData, const int32 ObjId) { - ObjectMap.FindOrAdd(ObjId) = AssetData.GetAsset(); + ObjectMap.FindOrAdd(ObjId) = AssetData.GetAsset(); } FString SElementusItemCreator::GetObjPath(const int32 ObjId) const { - return ObjectMap.Contains(ObjId) && ObjectMap.FindRef(ObjId).IsValid() ? ObjectMap.FindRef(ObjId)->GetPathName() : FString(); + return ObjectMap.Contains(ObjId) && ObjectMap.FindRef(ObjId).IsValid() ? ObjectMap.FindRef(ObjId)->GetPathName() : FString(); } void SElementusItemCreator::HandleNewEntryClassSelected(const UClass* Class) { - ItemClass = Class; + ItemClass = Class; } const UClass* SElementusItemCreator::GetSelectedEntryClass() const { - return ItemClass.Get(); + return ItemClass.Get(); } void SElementusItemCreator::UpdateFolders() { - AssetFoldersArr.Empty(); + AssetFoldersArr.Empty(); - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid()) - { - if (FPrimaryAssetTypeInfo Info; AssetManager->GetPrimaryAssetTypeInfo(FPrimaryAssetType(ElementusItemDataType), Info)) - { - for (const FString& Path : Info.AssetScanPaths) - { - AssetFoldersArr.Add(MakeShared(Path)); - } - } - } +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) +#endif + { + if (FPrimaryAssetTypeInfo Info; AssetManager->GetPrimaryAssetTypeInfo(FPrimaryAssetType(ElementusItemDataType), Info)) + { + for (const FString& Path : Info.AssetScanPaths) + { + AssetFoldersArr.Add(MakeShared(Path)); + } + } + } - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid(); IsValid(AssetManager) && AssetManager->HasInitialScanCompleted() && UElementusInventoryFunctions::HasEmptyParam(AssetFoldersArr)) - { - FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Asset Manager could not find any folder. Please check your Asset Manager settings."))); - } +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized(); +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid(); +#endif + IsValid(AssetManager) && AssetManager->HasInitialScanCompleted() && UElementusInventoryFunctions::HasEmptyParam(AssetFoldersArr)) + { + FMessageDialog::Open(EAppMsgType::Ok, + FText::FromString(TEXT("Asset Manager could not find any folder. Please check your Asset Manager settings."))); + } } FReply SElementusItemCreator::HandleCreateItemButtonClicked() const { - if (AssetFolder.IsNone() || AssetName.IsNone()) - { - FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Please enter the asset name and folder for the new item."))); + if (AssetFolder.IsNone() || AssetName.IsNone()) + { + FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Please enter the asset name and folder for the new item."))); - return FReply::Handled(); - } + return FReply::Handled(); + } - const FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked("AssetTools"); + const FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked("AssetTools"); - const FString PackageName = UPackageTools::SanitizePackageName(AssetFolder.ToString() + TEXT("/") + AssetName.ToString()); + const FString PackageName = UPackageTools::SanitizePackageName(AssetFolder.ToString() + TEXT("/") + AssetName.ToString()); - UDataAssetFactory* const Factory = NewObject(); + UDataAssetFactory* const Factory = NewObject(); - if (UObject* const NewData = AssetToolsModule.Get().CreateAsset(AssetName.ToString(), FPackageName::GetLongPackagePath(PackageName), UElementusItemData::StaticClass(), Factory)) - { - UElementusItemData* const ItemData = Cast(NewData); - ItemData->ItemId = ItemId; - ItemData->ItemObject = TSoftObjectPtr(Cast(ObjectMap.FindRef(0))); - ItemData->ItemClass = TSoftClassPtr(ItemClass.Get()); - ItemData->ItemName = ItemName; - ItemData->ItemDescription = ItemDescription; - ItemData->ItemType = static_cast(ItemType); - ItemData->bIsStackable = bIsStackable; - ItemData->ItemValue = ItemValue; - ItemData->ItemWeight = ItemWeight; - ItemData->ItemIcon = Cast(ObjectMap.FindRef(1)); - ItemData->ItemImage = Cast(ObjectMap.FindRef(2)); + if (UObject* const NewData = AssetToolsModule.Get().CreateAsset(AssetName.ToString(), FPackageName::GetLongPackagePath(PackageName), + UElementusItemData::StaticClass(), Factory)) + { + UElementusItemData* const ItemData = Cast(NewData); + ItemData->ItemId = ItemId; + ItemData->ItemObject = TSoftObjectPtr(Cast(ObjectMap.FindRef(0))); + ItemData->ItemClass = TSoftClassPtr(ItemClass.Get()); + ItemData->ItemName = ItemName; + ItemData->ItemDescription = ItemDescription; + ItemData->ItemType = static_cast(ItemType); + ItemData->bIsStackable = bIsStackable; + ItemData->ItemValue = ItemValue; + ItemData->ItemWeight = ItemWeight; + ItemData->ItemIcon = Cast(ObjectMap.FindRef(1)); + ItemData->ItemImage = Cast(ObjectMap.FindRef(2)); - TArray SyncAssets; - SyncAssets.Add(FAssetData(ItemData)); - GEditor->SyncBrowserToObjects(SyncAssets); + TArray SyncAssets; + SyncAssets.Add(FAssetData(ItemData)); + GEditor->SyncBrowserToObjects(SyncAssets); - const FString TempPackageName = ItemData->GetPackage()->GetName(); - const FString TempPackageFilename = FPackageName::LongPackageNameToFilename(TempPackageName, FPackageName::GetAssetPackageExtension()); + const FString TempPackageName = ItemData->GetPackage()->GetName(); + const FString TempPackageFilename = FPackageName::LongPackageNameToFilename(TempPackageName, FPackageName::GetAssetPackageExtension()); #if ENGINE_MAJOR_VERSION >= 5 - FSavePackageArgs SaveArgs; - SaveArgs.SaveFlags = RF_Public | RF_Standalone; - UPackage::SavePackage(ItemData->GetPackage(), ItemData, *TempPackageFilename, SaveArgs); + FSavePackageArgs SaveArgs; + SaveArgs.SaveFlags = RF_Public | RF_Standalone; + UPackage::SavePackage(ItemData->GetPackage(), ItemData, *TempPackageFilename, SaveArgs); #else UPackage::SavePackage(ItemData->GetPackage(), ItemData, RF_Public | RF_Standalone, *TempPackageFilename); #endif - } + } - return FReply::Handled(); + return FReply::Handled(); } bool SElementusItemCreator::IsCreateEnabled() const { - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid()) - { - return ItemId != 0 && !AssetManager->GetPrimaryAssetPath(FPrimaryAssetId(ElementusItemDataType, *("Item_" + FString::FromInt(ItemId)))).IsValid(); - } +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) +#endif + { + return ItemId != 0 && !AssetManager->GetPrimaryAssetPath(FPrimaryAssetId(ElementusItemDataType, *("Item_" + FString::FromInt(ItemId)))). + IsValid(); + } - return false; + return false; } TArray SElementusItemCreator::GetEnumValuesAsStringArray() const { - TArray EnumValues; - for (uint32 iterator = 0; iterator < static_cast(EElementusItemType::MAX); iterator++) - { - EnumValues.Add(MakeShared(UElementusInventoryFunctions::ElementusItemEnumTypeToString(static_cast(iterator)))); - } + TArray EnumValues; + for (uint32 Iterator = 0; Iterator < static_cast(EElementusItemType::MAX); Iterator++) + { + EnumValues.Add(MakeShared(UElementusInventoryFunctions::ElementusItemEnumTypeToString(static_cast(Iterator)))); + } - return EnumValues; -} \ No newline at end of file + return EnumValues; +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusItemCreator.h b/Source/ElementusInventoryEditor/Private/SElementusItemCreator.h index 6d3b6a7..337df06 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusItemCreator.h +++ b/Source/ElementusInventoryEditor/Private/SElementusItemCreator.h @@ -9,43 +9,43 @@ class SElementusItemCreator final : public SCompoundWidget { public: - SLATE_USER_ARGS(SElementusItemCreator) - { - } + SLATE_USER_ARGS(SElementusItemCreator) + { + } - SLATE_END_ARGS() + SLATE_END_ARGS() - void Construct(const FArguments& InArgs); + void Construct(const FArguments& InArgs); private: - TSharedRef ConstructContent(); + TSharedRef ConstructContent(); - FString GetObjPath(const int32 ObjId) const; - void OnObjChanged(const struct FAssetData& AssetData, const int32 ObjId); + FString GetObjPath(const int32 ObjId) const; + void OnObjChanged(const struct FAssetData& AssetData, const int32 ObjId); - const class UClass* GetSelectedEntryClass() const; - void HandleNewEntryClassSelected(const class UClass* Class); + const class UClass* GetSelectedEntryClass() const; + void HandleNewEntryClassSelected(const class UClass* Class); - void UpdateFolders(); + void UpdateFolders(); - FReply HandleCreateItemButtonClicked() const; - bool IsCreateEnabled() const; + FReply HandleCreateItemButtonClicked() const; + bool IsCreateEnabled() const; - TArray GetEnumValuesAsStringArray() const; + TArray GetEnumValuesAsStringArray() const; - TMap> ObjectMap; - TSharedPtr ImageIcon_ThumbnailPool; - TArray ItemTypesArr; - TArray AssetFoldersArr; + TMap> ObjectMap; + TSharedPtr ImageIcon_ThumbnailPool; + TArray ItemTypesArr; + TArray AssetFoldersArr; - FName AssetName; - FName AssetFolder; - int32 ItemId = 1; - TWeakObjectPtr ItemClass; - FName ItemName; - FText ItemDescription; - uint8 ItemType = 0; - bool bIsStackable = false; - float ItemValue = 0.f; - float ItemWeight = 0.f; + FName AssetName; + FName AssetFolder; + int32 ItemId = 1; + TWeakObjectPtr ItemClass; + FName ItemName; + FText ItemDescription; + uint8 ItemType = 0; + bool bIsStackable = false; + float ItemValue = 0.f; + float ItemWeight = 0.f; }; diff --git a/Source/ElementusInventoryEditor/Private/SElementusSearch.cpp b/Source/ElementusInventoryEditor/Private/SElementusSearch.cpp index 3bc4768..fa34901 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusSearch.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusSearch.cpp @@ -10,13 +10,13 @@ void SElementusSearch::Construct(const FArguments& InArgs) { - OnCheckStateChanged = InArgs._OnCheckboxStateChanged; - OnTextChangedDelegate = InArgs._OnSearchTextChanged; + OnCheckStateChanged = InArgs._OnCheckboxStateChanged; + OnTextChangedDelegate = InArgs._OnSearchTextChanged; - ChildSlot - [ - ConstructContent() - ]; + ChildSlot + [ + ConstructContent() + ]; } TSharedRef SElementusSearch::ConstructContent() @@ -25,106 +25,94 @@ TSharedRef SElementusSearch::ConstructContent() using FAppStyle = FEditorStyle; #endif - constexpr float SlotPadding = 4.f; + constexpr float SlotPadding = 4.f; - const auto CheckBoxCreator_Lambda = [this](const EElementusItemType& InType) -> const TSharedRef - { - constexpr float CheckBoxPadding = 2.f; - const int32 Index = static_cast(InType); + const auto CheckBoxCreator_Lambda = [this](const EElementusItemType& InType) -> const TSharedRef + { + constexpr float CheckBoxPadding = 2.f; + const int32 Index = static_cast(InType); - return SNew(SCheckBox) - .Padding(CheckBoxPadding) - .OnCheckStateChanged(this, &SElementusSearch::TriggerOnCheckboxStateChanged, Index) - .Content() - [ - SNew(STextBlock) - .Text(FText::FromString(UElementusInventoryFunctions::ElementusItemEnumTypeToString(static_cast(Index)))) - .Margin(CheckBoxPadding) - ]; - }; + return SNew(SCheckBox).Padding(CheckBoxPadding).OnCheckStateChanged(this, &SElementusSearch::TriggerOnCheckboxStateChanged, Index).Content() + [ + SNew(STextBlock) + .Text(FText::FromString(UElementusInventoryFunctions::ElementusItemEnumTypeToString(static_cast(Index)))) + .Margin(CheckBoxPadding) + ]; + }; - return SNew(SVerticalBox) - + SVerticalBox::Slot() - .AutoHeight() - [ - SNew(SSearchBox) - .OnTextChanged(this, &SElementusSearch::TriggerOnSearchTextChanged) - ] - + SVerticalBox::Slot() - .AutoHeight() - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Show types:"))) - .Font(FAppStyle::Get().GetFontStyle("NormalFontBold")) - ] - + SVerticalBox::Slot() - .AutoHeight() - .Padding(SlotPadding) - [ - SNew(SUniformGridPanel) - .SlotPadding(1.f) - + SUniformGridPanel::Slot(0, 0) - [ - CheckBoxCreator_Lambda(EElementusItemType::Accessory) - ] - + SUniformGridPanel::Slot(1, 0) - [ - CheckBoxCreator_Lambda(EElementusItemType::Armor) - ] - + SUniformGridPanel::Slot(0, 1) - [ - CheckBoxCreator_Lambda(EElementusItemType::Weapon) - ] - + SUniformGridPanel::Slot(1, 1) - [ - CheckBoxCreator_Lambda(EElementusItemType::Consumable) - ] - + SUniformGridPanel::Slot(0, 2) - [ - CheckBoxCreator_Lambda(EElementusItemType::Material) - ] - + SUniformGridPanel::Slot(1, 2) - [ - CheckBoxCreator_Lambda(EElementusItemType::Crafting) - ] - + SUniformGridPanel::Slot(0, 3) - [ - CheckBoxCreator_Lambda(EElementusItemType::Information) - ] - + SUniformGridPanel::Slot(1, 3) - [ - CheckBoxCreator_Lambda(EElementusItemType::Event) - ] - + SUniformGridPanel::Slot(0, 4) - [ - CheckBoxCreator_Lambda(EElementusItemType::Quest) - ] - + SUniformGridPanel::Slot(1, 4) - [ - CheckBoxCreator_Lambda(EElementusItemType::Junk) - ] - + SUniformGridPanel::Slot(0, 5) - [ - CheckBoxCreator_Lambda(EElementusItemType::Special) - ] - + SUniformGridPanel::Slot(1, 5) - [ - CheckBoxCreator_Lambda(EElementusItemType::Other) - ] - + SUniformGridPanel::Slot(0, 6) - [ - CheckBoxCreator_Lambda(EElementusItemType::None) - ] - ]; + return SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight() + [ + SNew(SSearchBox).OnTextChanged(this, &SElementusSearch::TriggerOnSearchTextChanged) + ] + + SVerticalBox::Slot().AutoHeight().Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Show types:"))).Font(FAppStyle::Get().GetFontStyle("NormalFontBold")) + ] + + SVerticalBox::Slot().AutoHeight().Padding(SlotPadding) + [ + SNew(SUniformGridPanel).SlotPadding(1.f) + + SUniformGridPanel::Slot(0, 0) + [ + CheckBoxCreator_Lambda(EElementusItemType::Accessory) + ] + + SUniformGridPanel::Slot(1, 0) + [ + CheckBoxCreator_Lambda(EElementusItemType::Armor) + ] + + SUniformGridPanel::Slot(0, 1) + [ + CheckBoxCreator_Lambda(EElementusItemType::Weapon) + ] + + SUniformGridPanel::Slot(1, 1) + [ + CheckBoxCreator_Lambda(EElementusItemType::Consumable) + ] + + SUniformGridPanel::Slot(0, 2) + [ + CheckBoxCreator_Lambda(EElementusItemType::Material) + ] + + SUniformGridPanel::Slot(1, 2) + [ + CheckBoxCreator_Lambda(EElementusItemType::Crafting) + ] + + SUniformGridPanel::Slot(0, 3) + [ + CheckBoxCreator_Lambda(EElementusItemType::Information) + ] + + SUniformGridPanel::Slot(1, 3) + [ + CheckBoxCreator_Lambda(EElementusItemType::Event) + ] + + SUniformGridPanel::Slot(0, 4) + [ + CheckBoxCreator_Lambda(EElementusItemType::Quest) + ] + + SUniformGridPanel::Slot(1, 4) + [ + CheckBoxCreator_Lambda(EElementusItemType::Junk) + ] + + SUniformGridPanel::Slot(0, 5) + [ + CheckBoxCreator_Lambda(EElementusItemType::Special) + ] + + SUniformGridPanel::Slot(1, 5) + [ + CheckBoxCreator_Lambda(EElementusItemType::Other) + ] + + SUniformGridPanel::Slot(0, 6) + [ + CheckBoxCreator_Lambda(EElementusItemType::None) + ] + ]; } void SElementusSearch::TriggerOnCheckboxStateChanged(const ECheckBoxState NewState, const int32 InType) const { - OnCheckStateChanged.ExecuteIfBound(NewState, InType); + OnCheckStateChanged.ExecuteIfBound(NewState, InType); } void SElementusSearch::TriggerOnSearchTextChanged(const FText& InText) const { - OnTextChangedDelegate.ExecuteIfBound(InText); -} \ No newline at end of file + OnTextChangedDelegate.ExecuteIfBound(InText); +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusSearch.h b/Source/ElementusInventoryEditor/Private/SElementusSearch.h index a92064d..f55683e 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusSearch.h +++ b/Source/ElementusInventoryEditor/Private/SElementusSearch.h @@ -13,22 +13,23 @@ DECLARE_DELEGATE_TwoParams(FOnElementusItemCheckStateChanged, ECheckBoxState, in class SElementusSearch final : public SCompoundWidget { public: - SLATE_USER_ARGS(SElementusSearch) - { - } - SLATE_EVENT(FOnElementusItemCheckStateChanged, OnCheckboxStateChanged) - SLATE_EVENT(FOnTextChanged, OnSearchTextChanged) + SLATE_USER_ARGS(SElementusSearch) + { + } - SLATE_END_ARGS() + SLATE_EVENT(FOnElementusItemCheckStateChanged, OnCheckboxStateChanged) + SLATE_EVENT(FOnTextChanged, OnSearchTextChanged) - void Construct(const FArguments& InArgs); + SLATE_END_ARGS() + + void Construct(const FArguments& InArgs); private: - TSharedRef ConstructContent(); + TSharedRef ConstructContent(); - void TriggerOnCheckboxStateChanged(ECheckBoxState NewState, int32 InType) const; - void TriggerOnSearchTextChanged(const FText& InText) const; + void TriggerOnCheckboxStateChanged(ECheckBoxState NewState, int32 InType) const; + void TriggerOnSearchTextChanged(const FText& InText) const; - FOnElementusItemCheckStateChanged OnCheckStateChanged; - FOnTextChanged OnTextChangedDelegate; + FOnElementusItemCheckStateChanged OnCheckStateChanged; + FOnTextChanged OnTextChangedDelegate; }; diff --git a/Source/ElementusInventoryEditor/Private/SElementusTable.cpp b/Source/ElementusInventoryEditor/Private/SElementusTable.cpp index bdb5fdc..bdf3082 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusTable.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusTable.cpp @@ -20,302 +20,298 @@ static const FName ColumnId_WeightLabel("Weight"); class SElementusItemTableRow final : public SMultiColumnTableRow { public: - SLATE_BEGIN_ARGS(SElementusItemTableRow) : _HightlightTextSource() - { - } + SLATE_BEGIN_ARGS(SElementusItemTableRow) : _HightlightTextSource() + { + } - SLATE_ARGUMENT(TSharedPtr, HightlightTextSource) - SLATE_END_ARGS() + SLATE_ARGUMENT(TSharedPtr, HightlightTextSource) + SLATE_END_ARGS() - void Construct(const FArguments& InArgs, const TSharedRef& InOwnerTableView, const FElementusItemPtr InEntryItem) - { - HighlightText = InArgs._HightlightTextSource; - Item = InEntryItem; + void Construct(const FArguments& InArgs, const TSharedRef& InOwnerTableView, const FElementusItemPtr& InEntryItem) + { + HighlightText = InArgs._HightlightTextSource; + Item = InEntryItem; - SMultiColumnTableRow::Construct(FSuperRowType::FArguments(), InOwnerTableView); - } + SMultiColumnTableRow::Construct(FSuperRowType::FArguments(), InOwnerTableView); + } protected: - virtual TSharedRef GenerateWidgetForColumn(const FName& ColumnName) override - { - const FSlateFontInfo CellFont = FCoreStyle::GetDefaultFontStyle("Regular", 10); - const FMargin CellMargin(4.f); - - const auto TextBlockCreator_Lambda = [this, &CellFont, &CellMargin](const FText& InText) -> TSharedRef - { - return SNew(STextBlock) - .Text(InText) - .Font(CellFont) - .Margin(CellMargin) - .HighlightText(HighlightText.IsValid() ? *HighlightText.Get() : FText::GetEmpty()); - }; - - if (ColumnName == ColumnId_PrimaryIdLabel) - { - return TextBlockCreator_Lambda(FText::FromString(Item->PrimaryAssetId.PrimaryAssetName.ToString())); - } - - if (ColumnName == ColumnId_ItemIdLabel) - { - return TextBlockCreator_Lambda(FText::FromString(FString::FromInt(Item->Id))); - } - - if (ColumnName == ColumnId_NameLabel) - { - return TextBlockCreator_Lambda(FText::FromString(Item->Name.ToString())); - } - - if (ColumnName == ColumnId_TypeLabel) - { - return TextBlockCreator_Lambda(FText::FromString(UElementusInventoryFunctions::ElementusItemEnumTypeToString(Item->Type))); - } - - if (ColumnName == ColumnId_ObjectLabel) - { - return TextBlockCreator_Lambda(FText::FromString(Item->Object.ToString())); - } - - if (ColumnName == ColumnId_ClassLabel) - { - return TextBlockCreator_Lambda(FText::FromString(Item->Class.ToString())); - } - - if (ColumnName == ColumnId_ValueLabel) - { - return TextBlockCreator_Lambda(FText::FromString(FString::SanitizeFloat(Item->Value))); - } - - if (ColumnName == ColumnId_WeightLabel) - { - return TextBlockCreator_Lambda(FText::FromString(FString::SanitizeFloat(Item->Weight))); - } - - return SNullWidget::NullWidget; - } + virtual TSharedRef GenerateWidgetForColumn(const FName& ColumnName) override + { + const FSlateFontInfo CellFont = FCoreStyle::GetDefaultFontStyle("Regular", 10); + const FMargin CellMargin(4.f); + + const auto TextBlockCreator_Lambda = [this, &CellFont, &CellMargin ](const FText& InText) -> TSharedRef + { + return SNew(STextBlock).Text(InText).Font(CellFont).Margin(CellMargin).HighlightText( + HighlightText.IsValid() ? *HighlightText.Get() : FText::GetEmpty()); + }; + + if (ColumnName == ColumnId_PrimaryIdLabel) + { + return TextBlockCreator_Lambda(FText::FromString(Item->PrimaryAssetId.PrimaryAssetName.ToString())); + } + + if (ColumnName == ColumnId_ItemIdLabel) + { + return TextBlockCreator_Lambda(FText::FromString(FString::FromInt(Item->Id))); + } + + if (ColumnName == ColumnId_NameLabel) + { + return TextBlockCreator_Lambda(FText::FromString(Item->Name.ToString())); + } + + if (ColumnName == ColumnId_TypeLabel) + { + return TextBlockCreator_Lambda(FText::FromString(UElementusInventoryFunctions::ElementusItemEnumTypeToString(Item->Type))); + } + + if (ColumnName == ColumnId_ObjectLabel) + { + return TextBlockCreator_Lambda(FText::FromString(Item->Object.ToString())); + } + + if (ColumnName == ColumnId_ClassLabel) + { + return TextBlockCreator_Lambda(FText::FromString(Item->Class.ToString())); + } + + if (ColumnName == ColumnId_ValueLabel) + { + return TextBlockCreator_Lambda(FText::FromString(FString::SanitizeFloat(Item->Value))); + } + + if (ColumnName == ColumnId_WeightLabel) + { + return TextBlockCreator_Lambda(FText::FromString(FString::SanitizeFloat(Item->Weight))); + } + + return SNullWidget::NullWidget; + } private: - FElementusItemPtr Item; - TSharedPtr HighlightText; + FElementusItemPtr Item; + TSharedPtr HighlightText; }; void SElementusTable::Construct([[maybe_unused]] const FArguments&) { - const TSharedPtr HeaderRow = SNew(SHeaderRow); - - const auto HeaderColumnCreator_Lambda = [this](const FName& ColumnId, const FString& ColumnText, const float InWidth = 1.f) -> const SHeaderRow::FColumn::FArguments - { - return SHeaderRow::Column(ColumnId) - .DefaultLabel(FText::FromString(ColumnText)) - .FillWidth(InWidth) - .SortMode(this, &SElementusTable::GetColumnSort, ColumnId) - .OnSort(this, &SElementusTable::OnColumnSort) - .HeaderComboVisibility(EHeaderComboVisibility::OnHover); - }; - - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_PrimaryIdLabel, "Primary Asset Id", 0.75f)); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ItemIdLabel, "Id")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_NameLabel, "Name")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_TypeLabel, "Type")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ObjectLabel, "Object")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ClassLabel, "Class")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ValueLabel, "Value")); - HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_WeightLabel, "Weight")); - - ChildSlot - [ - ConstructContent(HeaderRow.ToSharedRef()) - ]; - - UAssetManager::CallOrRegister_OnCompletedInitialScan( - FSimpleMulticastDelegate::FDelegate::CreateLambda( - [this] - { - UpdateItemList(); - } - ) - ); + const TSharedPtr HeaderRow = SNew(SHeaderRow); + + const auto HeaderColumnCreator_Lambda = [this](const FName& ColumnId, const FString& ColumnText, + const float InWidth = 1.f) -> const SHeaderRow::FColumn::FArguments + { + return SHeaderRow::Column(ColumnId).DefaultLabel(FText::FromString(ColumnText)).FillWidth(InWidth). + SortMode(this, &SElementusTable::GetColumnSort, ColumnId).OnSort(this, &SElementusTable::OnColumnSort). + HeaderComboVisibility(EHeaderComboVisibility::OnHover); + }; + + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_PrimaryIdLabel, "Primary Asset Id", 0.75f)); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ItemIdLabel, "Id")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_NameLabel, "Name")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_TypeLabel, "Type")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ObjectLabel, "Object")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ClassLabel, "Class")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_ValueLabel, "Value")); + HeaderRow->AddColumn(HeaderColumnCreator_Lambda(ColumnId_WeightLabel, "Weight")); + + ChildSlot + [ + ConstructContent(HeaderRow.ToSharedRef()) + ]; + + UAssetManager::CallOrRegister_OnCompletedInitialScan(FSimpleMulticastDelegate::FDelegate::CreateLambda([this] + { + UpdateItemList(); + })); } -TSharedRef SElementusTable::ConstructContent(const TSharedRef HeaderRow) +TSharedRef SElementusTable::ConstructContent(const TSharedRef& HeaderRow) { - return SAssignNew(EdListView, SListView) - .ListItemsSource(&ItemArr) - .SelectionMode(ESelectionMode::Multi) - .IsFocusable(true) - .OnGenerateRow(this, &SElementusTable::OnGenerateWidgetForList) - .HeaderRow(HeaderRow) - .OnMouseButtonDoubleClick(this, &SElementusTable::OnTableItemDoubleClicked); + return SAssignNew(EdListView, SListView) + .ListItemsSource(&ItemArr) + .SelectionMode(ESelectionMode::Multi) + .IsFocusable(true) + .OnGenerateRow(this, &SElementusTable::OnGenerateWidgetForList) + .HeaderRow(HeaderRow) + .OnMouseButtonDoubleClick(this, &SElementusTable::OnTableItemDoubleClicked); } TSharedRef SElementusTable::OnGenerateWidgetForList(const FElementusItemPtr InItem, const TSharedRef& OwnerTable) const { - return SNew(SElementusItemTableRow, OwnerTable, InItem) - .Visibility(this, &SElementusTable::GetIsVisible, InItem) - .HightlightTextSource(SearchText); + return SNew(SElementusItemTableRow, OwnerTable, InItem).Visibility(this, &SElementusTable::GetIsVisible, InItem).HightlightTextSource(SearchText); } void SElementusTable::OnTableItemDoubleClicked(const FElementusItemPtr ElementusItemRowData) const { - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid()) - { - UAssetEditorSubsystem* const AssetEditorSubsystem = NewObject(); - const FSoftObjectPath AssetPath = AssetManager->GetPrimaryAssetPath(ElementusItemRowData->PrimaryAssetId); - - AssetEditorSubsystem->OpenEditorForAsset(AssetPath.ToString()); - } +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) +#endif + { + UAssetEditorSubsystem* const AssetEditorSubsystem = GEditor->GetEditorSubsystem(); + const FSoftObjectPath AssetPath = AssetManager->GetPrimaryAssetPath(ElementusItemRowData->PrimaryAssetId); + + AssetEditorSubsystem->OpenEditorForAsset(AssetPath.ToString()); + } } EVisibility SElementusTable::GetIsVisible(const FElementusItemPtr InItem) const { - EVisibility Output; - - if ([&InItem](const FString& InText) -> const bool - { - return InText.IsEmpty() - || InItem->PrimaryAssetId.ToString().Contains(InText, ESearchCase::IgnoreCase) - || FString::FromInt(InItem->Id).Contains(InText, ESearchCase::IgnoreCase) - || InItem->Name.ToString().Contains(InText, ESearchCase::IgnoreCase) - || UElementusInventoryFunctions::ElementusItemEnumTypeToString(InItem->Type).Contains(InText, ESearchCase::IgnoreCase) - || InItem->Class.ToString().Contains(InText, ESearchCase::IgnoreCase) - || FString::SanitizeFloat(InItem->Value).Contains(InText, ESearchCase::IgnoreCase) - || FString::SanitizeFloat(InItem->Weight).Contains(InText, ESearchCase::IgnoreCase); - }(SearchText.IsValid() ? SearchText->ToString() : FString()) - && (AllowedTypes.Contains(static_cast(InItem->Type)) || UElementusInventoryFunctions::HasEmptyParam(AllowedTypes))) - { - Output = EVisibility::Visible; - } - else - { - Output = EVisibility::Collapsed; - } - - return Output; + EVisibility Output; + + if ([&InItem](const FString& InText) -> const bool + { + return InText.IsEmpty() || InItem->PrimaryAssetId.ToString().Contains(InText, ESearchCase::IgnoreCase) || FString::FromInt(InItem->Id). + Contains(InText, ESearchCase::IgnoreCase) || InItem->Name.ToString().Contains(InText, ESearchCase::IgnoreCase) || + UElementusInventoryFunctions::ElementusItemEnumTypeToString(InItem->Type).Contains(InText, ESearchCase::IgnoreCase) || InItem->Class. + ToString().Contains(InText, ESearchCase::IgnoreCase) || FString::SanitizeFloat(InItem->Value).Contains(InText, ESearchCase::IgnoreCase) || + FString::SanitizeFloat(InItem->Weight).Contains(InText, ESearchCase::IgnoreCase); + }(SearchText.IsValid() ? SearchText->ToString() : FString()) && (AllowedTypes.Contains(static_cast(InItem->Type)) || + UElementusInventoryFunctions::HasEmptyParam(AllowedTypes))) + { + Output = EVisibility::Visible; + } + else + { + Output = EVisibility::Collapsed; + } + + return Output; } void SElementusTable::OnSearchTextModified(const FText& InText) { - SearchText = MakeShared(InText); - EdListView->RebuildList(); + SearchText = MakeShared(InText); + EdListView->RebuildList(); } void SElementusTable::OnSearchTypeModified(const ECheckBoxState InState, const int32 InType) { - switch (InState) - { - case ECheckBoxState::Checked: - AllowedTypes.Add(InType); - break; - case ECheckBoxState::Unchecked: - AllowedTypes.Remove(InType); - break; - case ECheckBoxState::Undetermined: - AllowedTypes.Remove(InType); - break; - } - - EdListView->RequestListRefresh(); + switch (InState) + { + case ECheckBoxState::Checked: + AllowedTypes.Add(InType); + break; + case ECheckBoxState::Unchecked: + AllowedTypes.Remove(InType); + break; + case ECheckBoxState::Undetermined: + AllowedTypes.Remove(InType); + break; + } + + EdListView->RequestListRefresh(); } void SElementusTable::UpdateItemList() { - ItemArr.Empty(); - - for (const FPrimaryAssetId& Iterator : UElementusInventoryFunctions::GetAllElementusItemIds()) - { - ItemArr.Add(MakeShared(Iterator)); - } - - EdListView->RequestListRefresh(); - - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid(); IsValid(AssetManager) && AssetManager->HasInitialScanCompleted() && UElementusInventoryFunctions::HasEmptyParam(ItemArr)) - { - FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Asset Manager could not find any Elementus Items. Please check your Asset Manager settings."))); - } + ItemArr.Empty(); + + for (const FPrimaryAssetId& Iterator : UElementusInventoryFunctions::GetAllElementusItemIds()) + { + ItemArr.Add(MakeShared(Iterator)); + } + + EdListView->RequestListRefresh(); + +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized(); +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid(); +#endif + IsValid(AssetManager) && AssetManager->HasInitialScanCompleted() && UElementusInventoryFunctions::HasEmptyParam(ItemArr)) + { + FMessageDialog::Open(EAppMsgType::Ok, + FText::FromString(TEXT("Asset Manager could not find any Elementus Items. Please check your Asset Manager settings."))); + } } TArray SElementusTable::GetSelectedItems() const { - return EdListView->GetSelectedItems(); + return EdListView->GetSelectedItems(); } void SElementusTable::OnColumnSort([[maybe_unused]] const EColumnSortPriority::Type, const FName& ColumnName, const EColumnSortMode::Type SortMode) { - ColumnBeingSorted = ColumnName; - CurrentSortMode = SortMode; - - const auto Compare_Lambda = [&SortMode](const auto& Val1, const auto& Val2) -> bool - { - switch (SortMode) - { - case EColumnSortMode::Ascending: - return Val1 < Val2; - - case EColumnSortMode::Descending: - return Val1 > Val2; - - case EColumnSortMode::None: - return Val1 < Val2; - - default: - return false; - } - }; - - const auto Sort_Lambda = [&ColumnName, &Compare_Lambda](const FElementusItemPtr& Val1, const FElementusItemPtr& Val2) -> bool - { - if (ColumnName == ColumnId_PrimaryIdLabel) - { - return Compare_Lambda(Val1->PrimaryAssetId.ToString(), Val2->PrimaryAssetId.ToString()); - } - - if (ColumnName == ColumnId_ItemIdLabel) - { - return Compare_Lambda(Val1->Id, Val2->Id); - } - - if (ColumnName == ColumnId_NameLabel) - { - return Compare_Lambda(Val1->Name.ToString(), Val2->Name.ToString()); - } - - if (ColumnName == ColumnId_TypeLabel) - { - const auto ItemTypeToString_Lambda = [&](const EElementusItemType& InType) -> FString - { - return *UElementusInventoryFunctions::ElementusItemEnumTypeToString(InType); - }; - - return Compare_Lambda(ItemTypeToString_Lambda(Val1->Type), ItemTypeToString_Lambda(Val2->Type)); - } - - if (ColumnName == ColumnId_ClassLabel) - { - return Compare_Lambda(Val1->Class.ToString(), Val2->Class.ToString()); - } - - if (ColumnName == ColumnId_ValueLabel) - { - return Compare_Lambda(Val1->Value, Val2->Value); - } - - if (ColumnName == ColumnId_WeightLabel) - { - return Compare_Lambda(Val1->Weight, Val2->Weight); - } - - return false; - }; - - Algo::Sort(ItemArr, Sort_Lambda); - EdListView->RequestListRefresh(); + ColumnBeingSorted = ColumnName; + CurrentSortMode = SortMode; + + const auto Compare_Lambda = [&SortMode](const auto& Val1, const auto& Val2) -> bool + { + switch (SortMode) + { + case EColumnSortMode::Ascending: + return Val1 < Val2; + + case EColumnSortMode::Descending: + return Val1 > Val2; + + case EColumnSortMode::None: + return Val1 < Val2; + + default: + return false; + } + }; + + const auto Sort_Lambda = [&ColumnName, &Compare_Lambda](const FElementusItemPtr& Val1, const FElementusItemPtr& Val2) -> bool + { + if (ColumnName == ColumnId_PrimaryIdLabel) + { + return Compare_Lambda(Val1->PrimaryAssetId.ToString(), Val2->PrimaryAssetId.ToString()); + } + + if (ColumnName == ColumnId_ItemIdLabel) + { + return Compare_Lambda(Val1->Id, Val2->Id); + } + + if (ColumnName == ColumnId_NameLabel) + { + return Compare_Lambda(Val1->Name.ToString(), Val2->Name.ToString()); + } + + if (ColumnName == ColumnId_TypeLabel) + { + const auto ItemTypeToString_Lambda = [&](const EElementusItemType& InType) -> FString + { + return *UElementusInventoryFunctions::ElementusItemEnumTypeToString(InType); + }; + + return Compare_Lambda(ItemTypeToString_Lambda(Val1->Type), ItemTypeToString_Lambda(Val2->Type)); + } + + if (ColumnName == ColumnId_ClassLabel) + { + return Compare_Lambda(Val1->Class.ToString(), Val2->Class.ToString()); + } + + if (ColumnName == ColumnId_ValueLabel) + { + return Compare_Lambda(Val1->Value, Val2->Value); + } + + if (ColumnName == ColumnId_WeightLabel) + { + return Compare_Lambda(Val1->Weight, Val2->Weight); + } + + return false; + }; + + Algo::Sort(ItemArr, Sort_Lambda); + EdListView->RequestListRefresh(); } EColumnSortMode::Type SElementusTable::GetColumnSort(const FName ColumnId) const { - if (ColumnBeingSorted != ColumnId) - { - return EColumnSortMode::None; - } + if (ColumnBeingSorted != ColumnId) + { + return EColumnSortMode::None; + } - return CurrentSortMode; -} \ No newline at end of file + return CurrentSortMode; +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusTable.h b/Source/ElementusInventoryEditor/Private/SElementusTable.h index 8d6b713..d6135d7 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusTable.h +++ b/Source/ElementusInventoryEditor/Private/SElementusTable.h @@ -10,70 +10,70 @@ struct FElementusItemRowData { - explicit FElementusItemRowData(const FPrimaryElementusItemId& InPrimaryAssetId) - { - const auto ItemData = UElementusInventoryFunctions::GetSingleItemDataById(InPrimaryAssetId, { TEXT("Data"), TEXT("SoftData"), }, false); - - PrimaryAssetId = InPrimaryAssetId; - Id = ItemData->ItemId; - Name = ItemData->ItemName; - Type = ItemData->ItemType; - Class = ItemData->ItemClass.IsValid() ? *ItemData->ItemClass.LoadSynchronous()->GetName() : FName(); - Object = ItemData->ItemObject.IsValid() ? *ItemData->ItemObject.LoadSynchronous()->GetName() : FName(); - Value = ItemData->ItemValue; - Weight = ItemData->ItemWeight; - - UElementusInventoryFunctions::UnloadElementusItem(InPrimaryAssetId); - } - - explicit FElementusItemRowData(const FPrimaryAssetId& InPrimaryAssetId) : FElementusItemRowData(FPrimaryElementusItemId(InPrimaryAssetId)) - { - } - - FPrimaryAssetId PrimaryAssetId; - int32 Id = -1; - FName Name = NAME_None; - EElementusItemType Type = EElementusItemType::None; - FName Class = NAME_None; - FName Object = NAME_None; - float Value = -1.f; - float Weight = -1.f; + explicit FElementusItemRowData(const FPrimaryElementusItemId& InPrimaryAssetId) + { + const auto ItemData = UElementusInventoryFunctions::GetSingleItemDataById(InPrimaryAssetId, {TEXT("Data"), TEXT("SoftData"),}, false); + + PrimaryAssetId = InPrimaryAssetId; + Id = ItemData->ItemId; + Name = ItemData->ItemName; + Type = ItemData->ItemType; + Class = ItemData->ItemClass.IsValid() ? *ItemData->ItemClass.LoadSynchronous()->GetName() : FName(); + Object = ItemData->ItemObject.IsValid() ? *ItemData->ItemObject.LoadSynchronous()->GetName() : FName(); + Value = ItemData->ItemValue; + Weight = ItemData->ItemWeight; + + UElementusInventoryFunctions::UnloadElementusItem(InPrimaryAssetId); + } + + explicit FElementusItemRowData(const FPrimaryAssetId& InPrimaryAssetId) : FElementusItemRowData(FPrimaryElementusItemId(InPrimaryAssetId)) + { + } + + FPrimaryAssetId PrimaryAssetId; + int32 Id = -1; + FName Name = NAME_None; + EElementusItemType Type = EElementusItemType::None; + FName Class = NAME_None; + FName Object = NAME_None; + float Value = -1.f; + float Weight = -1.f; }; using FElementusItemPtr = TSharedPtr; class SElementusTable final : public SCompoundWidget { - friend class SElementusFrame; - friend class SElementusUtils; + friend class SElementusFrame; + friend class SElementusUtils; public: - SLATE_USER_ARGS(SElementusTable) - { - } + SLATE_USER_ARGS(SElementusTable) + { + } - SLATE_END_ARGS() + SLATE_END_ARGS() - void Construct(const FArguments& InArgs); + void Construct(const FArguments& InArgs); private: - TSharedRef ConstructContent(const TSharedRef HeaderRow); - - TSharedRef OnGenerateWidgetForList(const FElementusItemPtr InItem, const TSharedRef& OwnerTable) const; - void OnTableItemDoubleClicked(FElementusItemPtr ElementusItemRowData) const; - void OnColumnSort(EColumnSortPriority::Type SortPriority, const FName& ColumnName, EColumnSortMode::Type SortMode); - EColumnSortMode::Type GetColumnSort(const FName ColumnId) const; - EVisibility GetIsVisible(const FElementusItemPtr InItem) const; - void OnSearchTextModified(const FText& InText); - void OnSearchTypeModified(const ECheckBoxState InState, const int32 InType); - void UpdateItemList(); - TArray GetSelectedItems() const; - - TArray ItemArr; - TArray AllowedTypes; - TSharedPtr SearchText; - FName ColumnBeingSorted = NAME_None; - EColumnSortMode::Type CurrentSortMode = EColumnSortMode::None; - - TSharedPtr> EdListView; + TSharedRef ConstructContent(const TSharedRef& HeaderRow); + + TSharedRef OnGenerateWidgetForList(const FElementusItemPtr InItem, const TSharedRef& OwnerTable) const; + void OnTableItemDoubleClicked(const FElementusItemPtr ElementusItemRowData) const; + void OnColumnSort(EColumnSortPriority::Type SortPriority, const FName& ColumnName, EColumnSortMode::Type SortMode); + EColumnSortMode::Type GetColumnSort(const FName ColumnId) const; + EVisibility GetIsVisible(const FElementusItemPtr InItem) const; + void OnSearchTextModified(const FText& InText); + void OnSearchTypeModified(const ECheckBoxState InState, const int32 InType); + void UpdateItemList(); + TArray GetSelectedItems() const; + + TArray ItemArr; + TArray AllowedTypes; + TSharedPtr SearchText; + FName ColumnBeingSorted = NAME_None; + EColumnSortMode::Type CurrentSortMode = EColumnSortMode::None; + + TSharedPtr> EdListView; }; diff --git a/Source/ElementusInventoryEditor/Private/SElementusUtils.cpp b/Source/ElementusInventoryEditor/Private/SElementusUtils.cpp index a61b2fd..a2923b6 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusUtils.cpp +++ b/Source/ElementusInventoryEditor/Private/SElementusUtils.cpp @@ -11,12 +11,12 @@ void SElementusUtils::Construct(const FArguments& InArgs) { - TableSource = InArgs._TableSource; + TableSource = InArgs._TableSource; - ChildSlot - [ - ConstructContent() - ]; + ChildSlot + [ + ConstructContent() + ]; } TSharedRef SElementusUtils::ConstructContent() @@ -25,79 +25,73 @@ TSharedRef SElementusUtils::ConstructContent() using FAppStyle = FEditorStyle; #endif - constexpr float SlotPadding = 2.f; + constexpr float SlotPadding = 2.f; - const auto ButtonCreator_Lambda = [this](const FString& InStr, const FString& Tooltip, const uint32& ButtonId) -> TSharedRef - { - return SNew(SButton) - .Text(FText::FromString(InStr)) - .ToolTip(SNew(SToolTip).Text(FText::FromString(Tooltip))) - .HAlign(HAlign_Center) - .OnClicked(this, &SElementusUtils::OnButtonClicked, ButtonId); - }; + const auto ButtonCreator_Lambda = [this](const FString& InStr, const FString& Tooltip, const uint32& ButtonId) -> TSharedRef + { + return SNew(SButton).Text(FText::FromString(InStr)).ToolTip(SNew(SToolTip).Text(FText::FromString(Tooltip))).HAlign(HAlign_Center).OnClicked( + this, &SElementusUtils::OnButtonClicked, ButtonId); + }; - return SNew(SVerticalBox) - + SVerticalBox::Slot() - .AutoHeight() - .Padding(SlotPadding) - [ - SNew(STextBlock) - .Text(FText::FromString(TEXT("Utils:"))) - .Font(FAppStyle::Get().GetFontStyle("NormalFontBold")) - ] - + SVerticalBox::Slot() - .AutoHeight() - .Padding(SlotPadding) - [ - SNew(SUniformGridPanel) - .SlotPadding(SlotPadding / 2.f) - + SUniformGridPanel::Slot(0, 0) - [ - ButtonCreator_Lambda("Create Item", "Open the item creator window", 0) - ] - + SUniformGridPanel::Slot(1, 0) - [ - ButtonCreator_Lambda("Delete Items", "Delete the selected items", 1) - ] - + SUniformGridPanel::Slot(0, 1) - [ - ButtonCreator_Lambda("Update Table", "Update the items table", 2) - ] - ]; + return SNew(SVerticalBox) + + SVerticalBox::Slot().AutoHeight().Padding(SlotPadding) + [ + SNew(STextBlock).Text(FText::FromString(TEXT("Utils:"))).Font(FAppStyle::Get().GetFontStyle("NormalFontBold")) + ] + + SVerticalBox::Slot().AutoHeight().Padding(SlotPadding) + [ + SNew(SUniformGridPanel).SlotPadding(SlotPadding / 2.f) + + SUniformGridPanel::Slot(0, 0) + [ + ButtonCreator_Lambda("Create Item", "Open the item creator window", 0) + ] + + SUniformGridPanel::Slot(1, 0) + [ + ButtonCreator_Lambda("Delete Items", "Delete the selected items", 1) + ] + + SUniformGridPanel::Slot(0, 1) + [ + ButtonCreator_Lambda("Update Table", "Update the items table", 2) + ] + ]; } FReply SElementusUtils::OnButtonClicked(const uint32 ButtonId) const { - if (ButtonId == 0) - { - FGlobalTabmanager::Get()->TryInvokeTab(ItemCreatorTabId); - } - else if (ButtonId == 1) - { - if (const UAssetManager* const AssetManager = UAssetManager::GetIfValid()) - { - TArray AssetsToDelete; - for (const FElementusItemPtr& Iterator : TableSource->GetSelectedItems()) - { - FAssetData AssetData; - AssetManager->GetPrimaryAssetData(Iterator->PrimaryAssetId, AssetData); - AssetsToDelete.Add(AssetData); - } + if (ButtonId == 0) + { + FGlobalTabmanager::Get()->TryInvokeTab(ItemCreatorTabId); + } + else if (ButtonId == 1) + { +#if ENGINE_MAJOR_VERSION > 5 || (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3) + if (UAssetManager* const AssetManager = UAssetManager::GetIfInitialized()) +#else + if (UAssetManager* const AssetManager = UAssetManager::GetIfValid()) +#endif + { + TArray AssetsToDelete; + for (const FElementusItemPtr& Iterator : TableSource->GetSelectedItems()) + { + FAssetData AssetData; + AssetManager->GetPrimaryAssetData(Iterator->PrimaryAssetId, AssetData); + AssetsToDelete.Add(AssetData); + } - if (ObjectTools::DeleteAssets(AssetsToDelete) > 0) - { - TableSource->UpdateItemList(); - } - } - } - else if (ButtonId == 2) - { - TableSource->UpdateItemList(); - } - else - { - FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Work in Progress - ButtonId: ") + FString::FromInt(ButtonId))); - } + if (ObjectTools::DeleteAssets(AssetsToDelete) > 0) + { + TableSource->UpdateItemList(); + } + } + } + else if (ButtonId == 2) + { + TableSource->UpdateItemList(); + } + else + { + FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(TEXT("Work in Progress - ButtonId: ") + FString::FromInt(ButtonId))); + } - return FReply::Handled(); -} \ No newline at end of file + return FReply::Handled(); +} diff --git a/Source/ElementusInventoryEditor/Private/SElementusUtils.h b/Source/ElementusInventoryEditor/Private/SElementusUtils.h index 73bdb81..50c81bb 100644 --- a/Source/ElementusInventoryEditor/Private/SElementusUtils.h +++ b/Source/ElementusInventoryEditor/Private/SElementusUtils.h @@ -11,18 +11,18 @@ class SElementusTable; class SElementusUtils final : public SCompoundWidget { public: - SLATE_USER_ARGS(SElementusUtils) : _TableSource() - { - } + SLATE_USER_ARGS(SElementusUtils) : _TableSource() + { + } - SLATE_ARGUMENT(TSharedPtr, TableSource) - SLATE_END_ARGS() + SLATE_ARGUMENT(TSharedPtr, TableSource) + SLATE_END_ARGS() - void Construct(const FArguments& InArgs); + void Construct(const FArguments& InArgs); private: - TSharedRef ConstructContent(); - FReply OnButtonClicked(const uint32 ButtonId) const; + TSharedRef ConstructContent(); + FReply OnButtonClicked(const uint32 ButtonId) const; - TSharedPtr TableSource; + TSharedPtr TableSource; }; diff --git a/Source/ElementusInventoryEditor/Public/ElementusInventoryEditor.h b/Source/ElementusInventoryEditor/Public/ElementusInventoryEditor.h index c11466c..42ecc09 100644 --- a/Source/ElementusInventoryEditor/Public/ElementusInventoryEditor.h +++ b/Source/ElementusInventoryEditor/Public/ElementusInventoryEditor.h @@ -9,12 +9,12 @@ class FElementusInventoryEditorModule : public IModuleInterface { protected: - virtual void StartupModule() override; - virtual void ShutdownModule() override; + virtual void StartupModule() override; + virtual void ShutdownModule() override; - TSharedRef OnSpawnTab(const FSpawnTabArgs& SpawnTabArgs, FName TabId) const; + TSharedRef OnSpawnTab(const FSpawnTabArgs& SpawnTabArgs, FName TabId) const; private: - void RegisterMenus(); - FPropertyEditorModule* PropertyEditorModule = nullptr; + void RegisterMenus(); + FPropertyEditorModule* PropertyEditorModule = nullptr; };