第一次提交

This commit is contained in:
不明不惑
2026-03-03 01:23:02 +08:00
commit 3e434877e8
1053 changed files with 102411 additions and 0 deletions

View File

@@ -0,0 +1,239 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_LogChannels.h"
#include "Engine/TimerHandle.h"
#include "Engine/Engine.h"
#include "UObject/Object.h"
#include "Engine/CancellableAsyncAction.h"
#include "GIS_AsyncAction_Wait.generated.h"
/**
* Delegate triggered when an async wait action completes or is cancelled.
* 异步等待动作完成或取消时触发的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FGIS_AsyncAction_WaitSignature);
/**
* Base class for asynchronous wait actions on an actor.
* 在演员上执行异步等待动作的基类。
* @details Provides functionality to wait for specific conditions on an actor, with timer-based checks.
* @细节 提供在演员上等待特定条件的功能,通过定时器检查。
*/
UCLASS(Abstract)
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_Wait : public UCancellableAsyncAction
{
GENERATED_BODY()
public:
/**
* Constructor for the async wait action.
* 异步等待动作的构造函数。
*/
UGIS_AsyncAction_Wait();
/**
* Delegate triggered when the wait action completes successfully.
* 等待动作成功完成时触发的委托。
*/
UPROPERTY(BlueprintAssignable)
FGIS_AsyncAction_WaitSignature OnCompleted;
/**
* Delegate triggered when the wait action is cancelled.
* 等待动作取消时触发的委托。
*/
UPROPERTY(BlueprintAssignable)
FGIS_AsyncAction_WaitSignature OnCancelled;
/**
* Gets the world associated with this action.
* 获取与此动作关联的世界。
* @return The world object, or nullptr if not set. 世界对象如果未设置则返回nullptr。
*/
virtual UWorld* GetWorld() const override;
/**
* Gets the target actor for the wait action.
* 获取等待动作的目标演员。
* @return The target actor, or nullptr if not set. 目标演员如果未设置则返回nullptr。
*/
virtual AActor* GetActor() const;
/**
* Activates the wait action, starting the timer.
* 激活等待动作,启动定时器。
*/
virtual void Activate() override;
/**
* Completes the wait action, triggering the OnCompleted delegate.
* 完成等待动作触发OnCompleted委托。
*/
virtual void Complete();
/**
* Cancels the wait action, triggering the OnCancelled delegate.
* 取消等待动作触发OnCancelled委托。
*/
virtual void Cancel() override;
/**
* Determines whether delegates should be broadcast.
* 确定是否应广播委托。
* @return True if delegates should be broadcast, false otherwise. 如果应广播委托则返回true否则返回false。
*/
virtual bool ShouldBroadcastDelegates() const override;
/**
* Called when the target actor is destroyed.
* 目标演员销毁时调用。
* @param DestroyedActor The actor that was destroyed. 被销毁的演员。
*/
UFUNCTION()
virtual void OnTargetDestroyed(AActor* DestroyedActor);
protected:
/**
* Creates a new wait action instance.
* 创建新的等待动作实例。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param TargetActor The target actor to wait for. 要等待的目标演员。
* @param WaitInterval The interval between checks (in seconds). 检查间隔(以秒为单位)。
* @param MaxWaitTimes The maximum number of checks before timeout (-1 for no limit). 最大检查次数,超时前(-1表示无限制
* @return The created wait action, or nullptr if invalid parameters. 创建的等待动作如果参数无效则返回nullptr。
* @details Logs warnings if the world context, world, target actor, or wait interval is invalid.
* @细节 如果世界上下文、世界、目标演员或等待间隔无效,则记录警告。
*/
template <typename ActionType = UGIS_AsyncAction_Wait>
static ActionType* CreateWaitAction(UObject* WorldContext, AActor* TargetActor, float WaitInterval, int32 MaxWaitTimes)
{
if (!IsValid(WorldContext))
{
GIS_LOG(Warning, "invalid world context!")
return nullptr;
}
UWorld* World = GEngine->GetWorldFromContextObject(WorldContext, EGetWorldErrorMode::LogAndReturnNull);
if (!IsValid(World))
{
GIS_LOG(Warning, "can't get world from context:%s", *GetNameSafe(WorldContext));
return nullptr;
}
if (!IsValid(TargetActor))
{
GIS_LOG(Warning, "invalid target actor.");
return nullptr;
}
if (WaitInterval <= 0.f)
{
GIS_LOG(Warning, "WaitInterval %f must be greater than zero!", WaitInterval);
return nullptr;
}
ActionType* NewAction = Cast<ActionType>(NewObject<UGIS_AsyncAction_Wait>(GetTransientPackage(), ActionType::StaticClass()));
NewAction->SetWorld(World);
NewAction->SetTargetActor(TargetActor);
NewAction->SetWaitInterval(WaitInterval);
NewAction->SetMaxWaitTimes(MaxWaitTimes);
NewAction->RegisterWithGameInstance(World->GetGameInstance());
return NewAction;
}
/**
* Sets the world for the wait action.
* 设置等待动作的世界。
* @param NewWorld The world to set. 要设置的世界。
*/
void SetWorld(UWorld* NewWorld);
/**
* Sets the target actor for the wait action.
* 设置等待动作的目标演员。
* @param NewTargetActor The target actor to set. 要设置的目标演员。
*/
void SetTargetActor(AActor* NewTargetActor);
/**
* Sets the interval between checks.
* 设置检查间隔。
* @param NewWaitInterval The interval (in seconds). 间隔(以秒为单位)。
*/
void SetWaitInterval(float NewWaitInterval);
/**
* Sets the maximum number of checks before timeout.
* 设置超时前的最大检查次数。
* @param NewMaxWaitTimes The maximum number of checks (-1 for no limit). 最大检查次数(-1表示无限制
*/
void SetMaxWaitTimes(int32 NewMaxWaitTimes);
/**
* Stops the timer for the wait action.
* 停止等待动作的定时器。
*/
void StopWaiting();
/**
* Called when the timer ticks to check the wait condition.
* 定时器触发时调用以检查等待条件。
*/
UFUNCTION()
void OnTimer();
/**
* Cleans up resources used by the wait action.
* 清理等待动作使用的资源。
*/
virtual void Cleanup();
/**
* Executes the specific wait condition check.
* 执行特定的等待条件检查。
*/
UFUNCTION()
virtual void OnExecutionAction();
private:
/**
* Weak reference to the world for the wait action.
* 等待动作的世界的弱引用。
*/
TWeakObjectPtr<UWorld> WorldPtr{nullptr};
/**
* Weak reference to the target actor for the wait action.
* 等待动作的目标演员的弱引用。
*/
UPROPERTY()
TWeakObjectPtr<AActor> TargetActorPtr{nullptr};
/**
* Handle for the timer used to check the wait condition.
* 用于检查等待条件的定时器句柄。
*/
UPROPERTY()
FTimerHandle TimerHandle;
/**
* Interval between checks (in seconds).
* 检查间隔(以秒为单位)。
*/
float WaitInterval = 0.2f;
/**
* Current number of checks performed.
* 当前执行的检查次数。
*/
int32 WaitTimes = 0;
/**
* Maximum number of checks before timeout (-1 for no limit).
* 超时前的最大检查次数(-1表示无限制
*/
int32 MaxWaitTimes{-1};
};

View File

@@ -0,0 +1,84 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_AsyncAction_Wait.h"
#include "GIS_AsyncAction_WaitEquipmentSystem.generated.h"
class UGIS_EquipmentSystemComponent;
/**
* Async action to wait for a valid equipment system component on an actor.
* 在演员上等待有效装备系统组件的异步动作。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_WaitEquipmentSystem : public UGIS_AsyncAction_Wait
{
GENERATED_BODY()
public:
/**
* Waits for a valid equipment system component on the target actor.
* 在目标演员上等待有效的装备系统组件。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param TargetActor The target actor to wait for. 要等待的目标演员。
* @return The created wait action. 创建的等待动作。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Async", meta = (WorldContext = "WorldContext", DefaultToSelf="TargetActor", BlueprintInternalUseOnly = "true"))
static UGIS_AsyncAction_WaitEquipmentSystem* WaitEquipmentSystem(UObject* WorldContext, AActor* TargetActor);
protected:
/**
* Checks for the presence of a valid equipment system component.
* 检查是否存在有效的装备系统组件。
*/
virtual void OnExecutionAction() override;
};
/**
* Async action to wait for a valid and initialized equipment system component on an actor.
* 在演员上等待有效且已初始化的装备系统组件的异步动作。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_WaitEquipmentSystemInitialized : public UGIS_AsyncAction_WaitEquipmentSystem
{
GENERATED_BODY()
public:
/**
* Waits for a valid and initialized equipment system component on the target actor.
* 在目标演员上等待有效且已初始化的装备系统组件。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param TargetActor The target actor to wait for. 要等待的目标演员。
* @return The created wait action. 创建的等待动作。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Async", meta = (WorldContext = "WorldContext", DefaultToSelf="TargetActor", BlueprintInternalUseOnly = "true"))
static UGIS_AsyncAction_WaitEquipmentSystem* WaitEquipmentSystemInitialized(UObject* WorldContext, AActor* TargetActor);
protected:
/**
* Checks for the presence and initialization of the equipment system component.
* 检查装备系统组件的存在和初始化状态。
*/
virtual void OnExecutionAction() override;
/**
* Cleans up resources and event bindings.
* 清理资源和事件绑定。
*/
virtual void Cleanup() override;
/**
* Called when the equipment system component is initialized.
* 装备系统组件初始化时调用。
*/
UFUNCTION()
virtual void OnSystemInitialized();
/**
* Weak reference to the equipment system component being waited for.
* 等待的装备系统组件的弱引用。
*/
TWeakObjectPtr<UGIS_EquipmentSystemComponent> EquipmentSystemPtr;
};

View File

@@ -0,0 +1,83 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_AsyncAction_Wait.h"
#include "GIS_InventoryMeesages.h"
#include "GIS_AsyncAction_WaitInventorySystem.generated.h"
/**
* Async action to wait for a valid inventory system component on an actor.
* 在演员上等待有效库存系统组件的异步动作。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_WaitInventorySystem : public UGIS_AsyncAction_Wait
{
GENERATED_BODY()
public:
/**
* Waits for a valid inventory system component on the target actor.
* 在目标演员上等待有效的库存系统组件。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param TargetActor The target actor to wait for. 要等待的目标演员。
* @return The created wait action. 创建的等待动作。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Async", meta = (WorldContext = "WorldContext", DefaultToSelf="TargetActor", BlueprintInternalUseOnly = "true"))
static UGIS_AsyncAction_WaitInventorySystem* WaitInventorySystem(UObject* WorldContext, AActor* TargetActor);
protected:
/**
* Checks for the presence of a valid inventory system component.
* 检查是否存在有效的库存系统组件。
*/
virtual void OnExecutionAction() override;
};
/**
* Async action to wait for a valid and initialized inventory system component on an actor.
* 在演员上等待有效且已初始化的库存系统组件的异步动作。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_WaitInventorySystemInitialized : public UGIS_AsyncAction_WaitInventorySystem
{
GENERATED_BODY()
public:
/**
* Waits for a valid and initialized inventory system component on the target actor.
* 在目标演员上等待有效且已初始化的库存系统组件。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param TargetActor The target actor to wait for. 要等待的目标演员。
* @return The created wait action. 创建的等待动作。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Async", meta = (WorldContext = "WorldContext", DefaultToSelf="TargetActor", BlueprintInternalUseOnly = "true"))
static UGIS_AsyncAction_WaitInventorySystem* WaitInventorySystemInitialized(UObject* WorldContext, AActor* TargetActor);
protected:
/**
* Checks for the presence and initialization of the inventory system component.
* 检查库存系统组件的存在和初始化状态。
*/
virtual void OnExecutionAction() override;
/**
* Cleans up resources and event bindings.
* 清理资源和事件绑定。
*/
virtual void Cleanup() override;
/**
* Called when the inventory system component is initialized.
* 库存系统组件初始化时调用。
*/
UFUNCTION()
virtual void OnSystemInitialized();
/**
* Weak reference to the inventory system component being waited for.
* 等待的库存系统组件的弱引用。
*/
TWeakObjectPtr<UGIS_InventorySystemComponent> InventorySysPtr;
};

View File

@@ -0,0 +1,56 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/CancellableAsyncAction.h"
#include "Templates/SubclassOf.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "GIS_AsyncAction_WaitItemFragmentDataChanged.generated.h"
class UGIS_ItemFragment;
class UGIS_ItemInstance;
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FGIS_WaitFragmentStateChangedSignature, const UGIS_ItemFragment*, Fragment, const FInstancedStruct&, Data);
/**
* Async action to wait for a fragment data changed on an item instance.
* 在道具实例上等待指定道具片段的运行时数据变更。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_AsyncAction_WaitItemFragmentDataChanged : public UCancellableAsyncAction
{
GENERATED_BODY()
public:
/**
* Wait for a fragment data changed on an item instance.
* 在道具实例上等待指定道具片段的运行时数据变更。
* @param WorldContext The world context object to get the world reference. 用于获取世界引用的世界上下文对象。
* @param ItemInstance The target item instance to wait for. 要等待的目标道具。
* @param FragmentClass The fragment type to wait for. 要等待的片段类型。
* @return The created wait action. 创建的等待动作。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Async", meta = (WorldContext = "WorldContext", DefaultToSelf="ItemInstnace", BlueprintInternalUseOnly = "true"))
static UGIS_AsyncAction_WaitItemFragmentDataChanged* WaitItemFragmentStateChanged(UObject* WorldContext, UGIS_ItemInstance* ItemInstance, TSoftClassPtr<UGIS_ItemFragment> FragmentClass);
virtual void Activate() override;
virtual void Cancel() override;
UPROPERTY(BlueprintAssignable, Category="GIS|Async")
FGIS_WaitFragmentStateChangedSignature OnStateChanged;
protected:
UFUNCTION()
void OnFragmentStateChanged(const UGIS_ItemFragment* Fragment, const FInstancedStruct& State);
TWeakObjectPtr<UGIS_ItemInstance> ItemInstance;
TSubclassOf<UGIS_ItemFragment> FragmentClass;
};

View File

@@ -0,0 +1,259 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Interface.h"
#include "GameplayTagContainer.h"
#include "GIS_GameplayTagFloat.generated.h"
struct FGIS_GameplayTagFloatContainer;
/**
* Interface for objects that own a gameplay tag float container.
* 拥有游戏标签浮点容器对象的接口。
*/
UINTERFACE(meta=(CannotImplementInterfaceInBlueprint))
class GENERICINVENTORYSYSTEM_API UGIS_GameplayTagFloatContainerOwner : public UInterface
{
GENERATED_BODY()
};
/**
* Interface class for handling updates to float attributes in a gameplay tag container.
* 处理游戏标签容器中浮点属性更新的接口类。
*/
class GENERICINVENTORYSYSTEM_API IGIS_GameplayTagFloatContainerOwner
{
GENERATED_BODY()
public:
/**
* Called when a float attribute associated with a gameplay tag is updated.
* 当与游戏标签关联的浮点属性更新时调用。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
virtual void OnTagFloatUpdate(const FGameplayTag& Tag, float OldValue, float NewValue) = 0;
};
/**
* Represents a gameplay tag and float value pair.
* 表示一个游戏标签和浮点值的键值对。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_GameplayTagFloat : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* Default constructor for the gameplay tag float pair.
* 游戏标签浮点对的默认构造函数。
*/
FGIS_GameplayTagFloat()
{
}
/**
* Constructor for the gameplay tag float pair with initial values.
* 使用初始值构造游戏标签浮点对。
* @param InTag The gameplay tag for the pair. 键值对的游戏标签。
* @param InValue The float value for the pair. 键值对的浮点值。
*/
FGIS_GameplayTagFloat(FGameplayTag InTag, float InValue)
: Tag(InTag)
, Value(InValue)
{
}
/**
* Gets a debug string representation of the tag-value pair.
* 获取标签-值对的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString() const;
friend FGIS_GameplayTagFloatContainer;
/**
* The gameplay tag identifying the attribute.
* 标识属性的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGameplayTag Tag;
/**
* The float value associated with the tag.
* 与标签关联的浮点值。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
float Value = 0;
/**
* The previous float value of the attribute (not replicated).
* 属性的前一个浮点值(不复制)。
*/
UPROPERTY(NotReplicated)
float PrevValue = 0;
};
/**
* Container for storing gameplay tag float pairs.
* 存储游戏标签浮点对的容器。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_GameplayTagFloatContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for the float container.
* 浮点容器的默认构造函数。
*/
FGIS_GameplayTagFloatContainer()
// : Owner(nullptr)
{
}
/**
* Constructor for the float container with an owning object.
* 使用拥有对象构造浮点容器。
* @param InObject The object that owns this container. 拥有此容器的对象。
*/
FGIS_GameplayTagFloatContainer(UObject* InObject)
: ContainerOwner(InObject)
{
}
/**
* Adds a new tag-value pair to the container.
* 向容器添加新的标签-值对。
* @param Tag The gameplay tag to add. 要添加的游戏标签。
* @param Value The float value to associate with the tag. 与标签关联的浮点值。
*/
void AddItem(FGameplayTag Tag, float Value);
/**
* Sets the value for an existing tag or adds a new tag-value pair.
* 为现有标签设置值或添加新的标签-值对。
* @param Tag The gameplay tag to set. 要设置的游戏标签。
* @param Value The float value to set. 要设置的浮点值。
*/
void SetItem(FGameplayTag Tag, float Value);
/**
* Removes a specified amount from a tag-value pair.
* 从标签-值对中移除指定数量。
* @param Tag The gameplay tag to remove value from. 要移除值的游戏标签。
* @param Value The amount to remove. 要移除的数量。
*/
void RemoveItem(FGameplayTag Tag, float Value);
/**
* Sets all items in the container.
* 设置容器中的所有条目。
* @param NewItems The array of tag-value pairs to set. 要设置的标签-值对数组。
*/
void SetItems(const TArray<FGIS_GameplayTagFloat>& NewItems);
/**
* Clears all items from the container.
* 清空容器中的所有条目。
*/
void EmptyItems();
/**
* Gets the value associated with a specific tag.
* 获取与指定标签关联的值。
* @param Tag The gameplay tag to query. 要查询的游戏标签。
* @return The float value associated with the tag. 与标签关联的浮点值。
*/
float GetValue(FGameplayTag Tag) const
{
return TagToValueMap.FindRef(Tag);
}
/**
* Checks if the container contains a specific tag.
* 检查容器是否包含指定标签。
* @param Tag The gameplay tag to check. 要检查的游戏标签。
* @return True if the tag exists in the container, false otherwise. 如果标签存在于容器中则返回true否则返回false。
*/
bool ContainsTag(FGameplayTag Tag) const
{
return TagToValueMap.Contains(Tag);
}
//~FFastArraySerializer contract
/**
* Called before items are removed during replication.
* 复制期间移除条目前调用。
* @param RemovedIndices The indices of items to remove. 要移除的条目索引。
* @param FinalSize The final size of the items array after removal. 移除后条目数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after items are added during replication.
* 复制期间添加条目后调用。
* @param AddedIndices The indices of added items. 添加的条目索引。
* @param FinalSize The final size of the items array after addition. 添加后条目数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after items are changed during replication.
* 复制期间条目更改后调用。
* @param ChangedIndices The indices of changed items. 更改的条目索引。
* @param FinalSize The final size of the items array after change. 更改后条目数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for network replication.
* 处理网络复制的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_GameplayTagFloat, FGIS_GameplayTagFloatContainer>(Items, DeltaParms, *this);
}
/**
* The object that owns this container.
* 拥有此容器的对象。
*/
UPROPERTY()
TObjectPtr<UObject> ContainerOwner{nullptr};
/**
* Replicated list of gameplay tag float pairs.
* 游戏标签浮点对的复制列表。
*/
UPROPERTY(EditAnywhere, SaveGame, BlueprintReadWrite, Category="GIS", meta=(TitleProperty="{Tag}->{Value}"))
TArray<FGIS_GameplayTagFloat> Items;
/**
* Accelerated map of tags to values for efficient queries.
* 标签到值的加速映射,用于高效查询。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, NotReplicated, SaveGame, Category="GIS", meta=(ForceInlineRow))
TMap<FGameplayTag, float> TagToValueMap;
};
/**
* Traits for the float container to enable network delta serialization.
* 浮点容器的特性,用于启用网络增量序列化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_GameplayTagFloatContainer> : TStructOpsTypeTraitsBase2<FGIS_GameplayTagFloatContainer>
{
enum
{
WithNetDeltaSerializer = true,
};
};

View File

@@ -0,0 +1,248 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Interface.h"
#include "GameplayTagContainer.h"
#include "GIS_GameplayTagInteger.generated.h"
struct FGIS_GameplayTagIntegerContainer;
/**
* Interface for objects that own a gameplay tag integer container.
* 拥有游戏标签整型容器对象的接口。
*/
UINTERFACE(meta=(CannotImplementInterfaceInBlueprint))
class GENERICINVENTORYSYSTEM_API UGIS_GameplayTagIntegerContainerOwner : public UInterface
{
GENERATED_BODY()
};
/**
* Interface class for handling updates to integer attributes in a gameplay tag container.
* 处理游戏标签容器中整型属性更新的接口类。
*/
class GENERICINVENTORYSYSTEM_API IGIS_GameplayTagIntegerContainerOwner
{
GENERATED_BODY()
public:
/**
* Called when an integer attribute associated with a gameplay tag is updated.
* 当与游戏标签关联的整型属性更新时调用。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
virtual void OnTagIntegerUpdate(const FGameplayTag& Tag, int32 OldValue, int32 NewValue) = 0;
};
/**
* Represents a gameplay tag and integer value pair.
* 表示一个游戏标签和整型值的键值对。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_GameplayTagInteger : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* Default constructor for the gameplay tag integer pair.
* 游戏标签整型对的默认构造函数。
*/
FGIS_GameplayTagInteger()
{
}
/**
* Constructor for the gameplay tag integer pair with initial values.
* 使用初始值构造游戏标签整型对。
* @param InTag The gameplay tag for the pair. 键值对的游戏标签。
* @param InValue The integer value for the pair. 键值对的整型值。
*/
FGIS_GameplayTagInteger(FGameplayTag InTag, int32 InValue)
: Tag(InTag)
, Value(InValue)
{
}
/**
* Gets a debug string representation of the tag-value pair.
* 获取标签-值对的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString() const;
friend FGIS_GameplayTagIntegerContainer;
/**
* The gameplay tag identifying the attribute.
* 标识属性的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGameplayTag Tag;
/**
* The integer value associated with the tag.
* 与标签关联的整型值。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
int32 Value = 0;
/**
* The previous integer value of the attribute (not replicated).
* 属性的前一个整型值(不复制)。
* @attention Likely a typo in the original code; should be int32 instead of float.
* @注意 原始代码中可能有误应为int32而非float。
*/
UPROPERTY(NotReplicated)
float PrevValue = 0;
};
/**
* Container for storing gameplay tag integer pairs.
* 存储游戏标签整型对的容器。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_GameplayTagIntegerContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for the integer container.
* 整型容器的默认构造函数。
*/
FGIS_GameplayTagIntegerContainer()
// : Owner(nullptr)
{
}
/**
* Constructor for the integer container with an owning object.
* 使用拥有对象构造整型容器。
* @param InObject The object that owns this container. 拥有此容器的对象。
*/
FGIS_GameplayTagIntegerContainer(UObject* InObject)
: ContainerOwner(InObject)
{
}
/**
* Adds a new tag-value pair to the container.
* 向容器添加新的标签-值对。
* @param Tag The gameplay tag to add. 要添加的游戏标签。
* @param Value The integer value to associate with the tag. 与标签关联的整型值。
*/
void AddItem(FGameplayTag Tag, int32 Value);
/**
* Sets the value for an existing tag or adds a new tag-value pair.
* 为现有标签设置值或添加新的标签-值对。
* @param Tag The gameplay tag to set. 要设置的游戏标签。
* @param Value The integer value to set. 要设置的整型值。
*/
void SetItem(FGameplayTag Tag, int32 Value);
/**
* Removes a specified amount from a tag-value pair.
* 从标签-值对中移除指定数量。
* @param Tag The gameplay tag to remove value from. 要移除值的游戏标签。
* @param Value The amount to remove. 要移除的数量。
*/
void RemoveItem(FGameplayTag Tag, int32 Value);
/**
* Gets the value associated with a specific tag.
* 获取与指定标签关联的值。
* @param Tag The gameplay tag to query. 要查询的游戏标签。
* @return The integer value associated with the tag. 与标签关联的整型值。
*/
int32 GetValue(FGameplayTag Tag) const
{
return TagToValueMap.FindRef(Tag);
}
/**
* Checks if the container contains a specific tag.
* 检查容器是否包含指定标签。
* @param Tag The gameplay tag to check. 要检查的游戏标签。
* @return True if the tag exists in the container, false otherwise. 如果标签存在于容器中则返回true否则返回false。
*/
bool ContainsTag(FGameplayTag Tag) const
{
return TagToValueMap.Contains(Tag);
}
//~FFastArraySerializer contract
/**
* Called before items are removed during replication.
* 复制期间移除条目前调用。
* @param RemovedIndices The indices of items to remove. 要移除的条目索引。
* @param FinalSize The final size of the items array after removal. 移除后条目数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after items are added during replication.
* 复制期间添加条目后调用。
* @param AddedIndices The indices of added items. 添加的条目索引。
* @param FinalSize The final size of the items array after addition. 添加后条目数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after items are changed during replication.
* 复制期间条目更改后调用。
* @param ChangedIndices The indices of changed items. 更改的条目索引。
* @param FinalSize The final size of the items array after change. 更改后条目数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for network replication.
* 处理网络复制的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_GameplayTagInteger, FGIS_GameplayTagIntegerContainer>(Items, DeltaParms, *this);
}
/**
* The object that owns this container.
* 拥有此容器的对象。
*/
UPROPERTY()
TObjectPtr<UObject> ContainerOwner{nullptr};
/**
* Replicated list of gameplay tag integer pairs.
* 游戏标签整型对的复制列表。
*/
UPROPERTY(EditAnywhere, SaveGame, BlueprintReadWrite, Category="GIS", meta=(TitleProperty="{Tag}->{Value}"))
TArray<FGIS_GameplayTagInteger> Items;
/**
* Accelerated map of tags to values for efficient queries.
* 标签到值的加速映射,用于高效查询。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, NotReplicated, SaveGame, Category="GIS", meta=(ForceInlineRow))
TMap<FGameplayTag, int32> TagToValueMap;
};
/**
* Traits for the integer container to enable network delta serialization.
* 整型容器的特性,用于启用网络增量序列化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_GameplayTagIntegerContainer> : TStructOpsTypeTraitsBase2<FGIS_GameplayTagIntegerContainer>
{
enum
{
WithNetDeltaSerializer = true,
};
};

View File

@@ -0,0 +1,145 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "GIS_CollectionContainer.generated.h"
class UGIS_ItemCollectionDefinition;
class UGIS_InventorySystemComponent;
class UGIS_ItemCollection;
struct FGIS_CollectionContainer;
/**
* Structure representing an entry in the collection container.
* 表示集合容器中条目的结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_CollectionEntry : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* Default constructor for collection entry.
* 集合条目的默认构造函数。
*/
FGIS_CollectionEntry() : Instance(nullptr)
{
}
/**
* Unique ID of the collection entry.
* 集合条目的唯一ID。
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
FGuid Id = FGuid();
/**
* The collection definition associated with this entry.
* 与此条目关联的集合定义。
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
TObjectPtr<const UGIS_ItemCollectionDefinition> Definition;
/**
* The collection instance associated with this entry.
* 与此条目关联的集合实例。
*/
UPROPERTY(VisibleAnywhere, Category="GIS", meta=(ShowInnerProperties))
TObjectPtr<UGIS_ItemCollection> Instance = nullptr;
/**
* Checks if the collection entry is valid.
* 检查集合条目是否有效。
* @return True if the entry is valid, false otherwise. 如果条目有效则返回true否则返回false。
*/
bool IsValidEntry() const;
};
/**
* Container for storing a list of item collections with replication support.
* 用于存储道具集合列表的容器,支持复制。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_CollectionContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for collection container.
* 集合容器的默认构造函数。
*/
FGIS_CollectionContainer()
: OwningComponent(nullptr)
{
}
/**
* Constructor for collection container with an owning inventory component.
* 使用所属库存组件构造集合容器。
* @param InInventory The owning inventory system component. 所属的库存系统组件。
*/
FGIS_CollectionContainer(UGIS_InventorySystemComponent* InInventory);
//~FFastArraySerializer contract
/**
* Called before collection entries are removed during replication.
* 复制期间在移除集合条目前调用。
* @param RemovedIndices The indices of removed entries. 移除条目的索引。
* @param FinalSize The final size of the array after removal. 移除后数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after collection entries are added during replication.
* 复制期间在添加集合条目后调用。
* @param AddedIndices The indices of added entries. 添加条目的索引。
* @param FinalSize The final size of the array after addition. 添加后数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after collection entries are changed during replication.
* 复制期间在集合条目更改后调用。
* @param ChangedIndices The indices of changed entries. 更改条目的索引。
* @param FinalSize The final size of the array after changes. 更改后数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for the collection container.
* 处理集合容器的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_CollectionEntry, FGIS_CollectionContainer>(Entries, DeltaParms, *this);
}
/**
* Replicated list of collection entries.
* 复制的集合条目列表。
*/
UPROPERTY(VisibleAnywhere, Category="InventorySystem", meta=(ShowOnlyInnerProperties, DisplayName="Collections"))
TArray<FGIS_CollectionEntry> Entries;
/**
* The inventory system component that owns this container.
* 拥有此容器的库存系统组件。
*/
UPROPERTY()
TObjectPtr<UGIS_InventorySystemComponent> OwningComponent;
};
/**
* Template specialization to enable network delta serialization for the collection container.
* 为集合容器启用网络增量序列化的模板特化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_CollectionContainer> : TStructOpsTypeTraitsBase2<FGIS_CollectionContainer>
{
enum { WithNetDeltaSerializer = true };
};

View File

@@ -0,0 +1,651 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Engine/EngineTypes.h"
#include "Engine/DataAsset.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_InventoryMeesages.h"
#include "Items/GIS_ItemInfo.h"
#include "Items/GIS_ItemStack.h"
#include "GIS_ItemCollection.generated.h"
class UGIS_ItemRestriction;
class UGIS_SerializationFunctionLibrary;
class UGIS_ItemRestrictionSet;
class UGIS_InventorySubsystem;
class UGIS_ItemCollection;
class UGIS_InventorySystemComponent;
/**
* Delegate triggered when the item collection is updated.
* 道具集合更新时触发的委托。
* @param Message The update message containing collection changes. 包含集合变更的更新消息。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Collection_UpdateSignature, const FGIS_InventoryCollectionUpdateMessage&, Message);
/**
* Holds static configuration for an item collection.
* 存储道具集合的静态配置。
*/
UCLASS(BlueprintType, NotBlueprintable)
class GENERICINVENTORYSYSTEM_API UGIS_ItemCollectionDefinition : public UDataAsset
{
GENERATED_BODY()
public:
/**
* Checks if the collection definition supports networking.
* 检查集合定义是否支持网络。
* @return True if networking is supported, false otherwise. 如果支持网络则返回true否则返回false。
*/
virtual bool IsSupportedForNetworking() const override;
/**
* The unique tag of the item collection for querying in the inventory.
* 道具集合的唯一标签,用于在库存中查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Common", meta=(Categories="GIS.Collection"))
FGameplayTag CollectionTag;
/**
* Restrictions applied to the collection for complex use cases.
* 为复杂用例应用于集合的限制。
* @details Restrictions perform pre-checks to determine if items can be added or removed.
* @细节 限制会在道具操作前执行检查,以决定是否可以添加或移除道具。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Instanced, Category="Common")
TArray<TObjectPtr<UGIS_ItemRestriction>> Restrictions;
/**
* Options for handling overflow when an item cannot fit in the collection.
* 当道具无法放入集合时处理溢出的选项。
*/
UPROPERTY(EditAnywhere, Category="Common")
FGIS_ItemOverflowOptions OverflowOptions;
/**
* Gets the class for instantiating the collection.
* 获取用于实例化集合的类。
* @return The collection instance class. 集合实例类。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Common")
virtual TSubclassOf<UGIS_ItemCollection> GetCollectionInstanceClass() const;
};
/**
* Base class for a normal item collection.
* 常规道具集合的基类。
*/
UCLASS(BlueprintType, DefaultToInstanced, EditInlineNew, CollapseCategories, DisplayName="GIS Collection (Normal)")
class GENERICINVENTORYSYSTEM_API UGIS_ItemCollection : public UObject
{
GENERATED_BODY()
friend UGIS_ItemCollectionDefinition;
friend UGIS_InventorySystemComponent;
friend FGIS_ItemStackContainer;
public:
/**
* Helper struct to lock notifications during collection updates.
* 用于在集合更新期间锁定通知的辅助结构体。
*/
struct GIS_CollectionNotifyLocker
{
/**
* Constructor that locks notifications for the collection.
* 为集合锁定通知的构造函数。
* @param InItemCollection The collection to lock notifications for. 要锁定通知的集合。
*/
GIS_CollectionNotifyLocker(UGIS_ItemCollection& InItemCollection);
/**
* Destructor that unlocks notifications.
* 解锁通知的析构函数。
*/
~GIS_CollectionNotifyLocker();
/**
* The collection being managed.
* 被管理的集合。
*/
UGIS_ItemCollection& ItemCollection;
};
/**
* Constructor for the item collection.
* 道具集合的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_ItemCollection(const FObjectInitializer& ObjectInitializer);
//~UObject interface
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Calls a remote function on the object.
* 在对象上调用远程函数。
* @param Function The function to call. 要调用的函数。
* @param Parms The function parameters. 函数参数。
* @param OutParms The output parameters. 输出参数。
* @param Stack The function call stack. 函数调用堆栈。
* @return True if the function call was successful, false otherwise. 如果函数调用成功则返回true否则返回false。
*/
virtual bool CallRemoteFunction(UFunction* Function, void* Parms, FOutParmRec* OutParms, FFrame* Stack) override;
/**
* Gets the function call space for the object.
* 获取对象的函数调用空间。
* @param Function The function to query. 要查询的函数。
* @param Stack The function call stack. 函数调用堆栈。
* @return The call space identifier. 调用空间标识符。
*/
virtual int32 GetFunctionCallspace(UFunction* Function, FFrame* Stack) override;
/**
* Checks if the object supports networking.
* 检查对象是否支持网络。
* @return True if networking is supported, false otherwise. 如果支持网络则返回true否则返回false。
*/
virtual bool IsSupportedForNetworking() const override { return true; }
//~End of UObject interface
/**
* Checks if the collection is initialized.
* 检查集合是否已初始化。
* @return True if the collection is initialized, false otherwise. 如果集合已初始化则返回true否则返回false。
*/
bool IsInitialized() const;
/**
* Gets the inventory that owns this collection.
* 获取拥有此集合的库存。
* @return The owning inventory, or nullptr if not set. 所属库存如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemCollection")
UGIS_InventorySystemComponent* GetOwningInventory() const { return OwningInventory; };
/**
* Gets the unique tag of this collection.
* 获取此集合的唯一标签。
* @return The collection tag. 集合标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
FGameplayTag GetCollectionTag() const { return CollectionTag; };
/**
* Gets the unique ID of this collection.
* 获取此集合的唯一ID。
* @return The collection ID. 集合ID。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
FGuid GetCollectionId() const { return CollectionId; };
/**
* Gets the definition from which this collection was created.
* 获取此集合的源定义。
* @return The collection definition, or nullptr if not set. 集合定义如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
const UGIS_ItemCollectionDefinition* GetDefinition() const { return Definition; };
/**
* Gets the display name of the collection.
* 获取集合的显示名称。
* @return The display name. 显示名称。
*/
FString GetCollectionName() const;
/**
* Gets a debug string representation of the collection.
* 获取集合的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString() const;
#pragma region HasRegion
/**
* Checks if the collection contains a specified item.
* 检查集合是否包含指定道具。
* @param Item The item instance to check. 要检查的道具实例。
* @param Amount The amount to check for. 要检查的数量。
* @param SimilarItem Whether to check for similar items or exact matches. 是否检查相似道具或精确匹配。
* @return True if the collection contains at least the specified amount, false otherwise. 如果集合包含至少指定数量则返回true否则返回false。
*/
virtual bool HasItem(const UGIS_ItemInstance* Item, int32 Amount, bool SimilarItem = true) const;
#pragma endregion HasRegion
#pragma region Add&Remove
/**
* Adds an item to the collection.
* 将道具添加到集合。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @return The item that was not added or empty if added successfully. 未添加的道具,如果成功添加则为空。
*/
virtual FGIS_ItemInfo AddItem(const FGIS_ItemInfo& ItemInfo);
/**
* Adds multiple items to the collection.
* 将多个道具添加到集合。
* @param ItemInfos The array of item information to add. 要添加的道具信息数组。
* @return The number of items added. 添加的道具数量。
*/
virtual int32 AddItems(const TArray<FGIS_ItemInfo>& ItemInfos);
/**
* Adds a specific amount of an item to the collection.
* 将指定数量的道具添加到集合。
* @param Item The item instance to add. 要添加的道具实例。
* @param Amount The amount to add. 要添加的数量。
* @return The item that was actually added. 实际添加的道具。
*/
FGIS_ItemInfo AddItem(UGIS_ItemInstance* Item, int32 Amount);
/**
* Checks if an item can be added to the collection.
* 检查道具是否可以添加到集合。
* @param InItemInfo The item information to check. 要检查的道具信息。
* @param OutItemInfo The item information that can be added (output). 可添加的道具信息(输出)。
* @return True if at least one item can be added, false otherwise. 如果至少可以添加一个道具则返回true否则返回false。
*/
virtual bool CanAddItem(const FGIS_ItemInfo& InItemInfo, FGIS_ItemInfo& OutItemInfo);
/**
* Checks if an item can be stacked with an existing stack.
* 检查道具是否可以与现有栈堆叠。
* @param ItemInfo The item information to check. 要检查的道具信息。
* @param ItemStack The item stack to check against. 要检查的道具栈。
* @return True if the item can be stacked, false otherwise. 如果道具可以堆叠则返回true否则返回false。
*/
virtual bool CanItemStack(const FGIS_ItemInfo& ItemInfo, const FGIS_ItemStack& ItemStack) const;
/**
* Checks conditions for removing an item from the collection.
* 检查从集合移除道具的条件。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @param OutItemInfo The item information that can be removed (output). 可移除的道具信息(输出)。
* @return True if the item can be removed, false otherwise. 如果道具可以移除则返回true否则返回false。
*/
virtual bool RemoveItemCondition(const FGIS_ItemInfo& ItemInfo, FGIS_ItemInfo& OutItemInfo);
/**
* Removes an item from the collection.
* 从集合中移除道具。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @return The item that was removed, or empty if nothing was removed. 移除的道具,如果未移除则为空。
*/
virtual FGIS_ItemInfo RemoveItem(const FGIS_ItemInfo& ItemInfo);
/**
* Removes all items from the collection.
* 从集合中移除所有道具。
*/
virtual void RemoveAll();
#pragma endregion Add&Remove
#pragma region GetReference
/**
* Gets item information by stack ID.
* 通过栈ID获取道具信息。
* @param InStackId The stack ID to query. 要查询的栈ID。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if item information was found, false otherwise. 如果找到道具信息则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
bool GetItemInfoByStackId(FGuid InStackId, FGIS_ItemInfo& OutItemInfo) const;
/**
* Finds item information by stack ID.
* 通过栈ID查找道具信息。
* @param InStackId The stack ID to query. 要查询的栈ID。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if item information was found, false otherwise. 如果找到道具信息则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemCollection", meta=(ExpandBoolAsExecs="ReturnValue"))
bool FindItemInfoByStackId(FGuid InStackId, FGIS_ItemInfo& OutItemInfo) const;
/**
* Retrieves information about a specific item instance.
* 获取指定道具实例的信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if information was found, false otherwise. 如果找到信息则返回true否则返回false。
*/
virtual bool GetItemInfo(const UGIS_ItemInstance* Item, FGIS_ItemInfo& OutItemInfo) const;
/**
* Gets item information by item definition.
* 通过道具定义获取道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if information was found, false otherwise. 如果找到信息则返回true否则返回false。
*/
bool GetItemInfoByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition>& ItemDefinition, FGIS_ItemInfo& OutItemInfo);
/**
* Gets all item information for a specific item definition.
* 获取指定道具定义的所有道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfos The array of item information (output). 道具信息数组(输出)。
* @return True if information was found, false otherwise. 如果找到信息则返回true否则返回false。
*/
bool GetItemInfosByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition>& ItemDefinition, TArray<FGIS_ItemInfo>& OutItemInfos);
/**
* Gets the amount of a specific item in the collection.
* 获取集合中指定道具的数量。
* @param Item The item instance to query. 要查询的道具实例。
* @param SimilarItem Whether to count similar items or exact matches. 是否计数相似道具或精确匹配。
* @return The amount of the item in the collection. 集合中的道具数量。
*/
int32 GetItemAmount(const UGIS_ItemInstance* Item, bool SimilarItem = true) const;
/**
* Gets the amount of items with a specific definition in the collection.
* 获取集合中具有指定定义的道具数量。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param CountStacks Whether to count the number of stacks instead of total amount. 是否计数栈数量而不是总数量。
* @return The number of items or stacks in the collection. 集合中的道具或栈数量。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemCollection")
int32 GetItemAmount(TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, bool CountStacks = false) const;
/**
* Gets all item information in the collection.
* 获取集合中的所有道具信息。
* @return Array of item information. 道具信息数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
TArray<FGIS_ItemInfo> GetAllItemInfos() const;
/**
* Gets all item instances in the collection.
* 获取集合中的所有道具实例。
* @return Array of item instances. 道具实例数组。
*/
TArray<UGIS_ItemInstance*> GetAllItems() const;
#pragma endregion GetReference
#pragma region Giver
/**
* Gives an item to another collection.
* 将道具给予另一个集合。
* @param ItemInfo The item information to give. 要给予的道具信息。
* @param ItemCollection The target collection to receive the item. 接收道具的目标集合。
* @return The item information that was given. 给予的道具信息。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
virtual FGIS_ItemInfo GiveItem(const FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ItemCollection);
/**
* Server function to give an item to another collection.
* 服务器函数,将道具给予另一个集合。
* @param ItemInfo The item information to give. 要给予的道具信息。
* @param ItemCollection The target collection to receive the item. 接收道具的目标集合。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|ItemCollection")
void ServerGiveItem(const FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ItemCollection);
/**
* Implementation of ServerGiveItem.
* ServerGiveItem 的实现。
* @param ItemInfo The item information to give. 要给予的道具信息。
* @param ItemCollection The target collection to receive the item. 接收道具的目标集合。
*/
virtual void ServerGiveItem_Implementation(const FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ItemCollection);
/**
* Gives all items in this collection to another collection.
* 将此集合中的所有道具给予另一个集合。
* @param OtherItemCollection The target collection to receive the items. 接收道具的目标集合。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
virtual void GiveAllItems(UGIS_ItemCollection* OtherItemCollection);
/**
* Server function to give all items to another collection.
* 服务器函数,将所有道具给予另一个集合。
* @param OtherItemCollection The target collection to receive the items. 接收道具的目标集合。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|ItemCollection")
void ServerGiveAllItems(UGIS_ItemCollection* OtherItemCollection);
/**
* Calculates how many items can fit given a limited number of additional stacks.
* 计算在有限额外栈数下可以容纳的道具数量。
* @param ItemInfo The item information to check. 要检查的道具信息。
* @param AvailableAdditionalStacks The number of additional stacks allowed. 允许的额外栈数。
* @return The number of items that can fit. 可容纳的道具数量。
*/
virtual int32 GetItemAmountFittingInLimitedAdditionalStacks(const FGIS_ItemInfo& ItemInfo, int32 AvailableAdditionalStacks) const;
#pragma endregion Giver
/**
* Event triggered when the item collection is updated.
* 道具集合更新时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Collection_UpdateSignature OnItemCollectionUpdate;
#pragma region ItemStacks
/**
* Gets all item stacks in the collection.
* 获取集合中的所有道具栈。
* @return Array of item stacks. 道具栈数组。
*/
const TArray<FGIS_ItemStack>& GetAllItemStacks() const;
/**
* Gets the number of item stacks in the collection.
* 获取集合中的道具栈数量。
* @return The number of item stacks. 道具栈数量。
*/
int32 GetItemStacksNum() const;
protected:
/**
* Adds an item stack to the collection.
* 将道具栈添加到集合。
* @param Stack The item stack to add. 要添加的道具栈。
*/
virtual void AddItemStack(const FGIS_ItemStack& Stack);
/**
* Removes an item stack at a specific index.
* 在指定索引移除道具栈。
* @param Idx The index of the stack to remove. 要移除的栈索引。
* @param bRemoveFromCollection Whether to remove the item instance from the collection. 是否从集合中移除道具实例。
*/
virtual void RemoveItemStackAtIndex(int32 Idx, bool bRemoveFromCollection = true);
/**
* Updates the amount of an item stack at a specific index.
* 更新指定索引的道具栈数量。
* @param Idx The index of the stack to update. 要更新的栈索引。
* @param NewAmount The new amount for the stack. 栈的新数量。
*/
virtual void UpdateItemStackAmountAtIndex(int32 Idx, int32 NewAmount);
/**
* Called before an item stack is added (server-side only).
* 在添加道具栈之前调用(仅限服务器端)。
* @param Stack The item stack to add. 要添加的道具栈。
* @param Idx The index where the stack will be added. 栈将添加的索引。
*/
virtual void OnPreItemStackAdded(const FGIS_ItemStack& Stack, int32 Idx);
/**
* Called when an item stack is added (client and server).
* 道具栈添加时调用(客户端和服务器)。
* @param Stack The added item stack. 添加的道具栈。
*/
virtual void OnItemStackAdded(const FGIS_ItemStack& Stack);
/**
* Called when an item stack is removed (client and server).
* 道具栈移除时调用(客户端和服务器)。
* @param Stack The removed item stack. 移除的道具栈。
*/
virtual void OnItemStackRemoved(const FGIS_ItemStack& Stack);
/**
* Called when an item stack is updated (client and server).
* 道具栈更新时调用(客户端和服务器)。
* @param Stack The updated item stack. 更新的道具栈。
*/
virtual void OnItemStackUpdated(const FGIS_ItemStack& Stack);
/**
* Processes pending item stacks.
* 处理待处理的道具栈。
*/
void ProcessPendingItemStacks();
/**
* Store the stack id and position mapping within this collection.
* 存储在此集合中Stack id到位置的映射关系。
*/
UPROPERTY(VisibleInstanceOnly, Category="ItemCollection", Transient, meta=(ForceInlineRow))
TMap<FGuid, int32> StackToIdxMap;
/**
* Store the stack id and position mapping within this collection.
* 存储在此集合中Stack id到位置的映射关系。
*/
// UPROPERTY(VisibleInstanceOnly, Category="ItemCollection", Transient)
// TMap<FGuid, int32> IdxToStackMap;
private:
/**
* Temporary storage for pending item stacks.
* 待处理道具栈的临时存储。
*/
UPROPERTY(VisibleInstanceOnly, Category="ItemCollection", Transient)
TMap<FGuid, FGIS_ItemStack> PendingItemStacks;
#pragma endregion
protected:
/**
* Internal function to add an item to the collection.
* 内部函数,将道具添加到集合。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @return The item that was actually added. 实际添加的道具。
*/
virtual FGIS_ItemInfo AddInternal(const FGIS_ItemInfo& ItemInfo);
/**
* Handles overflow when an item cannot be fully added.
* 处理道具无法完全添加时的溢出。
* @param OriginalItemInfo The original item information. 原始道具信息。
* @param ItemInfoAdded The item information that was added. 已添加的道具信息。
*/
virtual void HandleItemOverflow(const FGIS_ItemInfo& OriginalItemInfo, const FGIS_ItemInfo& ItemInfoAdded);
/**
* Internal function to remove an item from the collection.
* 内部函数,从集合中移除道具。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @return The item that was removed. 移除的道具。
*/
virtual FGIS_ItemInfo RemoveInternal(const FGIS_ItemInfo& ItemInfo);
/**
* Simplifies internal item removal logic.
* 简化内部道具移除逻辑。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @param AlreadyRemoved The amount already removed (modified). 已移除的数量(可修改)。
* @param StackIndex The stack index to remove from. 要移除的栈索引。
* @return The item stack was actually removed. 实际被移除的道具栈。
*/
virtual FGIS_ItemStack SimpleInternalItemRemove(const FGIS_ItemInfo& ItemInfo, int32& AlreadyRemoved, int32 StackIndex);
/**
* Indicates whether the collection is initialized.
* 指示集合是否已初始化。
*/
UPROPERTY(Transient)
bool bInitialized = false;
/**
* Counter for locking notifications.
* 用于锁定通知的计数器。
*/
int32 NotifyLocker = 0;
/**
* Container for item stacks.
* 道具栈的容器。
*/
UPROPERTY(VisibleInstanceOnly, Category="ItemCollection", Replicated, meta=(ShowOnlyInnerProperties))
FGIS_ItemStackContainer Container;
/**
* The unique tag of the item collection for querying in the inventory.
* 道具集合的唯一标签,用于在库存中查询。
*/
UPROPERTY(Transient)
FGameplayTag CollectionTag;
/**
* The collection definition.
* 集合定义。
*/
UPROPERTY(Transient)
TObjectPtr<const UGIS_ItemCollectionDefinition> Definition{nullptr};
/**
* The unique ID of the collection.
* 集合的唯一ID。
*/
UPROPERTY(Transient)
FGuid CollectionId;
/**
* The inventory that owns this collection.
* 拥有此集合的库存。
*/
UPROPERTY()
TObjectPtr<UGIS_InventorySystemComponent> OwningInventory;
/**
* Sets the collection definition.
* 设置集合定义。
* @param NewDefinition The new collection definition. 新的集合定义。
*/
virtual void SetDefinition(const UGIS_ItemCollectionDefinition* NewDefinition);
/**
* Sets the unique tag of the collection.
* 设置集合的唯一标签。
* @param NewTag The new collection tag. 新的集合标签。
*/
void SetCollectionTag(FGameplayTag NewTag);
/**
* Sets the unique ID of the collection.
* 设置集合的唯一ID。
* @param NewId The new collection ID. 新的集合ID。
*/
void SetCollectionId(FGuid NewId);
/**
* Sets the owning inventory for the collection.
* 设置集合的所属库存。
* @param NewInventory The new owning inventory. 新的所属库存。
*/
void SetInventory(UGIS_InventorySystemComponent* NewInventory) { OwningInventory = NewInventory; };
};

View File

@@ -0,0 +1,133 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemCollection.h"
#include "GIS_ItemMultiStackCollection.generated.h"
class UGIS_ItemMultiStackCollection;
/**
* Definition for a multi-stack item collection.
* 多栈道具集合的定义。
*/
UCLASS(BlueprintType)
class UGIS_ItemMultiStackCollectionDefinition : public UGIS_ItemCollectionDefinition
{
GENERATED_BODY()
public:
/**
* Constructor for the multi-stack collection definition.
* 多栈集合定义的构造函数。
*/
UGIS_ItemMultiStackCollectionDefinition();
/**
* Gets the class for instantiating the collection.
* 获取用于实例化集合的类。
* @return The collection instance class. 集合实例类。
*/
virtual TSubclassOf<UGIS_ItemCollection> GetCollectionInstanceClass() const override;
/**
* Default stack size limit for items without a StackSizeLimitAttribute.
* 没有StackSizeLimitAttribute的道具的默认栈大小限制。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="StackSettings")
int32 DefaultStackSizeLimit = 99;
/**
* The integer attribute in the item definition to determine stack size (optional).
* 道具定义中用于确定栈大小的整型属性(可选)。
* @attention This is optional.
* @注意 这是可选的。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="StackSettings")
FGameplayTag StackSizeLimitAttribute;
};
/**
* An item collection that supports multiple stacks of the same item.
* 支持相同道具多栈的道具集合。
*/
UCLASS(DisplayName="GIS Item Collection (Multi Stack)")
class GENERICINVENTORYSYSTEM_API UGIS_ItemMultiStackCollection : public UGIS_ItemCollection
{
GENERATED_BODY()
public:
/**
* Constructor for the multi-stack item collection.
* 多栈道具集合的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_ItemMultiStackCollection(const FObjectInitializer& ObjectInitializer);
/**
* Retrieves information about an item instance in the collection.
* 获取集合中道具实例的信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if information was found, false otherwise. 如果找到信息则返回true否则返回false。
*/
virtual bool GetItemInfo(const UGIS_ItemInstance* Item, FGIS_ItemInfo& OutItemInfo) const override;
protected:
/**
* Calculates how many items can fit given a limited number of additional stacks.
* 计算在有限额外栈数下可以容纳的道具数量。
* @param ItemInfo The item information to check. 要检查的道具信息。
* @param AvailableAdditionalStacks The number of additional stacks allowed. 允许的额外栈数。
* @return The number of items that can fit. 可容纳的道具数量。
*/
virtual int32 GetItemAmountFittingInLimitedAdditionalStacks(const FGIS_ItemInfo& ItemInfo, int32 AvailableAdditionalStacks) const override;
/**
* Internal function to add an item to the collection.
* 内部函数,将道具添加到集合。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @return The item that was actually added. 实际添加的道具。
*/
virtual FGIS_ItemInfo AddInternal(const FGIS_ItemInfo& ItemInfo) override;
/**
* Gets the maximum stack size for an item.
* 获取道具的最大栈大小。
* @param Item The item instance to query. 要查询的道具实例。
* @return The maximum stack size for the item. 道具的最大栈大小。
*/
int32 GetMaxStackSize(UGIS_ItemInstance* Item) const;
private:
/**
* Internal function to remove an item from the collection.
* 内部函数,从集合中移除道具。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @return The item that was removed. 移除的道具。
*/
virtual FGIS_ItemInfo RemoveInternal(const FGIS_ItemInfo& ItemInfo) override;
/**
* Removes items from a specific stack.
* 从指定栈移除道具。
* @param Index The index of the stack to remove from. 要移除的栈索引。
* @param PrevStackIndexWithSameItem The previous stack index with the same item. 具有相同道具的前一个栈索引。
* @param MaxStackSize The maximum stack size. 最大栈大小。
* @param AmountToRemove The amount to remove (modified). 要移除的数量(可修改)。
* @param AlreadyRemoved The amount already removed (modified). 已移除的数量(可修改)。
* @return The stack index with the item. 包含道具的栈索引。
*/
int32 RemoveItemFromStack(int32 Index, int32 PrevStackIndexWithSameItem, int32 MaxStackSize, int32& AmountToRemove, int32& AlreadyRemoved);
/**
* Increases the amount in a specific stack.
* 增加指定栈中的数量。
* @param StackIdx The stack index to increase. 要增加的栈索引。
* @param MaxStackSize The maximum stack size. 最大栈大小。
* @param AmountToAdd The amount to add (modified). 要添加的数量(可修改)。
* @return The amount added to the stack. 添加到栈的数量。
*/
int32 IncreaseStackAmount(int32 StackIdx, int32 MaxStackSize, int32& AmountToAdd);
};

View File

@@ -0,0 +1,120 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Items/GIS_ItemInfo.h"
#include "GIS_ItemRestriction.generated.h"
/**
* Base class for item restrictions used to limit item collection operations.
* 用于限制道具集合操作的道具限制基类。
* @details Subclasses can extend this to implement custom restrictions.
* @细节 子类可以扩展此类以实现自定义限制。
*/
UCLASS(Blueprintable, BlueprintType, DefaultToInstanced, EditInlineNew, CollapseCategories, Abstract, Const)
class GENERICINVENTORYSYSTEM_API UGIS_ItemRestriction : public UObject
{
GENERATED_BODY()
public:
/**
* Checks if an item can be added to the collection.
* 检查道具是否可以添加到集合。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @param ReceivingCollection The collection to add the item to. 要添加到的集合。
* @return True if any valid item can be added, false otherwise. 如果可以添加任何有效道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category=ItemRestriction)
bool CanAddItem(UPARAM(ref) FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const;
/**
* Checks if an item can be removed from the collection.
* 检查道具是否可以从集合中移除。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @return True if any valid item can be removed, false otherwise. 如果可以移除任何有效道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category=ItemRestriction)
bool CanRemoveItem(UPARAM(ref) FGIS_ItemInfo& ItemInfo) const;
/**
* Gets the reason for rejecting an add operation.
* 获取拒绝添加操作的原因。
* @return The rejection reason text. 拒绝原因文本。
*/
UFUNCTION(BlueprintPure, BlueprintNativeEvent, Category=ItemRestriction)
FText GetRejectAddReason() const;
/**
* Implementation of GetRejectAddReason.
* GetRejectAddReason 的实现。
* @return The rejection reason text. 拒绝原因文本。
*/
virtual FText GetRejectAddReason_Implementation() const { return RejectAddReason; }
/**
* Gets the reason for rejecting a remove operation.
* 获取拒绝移除操作的原因。
* @return The rejection reason text. 拒绝原因文本。
*/
UFUNCTION(BlueprintPure, BlueprintNativeEvent, Category=ItemRestriction)
FText GetRejectRemoveReason() const;
/**
* Implementation of GetRejectRemoveReason.
* GetRejectRemoveReason 的实现。
* @return The rejection reason text. 拒绝原因文本。
*/
virtual FText GetRejectRemoveReason_Implementation() const { return RejectAddReason; }
protected:
/**
* Internal check for adding an item to the collection.
* 检查道具是否可以添加到集合的内部函数。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @param ReceivingCollection The collection to add the item to. 要添加到的集合。
* @return True if the item can be added, false otherwise. 如果道具可以添加则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category=ItemRestriction, meta=(DisplayName=CanAddItem))
bool CanAddItemInternal(UPARAM(ref) FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const;
/**
* Implementation of CanAddItemInternal.
* CanAddItemInternal 的实现。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @param ReceivingCollection The collection to add the item to. 要添加到的集合。
* @return True if the item can be added, false otherwise. 如果道具可以添加则返回true否则返回false。
*/
virtual bool CanAddItemInternal_Implementation(FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const;
/**
* Internal check for removing an item from the collection.
* 检查道具是否可以从集合移除的内部函数。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @return True if the item can be removed, false otherwise. 如果道具可以移除则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category=ItemRestriction, meta=(DisplayName=CanRemoveItem))
bool CanRemoveItemInternal(UPARAM(ref) FGIS_ItemInfo& ItemInfo) const;
/**
* Implementation of CanRemoveItemInternal.
* CanRemoveItemInternal 的实现。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @return True if the item can be removed, false otherwise. 如果道具可以移除则返回true否则返回false。
*/
virtual bool CanRemoveItemInternal_Implementation(FGIS_ItemInfo& ItemInfo) const;
/**
* The reason for rejecting an add operation.
* 拒绝添加操作的原因。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=ItemRestriction)
FText RejectAddReason;
/**
* The reason for rejecting a remove operation.
* 拒绝移除操作的原因。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=ItemRestriction)
FText RejectRemoveReason;
};

View File

@@ -0,0 +1,60 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemRestriction.h"
#include "GIS_ItemRestriction_StackSizeLimit.generated.h"
/**
* Restricts the maximum amount of an item within a specified collection.
* 限制指定集合中道具的最大数量。
* @attention Not suitable for MultiStackItemCollection.
* @注意 不适用于MultiStackItemCollection。
*/
UCLASS(NotBlueprintable, DisplayName=ItemRestriction_StackSizeLimit)
class GENERICINVENTORYSYSTEM_API UGIS_ItemRestriction_StackSizeLimit final : public UGIS_ItemRestriction
{
GENERATED_BODY()
public:
/**
* Constructor for the stack size limit restriction.
* 栈大小限制的构造函数。
*/
UGIS_ItemRestriction_StackSizeLimit();
protected:
/**
* Internal check for adding an item to the collection.
* 检查道具是否可以添加到集合的内部函数。
* @param ItemInfo The item information to check (modifiable). 要检查的道具信息(可修改)。
* @param ReceivingCollection The collection to add the item to. 要添加到的集合。
* @return True if the item can be added within the stack size limit, false otherwise. 如果道具可以在栈大小限制内添加则返回true否则返回false。
*/
virtual bool CanAddItemInternal_Implementation(FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const override;
/**
* Gets the stack size limit for a specific item.
* 获取指定道具的栈大小限制。
* @param Item The item instance to query. 要查询的道具实例。
* @return The stack size limit for the item. 道具的栈大小限制。
*/
int32 GetStackSizeLimit(const UGIS_ItemInstance* Item) const;
/**
* The default stack size limit for any items.
* 针对所有道具的默认栈大小限制。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemRestriction)
int32 DefaultStackSizeLimit;
/**
* The integer attribute in the item definition used to limit the stack size for non-unique items (unique items cannot stack).
* 道具定义中用于限制非唯一道具栈大小的整型属性(唯一道具无法堆叠)。
* @attention This is optional.
* @注意 这是可选的。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemRestriction)
FGameplayTag StackSizeLimitAttributeTag;
};

View File

@@ -0,0 +1,34 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemRestriction.h"
#include "GIS_ItemRestriction_StacksNumLimit.generated.h"
/**
* Restricts the total number of stacks for an item collection.
* 限制道具集合的总堆叠数量。
*/
UCLASS(NotBlueprintable, DisplayName=ItemRestriction_StacksNumLimit)
class GENERICINVENTORYSYSTEM_API UGIS_ItemRestriction_StacksNumLimit final : public UGIS_ItemRestriction
{
GENERATED_BODY()
protected:
/**
* Checks if an item can be added to the collection based on stack limits.
* 检查是否可以根据堆叠限制将道具添加到集合。
* @param ItemInfo Information about the item to add. 要添加的道具信息。
* @param ReceivingCollection The collection receiving the item. 接收道具的集合。
* @return True if the item can be added, false otherwise. 如果可以添加道具则返回true否则返回false。
*/
virtual bool CanAddItemInternal_Implementation(FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const override;
/**
* Maximum number of stacks allowed in the collection.
* 集合中允许的最大堆叠数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemRestriction)
int32 MaxStacksNum = 30;
};

View File

@@ -0,0 +1,34 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemRestriction.h"
#include "GIS_ItemRestriction_TagRequirements.generated.h"
/**
* Restricts items to those that satisfy a specific tag query for addition to a collection.
* 限制只有满足特定标签查询的道具可以添加到集合。
*/
UCLASS(NotBlueprintable, DisplayName=ItemRestriction_TagRequirements)
class GENERICINVENTORYSYSTEM_API UGIS_ItemRestriction_TagRequirements final : public UGIS_ItemRestriction
{
GENERATED_BODY()
protected:
/**
* Tag query that items must satisfy to be added to the collection.
* 道具必须满足的标签查询才能添加到集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemRestriction)
FGameplayTagQuery TagQuery;
/**
* Checks if an item satisfies the tag query for addition to the collection.
* 检查道具是否满足标签查询以添加到集合。
* @param ItemInfo Information about the item to add. 要添加的道具信息。
* @param ReceivingCollection The collection receiving the item. 接收道具的集合。
* @return True if the item can be added, false otherwise. 如果可以添加道具则返回true否则返回false。
*/
virtual bool CanAddItemInternal_Implementation(FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const override;
};

View File

@@ -0,0 +1,29 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemRestriction.h"
#include "GIS_ItemRestriction_UniqueOnly.generated.h"
/**
* Restricts a collection to only accept unique items.
* 限制集合仅接受唯一道具。
* @details Prevents duplicate items from being added to the collection.
* @细节 防止重复道具被添加到集合。
*/
UCLASS(NotBlueprintable, DisplayName=ItemRestriction_UniqueOnly)
class GENERICINVENTORYSYSTEM_API UGIS_ItemRestriction_UniqueOnly final : public UGIS_ItemRestriction
{
GENERATED_BODY()
protected:
/**
* Checks if an item is unique before adding it to the collection.
* 在将道具添加到集合之前检查其是否唯一。
* @param ItemInfo Information about the item to add. 要添加的道具信息。
* @param ReceivingCollection The collection receiving the item. 接收道具的集合。
* @return True if the item is unique and can be added, false otherwise. 如果道具唯一且可添加则返回true否则返回false。
*/
virtual bool CanAddItemInternal_Implementation(FGIS_ItemInfo& ItemInfo, UGIS_ItemCollection* ReceivingCollection) const override;
};

View File

@@ -0,0 +1,418 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemCollection.h"
#include "GIS_ItemSlotCollection.generated.h"
/**
* A slot-based item collection definition, suitable for equipment or skill bars.
* 基于槽的道具集合定义,适合用于装备或技能栏。
* @details Stores items in a slot-to-item style, ideal for equipment, skill bars, etc.
* @细节 以槽对应道具的方式存储,适合装备、技能栏等场景。
*/
UCLASS(BlueprintType)
class GENERICINVENTORYSYSTEM_API UGIS_ItemSlotCollectionDefinition : public UGIS_ItemCollectionDefinition
{
GENERATED_BODY()
public:
/**
* Gets the class for instantiating the collection.
* 获取用于实例化集合的类。
* @return The collection instance class. 集合实例类。
*/
virtual TSubclassOf<UGIS_ItemCollection> GetCollectionInstanceClass() const override;
/**
* Checks if the specified slot index is valid within SlotDefinitions.
* 检查指定槽索引在SlotDefinitions中是否有效。
* @param SlotIndex The slot index to check. 要检查的槽索引。
* @return True if the slot index is valid, false otherwise. 如果槽索引有效则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|CollectionDefinition")
virtual bool IsValidSlotIndex(int32 SlotIndex) const;
/**
* Gets the index of a slot based on its tag within SlotDefinitions.
* 根据槽标签获取SlotDefinitions中的槽索引。
* @param SlotName The slot tag to query. 要查询的槽标签。
* @return The index of the slot, or INDEX_NONE if not found. 槽的索引如果未找到则返回INDEX_NONE。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|CollectionDefinition")
virtual int32 GetIndexOfSlot(UPARAM(meta=(Categories="GIS.Slots"))
const FGameplayTag& SlotName) const;
/**
* Gets the slot tag for a given slot index within SlotDefinitions.
* 根据槽索引获取SlotDefinitions中的槽标签。
* @param SlotIndex The slot index to query. 要查询的槽索引。
* @return The slot tag, or invalid tag if not found. 槽标签,如果未找到则返回无效标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|CollectionDefinition")
virtual FGameplayTag GetSlotOfIndex(int32 SlotIndex) const;
/**
* Gets all slot definitions within this collection definition.
* 获取此集合定义中的所有槽定义。
* @return Array of slot definitions. 槽定义数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|CollectionDefinition")
const TArray<FGIS_ItemSlotDefinition>& GetSlotDefinitions() const;
/**
* Gets the slot definition for a given slot index.
* 获取指定槽索引的槽定义。
* @param SlotIndex The slot index to query. 要查询的槽索引。
* @param OutDefinition The slot definition (output). 槽定义(输出)。
* @return True if the slot definition was found, false otherwise. 如果找到槽定义则返回true否则返回false。
*/
bool GetSlotDefinition(int32 SlotIndex, FGIS_ItemSlotDefinition& OutDefinition) const;
/**
* Gets the slot definition for a given slot tag.
* 获取指定槽标签的槽定义。
* @param SlotName The slot tag to query. 要查询的槽标签。
* @param OutDefinition The slot definition (output). 槽定义(输出)。
* @return True if the slot definition was found, false otherwise. 如果找到槽定义则返回true否则返回false。
*/
bool GetSlotDefinition(const FGameplayTag& SlotName, FGIS_ItemSlotDefinition& OutDefinition) const;
/**
* Gets the index of a slot within a specified group.
* 获取指定槽在指定槽组内的索引。
* @param GroupTag The group tag to query. 要查询的组标签。
* @param SlotTag The slot tag to query. 要查询的槽标签。
* @return The index of the slot within the group, or -1 if not found. 槽在组内的索引,如果未找到则返回-1。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|CollectionDefinition")
int32 GetSlotIndexWithinGroup(UPARAM(meta=(Categories="GIS.Slots"))
FGameplayTag GroupTag, FGameplayTag SlotTag) const;
/**
* Whether newly added items replace existing items if they are not stackable.
* 新添加的道具如果无法堆叠,是否替换现有道具。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Common", meta=(DisplayAfter="OverflowOptions"))
bool bNewItemPriority = true;
/**
* Whether replaced items are returned to the source collection of the new item.
* 被替换的道具是否返回到新道具的源集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Common", meta=(EditCondition="bNewItemPriority"))
bool bTryGivePrevItemToNewItemCollection = true;
/**
* Defines all available item slots in the collection.
* 定义集合中的所有可用道具槽。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="SlotSettings", meta=(TitleProperty="SlotName:{Name}"))
TArray<FGIS_ItemSlotDefinition> SlotDefinitions;
/**
* List of parent slot tags for grouping slots; only one slot per group can be active at a time.
* 用于分组的父级槽标签列表,每个组同时只能激活一个槽。
* @attention Used by the equipment system.
* @注意 由装备系统使用。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="SlotSettings", meta=(AllowPrivateAccess=True, Categories="GIS.Slots"))
TArray<FGameplayTag> SlotGroups;
/**
* Cached mapping of slot indices to slot tags for faster access, updated on save in the editor.
* 槽索引到槽标签的缓存映射,用于快速访问,在编辑器保存时更新。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Advanced", meta=(ForceInlineRow))
TMap<int32, FGameplayTag> IndexToTagMap;
/**
* Cached mapping of slot tags to slot indices for faster access, updated on save in the editor.
* 槽标签到槽索引的缓存映射,用于快速访问,在编辑器保存时更新。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Advanced", meta=(ForceInlineRow))
TMap<FGameplayTag, int32> TagToIndexMap;
/**
* Cached grouping of slot definitions by slot groups, updated on save in the editor.
* 按槽组分组的槽定义缓存,在编辑器保存时更新。
*/
UPROPERTY(VisibleAnywhere, Category="Advanced", meta=(ForceInlineRow))
TMap<FGameplayTag, FGIS_ItemSlotGroup> SlotGroupMap;
#if WITH_EDITOR
/**
* Called before saving the object in the editor.
* 在编辑器中保存对象前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};
/**
* A slot-based item collection that organizes items in slots, each holding an item stack.
* 基于槽的道具集合,按槽组织道具,每个槽可持有道具栈。
*/
UCLASS(BlueprintType, EditInlineNew, CollapseCategories, DisplayName="GIS Item Collection (Slotted)")
class GENERICINVENTORYSYSTEM_API UGIS_ItemSlotCollection : public UGIS_ItemCollection
{
GENERATED_BODY()
friend UGIS_ItemSlotCollectionDefinition;
public:
/**
* Constructor for the slot-based item collection.
* 基于槽的道具集合的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_ItemSlotCollection(const FObjectInitializer& ObjectInitializer);
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Gets the definition of this slot-based collection.
* 获取此基于槽的集合的定义。
* @return The collection definition, or nullptr if not set. 集合定义如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
const UGIS_ItemSlotCollectionDefinition* GetMyDefinition() const;
/**
* Adds an item to the collection, typically for unique items.
* 将道具添加到集合,通常用于唯一道具。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @return The item that was not added, the previously equipped item if replaced, or empty if added successfully. 未添加的道具、替换的先前道具或成功添加时为空。
*/
virtual FGIS_ItemInfo AddItem(const FGIS_ItemInfo& ItemInfo) override;
/**
* Adds an item to the specified slot (authority only).
* 将道具添加到指定槽(仅限权限)。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @param SlotIndex The index of the slot to add the item to. 要添加到的槽索引。
* @return The item that was actually added. 实际添加的道具。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
virtual FGIS_ItemInfo AddItem(const FGIS_ItemInfo& ItemInfo, int32 SlotIndex);
/**
* Server function to add an item to the specified slot.
* 服务器函数,将道具添加到指定槽。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @param SlotIndex The index of the slot to add the item to. 要添加到的槽索引。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
void ServerAddItem(const FGIS_ItemInfo& ItemInfo, int32 SlotIndex);
/**
* Adds an item to the slot with the specified tag (authority only).
* 将道具添加到指定标签的槽(仅限权限)。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @param SlotName The tag of the slot to add the item to. 要添加到的槽标签。
* @return The item that was actually added. 实际添加的道具。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
FGIS_ItemInfo AddItemBySlotName(const FGIS_ItemInfo& ItemInfo, FGameplayTag SlotName);
/**
* Server function to add an item to the slot with the specified tag.
* 服务器函数,将道具添加到指定标签的槽。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @param SlotName The tag of the slot to add the item to. 要添加到的槽标签。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemCollection")
void ServerAddItemBySlotName(const FGIS_ItemInfo& ItemInfo, FGameplayTag SlotName);
/**
* Removes an item from the collection.
* 从集合中移除道具。
* @param ItemInfo The item information to remove. 要移除的道具信息。
* @return The item that was removed, or empty if nothing was removed. 移除的道具,如果未移除则为空。
*/
virtual FGIS_ItemInfo RemoveItem(const FGIS_ItemInfo& ItemInfo) override;
/**
* Removes an item from the specified slot.
* 从指定槽移除道具。
* @param SlotIndex The index of the slot to remove the item from. 要移除道具的槽索引。
* @param Amount The amount to remove (-1 to remove all). 要移除的数量(-1表示全部移除
* @return The item information that was removed. 移除的道具信息。
*/
virtual FGIS_ItemInfo RemoveItem(int32 SlotIndex, int32 Amount = -1);
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
bool IsItemFitWithSlot(const UGIS_ItemInstance* Item, int32 SlotIndex) const;
/**
* Gets a suitable slot index for an incoming item.
* 获取适合传入道具的槽索引。
* @param Item The item instance to check. 要检查的道具实例。
* @return A valid slot index, or INDEX_NONE if none is suitable. 有效槽索引如果没有合适的槽则返回INDEX_NONE。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
int32 GetTargetSlotIndex(const UGIS_ItemInstance* Item) const;
/**
* Gets the item information at a specific slot by tag.
* 通过槽标签获取指定槽的道具信息。
* @param SlotTag The slot tag to query. 要查询的槽标签。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if item information was found, false otherwise. 如果找到道具信息则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
virtual bool GetItemInfoAtSlot(FGameplayTag SlotTag, FGIS_ItemInfo& OutItemInfo) const;
/**
* Finds the item information at a specific slot by tag.
* 通过槽标签查找指定槽的道具信息。
* @param SlotTag The slot tag to query. 要查询的槽标签。
* @param OutItemInfo The item information (output). 道具信息(输出)。
* @return True if item information was found, false otherwise. 如果找到道具信息则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemCollection", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool FindItemInfoAtSlot(FGameplayTag SlotTag, FGIS_ItemInfo& OutItemInfo) const;
/**
* Gets the item stack at a specific slot by tag (commented out).
* 通过槽标签获取指定槽的道具栈(已注释)。
*/
virtual bool GetItemStackAtSlot(FGameplayTag SlotTag, FGIS_ItemStack& OutItemStack) const;
/**
* Finds the item stack at a specific slot by tag (commented out).
* 通过槽标签查找指定槽的道具栈(已注释)。
*/
virtual bool FindItemStackAtSlot(FGameplayTag SlotTag, FGIS_ItemStack& OutItemStack) const;
/**
* Gets the item information at a specific slot by index.
* 通过槽索引获取指定槽的道具信息。
* @param SlotIndex The slot index to query. 要查询的槽索引。
* @return The item information at the slot. 槽中的道具信息。
*/
FGIS_ItemInfo GetItemInfoAtSlot(int32 SlotIndex) const;
/**
* Gets the item stack at a specific slot by index.
* 通过槽索引获取指定槽的道具栈。
* @param SlotIndex The slot index to query. 要查询的槽索引。
* @return The item stack at the slot. 槽中的道具栈。
*/
FGIS_ItemStack GetItemStackAtSlot(int32 SlotIndex) const;
/**
* Gets the slot tag where an item is equipped.
* 获取道具装备的槽标签。
* @param Item The item instance to query. 要查询的道具实例。
* @return The slot tag, or invalid if not equipped. 槽标签,如果未装备则返回无效标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
FGameplayTag GetItemSlotName(const UGIS_ItemInstance* Item) const;
/**
* Gets the slot index where an item is equipped.
* 获取道具装备的槽索引。
* @param Item The item instance to query. 要查询的道具实例。
* @return The slot index, or -1 if not equipped. 槽索引,如果未装备则返回-1。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
int32 GetItemSlotIndex(const UGIS_ItemInstance* Item) const;
/**
* Internal function to add an item to a specific slot.
* 内部函数,将道具添加到指定槽。
* @param ItemInfo The item information to add. 要添加的道具信息。
* @param SlotIndex The index of the slot to add the item to. 要添加到的槽索引。
* @return The item that was actually added. 实际添加的道具。
*/
virtual FGIS_ItemInfo AddItemInternal(const FGIS_ItemInfo& ItemInfo, int32 SlotIndex);
/**
* Converts a stack ID to a slot index.
* 将栈ID转换为槽索引。
* @param InStackId The stack ID to query. 要查询的栈ID。
* @return The corresponding slot index, or -1 if not found. 对应的槽索引,如果未找到则返回-1。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
int32 StackIdToSlotIndex(FGuid InStackId) const;
/**
* Converts a slot index to a stack index.
* 将槽索引转换为栈索引。
* @param InSlotIndex The slot index to query. 要查询的槽索引。
* @return The corresponding stack index, or -1 if not found. 对应的栈索引,如果未找到则返回-1。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
int32 SlotIndexToStackIndex(int32 InSlotIndex) const;
/**
* Converts a slot index to a stack ID.
* 将槽索引转换为栈ID。
* @param InSlotIndex The slot index to query. 要查询的槽索引。
* @return The corresponding stack ID, or invalid if not found. 对应的栈ID如果未找到则返回无效ID。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemCollection")
FGuid SlotIndexToStackId(int32 InSlotIndex) const;
/**
* Mapping of slot indices to stack IDs for equipped items.
* 槽索引到装备道具栈ID的映射。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="ItemCollection", ReplicatedUsing=OnRep_ItemsBySlot)
TArray<FGuid> ItemBySlots;
UPROPERTY(VisibleInstanceOnly, Category="ItemCollection", Transient)
TMap<int32, FGuid> SlotToStackMap;
/**
* The definition of this slot-based collection.
* 此基于槽的集合的定义。
*/
UPROPERTY()
TObjectPtr<const UGIS_ItemSlotCollectionDefinition> MyDefinition;
/**
* Called when the ItemBySlots array is replicated.
* ItemBySlots数组复制时调用。
*/
UFUNCTION()
void OnRep_ItemsBySlot();
protected:
/**
* Sets the collection definition.
* 设置集合定义。
* @param NewDefinition The new collection definition. 新的集合定义。
*/
virtual void SetDefinition(const UGIS_ItemCollectionDefinition* NewDefinition) override;
/**
* Called before an item stack is added to the collection.
* 在集合添加道具栈之前调用。
* @param Stack The item stack to add. 要添加的道具栈。
* @param Idx The index where the stack will be added. 栈将添加的索引。
*/
virtual void OnPreItemStackAdded(const FGIS_ItemStack& Stack, int32 Idx) override;
virtual void OnItemStackAdded(const FGIS_ItemStack& Stack) override;
virtual void OnItemStackRemoved(const FGIS_ItemStack& Stack) override;
/**
* Sets the amount for an item in a specific slot.
* 在指定槽中设置道具数量。
* @param ItemInfo The item information to set. 要设置的道具信息。
* @param SlotIndex The slot index to set the item in. 要设置的槽索引。
* @param RemovePreviousItem Whether to replace the previous item if the slot is at capacity. 如果槽已满,是否替换之前的道具。
* @param ItemInfoAdded The item information that was set (output). 已设置的道具信息(输出)。
* @return True if the item was set successfully, false otherwise. 如果道具设置成功则返回true否则返回false。
*/
virtual bool SetItemAmount(const FGIS_ItemInfo& ItemInfo, int32 SlotIndex, bool RemovePreviousItem, FGIS_ItemInfo& ItemInfoAdded);
};

View File

@@ -0,0 +1,103 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_MixinTargetInterface.h"
#include "UObject/Object.h"
#include "GIS_ItemFragment.generated.h"
class UGIS_ItemInstance;
/**
* Base class for item fragments, which are data objects attached to item definitions.
* 道具片段,即道具定义上附加的数据对象的基类。
* @details Allows users to create custom item fragment classes for extending item functionality.
* @细节 允许用户创建自定义道具片段类以扩展道具功能。
*/
UCLASS(BlueprintType, Blueprintable, DefaultToInstanced, EditInlineNew, Abstract, CollapseCategories, HideDropdown, Const)
class GENERICINVENTORYSYSTEM_API UGIS_ItemFragment : public UObject, public IGIS_MixinTargetInterface
{
GENERATED_BODY()
public:
/**
* Called when an item instance is created, allowing fragment-specific initialization.
* 在道具实例创建时调用,允许特定片段的初始化。
* @param ItemInstance The item instance being created. 被创建的道具实例。
*/
virtual void OnInstanceCreated(UGIS_ItemInstance* ItemInstance) const
{
Bp_OnInstancedCrated(ItemInstance);
}
/**
* Determines if the fragment's runtime data can be serialized.
* 确定片段的运行时数据是否可以序列化。
* @return True if the data is serializable, false otherwise. 如果数据可序列化则返回true否则返回false。
*/
virtual bool IsMixinDataSerializable() const override;
/**
* Retrieves the compatible data structure for serialization or replication.
* 获取用于序列化或复制的兼容数据结构。
* @return The script struct compatible with this fragment. 与此片段兼容的脚本结构。
*/
virtual TObjectPtr<const UScriptStruct> GetCompatibleMixinDataType() const override;
/**
* Generate default runtime data for compatible data type.
* 生成兼容的混合数据类型的默认值。
* @param DefaultState The default value of compatible data. 兼容的数据结构默认值。
* @return If has default value. 是否具备默认值?
*/
virtual bool MakeDefaultMixinData(FInstancedStruct& DefaultState) const override;
protected:
/**
* Blueprint event for handling instance creation logic.
* 处理实例创建逻辑的蓝图事件。
* @param ItemInstance The item instance being created. 被创建的道具实例。
*/
UFUNCTION(BlueprintImplementableEvent, Category="ItemFragment", meta=(DisplayName="On Instance Created"))
void Bp_OnInstancedCrated(UGIS_ItemInstance* ItemInstance) const;
/**
* Returns the struct type for runtime data serialization or replication.
* 返回运行时数据序列化或复制的结构类型。
* @return The compatible runtime data struct type. 兼容的运行时数据结构类型。
*/
UFUNCTION(BlueprintNativeEvent, BlueprintPure, Category="ItemFragment")
const UScriptStruct* GetCompatibleStateType() const;
/**
* Provide default values for fragment's runtime data type.
* 针对运行时数据类型提供默认值。
* @param DefaultState The default data. 默认数据
* @return If has default value. 是否具备默认值。
*/
UFUNCTION(BlueprintNativeEvent, BlueprintPure, Category="ItemFragment")
bool MakeDefaultState(FInstancedStruct& DefaultState) const;
/**
* Determines if the fragment's runtime data supports serialization to disk.
* 确定片段的运行时数据是否支持序列化到磁盘。
* @details Runtime data is replicated over the network, but serialization to disk is optional.
* @细节 运行时数据通过网络复制,但序列化到磁盘是可选的。
* @return True if the data supports serialization, false otherwise. 如果数据支持序列化则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, BlueprintPure, Category="ItemFragment")
bool IsStateSerializable() const;
public:
#if WITH_EDITOR
/**
* Override this to add your custom data validation logic on save.
* @note Only called on editor, not runtime.
* @param OutMessage The output message.
* @return return true if no any data validation errors.
*/
UFUNCTION(BlueprintNativeEvent, BlueprintPure, Category="ItemFragment")
bool FragmentDataValidation(FText& OutMessage) const;
#endif
};

View File

@@ -0,0 +1,89 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemFragment.h"
#include "Attributes/GIS_GameplayTagFloat.h"
#include "Attributes/GIS_GameplayTagInteger.h"
#include "GIS_ItemFragment_DynamicAttributes.generated.h"
/**
* Item fragment for adding dynamic attributes to an item instance.
* 为道具实例添加动态属性的道具片段。
* @details Initial attributes are applied to the item instance upon creation.
* @细节 初始属性在道具实例创建时应用。
* @attention Use static attributes in the item definition for attributes that don't change at runtime.
* @注意 对于运行时不更改的属性,请使用道具定义中的静态属性。
*/
UCLASS(DisplayName="Dynamic Attribute Settings", Category="BuiltIn")
class GENERICINVENTORYSYSTEM_API UGIS_ItemFragment_DynamicAttributes : public UGIS_ItemFragment
{
GENERATED_BODY()
protected:
/**
* Array of initial float attributes applied to
System: the item instance.
* 应用于道具实例的初始浮点属性数组。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Attribute, meta=(TitleProperty="{Tag} -> {Value}"))
TArray<FGIS_GameplayTagFloat> InitialFloatAttributes;
/**
* Array of initial integer attributes applied to the item instance.
* 应用于道具实例的初始整型属性数组。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Attribute, meta=(TitleProperty="{Tag} -> {Value}"))
TArray<FGIS_GameplayTagInteger> InitialIntegerAttributes;
/**
* Cached map for faster access to integer attributes.
* 用于快速访问整型属性的缓存映射。
*/
UPROPERTY()
TMap<FGameplayTag, int32> IntegerAttributeMap;
/**
* Cached map for faster access to float attributes.
* 用于快速访问浮点属性的缓存映射。
*/
UPROPERTY()
TMap<FGameplayTag, float> FloatAttributeMap;
public:
/**
* Initializes the item instance with dynamic attributes upon creation.
* 在道具实例创建时使用动态属性进行初始化。
* @param Instance The item instance to initialize. 要初始化的道具实例。
*/
virtual void OnInstanceCreated(UGIS_ItemInstance* Instance) const override;
/**
* Retrieves the default value of a float attribute by tag.
* 通过标签获取浮点属性的默认值。
* @param AttributeTag The tag identifying the attribute. 标识属性的标签。
* @return The default value of the float attribute. 浮点属性的默认值。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemFragment|DynamicAttributes")
float GetFloatAttributeDefault(FGameplayTag AttributeTag) const;
/**
* Retrieves the default value of an integer attribute by tag.
* 通过标签获取整型属性的默认值。
* @param AttributeTag The tag identifying the attribute. 标识属性的标签。
* @return The default value of the integer attribute. 整型属性的默认值。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemFragment|DynamicAttributes")
int32 GetIntegerAttributeDefault(FGameplayTag AttributeTag) const;
#if WITH_EDITOR
/**
* Called before saving the object to perform editor-specific operations.
* 在保存对象之前调用以执行编辑器特定的操作。
* @param SaveContext The context for the save operation. 保存操作的上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,66 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_EquipmentStructLibrary.h"
#include "GIS_ItemFragment.h"
#include "GIS_ItemFragment_Equippable.generated.h"
class UGIS_EquipmentInstance;
/**
* Item fragment for defining equippable item behavior.
* 定义可装备道具行为的道具片段。
* @details Configures equipment instance and spawning behavior for equipped items.
* @细节 配置装备实例和已装备道具的生成行为。
*/
UCLASS(DisplayName="Equippable Settings", Category="BuiltIn")
class GENERICINVENTORYSYSTEM_API UGIS_ItemFragment_Equippable : public UGIS_ItemFragment
{
GENERATED_BODY()
public:
/**
* Constructor for the equippable item fragment.
* 可装备道具片段的构造函数。
*/
UGIS_ItemFragment_Equippable();
/**
* Specifies the equipment instance class handling equipment logic.
* 指定处理装备逻辑的装备实例类。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Equipment, NoClear, meta = (MustImplement = "/Script/GenericInventorySystem.GIS_EquipmentInterface", AllowAbstract = "false"))
TSoftClassPtr<UObject> InstanceType;
/**
* Indicates if the equipment instance is actor-based, set automatically based on InstanceType.
* 指示装备实例是否基于Actor根据InstanceType自动设置。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Equipment, meta=(EditCondition="false"))
bool bActorBased{false};
/**
* Determines if the equipment instance is automatically activated upon equipping.
* 确定装备实例在装备时是否自动激活。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Equipment)
bool bAutoActivate{false};
/**
* List of actors to spawn on the pawn when the item is equipped, such as weapons or armor.
* 在道具装备时在Pawn上生成的Actor列表如武器或盔甲。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Equipment, meta=(EditCondition="!bActorBased", EditConditionHides))
TArray<FGIS_EquipmentActorToSpawn> ActorsToSpawn;
#if WITH_EDITOR
/**
* Called before saving the object to perform editor-specific operations.
* 在保存对象之前调用以执行编辑器特定的操作。
* @param SaveContext The context for the save operation. 保存操作的上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,42 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CurrencyEntry.h"
#include "GIS_ItemFragment.h"
#include "GIS_ItemFragment_Shoppable.generated.h"
/**
* Item fragment for defining shop-related properties of an item.
* 定义道具商店相关属性的道具片段。
* @details Specifies buy and sell prices for the item in various currencies.
* @细节 指定道具在不同货币中的购买和出售价格。
*/
UCLASS(DisplayName="Shoppable Settings", Category="BuiltIn")
class GENERICINVENTORYSYSTEM_API UGIS_ItemFragment_Shoppable : public UGIS_ItemFragment
{
GENERATED_BODY()
public:
/**
* Initializes shop-related data for the item instance upon creation.
* 在道具实例创建时初始化商店相关数据。
* @param Instance The item instance to initialize. 要初始化的道具实例。
*/
virtual void OnInstanceCreated(UGIS_ItemInstance* Instance) const override;
/**
* List of currencies and amounts required to purchase the item.
* 购买道具所需的货币和金额列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=Shoppable, meta=(TitleProperty="Definition"))
TArray<FGIS_CurrencyEntry> BuyCurrencyAmounts;
/**
* List of currencies and amounts received when selling the item.
* 出售道具时获得的货币和金额列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category=Shoppable, meta=(TitleProperty="Definition"))
TArray<FGIS_CurrencyEntry> SellCurrencyAmounts;
};

View File

@@ -0,0 +1,188 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/Texture2D.h"
#include "Styling/SlateBrush.h"
#include "GameplayTagContainer.h"
#include "UObject/Object.h"
#include "GIS_CoreStructLibray.generated.h"
class UGIS_ItemInstance;
class UGIS_ItemDefinition;
/**
* Structure representing an item definition with an associated amount.
* 表示道具定义及其关联数量的结构体。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_ItemDefinitionAmount
{
GENERATED_BODY()
FGIS_ItemDefinitionAmount();
FGIS_ItemDefinitionAmount(TSoftObjectPtr<UGIS_ItemDefinition> InDefinition, int32 InAmount);
/**
* The item definition.
* 道具定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TSoftObjectPtr<UGIS_ItemDefinition> Definition;
/**
* The amount of the item.
* 道具数量。
* @attention Minimum value is 1.
* @注意 最小值为1。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS", meta=(ClampMin="1"))
int32 Amount = 1;
#if WITH_EDITORONLY_DATA
/**
* Friendly name for displaying in the editor.
* 在编辑器中显示的友好名称。
*/
UPROPERTY(VisibleAnywhere, Category=AlwaysHidden, Meta=(EditCondition=False, EditConditionHides))
FString EditorFriendlyName;
#endif
};
/**
* Structure representing a default loadout with a tag and associated items.
* 表示默认装备配置的结构体,包含标签和关联的道具。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_DefaultLoadout
{
GENERATED_BODY()
/**
* The gameplay tag for the loadout.
* 装备配置的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGameplayTag Tag;
/**
* List of default items for the loadout.
* 装备配置的默认道具列表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGIS_ItemDefinitionAmount> DefaultItems;
};
/**
* Structure defining options for handling item overflow in an inventory.
* 定义库存中道具溢出处理选项的结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemOverflowOptions
{
GENERATED_BODY()
/**
* Whether to return overflow items to their source (if specified) when the inventory is full.
* 当库存满时,是否将溢出的道具返回其来源(如果指定)。
*/
UPROPERTY(EditAnywhere, Category=Overflow)
bool bReturnOverflow = true;
/**
* Whether to send a rejection message when items cannot be added due to overflow.
* 当道具因溢出无法添加时,是否发送拒绝消息。
*/
UPROPERTY(EditAnywhere, Category=Overflow)
bool bSendRejectedMessage = true;
};
/**
* Structure representing an item slot definition, primarily used in item slot collections.
* 表示道具槽定义的结构体,主要用于道具槽集合。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_ItemSlotDefinition
{
GENERATED_BODY()
/**
* The gameplay tag for the item slot.
* 道具槽的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot, meta=(Categories="GIS.Slots"))
FGameplayTag Tag;
/**
* The icon for the item slot.
* 道具槽的图标。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot)
TSoftObjectPtr<UTexture2D> Icon;
/**
* The Slate brush for the item slot icon.
* 道具槽图标的Slate画刷。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot)
FSlateBrush IconBrush;
/**
* The display name of the item slot.
* 道具槽的显示名称。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot)
FText Name;
/**
* The description of the item slot.
* 道具槽的描述。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot)
FText Desc;
/**
* Gameplay tag query that item tags must match to be equipped in this slot.
* 道具标签必须匹配的游戏标签查询,才能装备到此槽。
* @attention If empty, no items can be equipped in this slot.
* @注意 如果为空,则无法将任何道具装备到此槽。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=ItemSlot)
FGameplayTagQuery TagQuery;
/**
* Checks if an item can be equipped in this slot based on its tags.
* 检查道具是否可以根据其标签装备到此槽。
* @param Item The item instance to check. 要检查的道具实例。
* @return True if the item matches the slot's tag query, false otherwise. 如果道具匹配槽的标签查询则返回true否则返回false。
*/
bool MatchItem(const UGIS_ItemInstance* Item) const;
};
/**
* Structure representing a group of item slots with index-to-slot and slot-to-index mappings.
* 表示一组道具槽的结构体,包含索引到槽和槽到索引的映射。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemSlotGroup
{
GENERATED_BODY()
/**
* Mapping of indices to slot tags in the group.
* 组内索引到槽标签的映射。
*/
UPROPERTY(VisibleAnywhere, Category=ItemSlot, meta=(ForceInlineRow))
TMap<int32, FGameplayTag> IndexToSlotMap;
/**
* Mapping of slot tags to indices in the group.
* 组内槽标签到索引的映射。
*/
UPROPERTY(VisibleAnywhere, Category=ItemSlot, meta=(ForceInlineRow))
TMap<FGameplayTag, int32> SlotToIndexMap;
};

View File

@@ -0,0 +1,383 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "Templates/SubclassOf.h"
#include "UObject/Object.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "GIS_MixinContainer.generated.h"
/**
* Record of mixin for serialization.
* 用于序列化的混合数据记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_MixinRecord
{
GENERATED_BODY()
/**
* The asset path of target object.
* 目标对象的资产路径。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FString TargetPath;
/**
* The runtime state of this fragment.
* 片段的运行时数据。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FInstancedStruct Data;
/**
* Equality operator to compare mixin records.
* 比较混合数据记录的相等性运算符。
* @param Other The another mixin record to compare with. 要比较的其他Mixin记录。
* @return True if the record's target path are equal, false otherwise. 如果目标路径相等则返回true否则返回false。
*/
bool operator==(const FGIS_MixinRecord& Other) const;
/**
* Checks if the mixin record is valid.
* 检查Mixin记录是否有效。
* @return True if the target path and data are valid, false otherwise. 如果片段类型和状态有效则返回true否则返回false。
*/
bool IsValid() const;
};
/**
* Stores the mixed-in data of a const target object (attaches additional runtime data to a const object).
* 针对常量目标对象存储其混合数据(将额外的运行时数据附加到常量对象)。
* @details A wrapper of InstancedStruct, allowing storage of any struct data. For save games, ensure struct fields are serializable (marked with SaveGame).
* @细节 这是实例化结构的包装允许存储任意结构体数据。对于存档应确保结构体字段标记为SaveGame并受虚幻序列化系统支持。
*/
USTRUCT(BlueprintType)
struct FGIS_Mixin : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* The target object to which the data is attached.
* 数据附加的目标对象。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Mixin")
TObjectPtr<const UObject> Target;
/**
* The mixed-in data attached to the target object.
* 附加到目标对象的混合数据。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Mixin")
FInstancedStruct Data;
/**
* Timestamp of the last data change.
* 数据最后更改的时间戳。
*/
UPROPERTY()
float Timestamp;
/**
* Timestamp of the last replication (not replicated).
* 最后一次复制的时间戳(不复制)。
*/
UPROPERTY(NotReplicated)
float LastReplicatedTimestamp;
/**
* Default constructor for mixin.
* 混合数据的默认构造函数。
*/
FGIS_Mixin()
: FGIS_Mixin(nullptr, FInstancedStruct())
{
}
/**
* Constructor for mixin with target class and data.
* 使用目标类和数据构造混合数据。
* @param InClass The target class for the mixin. 混合数据的目标类。
* @param InData The instanced struct data to mix in. 要混合的实例化结构数据。
*/
FGIS_Mixin(const TSubclassOf<UObject>& InClass, const FInstancedStruct& InData)
: Target(InClass), Data(InData)
{
Timestamp = 0.f;
LastReplicatedTimestamp = 0.f;
}
/**
* Destructor for mixin.
* 混合数据的析构函数。
*/
~FGIS_Mixin()
{
Reset();
}
/**
* Checks if the mixin is valid.
* 检查混合数据是否有效。
* @return True if the mixin is valid (target and data are set), false otherwise. 如果混合数据有效目标和数据已设置则返回true否则返回false。
*/
bool IsValid() const
{
return Target != nullptr && Data.IsValid();
}
/**
* Resets the mixin to its default state.
* 将混合数据重置为默认状态。
*/
void Reset()
{
Target = nullptr;
Data.Reset();
}
/**
* Computes the hash value for the mixin entry.
* 计算混合数据条目的哈希值。
* @param Entry The mixin entry to hash. 要哈希的混合数据条目。
* @return The hash value. 哈希值。
*/
friend uint32 GetTypeHash(const FGIS_Mixin& Entry);
};
/**
* Template specialization to enable copying for FGIS_Mixin.
* 为 FGIS_Mixin 启用复制的模板特化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_Mixin> : TStructOpsTypeTraitsBase2<FGIS_Mixin>
{
enum
{
WithCopy = true
};
};
/**
* Container for storing runtime data for various const objects within the owning object.
* 用于存储拥有对象中多个常量对象的运行时数据的容器。
* @details For example, ItemInstance uses this container to store runtime data for each fragment, as fragments themselves are const (cannot be modified at runtime). Only necessary runtime data is serialized/replicated instead of the entire fragments.
* @细节 例如ItemInstance 使用此容器存储每个片段的运行时数据,因为片段本身是常量(运行时无法修改)。仅序列化/复制必要的运行时数据,而不是整个片段。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_MixinContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for mixin container.
* 混合数据容器的默认构造函数。
*/
FGIS_MixinContainer()
: OwningObject(nullptr)
{
}
/**
* Constructor for mixin container with an owning object.
* 使用所属对象构造混合数据容器。
* @param NewObject The object that owns this container. 拥有此容器的对象。
*/
explicit FGIS_MixinContainer(UObject* NewObject)
: OwningObject(NewObject)
{
}
/**
* Retrieves data for a target class.
* 获取目标类的数据。
* @param TargetClass The class of the target object. 目标对象的类。
* @param OutData The retrieved instanced struct data (output). 检索到的实例化结构数据(输出)。
* @return True if data was found, false otherwise. 如果找到数据则返回true否则返回false。
*/
// bool GetDataByTargetClass(const TSubclassOf<UObject>& TargetClass, FInstancedStruct& OutData) const;
/**
* Retrieves data for a target object.
* 获取目标对象的数据。
* @param Target The target object which the data attached to. 数据所附加到的目标对象。
* @param OutData The retrieved instanced struct data (output). 检索到的实例化结构数据(输出)。
* @return True if data was found, false otherwise. 如果找到数据则返回true否则返回false。
*/
bool GetDataByTarget(const UObject* Target, FInstancedStruct& OutData) const;
/**
* Finds the index of a target object in the container.
* 查找容器中目标对象的索引。
* @param Target The target object to find. 要查找的目标对象。
* @return The index of the target object, or INDEX_NONE if not found. 目标对象的索引如果未找到则返回INDEX_NONE。
*/
int32 IndexOfTarget(const UObject* Target) const;
/**
* Finds the index of a target class in the container.
* 查找容器中目标类的索引。
* @param TargetClass The class of the target object. 目标对象的类。
* @return The index of the target class, or INDEX_NONE if not found. 目标类的索引如果未找到则返回INDEX_NONE。
*/
int32 IndexOfTargetByClass(const TSubclassOf<UObject>& TargetClass) const;
/**
* Sets data for a target object.
* 为目标对象设置数据。
* @param Target The target object. 目标对象。
* @param Data The instanced struct data to set. 要设置的实例化结构数据。
* @return The index of the updated or added entry. 更新或添加条目的索引。
*/
int32 SetDataForTarget(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data);
bool IsObjectLoadedFromDisk(const UObject* Object) const;
/**
* Updates data for a target class.
* 更新目标类的数据。
* @param TargetClass The class of the target object. 目标对象的类。
* @param Data The instanced struct data to update. 要更新的实例化结构数据。
* @return The index of the updated entry, or INDEX_NONE if not found. 更新条目的索引如果未找到则返回INDEX_NONE。
*/
int32 UpdateDataByTargetClass(const TSubclassOf<UObject>& TargetClass, const FInstancedStruct& Data);
/**
* Removes data associated with a target class.
* 移除与目标类关联的数据。
* @param TargetClass The class of the target object. 目标对象的类。
*/
void RemoveDataByTargetClass(const TSubclassOf<UObject>& TargetClass);
/**
* Checks if the data is compatible with the target object.
* 检查数据是否与目标对象兼容。
* @param Target The target object. 目标对象。
* @param Data The instanced struct data to check. 要检查的实例化结构数据。
* @return True if the data is compatible, false otherwise. 如果数据兼容则返回true否则返回false。
*/
bool CheckCompatibility(const UObject* Target, const FInstancedStruct& Data) const;
/**
* Retrieves all data stored in the container.
* 获取容器中存储的所有数据。
* @return Array of instanced struct data. 实例化结构数据的数组。
*/
TArray<FInstancedStruct> GetAllData() const;
/**
* Retrieves all serializable mixin in the container.
* 获取容器中所有可序列化的mixin
* @return Array of serializable mixin. 可序列化的Mixin数组
*/
TArray<FGIS_Mixin> GetSerializableMixins() const;
TArray<FGIS_MixinRecord> GetSerializableMixinRecords() const;
void RestoreFromRecords(const TArray<FGIS_MixinRecord>& Records);
static TArray<FGIS_Mixin> ConvertRecordsToMixins(const TArray<FGIS_MixinRecord>& Records);
/**
* Retrieves all serializable data stored in the container.
* 获取容器中存储的所有可序列化数据。
* @return Array of serializable instanced struct data. 可序列化实例化结构数据的数组。
*/
TArray<FInstancedStruct> GetAllSerializableData() const;
// -- Begin FFastArraySerializer implementation
/**
* Called after items are added during replication.
* 复制期间在添加项目后调用。
* @param AddedIndices The indices of added items. 添加项目的索引。
* @param FinalSize The final size of the array after addition. 添加后数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after items are changed during replication.
* 复制期间在项目更改后调用。
* @param ChangedIndices The indices of changed items. 更改项目的索引。
* @param FinalSize The final size of the array after changes. 更改后数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
/**
* Called before items are removed during replication.
* 复制期间在移除项目前调用。
* @param RemovedIndices The indices of removed items. 移除项目的索引。
* @param FinalSize The final size of the array after removal. 移除后数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Handles delta serialization for the mixin container.
* 处理混合数据容器的增量序列化。
* @param DeltaParams The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParams);
// -- End FFastArraySerializer implementation
protected:
/**
* Caches mixin data for faster access.
* 缓存混合数据以加速访问。
*/
void CacheMixins();
/**
* Updates data at a specific index.
* 在指定索引更新数据。
* @param Idx The index of the entry to update. 要更新的条目索引。
* @param Data The instanced struct data to set. 要设置的实例化结构数据。
* @return The index of the updated entry. 更新条目的索引。
*/
int32 UpdateDataAt(int32 Idx, const FInstancedStruct& Data);
/**
* The object that owns this container.
* 拥有此容器的对象。
*/
UPROPERTY()
TObjectPtr<UObject> OwningObject;
/**
* List of a target object to data pairs.
* 目标对象到数据的键值对列表。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Mixin")
TArray<FGIS_Mixin> Mixins;
/**
* Cached map for faster access to mixin data (index may vary between client and server).
* 用于加速访问混合数据的缓存映射(客户端和服务器的索引可能不同)。
*/
UPROPERTY(NotReplicated)
TMap<TObjectPtr<const UObject>, int32> AcceleratedMap;
/**
* Hash of the last cached state.
* 最后缓存状态的哈希值。
*/
UPROPERTY()
uint32 LastCachedHash = INDEX_NONE;
};
/**
* Template specialization to enable network delta serialization for the mixin container.
* 为混合数据容器启用网络增量序列化的模板特化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_MixinContainer> : TStructOpsTypeTraitsBase2<FGIS_MixinContainer>
{
enum { WithNetDeltaSerializer = true };
};

View File

@@ -0,0 +1,59 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "UObject/Interface.h"
#include "GIS_MixinOwnerInterface.generated.h"
/**
* Interface class for objects that own a mixin container.
* 拥有混合数据容器的对象的接口类。
*/
UINTERFACE()
class GENERICINVENTORYSYSTEM_API UGIS_MixinOwnerInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for objects that own a mixin container, to be notified of mixin data changes.
* 拥有混合数据容器的对象应实现的接口,用于接收混合数据变更通知。
* @details For example, an item instance will implement this interface to get notified when data attached to different fragment classes is added, changed, or removed.
* @细节 例如,道具实例将实现此接口,以在附加到不同片段类的数据被添加、更改或移除时收到通知。
*/
class GENERICINVENTORYSYSTEM_API IGIS_MixinOwnerInterface
{
GENERATED_BODY()
public:
/**
* Called when mixin data is added to the owning object.
* 当混合数据被添加到拥有对象时调用。
* @param Target The target object to which the data is attached. 数据附加到的对象。
* @param Data The added instanced struct data. 添加的实例化结构数据。
*/
virtual void OnMixinDataAdded(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) = 0;
/**
* Called when mixin data is updated in the owning object.
* 当拥有对象中的混合数据被更新时调用。
* @param Target The target object to which the data is attached. 数据附加到的对象。
* @param Data The updated instanced struct data. 更新的实例化结构数据。
*/
virtual void OnMixinDataUpdated(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) = 0;
/**
* Called when mixin data is removed from the owning object.
* 当从拥有对象中移除混合数据时调用。
* @param Target The target object to which the data was attached. 数据附加到的对象。
* @param Data The removed instanced struct data. 移除的实例化结构数据。
*/
virtual void OnMixinDataRemoved(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) = 0;
};

View File

@@ -0,0 +1,53 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "UObject/Interface.h"
#include "GIS_MixinTargetInterface.generated.h"
UINTERFACE(meta=(CannotImplementInterfaceInBlueprint))
class UGIS_MixinTargetInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for objects to handle data mixin functionality.
* 处理数据混合功能的接口。
* @details Defines methods for serialization and compatibility of mixin data.
* @细节 定义了混合数据的序列化和兼容性方法。
*/
class GENERICINVENTORYSYSTEM_API IGIS_MixinTargetInterface
{
GENERATED_BODY()
public:
/**
* Determines if the mixin data can be serialized.
* 确定混合数据是否可以序列化。
* @return True if the data is serializable, false otherwise. 如果数据可序列化则返回true否则返回false。
*/
virtual bool IsMixinDataSerializable() const = 0;
/**
* Retrieves the compatible data structure for the mixin.
* 获取混合数据的兼容数据结构。
* @return The script struct compatible with the mixin data. 与混合数据兼容的脚本结构。
*/
virtual TObjectPtr<const UScriptStruct> GetCompatibleMixinDataType() const = 0;
/**
* Generate default runtime data for compatible data type.
* 生成兼容的混合数据类型的默认值。
* @param DefaultState The default value of compatible data. 兼容的数据结构默认值。
* @return If has default value. 是否具备默认值?
*/
virtual bool MakeDefaultMixinData(FInstancedStruct& DefaultState) const = 0;
};

View File

@@ -0,0 +1,188 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_GameplayTagFloat.h"
#include "GIS_GameplayTagInteger.h"
#include "Engine/DataAsset.h"
#include "GIS_ItemDefinition.generated.h"
class UGIS_ItemDefinitionSchema;
class UGIS_ItemFragment;
class UGIS_ItemInstance;
class UTexture2D;
/**
* An item definition is a data asset. Creating a new item definition is equivalent to creating a new instance of the item definition class.
* Essentially, item definitions are static data that can incorporate item data fragments to achieve complex data structures.
* 道具定义是一个数据资产,创建一个新道具定义相当于新建一个类型为道具定义的资产。道具定义本质上是静态数据,可以添加道具数据片段,以实现复杂的数据结构。
*/
UCLASS(BlueprintType, Const)
class GENERICINVENTORYSYSTEM_API UGIS_ItemDefinition : public UPrimaryDataAsset
{
GENERATED_BODY()
public:
/**
* Constructor for the item definition.
* 道具定义的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_ItemDefinition(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
/**
* Display name of the item on the UI.
* 道具在UI上的显示名称。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Display)
FText DisplayName;
/**
* Description of the item on the UI.
* 道具在UI上的描述。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Display)
FText Description;
/**
* Icon of the item on the UI.
* 道具在UI上的图标。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Display)
TObjectPtr<UTexture2D> Icon;
/**
* Indicates whether the item is unique, preventing it from being stacked.
* 表示道具是否唯一,唯一道具不可堆叠。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Common)
bool bUnique;
/**
* Gameplay tags associated with the item for querying, categorization, and validation.
* 与道具关联的游戏标签,用于查询、分类和验证。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Common, meta=(Categories="GIS.Item"))
FGameplayTagContainer ItemTags;
/**
* Static tag-to-float attributes for the item definition.
* 道具定义的静态标签到浮点数的属性映射。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Settings, meta=(TitleProperty="{Tag} -> {Value}", Categories="GIS.Attribute"))
TArray<FGIS_GameplayTagFloat> StaticFloatAttributes;
/**
* Static tag-to-integer attributes for the item definition.
* 道具定义的静态标签到整数的属性映射。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Settings, meta=(TitleProperty="{Tag} -> {Value}", Categories="GIS.Attribute"))
TArray<FGIS_GameplayTagInteger> StaticIntegerAttributes;
/**
* Array of item data fragments to form simple or complex data structures. No duplicate fragment types are allowed.
* 数据片段数组,用于构成简单或复杂的道具数据结构。不允许重复的片段类型。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category=Settings, Instanced, meta=(NoElementDuplicate))
TArray<TObjectPtr<UGIS_ItemFragment>> Fragments;
/**
* Gets a fragment by its class.
* 通过类获取数据片段。
* @param FragmentClass The class of the fragment to retrieve. 要检索的片段类。
* @return The fragment instance, or nullptr if not found. 片段实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemDefinition")
const UGIS_ItemFragment* GetFragment(TSubclassOf<UGIS_ItemFragment> FragmentClass) const;
/**
* Checks if the item definition has a specific float attribute.
* 检查道具定义是否具有特定的浮点属性。
* @param AttributeTag The tag of the attribute to check. 要检查的属性标签。
* @return True if the attribute exists, false otherwise. 如果属性存在则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemDefinition")
bool HasFloatAttribute(FGameplayTag AttributeTag) const;
/**
* Gets the value of a static float attribute.
* 获取静态浮点属性的值。
* @param AttributeTag The tag of the attribute to retrieve. 要检索的属性标签。
* @return The value of the float attribute, or 0 if not found. 浮点属性的值如果未找到则返回0。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemDefinition")
float GetFloatAttribute(FGameplayTag AttributeTag) const;
/**
* Checks if the item definition has a specific integer attribute.
* 检查道具定义是否具有特定的整数属性。
* @param AttributeTag The tag of the attribute to check. 要检查的属性标签。
* @return True if the attribute exists, false otherwise. 如果属性存在则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemDefinition")
bool HasIntegerAttribute(FGameplayTag AttributeTag) const;
/**
* Gets the value of a static integer attribute.
* 获取静态整数属性的值。
* @param AttributeTag The tag of the attribute to retrieve. 要检索的属性标签。
* @return The value of the integer attribute, or 0 if not found. 整数属性的值如果未找到则返回0。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemDefinition")
int32 GetIntegerAttribute(FGameplayTag AttributeTag) const;
/**
* Template function to find a fragment by its class.
* 模板函数,通过类查找数据片段。
* @param ResultClass The class of the fragment to find. 要查找的片段类。
* @return The fragment instance cast to the specified class, or nullptr if not found. 转换为指定类的片段实例如果未找到则返回nullptr。
*/
template <typename ResultClass>
const ResultClass* FindFragment() const
{
return static_cast<const ResultClass*>(GetFragment(ResultClass::StaticClass()));
}
/**
* Cached map for faster access to integer attributes.
* 用于快速访问整数属性的缓存映射。
*/
UPROPERTY()
TMap<FGameplayTag, int32> IntegerAttributeMap;
/**
* Cached map for faster access to float attributes.
* 用于快速访问浮点属性的缓存映射。
*/
UPROPERTY()
TMap<FGameplayTag, float> FloatAttributeMap;
/**
* Finds a fragment in an item definition by its class.
* 在道具定义中通过类查找数据片段。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param FragmentClass The class of the fragment to find. 要查找的片段类。
* @return The fragment instance, or nullptr if not found. 片段实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemDefinition", meta=(DeterminesOutputType=FragmentClass))
static const UGIS_ItemFragment* FindFragmentOfItemDefinition(TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, TSubclassOf<UGIS_ItemFragment> FragmentClass);
#if WITH_EDITOR
/**
* Called before the item definition is saved in the editor.
* 编辑器中道具定义保存前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
/**
* Validates the item definition's data in the editor.
* 在编辑器中验证道具定义的数据。
* @param Context The validation context. 验证上下文。
* @return The result of the data validation. 数据验证的结果。
*/
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,171 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_GameplayTagFloat.h"
#include "GIS_GameplayTagInteger.h"
#include "Engine/DataAsset.h"
#include "GIS_ItemDefinitionSchema.generated.h"
class UGIS_ItemInstance;
class UGIS_ItemDefinition;
class UGIS_ItemFragment;
/**
* Structure representing a validation entry for item definitions.
* 表示道具定义验证条目的结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemDefinitionValidationEntry
{
GENERATED_BODY()
/**
* Gameplay tag query to match items for this validation.
* 用于匹配此验证的游戏标签查询。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema, meta=(Categories="GIS.Item"))
FGameplayTagQuery ItemTagQuery;
/**
* The required item instance class for matching items.
* 匹配道具所需的道具实例类。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TSoftClassPtr<UGIS_ItemInstance> InstanceClass;
/**
* List of required fragment classes for the item definition.
* 道具定义所需的片段类列表。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TArray<TSoftClassPtr<UGIS_ItemFragment>> RequiredFragments;
/**
* List of forbidden fragment classes for the item definition.
* 道具定义禁止的片段类列表。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TArray<TSoftClassPtr<UGIS_ItemFragment>> ForbiddenFragments;
/**
* List of required float attributes with default values.
* 必需的浮点属性列表,包含默认值。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema, meta=(TitleProperty="{Tag} -> {Value}"))
TArray<FGIS_GameplayTagFloat> RequiredFloatAttributes;
/**
* List of required integer attributes with default values.
* 必需的整数属性列表,包含默认值。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema, meta=(TitleProperty="{Tag} -> {Value}"))
TArray<FGIS_GameplayTagInteger> RequiredIntegerAttributes;
/**
* Whether to enforce the bUnique property.
* 是否强制执行 bUnique 属性。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
bool bEnforceUnique = false;
/**
* The required value for bUnique if enforced.
* 如果强制执行 bUnique则指定其值。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema, meta=(EditCondition="bEnforceUnique"))
bool RequiredUniqueValue = false;
};
/**
* The item definition schema is a data asset used in the editor for item definition data validation.
* 道具定义模式是一种数据资产,用于在编辑器中进行道具定义的数据验证。
*/
UCLASS(NotBlueprintable)
class GENERICINVENTORYSYSTEM_API UGIS_ItemDefinitionSchema : public UDataAsset
{
GENERATED_BODY()
public:
/**
* Validates an item definition against the schema.
* 针对模式验证道具定义。
* @param Definition The item definition to validate. 要验证的道具定义。
* @param OutError The error message if validation fails. 如果验证失败,则返回错误消息。
* @return True if the validation passes, false otherwise. 如果验证通过则返回true否则返回false。
*/
static bool TryValidateItemDefinition(const UGIS_ItemDefinition* Definition, FText& OutError);
/**
* Performs pre-save validation and auto-fixes for an item definition.
* 对道具定义进行保存前验证和自动修复。
* @param Definition The item definition to validate and fix. 要验证和修复的道具定义。
* @param OutError The error message if validation fails. 如果验证失败,则返回错误消息。
*/
static void TryPreSaveItemDefinition(UGIS_ItemDefinition* Definition, FText& OutError);
/**
* Validates an item definition against the schema (instance method).
* 针对模式验证道具定义(实例方法)。
* @param Definition The item definition to validate. 要验证的道具定义。
* @param OutError The error message if validation fails. 如果验证失败,则返回错误消息。
* @return True if the validation passes, false otherwise. 如果验证通过则返回true否则返回false。
*/
virtual bool TryValidate(const UGIS_ItemDefinition* Definition, FText& OutError) const;
/**
* Performs pre-save validation and auto-fixes for an item definition (instance method).
* 对道具定义进行保存前验证和自动修复(实例方法)。
* @param Definition The item definition to validate and fix. 要验证和修复的道具定义。
* @param OutError The error message if validation fails. 如果验证失败,则返回错误消息。
*/
virtual void TryPreSave(UGIS_ItemDefinition* Definition, FText& OutError) const;
#if WITH_EDITOR
/**
* Called before the schema is saved in the editor.
* 编辑器中模式保存前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
/**
* Validates the schema's data in the editor.
* 在编辑器中验证模式的数据。
* @param Context The validation context. 验证上下文。
* @return The result of the data validation. 数据验证的结果。
*/
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
protected:
/**
* Array of validation entries for the schema.
* 模式的验证条目数组。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TArray<FGIS_ItemDefinitionValidationEntry> ValidationEntries;
/**
* List of required fragment classes for all item definitions.
* 所有道具定义所需的常规片段类列表。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TArray<TSoftClassPtr<UGIS_ItemFragment>> CommonRequiredFragments;
/**
* The required parent tag for all item definitions' ItemTags.
* 所有道具定义的 ItemTags 必须包含的父级标签。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
FGameplayTag RequiredParentTag;
/**
* Global fragment order for all item definitions.
* 所有道具定义的全局片段排序。
*/
UPROPERTY(EditDefaultsOnly, Category = Schema)
TArray<TSoftClassPtr<UGIS_ItemFragment>> FragmentOrder;
};

View File

@@ -0,0 +1,187 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Items/GIS_ItemStack.h"
#include "UObject/Object.h"
#include "GIS_ItemInfo.generated.h"
struct FGIS_ItemStack;
class UGIS_ItemCollection;
class UGIS_ItemInstance;
/**
* Item information is a temporary structure used to pass item-related information across different operations, such as its belonging collection, amount, and corresponding item instance.
* 道具信息是一个临时的结构体,用于在不同的操作中传递道具相关信息,例如其所属集合、数量及对应的道具实例等。
*/
USTRUCT(BlueprintType, DisplayName="GIS Item Information")
struct GENERICINVENTORYSYSTEM_API FGIS_ItemInfo
{
GENERATED_BODY()
/**
* Default constructor for item information.
* 道具信息的默认构造函数。
*/
FGIS_ItemInfo();
/**
* Constructor for item information with item, amount, and collection.
* 使用道具、数量和集合构造道具信息。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
* @param InCollection The item collection where the item originates. 道具来源的集合。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount, UGIS_ItemCollection* InCollection);
/**
* Constructor for item information with item, amount, collection, and stack ID.
* 使用道具、数量、集合和堆栈ID构造道具信息。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
* @param InCollection The item collection where the item originates. 道具来源的集合。
* @param InStackId The stack ID associated with the item. 与道具关联的堆栈ID。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount, UGIS_ItemCollection* InCollection, FGuid InStackId);
/**
* Constructor for item information with item and amount.
* 使用道具和数量构造道具信息。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount);
/**
* Constructor for item information with item, amount, and collection ID.
* 使用道具、数量和集合ID构造道具信息。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
* @param InCollectionId The collection ID associated with the item. 与道具关联的集合ID。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount, FGuid InCollectionId);
/**
* Constructor for item information with item, amount, and collection tag.
* 使用道具、数量和集合标签构造道具信息。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
* @param InCollectionTag The collection tag associated with the item. 与道具关联的集合标签。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount, FGameplayTag InCollectionTag);
/**
* Constructor for item information by copying another info and changing the amount.
* 通过复制其他道具信息并更改数量构造道具信息。
* @param InAmount The new item amount. 新的道具数量。
* @param OtherInfo The item info to copy. 要复制的道具信息。
*/
FGIS_ItemInfo(int32 InAmount, const FGIS_ItemInfo& OtherInfo);
FGIS_ItemInfo(int32 InAmount, int32 InIndex, const FGIS_ItemInfo& OtherInfo);
/**
* Constructor for item information by copying another info with a new item and amount.
* 通过复制其他道具信息并指定新道具和数量构造道具信息。
* @param InItem The new item instance. 新的道具实例。
* @param InAmount The new item amount. 新的道具数量。
* @param OtherInfo The item info to copy. 要复制的道具信息。
*/
FGIS_ItemInfo(UGIS_ItemInstance* InItem, int32 InAmount, const FGIS_ItemInfo& OtherInfo);
/**
* Constructor for item information from an item stack.
* 从道具堆栈构造道具信息。
* @param ItemStack The item stack to convert from. 要转换的道具堆栈。
*/
FGIS_ItemInfo(const FGIS_ItemStack& ItemStack);
/**
* Gets a debug string representation of the item information.
* 获取道具信息的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString() const;
/**
* Compares this item info with another for equality.
* 将此道具信息与另一个比较以判断是否相等。
* @param Other The other item info to compare with. 要比较的其他道具信息。
* @return True if the item infos are equal, false otherwise. 如果道具信息相等则返回true否则返回false。
*/
bool operator==(const FGIS_ItemInfo& Other) const;
/**
* Checks if the item information is valid.
* 检查道具信息是否有效。
* @return True if the item info is valid, false otherwise. 如果道具信息有效则返回true否则返回false。
*/
bool IsValid() const;
/**
* Gets the inventory system component associated with the item collection.
* 获取与道具集合关联的库存系统组件。
* @return The inventory system component, or nullptr if not found. 库存系统组件如果未找到则返回nullptr。
*/
UGIS_InventorySystemComponent* GetInventory() const;
/**
* Static constant representing an invalid or empty item info.
* 表示无效或空道具信息的静态常量。
*/
static FGIS_ItemInfo None;
/**
* The item instance associated with this information, with context-dependent usage.
* 与此信息关联的道具实例,用途因上下文而异。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS", meta=(DisplayName="Item Instance"))
TObjectPtr<UGIS_ItemInstance> Item;
/**
* The amount of the item instance in this information.
* 此信息中道具实例的数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS", meta=(DisplayName="Item Amount"))
int32 Amount;
/**
* The collection instance where the information originates, with context-dependent usage.
* 此信息的源集合,用途因上下文而异。
* @attention For adding items, it specifies the source collection for overflow return; for retrieving items, it indicates the source collection.
* @注意 添加道具时,指定溢出返回的源集合;取回道具时,表示来源集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TObjectPtr<UGIS_ItemCollection> ItemCollection;
/**
* The stack ID associated with this information, with context-dependent usage.
* 与此信息关联的堆栈ID用途因上下文而异。
* @attention For adding/removing items, it determines the target stack; for retrieving items, it indicates the source stack.
* @注意 添加/移除道具时,用于确定目标堆栈;取回道具时,表示来源堆栈。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGuid StackId;
/**
* The collection ID associated with this information, with context-dependent usage.
* 与此信息关联的集合ID用途因上下文而异。
* @attention For adding/removing items, it determines the target collection; for retrieving items, it is usually null.
* @注意 添加/移除道具时,用于确定目标集合;取回道具时,通常为空。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGuid CollectionId;
/**
* The collection tag associated with this information, with context-dependent usage.
* 与此信息关联的集合标签,用途因上下文而异。
* @attention For adding/removing items, it determines the target collection (lower priority than CollectionId); for retrieving items, it is usually null.
* @注意 添加/移除道具时用于确定目标集合优先级低于CollectionId取回道具时通常为空。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS", meta=(Categories="GIS.Collection"))
FGameplayTag CollectionTag;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
int32 Index{INDEX_NONE};
};

View File

@@ -0,0 +1,579 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagAssetInterface.h"
#include "GameplayTagContainer.h"
#include "Attributes/GIS_GameplayTagFloat.h"
#include "Attributes/GIS_GameplayTagInteger.h"
#include "GIS_MixinContainer.h"
#include "GIS_MixinOwnerInterface.h"
#include "UObject/Object.h"
#include "GIS_ItemInstance.generated.h"
class UGIS_InventorySystemComponent;
class UGIS_ItemFragment;
struct FGIS_ItemStack;
class UGIS_ItemCollection;
class UGIS_ItemDefinition;
/**
* Delegate triggered when fragment data is added, updated, or removed.
* 当片段数据被添加、更新或移除时触发的委托。
* @param Fragment The item fragment associated with the event. 与事件关联的道具片段。
* @param Data The instanced struct containing the fragment data. 包含片段数据的实例化结构体。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FGIS_ItemFragmentStateEventSignature, const UGIS_ItemFragment*, Fragment, const FInstancedStruct&, Data);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_ItemIntegerAttributeChangedEventSignature, const FGameplayTag&, AttributeTag, int32, OldValue, int32, NewValue);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_ItemFloatAttributeChangedEventSignature, const FGameplayTag&, AttributeTag, float, OldValue, float, NewValue);
/**
* The item instance created via item definition.
* 通过道具定义创建的道具实例。
*/
UCLASS(BlueprintType, Blueprintable, CollapseCategories)
class GENERICINVENTORYSYSTEM_API UGIS_ItemInstance : public UObject, public IGameplayTagAssetInterface, public IGIS_MixinOwnerInterface, public IGIS_GameplayTagFloatContainerOwner,
public IGIS_GameplayTagIntegerContainerOwner
{
GENERATED_BODY()
public:
/**
* Constructor for the item instance.
* 道具实例的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_ItemInstance(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
/**
* Gets the gameplay tags owned by this item instance.
* 获取此道具实例拥有的游戏标签。
* @param TagContainer The container to store the tags. 存储标签的容器。
*/
virtual void GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const override;
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Checks if the item instance supports networking.
* 检查道具实例是否支持网络。
* @return True if networking is supported, false otherwise. 如果支持网络则返回true否则返回false。
*/
virtual bool IsSupportedForNetworking() const override { return true; };
/**
* Gets the unique ID of the item instance.
* 获取道具实例的唯一ID。
* @return The item instance's unique ID. 道具实例的唯一ID。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual FGuid GetItemId() const;
/**
* Sets the unique ID of the item instance.
* 设置道具实例的唯一ID。
* @param NewId The new ID to set. 要设置的新ID。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual void SetItemId(FGuid NewId);
/**
* Checks if the item instance is unique (non-stackable).
* 检查道具实例是否唯一(不可堆叠)。
* @return True if the item is unique, false otherwise. 如果道具唯一则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual bool IsUnique() const;
/**
* Gets the display name of the item instance.
* 获取道具实例的显示名称。
* @return The display name of the item. 道具的显示名称。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual FText GetItemName() const;
/**
* Gets the item definition associated with this instance.
* 获取与此实例关联的道具定义。
* @return The item definition, or nullptr if not set. 道具定义如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
const UGIS_ItemDefinition* GetDefinition() const;
/**
* Sets the item definition for this instance (authority only).
* 设置此实例的道具定义(仅限权限)。
* @param NewDefinition The new item definition to set. 要设置的新道具定义。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void SetDefinition(const UGIS_ItemDefinition* NewDefinition);
/**
* Gets the description of the item instance.
* 获取道具实例的描述。
* @return The description of the item. 道具的描述。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual FText GetItemDescription() const;
/**
* Gets the gameplay tags associated with the item instance.
* 获取与道具实例关联的游戏标签。
* @return The gameplay tag container. 游戏标签容器。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual FGameplayTagContainer GetItemTags() const;
/**
* Gets a fragment from the item definition by its class.
* 从道具定义中按类获取片段。
* @param FragmentClass The class of the fragment to retrieve. 要检索的片段类。
* @return The fragment instance, or nullptr if not found. 片段实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemInstance", meta=(DeterminesOutputType="FragmentClass", DynamicOutputParam="ReturnValue"))
const UGIS_ItemFragment* GetFragment(TSubclassOf<UGIS_ItemFragment> FragmentClass) const;
/**
* Finds a fragment in the item definition by its class, with validity check.
* 在道具定义中按类查找片段,并进行有效性检查。
* @param FragmentClass The class of the fragment to find. 要查找的片段类。
* @param bValid Output parameter indicating if the fragment was found. 输出参数,指示是否找到片段。
* @return The fragment instance, or nullptr if not found. 片段实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemInstance", meta=(DeterminesOutputType="FragmentClass", DynamicOutputParam="ReturnValue", ExpandBoolAsExecs="bValid"))
const UGIS_ItemFragment* FindFragment(TSubclassOf<UGIS_ItemFragment> FragmentClass, bool& bValid) const;
/**
* Template function to find a fragment by its class.
* 按类查找片段的模板函数。
* @param ResultClass The class of the fragment to find. 要查找的片段类。
* @return The fragment instance cast to the specified class, or nullptr if not found. 转换为指定类的片段实例如果未找到则返回nullptr。
*/
template <typename ResultClass>
const ResultClass* FindFragmentByClass() const
{
return static_cast<const ResultClass*>(GetFragment(ResultClass::StaticClass()));
}
/**
* Checks if the item instance has any attribute with the specified tag.
* 检查道具实例是否具有指定标签的任何属性。
* @param AttributeTag The tag of the attribute to check. 要检查的属性标签。
* @return True if the attribute exists, false otherwise. 如果属性存在则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual bool HasAnyAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag) const;
/**
* Checks if the item instance has a float attribute with the specified tag.
* 检查道具实例是否具有指定标签的浮点属性。
* @param AttributeTag The tag of the attribute to check. 要检查的属性标签。
* @return True if the float attribute exists, false otherwise. 如果浮点属性存在则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual bool HasFloatAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag) const;
/**
* Gets the value of a float attribute.
* 获取浮点属性的值。
* @param AttributeTag The tag of the attribute to retrieve. 要检索的属性标签。
* @return The value of the float attribute, or 0 if not found. 浮点属性的值如果未找到则返回0。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual float GetFloatAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag) const;
/**
* Sets the value of a float attribute (authority only).
* 设置浮点属性的值(仅限权限)。
* @param AttributeTag The tag of the attribute to set. 要设置的属性标签。
* @param NewValue The new value to set. 要设置的新值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void SetFloatAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, float NewValue);
/**
* Adds a value to a float attribute (authority only).
* 为浮点属性添加值(仅限权限)。
* @param AttributeTag The tag of the attribute to modify. 要修改的属性标签。
* @param Value The value to add. 要添加的值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void AddFloatAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, float Value);
/**
* Removes a value from a float attribute (authority only).
* 从浮点属性中移除值(仅限权限)。
* @param AttributeTag The tag of the attribute to modify. 要修改的属性标签。
* @param Value The value to remove. 要移除的值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void RemoveFloatAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, float Value);
/**
* Checks if the item instance has an integer attribute with the specified tag.
* 检查道具实例是否具有指定标签的整数属性。
* @param AttributeTag The tag of the attribute to check. 要检查的属性标签。
* @return True if the integer attribute exists, false otherwise. 如果整数属性存在则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual bool HasIntegerAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag) const;
/**
* Gets the value of an integer attribute.
* 获取整数属性的值。
* @param AttributeTag The tag of the attribute to retrieve. 要检索的属性标签。
* @return The value of the integer attribute, or 0 if not found. 整数属性的值如果未找到则返回0。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
virtual int32 GetIntegerAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag) const;
/**
* Sets the value of an integer attribute (authority only).
* 设置整数属性的值(仅限权限)。
* @param AttributeTag The tag of the attribute to set. 要设置的属性标签。
* @param NewValue The new value to set. 要设置的新值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void SetIntegerAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, int32 NewValue);
/**
* Adds a value to an integer attribute (authority only).
* 为整数属性添加值(仅限权限)。
* @param AttributeTag The tag of the attribute to modify. 要修改的属性标签。
* @param Value The value to add. 要添加的值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void AddIntegerAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, int32 Value);
/**
* Removes a value from an integer attribute (authority only).
* 从整数属性中移除值(仅限权限)。
* @param AttributeTag The tag of the attribute to modify. 要修改的属性标签。
* @param Value The value to remove. 要移除的值。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|ItemInstance")
virtual void RemoveIntegerAttribute(UPARAM(meta=(Categories="GIS.Attribute"))
FGameplayTag AttributeTag, int32 Value);
/**
* Gets the collection where this item belongs to.
* 获取此道具的所属集合。
* @attention Only available in server side. 只在服务端有效。
* @return The owning collection, or nullptr if not set. 所属集合如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemInstance")
UGIS_ItemCollection* GetOwningCollection() const;
/**
* Gets the inventory that owns this item instance.
* 获取拥有此道具实例的库存。
* @return The owning inventory, or nullptr if not set. 所属库存如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ItemInstance")
UGIS_InventorySystemComponent* GetOwningInventory() const;
/**
* Assigns a collection to this item instance. server only
* 为此道具实例分配集合。仅服务端
* @param NewItemCollection The new collection to assign. 要分配的新集合。
*/
virtual void AssignCollection(UGIS_ItemCollection* NewItemCollection);
/**
* Unassigns a collection from this item instance. server only
* 从此道具实例中取消分配集合。仅服务端
* @param ItemCollection The collection to unassign. 要取消分配的集合。
*/
virtual void UnassignCollection(UGIS_ItemCollection* ItemCollection);
/**
* Resets the owning collection of this item instance.
* 重置此道具实例的所属集合。
*/
// void ResetCollection();
/**
* Checks if the item instance is valid.
* 检查道具实例是否有效。
* @return True if the item instance is valid, false otherwise. 如果道具实例有效则返回true否则返回false。
*/
bool IsItemValid() const;
/**
* Checks if this item instance is stackable equivalent to another.
* 检查此道具实例是否与另一个在堆叠上等价。
* @param OtherItem The other item instance to compare with. 要比较的其他道具实例。
* @return True if the items are stackable equivalent, false otherwise. 如果道具在堆叠上等价则返回true否则返回false。
*/
virtual bool StackableEquivalentTo(const UGIS_ItemInstance* OtherItem) const;
/**
* Checks if this item instance is similar to another.
* 检查此道具实例是否与另一个相似。
* @param OtherItem The other item instance to compare with. 要比较的其他道具实例。
* @return True if the items are similar, false otherwise. 如果道具相似则返回true否则返回false。
*/
virtual bool SimilarTo(const UGIS_ItemInstance* OtherItem) const;
/**
* Static function to check if two item instances are stackable equivalent.
* 静态函数,检查两个道具实例是否在堆叠上等价。
* @param Lhs The first item instance. 第一个道具实例。
* @param Rhs The second item instance. 第二个道具实例。
* @return True if the items are stackable equivalent, false otherwise. 如果道具在堆叠上等价则返回true否则返回false。
*/
static bool AreStackableEquivalent(const UGIS_ItemInstance* Lhs, const UGIS_ItemInstance* Rhs);
/**
* Static function to check if two item instances are similar (commented out).
* 静态函数,检查两个道具实例是否相似(已注释)。
*/
// static bool AreValueEquivalent(const UGIS_ItemInstance* Lhs, const UGIS_ItemInstance* Rhs);
/**
* Static function to check if two item instances are similar.
* 静态函数,检查两个道具实例是否相似。
* @param Lhs The first item instance. 第一个道具实例。
* @param Rhs The second item instance. 第二个道具实例。
* @return True if the items are similar, false otherwise. 如果道具相似则返回true否则返回false。
*/
static bool AreSimilar(const UGIS_ItemInstance* Lhs, const UGIS_ItemInstance* Rhs);
/**
* Called when the item instance is duplicated.
* 道具实例被复制时调用。
* @param SrcItem The source item instance being duplicated. 被复制的源道具实例。
*/
virtual void OnItemDuplicated(const UGIS_ItemInstance* SrcItem);
#pragma region Mixins
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
const FGIS_MixinContainer& GetFragmentStates() const;
/**
* Finds fragment state by its class.
* 按类查找片段数据。
* @param FragmentClass The class of the fragment to find. 要查找的片段类。
* @param OutState The found fragment state (output). 找到的片段状态(输出)。
* @return True if the data was found, false otherwise. 如果找到有效数据则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemInstance", meta=(DisplayName="Find Fragment State", ExpandBoolAsExecs="ReturnValue"))
virtual bool FindFragmentStateByClass(TSubclassOf<UGIS_ItemFragment> FragmentClass, FInstancedStruct& OutState) const;
/**
* Sets fragment data by its class.
* 按类设置片段数据。
* @param FragmentClass The class of the fragment to set. 要设置的片段类。
* @param NewState The fragment state to set. 要设置的片段数据。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|ItemInstance", meta=(DisplayName="Set Fragment State"))
virtual void SetFragmentStateByClass(TSubclassOf<UGIS_ItemFragment> FragmentClass, UPARAM(ref)
const FInstancedStruct& NewState);
/**
* Event triggered when fragment data is added to the item instance.
* 当片段数据添加到道具实例时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="ItemInstance")
FGIS_ItemFragmentStateEventSignature OnFragmentStateAddedEvent;
/**
* Event triggered when fragment data is removed from the item instance.
* 当从道具实例移除片段数据时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="ItemInstance")
FGIS_ItemFragmentStateEventSignature OnFragmentStateRemovedEvent;
/**
* Event triggered when fragment data is updated in the item instance.
* 当道具实例中的片段数据更新时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="ItemInstance")
FGIS_ItemFragmentStateEventSignature OnFragmentStateUpdatedEvent;
protected:
/**
* Called when mixin data is added to the item instance.
* 当混合数据添加到道具实例时调用。
* @param Target The target object for the mixin data. 混合数据的目标对象。
* @param Data The instanced struct containing the mixin data. 包含混合数据的实例化结构体。
*/
virtual void OnMixinDataAdded(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) override final;
/**
* Called when mixin data is updated in the item instance.
* 当道具实例中的混合数据更新时调用。
* @param Target The target object for the mixin data. 混合数据的目标对象。
* @param Data The instanced struct containing the updated mixin data. 包含更新混合数据的实例化结构体。
*/
virtual void OnMixinDataUpdated(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) override final;
/**
* Called when mixin data is removed from the item instance.
* 当从道具实例中移除混合数据时调用。
* @param Target The target object for the mixin data. 混合数据的目标对象。
* @param Data The instanced struct containing the removed mixin data. 包含移除混合数据的实例化结构体。
*/
virtual void OnMixinDataRemoved(const TObjectPtr<const UObject>& Target, const FInstancedStruct& Data) override final;
/**
* Called when fragment data is added to the item instance.
* 当片段数据添加到道具实例时调用。
* @param Fragment The fragment associated with the data. 与数据关联的片段。
* @param Data The instanced struct containing the fragment data. 包含片段数据的实例化结构体。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
void OnFragmentStateAdded(const UGIS_ItemFragment* Fragment, const FInstancedStruct& Data);
/**
* Called when fragment data is updated in the item instance.
* 当道具实例中的片段数据更新时调用。
* @param Fragment The fragment associated with the data. 与数据关联的片段。
* @param Data The instanced struct containing the updated fragment data. 包含更新片段数据的实例化结构体。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
void OnFragmentStateUpdated(const UGIS_ItemFragment* Fragment, const FInstancedStruct& Data);
/**
* Called when fragment data is removed from the item instance.
* 当从道具实例移除片段数据时调用。
* @param Fragment The fragment associated with the data. 与数据关联的片段。
* @param Data The instanced struct containing the removed fragment data. 包含移除片段数据的实例化结构体。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
void OnFragmentStateRemoved(const UGIS_ItemFragment* Fragment, const FInstancedStruct& Data);
#pragma endregion
#pragma region Containers
public:
/**
* Event triggered when a float attribute is changed inside the item instance.
* 当道具实例中的浮点型属性变化时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="ItemInstance")
FGIS_ItemFloatAttributeChangedEventSignature OnFloatAttributeChangedEvent;
/**
* Event triggered when an integer attribute is changed inside the item instance.
* 当道具实例中的整型属性变化时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="ItemInstance")
FGIS_ItemFloatAttributeChangedEventSignature OnIntegerAttributeChangedEvent;
/**
* Called when a float attribute is updated.
* 浮点型属性更新时调用。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
virtual void OnTagFloatUpdate(const FGameplayTag& Tag, float OldValue, float NewValue) override final;
/**
* Called when an integer attribute is updated.
* 整型属性更新时调用。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
virtual void OnTagIntegerUpdate(const FGameplayTag& Tag, int32 OldValue, int32 NewValue) override final;
protected:
/**
* Blueprint event triggered when a float attribute changes.
* 浮点型属性变化时触发的蓝图事件。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
UFUNCTION(BlueprintNativeEvent, Category="ItemInstance")
void OnFloatAttributeChanged(const FGameplayTag& Tag, float OldValue, float NewValue);
/**
* Blueprint event triggered when an integer attribute changes.
* 整型属性变化时触发的蓝图事件。
* @param Tag The gameplay tag identifying the attribute. 标识属性的游戏标签。
* @param OldValue The previous value of the attribute. 属性之前的值。
* @param NewValue The new value of the attribute. 属性的新值。
*/
UFUNCTION(BlueprintNativeEvent, Category="ItemInstance")
void OnIntegerAttributeChanged(const FGameplayTag& Tag, int32 OldValue, int32 NewValue);
#pragma endregion
/**
* Unique ID of this item instance, assigned at creation.
* 道具实例的唯一ID在创建时分配。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="ItemInstance", Replicated)
FGuid ItemId;
/**
* The item definition associated with this instance.
* 与此实例关联的道具定义。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="ItemInstance", Replicated)
TObjectPtr<const UGIS_ItemDefinition> Definition;
/**
* Container for integer attributes of the item instance.
* 道具实例的整数属性容器。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Replicated, Category="ItemInstance", SaveGame, meta=(DisplayName="Attributes (Integer)", ShowOnlyInnerProperties))
FGIS_GameplayTagIntegerContainer IntegerAttributes;
/**
* Container for float attributes of the item instance.
* 道具实例的浮点属性容器。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Replicated, Category="ItemInstance", SaveGame, meta=(DisplayName="Attributes (Float)", ShowOnlyInnerProperties))
FGIS_GameplayTagFloatContainer FloatAttributes;
/**
* Container for each fragment's runtime state.
* 每个片段运行时状态的容器。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Replicated, Category="ItemInstance", meta=(DisplayName="Fragment States", ShowOnlyInnerProperties))
FGIS_MixinContainer FragmentStates;
private:
#if UE_WITH_IRIS
/**
* Registers replication fragments for networking (Iris-specific).
* 为网络注册复制片段特定于Iris
* @param Context The fragment registration context. 片段注册上下文。
* @param RegistrationFlags The registration flags. 注册标志。
*/
virtual void RegisterReplicationFragments(UE::Net::FFragmentRegistrationContext& Context, UE::Net::EFragmentRegistrationFlags RegistrationFlags) override;
#endif // UE_WITH_IRIS
/**
* The collection that owns this item instance.
* 拥有此道具实例的集合。
*/
UPROPERTY(Replicated, Transient)
TObjectPtr<UGIS_ItemCollection> OwningCollection{nullptr};
};

View File

@@ -0,0 +1,48 @@
// // Copyright 2025 https://yuewu.dev/en All Rights Reserved.
//
// #pragma once
//
// #include "CoreMinimal.h"
// #include "GameplayTagContainer.h"
// #include "UObject/Interface.h"
// #include "GIS_ItemInterface.generated.h"
//
//
// // This class does not need to be modified.
// UINTERFACE(meta=(CannotImplementInterfaceInBlueprint))
// class GENERICINVENTORYSYSTEM_API UGIS_EnhancedItemInterface : public UInterface
// {
// GENERATED_BODY()
// };
//
// /**
// * 具备数值修正的道具
// */
// class GENERICINVENTORYSYSTEM_API IGIS_EnhancedItemInterface
// {
// GENERATED_BODY()
//
// public:
// UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
// virtual TMap<FGameplayTag, float> GetAdditionAttributes() const = 0;
// // virtual TMap<FGameplayTag, float> GetAdditionAttributes_Implementation() const = 0;
// virtual void OverrideAdditionAttribute(FGameplayTag AttributeTag, float Value) = 0;
//
// UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
// virtual TMap<FGameplayTag, float> GetMultiplierAttributes() const = 0;
// // virtual TMap<FGameplayTag, float> GetMultiplierAttributes_Implementation() const =0;
// virtual void OverrideMultiplierAttribute(FGameplayTag AttributeTag, float Value) = 0;
//
// /**强化等级*/
// UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
// virtual int32 GetEnhancedLevel() const = 0;
// virtual void SetEnhancedLevel(int32 Value) = 0;
// /**最大强化次数*/
// UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
// virtual int32 GetMaxEnhancedNumber() const = 0;
// virtual void SetMaxEnhancedNumber(int32 Value) = 0;
// /**当前强化次数*/
// UFUNCTION(BlueprintCallable, Category="GIS|ItemInstance")
// virtual int32 GetCurrentEnhancedNumber() const = 0;
// virtual void SetCurrentEnhancedNumber(int32 Value) = 0;
// };

View File

@@ -0,0 +1,268 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "GIS_ItemStack.generated.h"
class UActorComponent;
class UGIS_ItemCollection;
class UGIS_ItemSlotCollection;
class UGIS_ItemMultiStackCollection;
class UGIS_ItemDefinition;
class UGIS_ItemInstance;
class UGIS_InventorySystemComponent;
/**
* Enum defining the types of changes to an item stack.
* 定义道具堆栈变更类型的枚举。
*/
UENUM(BlueprintType)
enum class EGIS_ItemStackChangeType : uint8
{
WasAdded, // Item stack was added. 道具堆栈被添加。
WasRemoved, // Item stack was removed. 道具堆栈被移除。
Changed // Item stack was modified. 道具堆栈被修改。
};
/**
* Structure used to store the corresponding item instance, their amount, and their position within the collection.
* 道具堆栈是一个简单的结构体,用于存储对应的道具实例、数量以及在集合中的位置。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemStack : public FFastArraySerializerItem
{
GENERATED_BODY()
friend struct FGIS_ItemStackContainer;
/**
* Static constant representing an invalid stack ID.
* 表示无效堆栈ID的静态常量。
*/
static FGuid InvalidId;
/**
* Default constructor for item stack.
* 道具堆栈的默认构造函数。
*/
FGIS_ItemStack();
/**
* Gets a debug string representation of the item stack.
* 获取道具堆栈的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString();
/**
* Initializes the item stack with specified parameters.
* 使用指定参数初始化道具堆栈。
* @param InStackId The stack ID. 堆栈ID。
* @param InItem The item instance. 道具实例。
* @param InAmount The amount of the item. 道具数量。
* @param InCollection The collection the stack belongs to. 堆栈所属的集合。
*/
void Initialize(FGuid InStackId, UGIS_ItemInstance* InItem, int32 InAmount, UGIS_ItemCollection* InCollection, int32 InIndex = INDEX_NONE);
/**
* Checks if the item stack is valid.
* 检查道具堆栈是否有效。
* @return True if the stack is valid, false otherwise. 如果堆栈有效则返回true否则返回false。
*/
bool IsValidStack() const;
/**
* Resets the item stack to its default state.
* 将道具堆栈重置为默认状态。
*/
void Reset();
/**
* The item instance of this stack.
* 此堆栈中的道具实例。
*/
UPROPERTY(VisibleInstanceOnly, Category="GIS", meta=(DisplayName="ItemInstance", ShowInnerProperties, DisplayPriority=0))
TObjectPtr<UGIS_ItemInstance> Item{nullptr};
/**
* The quantity of the item in this stack.
* 此堆栈中的道具数量。
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
int32 Amount = 0;
/**
* The stack ID.
* 堆栈ID。
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
FGuid Id;
/**
* The collection this stack belongs to.
* 此堆栈所属的集合。
* @attention TODO: Should this really need to be replicated?
* @注意 TODO此属性是否真的需要复制
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
TObjectPtr<UGIS_ItemCollection> Collection = nullptr;
/**
* The collection ID (commented out).
* 集合ID已注释
*/
// UPROPERTY(VisibleAnywhere, Category="GIS")
// FGuid CollectionId;
/**
* The last observed count of the stack (not replicated).
* 堆栈的最后观察计数(不复制)。
*/
UPROPERTY(NotReplicated)
int32 LastObservedAmount = INDEX_NONE;
/**
* The position of the stack within the collection.
* 堆栈在集合中的位置。
*/
UPROPERTY(VisibleAnywhere, Category="GIS")
int32 Index = INDEX_NONE;
/**
* Compares this item stack with another for equality.
* 将此道具堆栈与另一个比较以判断是否相等。
* @param Other The other item stack to compare with. 要比较的其他道具堆栈。
* @return True if the stacks are equal, false otherwise. 如果堆栈相等则返回true否则返回false。
*/
bool operator==(const FGIS_ItemStack& Other) const;
/**
* Compares this item stack with another for inequality.
* 将此道具堆栈与另一个比较以判断是否不相等。
* @param Other The other item stack to compare with. 要比较的其他道具堆栈。
* @return True if the stacks are not equal, false otherwise. 如果堆栈不相等则返回true否则返回false。
*/
bool operator!=(const FGIS_ItemStack& Other) const;
/**
* Compares this item stack's ID with another ID for equality.
* 将此道具堆栈的ID与另一个ID比较以判断是否相等。
* @param OtherId The other ID to compare with. 要比较的其他ID。
* @return True if the IDs are equal, false otherwise. 如果ID相等则返回true否则返回false。
*/
bool operator==(const FGuid& OtherId) const;
/**
* Compares this item stack's ID with another ID for inequality.
* 将此道具堆栈的ID与另一个ID比较以判断是否不相等。
* @param OtherId The other ID to compare with. 要比较的其他ID。
* @return True if the IDs are not equal, false otherwise. 如果ID不相等则返回true否则返回false。
*/
bool operator!=(const FGuid& OtherId) const;
};
/**
* The container for item stacks, supporting fast array serialization.
* 道具堆栈的容器,支持快速数组序列化。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemStackContainer : public FFastArraySerializer
{
GENERATED_BODY()
friend UGIS_ItemCollection;
friend UGIS_ItemMultiStackCollection;
friend UGIS_ItemSlotCollection;
/**
* Default constructor for item stack container.
* 道具堆栈容器的默认构造函数。
*/
FGIS_ItemStackContainer() : OwningCollection(nullptr)
{
}
/**
* Constructor for item stack container with a specified collection.
* 使用指定集合构造道具堆栈容器。
* @param InCollection The owning collection. 所属集合。
*/
FGIS_ItemStackContainer(UGIS_ItemCollection* InCollection) : OwningCollection(InCollection)
{
}
//~FFastArraySerializer contract
/**
* Called before items are removed during replication.
* 复制期间在移除道具前调用。
* @param RemovedIndices The indices of removed items. 移除道具的索引。
* @param FinalSize The final size of the array after removal. 移除后数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after items are added during replication.
* 复制期间在添加道具后调用。
* @param AddedIndices The indices of added items. 添加道具的索引。
* @param FinalSize The final size of the array after addition. 添加后数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after items are changed during replication.
* 复制期间在道具更改后调用。
* @param ChangedIndices The indices of changed items. 更改道具的索引。
* @param FinalSize The final size of the array after changes. 更改后数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for the item stack container.
* 处理道具堆栈容器的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_ItemStack, FGIS_ItemStackContainer>(Stacks, DeltaParms, *this);
}
const FGIS_ItemStack* FindById(const FGuid& StackId) const;
const FGIS_ItemStack* FindByItemId(const FGuid& ItemId) const;
int32 IndexOfById(const FGuid& StackId) const;
int32 IndexOfByItemId(const FGuid& ItemId) const;
int32 IndexOfByIds(const FGuid& StackId, const FGuid& ItemId) const;
protected:
/**
* Replicated list of item stacks.
* 复制的道具堆栈列表。
*/
UPROPERTY(VisibleAnywhere, Category="GIS", meta=(ShowOnlyInnerProperties, DisplayName="Item Stacks"))
TArray<FGIS_ItemStack> Stacks;
/**
* The collection that owns this container (not replicated).
* 拥有此容器的集合(不复制)。
*/
UPROPERTY(NotReplicated)
TObjectPtr<UGIS_ItemCollection> OwningCollection;
};
/**
* Template specialization to enable network delta serialization for the item stack container.
* 为道具堆栈容器启用网络增量序列化的模板特化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_ItemStackContainer> : TStructOpsTypeTraitsBase2<FGIS_ItemStackContainer>
{
enum { WithNetDeltaSerializer = true };
};

View File

@@ -0,0 +1,297 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Engine/DataTable.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_CurrencyEntry.h"
#include "Items/GIS_ItemInfo.h"
#include "UObject/Object.h"
#include "GIS_CraftingStructLibrary.generated.h"
/**
* Struct for querying item ingredients required for crafting.
* 用于查询合成所需道具材料的结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_ItemIngredient
{
GENERATED_USTRUCT_BODY()
FGIS_ItemIngredient()
: NeedAmounts(0)
{
}
FGIS_ItemIngredient(int32 InNeedAmounts, const TArray<FGIS_ItemInfo>& InHoldItemAmounts)
: NeedAmounts(InNeedAmounts)
, HoldItemAmounts(InHoldItemAmounts)
{
}
/**
* Definition of the item required for crafting.
* 合成所需道具的定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition;
/**
* Required amount of the item for crafting.
* 合成所需道具的数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
int32 NeedAmounts;
/**
* List of held items and their amounts.
* 持有道具及其数量的列表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TArray<FGIS_ItemInfo> HoldItemAmounts;
/**
* Calculates the total amount of held items.
* 计算持有道具的总量。
* @return The total amount of held items. 持有道具的总量。
*/
FORCEINLINE int32 GetHoldAmount() const
{
int32 Count = 0;
for (const auto& ItemInfo : HoldItemAmounts)
{
Count += ItemInfo.Amount;
}
return Count;
}
};
/**
* Struct for querying currency ingredients required for crafting.
* 用于查询合成所需货币材料的结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_CurrencyIngredient
{
GENERATED_USTRUCT_BODY()
FGIS_CurrencyIngredient()
: NeedAmounts(0)
{
}
FGIS_CurrencyIngredient(TObjectPtr<const UGIS_CurrencyDefinition> InCurrencyDefinition, int32 InNeedAmounts, FGIS_CurrencyEntry InHoldAmounts)
: CurrencyDefinition(InCurrencyDefinition)
, NeedAmounts(InNeedAmounts)
, HoldCurrencyInfo(InHoldAmounts)
{
}
/**
* Definition of the currency required for crafting.
* 合成所需货币的定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TObjectPtr<const UGIS_CurrencyDefinition> CurrencyDefinition;
/**
* Required amount of the currency for crafting.
* 合成所需货币的数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
int32 NeedAmounts;
/**
* Information about the held currency.
* 持有货币的信息。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGIS_CurrencyEntry HoldCurrencyInfo;
};
/**
* Struct defining the cost data for crafting or enhancing items.
* 定义合成或强化道具的消耗数据的结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_CraftItemCostData
{
GENERATED_USTRUCT_BODY()
FGIS_CraftItemCostData() : bCostItem(false), bCostCurrency(true), bCostTime(false), Days(1)
{
};
/**
* Determines if items are consumed during crafting.
* 确定合成时是否消耗道具。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Crafting")
bool bCostItem;
/**
* List of items consumed during crafting.
* 合成时消耗的道具列表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(EditCondition="bCostItem"), Category="Crafting", meta=(TitleProperty="Definition"))
TArray<FGIS_ItemDefinitionAmount> CostItems;
/**
* Determines if currencies are consumed during crafting.
* 确定合成时是否消耗货币。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Crafting")
bool bCostCurrency;
/**
* List of currencies consumed during crafting.
* 合成时消耗的货币列表。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(EditCondition="bCostCurrency"), Category="Crafting")
TArray<FGIS_CurrencyEntry> CostCurrencies;
/**
* Determines if time is consumed during crafting.
* 确定合成时是否消耗时间。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Crafting")
bool bCostTime;
/**
* Time consumed for crafting, in days.
* 合成消耗的时间(以天为单位)。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, meta=(EditCondition="bCostTime"), Category="Crafting")
float Days;
};
/**
* Data table struct for item crafting recipes.
* 道具合成配方的数据表结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_CraftingItemData : public FTableRowBase
{
GENERATED_USTRUCT_BODY()
/**
* Gameplay tag defining the crafting item.
* 定义合成道具的游戏标签。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGameplayTag CraftingItemDefinition;
/**
* Definition of the crafting item.
* 合成道具的定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TSoftObjectPtr<const UGIS_ItemDefinition> CraftingDefinition;
/**
* Type of crafting operation.
* 合成操作的类型。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGameplayTag CraftingItemType;
/**
* Cost data for the crafting operation.
* 合成操作的消耗数据。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGIS_CraftItemCostData CraftItemCost;
/**
* Definition of the output item produced by crafting.
* 合成产出的道具定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS")
TSoftObjectPtr<const UGIS_ItemDefinition> OutputItemDefinition;
};
/**
* Data table struct for item enhancement data.
* 道具强化数据的数据表结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_ItemEnhancedData : public FTableRowBase
{
GENERATED_USTRUCT_BODY()
FGIS_ItemEnhancedData() : EnhancedLevel(1), bDestroy(false), Downgrading(false)
{
};
/**
* Set of item types that can use this enhancement data.
* 可以使用此强化数据的道具类型集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGameplayTagContainer ItemTypeSet;
/**
* Tag query for items eligible for this enhancement.
* 适用于此强化的道具标签查询。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGameplayTagQuery ItemTagQuery;
/**
* Level of enhancement applied to the item.
* 应用于道具的强化等级。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
int32 EnhancedLevel;
/**
* Prefix added to the item name after enhancement.
* 强化后添加到道具名称的前缀。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FName EnhancedNamePrefix;
/**
* Cost data for the enhancement operation.
* 强化操作的消耗数据。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGIS_CraftItemCostData EnhancedItemCost;
/**
* Constant attribute bonuses applied by the enhancement.
* 强化应用的常量属性加成。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS")
TMap<FGameplayTag, float> AdditionAttributes;
/**
* Multiplier attribute bonuses applied by the enhancement.
* 强化应用的系数属性加成。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS")
TMap<FGameplayTag, float> MultiplierAttributes;
/**
* Success rate of the enhancement operation.
* 强化操作的成功率。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS", meta=(ClampMin = 0.f, ClampMax = 1.f))
float SuccessRate = 1.f;
/**
* Determines if the item is destroyed on enhancement failure (deprecated).
* 确定强化失败时道具是否销毁(已弃用)。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS", meta=(DeprecatedProperty))
bool bDestroy;
/**
* Level reduction on enhancement failure (deprecated).
* 强化失败时的等级降低(已弃用)。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="GIS", meta=(EditCondition="!bDestroy", DeprecatedProperty))
int32 Downgrading;
};

View File

@@ -0,0 +1,146 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CraftingStructLibrary.h"
#include "Components/ActorComponent.h"
#include "GIS_CraftingSystemComponent.generated.h"
class UGIS_ItemFragment_CraftingRecipe;
class UGIS_CurrencySystemComponent;
class UGIS_CraftingRecipe;
/**
* Actor component for handling crafting functionality in the inventory system.
* 用于在库存系统中处理制作功能的演员组件。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_CraftingSystemComponent : public UActorComponent
{
GENERATED_BODY()
public:
/**
* Constructor for the crafting system component.
* 制作系统组件的构造函数。
*/
UGIS_CraftingSystemComponent();
/**
* Attempts to craft items using a recipe.
* 尝试使用配方制作道具。
* @param Recipe The item definition containing recipe data. 包含配方数据的道具定义。
* @param Inventory The inventory that pays the crafting cost. 用于支付制作成本的库存。
* @param Quantity The multiplier for crafting output. 制作输出的倍率。
* @return True if crafting succeeds, false otherwise. 如果制作成功返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|CraftingSystem")
bool Craft(const UGIS_ItemDefinition* Recipe, UGIS_InventorySystemComponent* Inventory, int32 Quantity = 1);
/**
* Checks if the parameters are valid for crafting an item.
* 检查参数是否满足制作道具的条件。
* @param RecipeDefinition The item definition with recipe data. 包含配方数据的道具定义。
* @param Inventory The inventory containing the items. 包含道具的库存。
* @param Quantity The amount to craft. 要制作的数量。
* @return True if crafting is possible, false otherwise. 如果可以制作则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CraftingSystem")
bool CanCraft(const UGIS_ItemDefinition* RecipeDefinition, UGIS_InventorySystemComponent* Inventory, int32 Quantity = 1);
protected:
/**
* Internal function to check if crafting is possible.
* 内部函数,检查是否可以制作。
* @param RecipeDefinition The item definition with recipe data. 包含配方数据的道具定义。
* @param Inventory The inventory containing the items. 包含道具的库存。
* @param Quantity The amount to craft. 要制作的数量。
* @return True if crafting is possible, false otherwise. 如果可以制作则返回true否则返回false。
*/
virtual bool CanCraftInternal(const UGIS_ItemDefinition* RecipeDefinition, UGIS_InventorySystemComponent* Inventory, int32 Quantity = 1);
/**
* Internal function to perform crafting.
* 内部函数,执行制作。
* @param RecipeDefinition The item definition with recipe data. 包含配方数据的道具定义。
* @param Inventory The inventory that pays the crafting cost. 用于支付制作成本的库存。
* @param Quantity The multiplier for crafting output. 制作输出的倍率。
* @return True if crafting succeeds, false otherwise. 如果制作成功返回true否则返回false。
*/
virtual bool CraftInternal(const UGIS_ItemDefinition* RecipeDefinition, UGIS_InventorySystemComponent* Inventory, int32 Quantity = 1);
/**
* Produces crafting output for the inventory, adding output items by default.
* 为库存生成制作输出,默认将输出道具添加到库存。
* @details Override to implement custom logic, such as a crafting queue.
* @细节 可覆写以实现自定义逻辑,例如制作队列(延迟获得结果)。
* @param RecipeDefinition The item definition with recipe data. 包含配方数据的道具定义。
* @param Inventory The inventory to receive the output. 接收输出的库存。
* @param Quantity The multiplier for crafting output. 制作输出的倍率。
*/
virtual void ProduceCraftingOutput(const UGIS_ItemDefinition* RecipeDefinition, UGIS_InventorySystemComponent* Inventory, int32 Quantity = 1);
/**
* Checks if the recipe definition is valid (contains valid crafting data).
* 检查配方定义是否有效(包含有效的制作数据)。
* @details Override to apply custom validation rules, such as checking for specific fragments.
* @细节 可覆写以应用自定义验证规则,例如检查特定道具片段是否存在。
* @param RecipeDefinition The item definition to validate. 要验证的道具定义。
* @return True if the recipe is valid, false otherwise. 如果配方有效则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|CraftingSystem")
bool IsValidRecipe(const UGIS_ItemDefinition* RecipeDefinition) const;
/**
* Gets the recipe fragment for the default crafting implementation.
* 获取默认制作实现所需的配方片段。
* @param RecipeDefinition The item definition to retrieve data from. 要从中获取数据的道具定义。
* @return The crafting recipe fragment, or nullptr if not found. 制作配方片段如果未找到则返回nullptr。
*/
const UGIS_ItemFragment_CraftingRecipe* GetRecipeFragment(const UGIS_ItemDefinition* RecipeDefinition) const;
/**
* Selects the maximum number of item infos for required item ingredients from the inventory.
* 从库存中选择满足道具成分需求的最大道具信息。
* @param Inventory The inventory to select items from. 要从中选择道具的库存。
* @param ItemIngredients The required item ingredients. 所需的道具成分。
* @param Quantity The amount to craft. 要制作的数量。
* @return True if sufficient items are selected, false otherwise. 如果选择了足够的道具则返回true否则返回false。
*/
virtual bool SelectItemForIngredients(const UGIS_InventorySystemComponent* Inventory, const TArray<FGIS_ItemDefinitionAmount>& ItemIngredients, int32 Quantity);
/**
* Checks if selected items are sufficient for the required item ingredients.
* 检查已选道具是否足以满足道具成分需求。
* @param ItemIngredients The required item ingredients. 所需的道具成分。
* @param Quantity The amount to craft. 要制作的数量。
* @param SelectedItems The selected items from the inventory. 从库存中选择的道具。
* @param ItemsToIgnore Items to ignore during checking. 检查时要忽略的道具。
* @param NumOfItemsToIgnore Number of items to ignore (output). 要忽略的道具数量(输出)。
* @return True if the selected items are sufficient, false otherwise. 如果选择的道具足够则返回true否则返回false。
*/
virtual bool CheckIfEnoughItemIngredients(const TArray<FGIS_ItemDefinitionAmount>& ItemIngredients,
int32 Quantity, const TArray<FGIS_ItemInfo>& SelectedItems, TArray<FGIS_ItemInfo>& ItemsToIgnore, int32& NumOfItemsToIgnore);
/**
* Removes item ingredients from the inventory's default collection one by one.
* 从库存的默认集合中逐一移除道具成分。
* @param Inventory The inventory to remove items from. 要从中移除道具的库存。
* @param ItemIngredients The item ingredients to remove. 要移除的道具成分。
* @return True if all items were successfully removed, false otherwise. 如果所有道具移除成功则返回true否则返回false。
*/
virtual bool RemoveItemIngredients(UGIS_InventorySystemComponent* Inventory, const TArray<FGIS_ItemInfo>& ItemIngredients);
/**
* Cache for selected items during crafting.
* 制作过程中选择的道具缓存。
*/
TArray<FGIS_ItemInfo> SelectedItemsCache;
/**
* Number of selected items in the cache.
* 缓存中选择的道具数量。
*/
int32 NumOfSelectedItemsCache;
};

View File

@@ -0,0 +1,47 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_CurrencyEntry.h"
#include "GIS_ItemFragment.h"
#include "GIS_ItemFragment_CraftingRecipe.generated.h"
/**
* Item fragment defining a crafting recipe for producing items.
* 定义用于生产道具的合成配方的道具片段。
* @details Specifies input items, currencies, and output items for crafting.
* @细节 指定用于合成的输入道具、货币和输出道具。
*/
UCLASS(DisplayName="Crafting Recipe Settings", Category="BuiltIn")
class GENERICINVENTORYSYSTEM_API UGIS_ItemFragment_CraftingRecipe : public UGIS_ItemFragment
{
GENERATED_BODY()
public:
/**
* List of required items and their quantities for crafting.
* 合成所需的道具及其数量列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Crafting", meta=(TitleProperty="{Definition}->{Amount}"))
TArray<FGIS_ItemDefinitionAmount> InputItems;
/**
* List of required currencies and their amounts for crafting.
* 合成所需的货币及其数量列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Ingredients", meta=(TitleProperty="{Tag}->{Amount}"))
TArray<FGIS_CurrencyEntry> InputCurrencies;
/**
* List of items produced by the crafting recipe.
* 合成配方产出的道具列表。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Crafting", meta=(TitleProperty="EditorFriendlyName"))
TArray<FGIS_ItemDefinitionAmount> OutputItems;
#if WITH_EDITOR
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
#endif
};

View File

@@ -0,0 +1,50 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_DropperComponent.h"
#include "GIS_CurrencyDropper.generated.h"
class UGIS_CurrencySystemComponent;
/**
* Component for handling currency drop logic.
* 处理货币掉落逻辑的组件。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_CurrencyDropper : public UGIS_DropperComponent
{
GENERATED_BODY()
public:
/**
* Initializes the currency dropper component at the start of play.
* 在游戏开始时初始化货币掉落组件。
*/
virtual void BeginPlay() override;
/**
* Executes the currency drop logic.
* 执行货币掉落逻辑。
*/
virtual void Drop() override;
protected:
/**
* Reference to the currency system component.
* 货币系统组件的引用。
*/
UPROPERTY()
UGIS_CurrencySystemComponent* MyCurrency;
#if WITH_EDITOR
/**
* Validates the component's data in the editor.
* 在编辑器中验证组件的数据。
* @param Context The data validation context. 数据验证上下文。
* @return The result of the data validation. 数据验证的结果。
*/
virtual EDataValidationResult IsDataValid(FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,79 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/SceneComponent.h"
#include "GIS_DropperComponent.generated.h"
/**
* Abstract base class for a component that handles dropping items in the game world.
* 用于在游戏世界中处理道具掉落的抽象基类组件。
*/
UCLASS(Abstract, ClassGroup=(GIS))
class GENERICINVENTORYSYSTEM_API UGIS_DropperComponent : public UActorComponent
{
GENERATED_BODY()
public:
/**
* Constructor for the dropper component, sets default values for properties.
* 掉落组件的构造函数,设置属性的默认值。
*/
UGIS_DropperComponent();
/**
* Drops an item in the game world (authority only).
* 在游戏世界中掉落道具(仅限权限)。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|Dropper")
virtual void Drop();
protected:
/**
* Creates an instance of the pickup actor using the specified PickupActorClass.
* 使用指定的PickupActorClass创建拾取Actor的实例。
* @return The spawned pickup actor instance, or nullptr if creation fails. 创建的拾取Actor实例如果创建失败则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Dropper")
AActor* CreatePickupActorInstance();
/**
* Calculates the origin point for dropping the item.
* 计算道具掉落的原点位置。
* @return The calculated drop origin as a vector. 掉落原点的向量。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Dropper")
FVector CalcDropOrigin() const;
/**
* Calculates a random offset to apply to the drop location.
* 计算应用于掉落位置的随机偏移量。
* @return The random offset vector. 随机偏移量向量。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Dropper")
FVector CalcDropOffset() const;
/**
* The class of the actor to spawn as the dropped item.
* 作为掉落物生成的Actor类。
* @attention Must implement the GIS_PickupActorInterface.
* @注意 必须实现GIS_PickupActorInterface接口。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(ExposeOnSpawn, MustImplement="/Script/GenericInventorySystem.GIS_PickupActorInterface"))
TSoftClassPtr<AActor> PickupActorClass;
/**
* Optional actor whose transform is used as the drop origin.
* 可选的Actor其变换用作掉落原点。
*/
UPROPERTY(EditInstanceOnly, BlueprintReadOnly, Category="Dropper")
TObjectPtr<AActor> DropTransform{nullptr};
/**
* The radius within which the item can be dropped.
* 道具掉落的半径。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(ExposeOnSpawn))
float DropRadius = 50.f;
};

View File

@@ -0,0 +1,51 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_DropperComponent.h"
#include "Items/GIS_ItemInfo.h"
#include "GIS_ItemDropperComponent.generated.h"
class UGIS_InventorySystemComponent;
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_ItemDropperComponent : public UGIS_DropperComponent
{
GENERATED_BODY()
public:
/**
* Get the item infos of this dropper will drops.
* 获取要掉落的道具信息。
*/
UFUNCTION(BlueprintCallable, Category="GIS|Dropper")
TArray<FGIS_ItemInfo> GetItemsToDrop() const;
virtual void Drop() override;
protected:
virtual void BeginPlay() override;
virtual TArray<FGIS_ItemInfo> GetItemsToDropInternal() const;
virtual void DropItemsInternal(const TArray<FGIS_ItemInfo>& ItemInfos);
virtual void DropInventoryPickup(const TArray<FGIS_ItemInfo>& ItemInfos);
virtual void DropItemPickup(const FGIS_ItemInfo& ItemInfo);
/**
* Target collection to drop.
* 指定要掉落库存中的哪个集合里的道具.
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(Categories="GIS.Collection"))
FGameplayTag CollectionTag;
/**
* If the drops is inventory pickup or item pickups?
* 指定以InventoryPickup的方式掉落还是以ItemPickup
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper")
bool bDropAsInventory{true};
};

View File

@@ -0,0 +1,55 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_ItemDropperComponent.h"
#include "GIS_RandomItemDropperComponent.generated.h"
/**
* Component for handling random item drop logic.
* 处理随机道具掉落逻辑的组件。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_RandomItemDropperComponent : public UGIS_ItemDropperComponent
{
GENERATED_BODY()
protected:
/**
* Retrieves the list of items to drop randomly.
* 随机获取要掉落的道具列表。
* @return Array of item information for dropped items. 掉落道具的信息数组。
*/
virtual TArray<FGIS_ItemInfo> GetItemsToDropInternal() const override;
/**
* Selects a random item from the provided list based on weights.
* 根据权重从提供的列表中随机选择一个道具。
* @param ItemInfos List of item information to choose from. 可选择的道具信息列表。
* @param Sum Total weight sum for randomization. 用于随机化的总权重和。
* @return Reference to the selected item information. 选中的道具信息的引用。
*/
const FGIS_ItemInfo& GetRandomItemInfo(const TArray<FGIS_ItemInfo>& ItemInfos, int32 Sum) const;
/**
* Determines if items are dropped randomly.
* 确定是否随机掉落道具。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(DisplayAfter="bDropAsInventory"))
bool bRandomDrop{false};
/**
* Minimum number of items to drop when random drop is enabled.
* 启用随机掉落时掉落的最小道具数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(EditCondition="bRandomDrop", ClampMin=1))
int32 MinAmount{1};
/**
* Maximum number of items to drop when random drop is enabled.
* 启用随机掉落时掉落的最大道具数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dropper", meta=(EditCondition="bRandomDrop", ClampMin=1))
int32 MaxAmount{2};
};

View File

@@ -0,0 +1,45 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "GIS_EquipmentActorInterface.generated.h"
class UGIS_EquipmentInstance;
// This class does not need to be modified.
UINTERFACE()
class UGIS_EquipmentActorInterface : public UInterface
{
GENERATED_BODY()
};
/**
*
*/
class GENERICINVENTORYSYSTEM_API IGIS_EquipmentActorInterface
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintNativeEvent, Category="GIS|EquipmentActor", meta=(BlueprintProtected))
void ReceiveSourceEquipment(UGIS_EquipmentInstance* NewEquipmentInstance, int32 Idx);
virtual void ReceiveSourceEquipment_Implementation(UGIS_EquipmentInstance* NewEquipmentInstance, int32 Idx);
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|EquipmentActor")
UGIS_EquipmentInstance* GetSourceEquipment() const;
virtual UGIS_EquipmentInstance* GetSourceEquipment_Implementation() const;
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "GIS|EquipmentActor")
UPrimitiveComponent* GetPrimitiveComponent() const;
virtual UPrimitiveComponent* GetPrimitiveComponent_Implementation() const;
UFUNCTION(BlueprintNativeEvent, Category="GIS|EquipmentActor", meta=(BlueprintProtected))
void ReceiveEquipmentBeginPlay();
virtual void ReceiveEquipmentBeginPlay_Implementation();
UFUNCTION(BlueprintNativeEvent, Category="GIS|EquipmentActor", meta=(BlueprintProtected))
void ReceiveEquipmentEndPlay();
virtual void ReceiveEquipmentEndPlay_Implementation();
};

View File

@@ -0,0 +1,247 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/TimerHandle.h"
#include "GIS_EquipmentInterface.h"
#include "GIS_EquipmentStructLibrary.h"
#include "GIS_EquipmentInstance.generated.h"
class UGIS_EquipmentSystemComponent;
class AActor;
class APawn;
struct FFrame;
/**
* Delegate triggered when the active state of the equipment instance changes.
* 当装备实例的激活状态改变时触发的委托。
* @param bNewState The new active state of the equipment. 装备的新激活状态。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_ActiveStateChangedSignature, bool, bNewState);
/**
* An equipment instance is a UObject tasked with managing the internal logic and runtime states of equipment.
* 装备实例是一个UObject负责管理装备的内部逻辑和运行时状态。
* @attention This is the default implementation of EquipmentInterface. You can use other types of classes as equipment.
* @注意 这是EquipmentInterface的默认实现你可以使用其他类作为装备实例。
*/
UCLASS(BlueprintType, Blueprintable)
class GENERICINVENTORYSYSTEM_API UGIS_EquipmentInstance : public UObject, public IGIS_EquipmentInterface
{
GENERATED_BODY()
public:
/**
* Constructor for the equipment instance.
* 装备实例的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_EquipmentInstance(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
//~UObject interface
/**
* Checks if the equipment instance supports networking.
* 检查装备实例是否支持网络。
* @return True if networking is supported, false otherwise. 如果支持网络则返回true否则返回false。
*/
virtual bool IsSupportedForNetworking() const override;
/**
* Gets the world this equipment instance belongs to.
* 获取装备实例所属的世界。
* @return The world, or nullptr if not set. 世界如果未设置则返回nullptr。
*/
virtual UWorld* GetWorld() const override final;
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
//~End of UObject interface
// Begin IGIS_EquipmentInterface interface
virtual APawn* GetOwningPawn_Implementation() const override;
virtual UGIS_ItemInstance* GetSourceItem_Implementation() const override;
virtual bool IsEquipmentActive_Implementation() const override;
//EndIGIS_EquipmentInterface interface
/**
* Gets the owning pawn cast to a specific type.
* 获取转换为特定类型的所属Pawn。
* @param PawnType The desired pawn class. 期望的Pawn类。
* @return The owning pawn cast to the specified type, or nullptr if not valid. 转换为指定类型的所属Pawn如果无效则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|EquipmentInstance", meta=(DeterminesOutputType=PawnType))
APawn* GetTypedOwningPawn(TSubclassOf<APawn> PawnType) const;
/**
* Determines if the equipment can be activated. Override in Blueprint for custom logic.
* 判断装备是否可以激活,可在蓝图中重写以实现自定义逻辑。
* @return True if the equipment can be activated, false otherwise. 如果装备可以激活则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, BlueprintNativeEvent, Category="GIS|EquipmentInstance")
bool CanActivate() const;
/**
* Gets all actors spawned by this equipment instance.
* 获取由此装备实例生成的所有Actor。
* @return Array of spawned actors. 生成的Actor数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|EquipmentInstance")
TArray<AActor*> GetEquipmentActors() const { return EquipmentActors; }
/**
* Get the index of specified equipment actor managed by this equipment instance.获取由此装备实例所管理的装备Actor的下标。
* @param InEquipmentActor The equipment actor of this equipment instance. 此装备实例的其中一个装备Actor。
* @return -1 if passed-in actor not created by this instance. 如果传入Actor不是该EquipmentInstance创建的。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|EquipmentInstance")
int32 GetIndexOfEquipmentActor(const AActor* InEquipmentActor) const;
/**
* Gets the first spawned actor matching the desired class (including subclasses).
* 获取第一个匹配指定类型包括子类的由装备实例生成的Actor。
* @param DesiredClass The desired actor class. 期望的Actor类。
* @return The matching actor, or nullptr if not found. 匹配的Actor如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|EquipmentInstance", meta=(DeterminesOutputType="DesiredClass", DynamicOutputParam="ReturnValue"))
AActor* GetTypedEquipmentActor(TSubclassOf<AActor> DesiredClass) const;
/**
* Event triggered when the active state of the equipment changes.
* 装备激活状态改变时触发的事件。
*/
UPROPERTY(BlueprintAssignable, Category="EquipmentInstance")
FGIS_ActiveStateChangedSignature OnActiveStateChangedEvent;
protected:
// Begin IGIS_EquipmentInterface interface
virtual void ReceiveOwningPawn_Implementation(APawn* NewPawn) override;
virtual void ReceiveSourceItem_Implementation(UGIS_ItemInstance* NewItem) override;
virtual void OnEquipmentBeginPlay_Implementation() override;
virtual void OnEquipmentTick_Implementation(float DeltaSeconds) override;
virtual void OnEquipmentEndPlay_Implementation() override;
virtual void OnActiveStateChanged_Implementation(bool NewActiveState) override;
//EndIGIS_EquipmentInterface interface
protected:
#if UE_WITH_IRIS
/**
* Registers replication fragments for networking (Iris-specific).
* 为网络注册复制片段特定于Iris
* @param Context The fragment registration context. 片段注册上下文。
* @param RegistrationFlags The registration flags. 注册标志。
*/
virtual void RegisterReplicationFragments(UE::Net::FFragmentRegistrationContext& Context, UE::Net::EFragmentRegistrationFlags RegistrationFlags) override;
#endif // UE_WITH_IRIS
/**
* Gets the scene component to which spawned actors will attach.
* 获取生成Actor将附加到的场景组件。
* @param Pawn The pawn owning this equipment instance. 拥有此装备实例的Pawn。
* @return The scene component to attach to, or nullptr if not applicable. 要附加到的场景组件如果不适用则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, BlueprintPure, Category="GIS|EquipmentInstance")
USceneComponent* GetAttachParentForSpawnedActors(APawn* Pawn) const;
#pragma region Equipment Actors
/**
* Spawns and sets up actors associated with this equipment instance.
* 生成并设置与此装备实例关联的Actor。
* @param ActorsToSpawn The actors to spawn. 要生成的Actor。
*/
virtual void SpawnAndSetupEquipmentActors(const TArray<FGIS_EquipmentActorToSpawn>& ActorsToSpawn);
/**
* Destroys all actors associated with this equipment instance.
* 销毁与此装备实例关联的所有Actor。
*/
virtual void DestroyEquipmentActors();
/**
* Called before an actor is spawned to allow additional setup.
* 在Actor生成前调用以允许额外设置。
* @param SpawningActor The actor about to be spawned. 即将生成的Actor。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|EquipmentInstance")
void BeforeSpawningActor(AActor* SpawningActor) const;
/**
* Sets up actors after they have been spawned.
* 在Actor生成后进行设置。
* @param InActors The spawned actors to configure. 已生成的Actor需进行配置。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|EquipmentInstance")
void SetupEquipmentActors(const TArray<AActor*>& InActors);
/**
* Implementation of SetupEquipmentActors.
* SetupEquipmentActors 的实现。
* @param InActors The spawned actors to configure. 已生成的Actor需进行配置。
*/
virtual void SetupEquipmentActors_Implementation(const TArray<AActor*>& InActors);
/**
* Called when the equipment actors are replicated.
* 装备Actor复制时调用。
*/
UFUNCTION()
void OnRep_EquipmentActors();
/**
* Checks if the specified number of equipment actors is valid.
* 检查指定数量的装备Actor是否有效。
* @param Num The number of actors to check. 要检查的Actor数量。
* @return True if the number of actors is valid, false otherwise. 如果Actor数量有效则返回true否则返回false。
*/
bool IsEquipmentActorsValid(int32 Num) const;
/**
* Propagates initial state to all equipment actors.
* 将初始状态传播到所有装备Actor。
* @param InActors The actors to set up. 要设置的Actor。
*/
virtual void SetupInitialStateForEquipmentActors(const TArray<AActor*>& InActors);
/**
* Propagates active state to all equipment actors.
* 将激活状态传播到所有装备Actor。
* @param InActors The actors to set up. 要设置的Actor。
*/
virtual void SetupActiveStateForEquipmentActors(const TArray<AActor*>& InActors) const;
#pragma endregion
protected:
/**
* The pawn that owns this equipment instance.
* 拥有此装备实例的Pawn。
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category="EquipmentInstance")
TObjectPtr<APawn> OwningPawn;
/**
* The source item associated with this equipment instance.
* 与此装备实例关联的源道具。
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category="EquipmentInstance")
TObjectPtr<UGIS_ItemInstance> SourceItem;
/**
* Indicates whether the equipment instance is currently active.
* 指示装备实例当前是否处于激活状态。
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category="EquipmentInstance")
bool bIsActive;
/**
* Array of actors spawned by this equipment instance.
* 由此装备实例生成的Actor数组。
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category="EquipmentInstance", ReplicatedUsing=OnRep_EquipmentActors)
TArray<TObjectPtr<AActor>> EquipmentActors;
};

View File

@@ -0,0 +1,119 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "GIS_EquipmentInterface.generated.h"
class UGIS_ItemInstance;
class Apawn;
/**
* Interface class for objects that can act as equipment instances (no modifications needed).
* 可作为装备实例的对象的接口类(无需修改)。
*/
UINTERFACE()
class UGIS_EquipmentInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for objects that wish to function as equipment instances.
* 希望用作装备实例的对象应实现的接口。
* @details Any object implementing this interface can be used as an equipment instance in the equipment system.
* @细节 实现此接口的任何对象都可在装备系统中用作装备实例。
*/
class GENERICINVENTORYSYSTEM_API IGIS_EquipmentInterface
{
GENERATED_BODY()
public:
/**
* Receives the pawn owning this equipment.
* 接收拥有此装备的Pawn。
* @param NewPawn The pawn with the equipment system component attached. 挂载了装备系统组件的Pawn。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void ReceiveOwningPawn(APawn* NewPawn);
virtual void ReceiveOwningPawn_Implementation(APawn* NewPawn);
/**
* Gets the pawn owning this equipment.
* 获取拥有此装备的Pawn。
* @return The owning pawn, or nullptr if none. 所属Pawn如果没有则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
APawn* GetOwningPawn() const;
virtual APawn* GetOwningPawn_Implementation() const;
/**
* Receives the source item from which the equipment was created.
* 接收创建此装备的源道具。
* @param NewItem The source item instance. 源道具实例。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void ReceiveSourceItem(UGIS_ItemInstance* NewItem);
virtual void ReceiveSourceItem_Implementation(UGIS_ItemInstance* NewItem);
/**
* Gets the source item from which the equipment was created.
* 获取创建此装备的源道具。
* @return The source item instance, or nullptr if none. 源道具实例如果没有则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
UGIS_ItemInstance* GetSourceItem() const;
virtual UGIS_ItemInstance* GetSourceItem_Implementation() const;
/**
* Called after the equipment is added to the equipment system's equipment list.
* 在装备被添加到装备系统的装备列表后调用。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void OnEquipmentBeginPlay();
virtual void OnEquipmentBeginPlay_Implementation();
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void OnEquipmentTick(float DeltaSeconds);
virtual void OnOnEquipmentTick_Implementation(float DeltaSeconds);
/**
* Called before the equipment is removed from the equipment system's equipment list.
* 在从装备系统的装备列表移除装备之前调用。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void OnEquipmentEndPlay();
virtual void OnEquipmentEndPlay_Implementation();
/**
* Responds to changes in the equipment's active state.
* 响应装备激活状态的变化。
* @param bNewActiveState The new active state of the equipment. 装备的新激活状态。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
void OnActiveStateChanged(bool bNewActiveState);
virtual void OnActiveStateChanged_Implementation(bool bNewActiveState);
/**
* Checks if the equipment is active.
* 检查装备是否处于激活状态。
* @return True if the equipment is active, false otherwise. 如果装备处于激活状态则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
bool IsEquipmentActive() const;
virtual bool IsEquipmentActive_Implementation() const;
/**
* Checks if the equipment instance's replication is managed by the equipment system.
* 检查装备实例的复制是否由装备系统管理。
* @details By default, the equipment system manages only GIS_EquipmentInstance and its subclasses.
* @细节 默认情况下装备系统仅管理GIS_EquipmentInstance及其子类。
* @attention Do not override this method unless you fully understand its implications.
* @注意 除非完全了解其影响,否则不要覆写此方法。
* @return True if replication is managed by the equipment system, false otherwise. 如果复制由装备系统管理则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|Equipment")
bool IsReplicationManaged();
virtual bool IsReplicationManaged_Implementation();
};

View File

@@ -0,0 +1,270 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Object.h"
#include "GIS_EquipmentStructLibrary.generated.h"
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_EquipmentActorToSpawn
{
GENERATED_BODY()
FGIS_EquipmentActorToSpawn()
{
}
/**
* Actor class must implements GIS_EquipmentActorInterface!
*/
UPROPERTY(EditAnywhere, BlueprintReadonly, Category = Equipment, meta=(MustImplement="/Script/GenericInventorySystem.GIS_EquipmentActorInterface"))
TSoftClassPtr<AActor> ActorToSpawn;
/**
* If the spawned actor will attach to equipment owner?
*/
UPROPERTY(EditAnywhere, Category = Equipment)
bool bShouldAttach{true};
/**
* The socket to attach to.
*/
UPROPERTY(EditAnywhere, Category = Equipment, meta = (EditCondition = "bShouldAttach", EditConditionHides))
FName AttachSocket;
/**
* The relative transform to attach to.
*/
UPROPERTY(EditAnywhere, Category = Equipment, meta = (EditCondition = "bShouldAttach", EditConditionHides))
FTransform AttachTransform;
};
class UGIS_ItemInstance;
class UGIS_EquipmentInstance;
class UGIS_EquipItemInstance;
class UGIS_ItemDefinition;
class UGIS_EquipmentSystemComponent;
struct FGIS_EquipmentContainer;
/**
* Structure representing an equipment entry in the container.
* 表示容器中装备条目的结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_EquipmentEntry : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* Default constructor for equipment entry.
* 装备条目的默认构造函数。
*/
FGIS_EquipmentEntry()
{
}
/**
* Gets a debug string representation of the equipment entry.
* 获取装备条目的调试字符串表示。
* @return The debug string. 调试字符串。
*/
FString GetDebugString() const;
private:
friend FGIS_EquipmentContainer;
friend UGIS_EquipmentSystemComponent;
/**
* The equipment instance.
* 装备实例。
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment", meta = (ShowInnerProperties))
TObjectPtr<UObject> Instance = nullptr;
/**
* The item instance associated with this equipment.
* 与此装备关联的道具实例。
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment")
TObjectPtr<UGIS_ItemInstance> ItemInstance{nullptr};
/**
* The slot where the equipment is equipped.
* 装备所在的装备槽。
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment")
FGameplayTag EquippedSlot;
/**
* Which group the equipment belongs to.
* 此装备属于哪个组?
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment")
FGameplayTag EquippedGroup;
/**
* Indicates whether the equipment is active.
* 指示装备是否处于激活状态。
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment")
bool bActive{false};
/**
* Previous active state (not replicated).
* 上一个激活状态(不复制)。
*/
UPROPERTY(VisibleAnywhere, Category = "Equipment", NotReplicated)
bool bPrevActive = false;
UPROPERTY(VisibleAnywhere, Category = "Equipment", NotReplicated)
FGameplayTag PrevEquippedGroup;
bool CheckClientDataReady() const;
/**
* Checks if the equipment entry is valid.
* 检查装备条目是否有效。
* @return True if the entry is valid, false otherwise. 如果条目有效则返回true否则返回false。
*/
bool IsValidEntry() const;
};
/**
* Container for a list of applied equipment.
* 存储已应用装备列表的容器。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_EquipmentContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for equipment container.
* 装备容器的默认构造函数。
*/
FGIS_EquipmentContainer()
: OwningComponent(nullptr)
{
}
/**
* Constructor for equipment container with an owning component.
* 使用所属组件构造装备容器。
* @param InComponent The owning equipment system component. 所属的装备系统组件。
*/
FGIS_EquipmentContainer(UGIS_EquipmentSystemComponent* InComponent)
: OwningComponent(InComponent)
{
}
//~FFastArraySerializer contract
/**
* Called before equipment entries are removed during replication.
* 复制期间在移除装备条目前调用。
* @param RemovedIndices The indices of removed entries. 移除条目的索引。
* @param FinalSize The final size of the array after removal. 移除后数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after equipment entries are added during replication.
* 复制期间在添加装备条目后调用。
* @param AddedIndices The indices of added entries. 添加条目的索引。
* @param FinalSize The final size of the array after addition. 添加后数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after equipment entries are changed during replication.
* 复制期间在装备条目更改后调用。
* @param ChangedIndices The indices of changed entries. 更改条目的索引。
* @param FinalSize The final size of the array after changes. 更改后数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for the equipment container.
* 处理装备容器的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_EquipmentEntry, FGIS_EquipmentContainer>(Entries, DeltaParms, *this);
}
int32 IndexOfBySlot(const FGameplayTag& Slot) const;
//check if any equipment's group matches this group.
int32 IndexOfByGroup(const FGameplayTag& Group) const;
int32 IndexOfByInstance(const UObject* Instance) const;
int32 IndexOfByItem(const UGIS_ItemInstance* Item) const;
int32 IndexOfByItemId(const FGuid& ItemId) const;
/**
* Replicated list of equipment entries.
* 复制的装备条目列表。
*/
UPROPERTY(VisibleAnywhere, Category = "EquipmentSystem", meta = (ShowOnlyInnerProperties, DisplayName = "Equipments"))
TArray<FGIS_EquipmentEntry> Entries;
/**
* The equipment system component that owns this container.
* 拥有此容器的装备系统组件。
*/
UPROPERTY()
TObjectPtr<UGIS_EquipmentSystemComponent> OwningComponent;
};
/**
* Template specialization to enable network delta serialization for the equipment container.
* 为装备容器启用网络增量序列化的模板特化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_EquipmentContainer> : TStructOpsTypeTraitsBase2<FGIS_EquipmentContainer>
{
enum
{
WithNetDeltaSerializer = true
};
};
/**
* Structure representing a group active index entry.
* 表示组激活索引条目的结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_EquipmentGroupEntry : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* The group tag.
* 组标签。
*/
UPROPERTY(VisibleAnywhere, Category = "EquipmentGroup")
FGameplayTag GroupTag;
/**
* The active slot within the group.
* 组内的激活槽位。
*/
UPROPERTY(VisibleAnywhere, Category = "EquipmentGroup")
FGameplayTag ActiveSlot;
UPROPERTY(NotReplicated)
FGameplayTag LastSlot;
/**
* Checks if the entry is valid.
* 检查条目是否有效。
*/
bool IsValid() const { return GroupTag.IsValid(); }
};

View File

@@ -0,0 +1,753 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_EquipmentStructLibrary.h"
#include "GIS_InventoryMeesages.h"
#include "Items/GIS_ItemInfo.h"
#include "Components/PawnComponent.h"
#include "GIS_EquipmentSystemComponent.generated.h"
class UGIS_ItemSlotCollectionDefinition;
class UGIS_InventorySystemComponent;
class UGIS_EquipmentInstance;
class UGIS_ItemSlotCollection;
class UGIS_EquipItemInstance;
/**
* Delegate triggered when the equipment system is initialized.
* 装备系统初始化时触发的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FGIS_Equipment_InitializedSignature);
/**
* Delegate triggered when an equipment's state changes (equipped or unequipped).
* 装备状态更改(装备或卸下)时触发的委托。
* @param Equipment The equipment instance. 装备实例。
* @param SlotTag The slot tag associated with the equipment. 与装备关联的槽标签。
* @param bEquipped Whether the equipment is equipped. 装备是否已装备。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_Equipment_StateChangedSignature, UObject *, Equipment, FGameplayTag, SlotTag, bool, bEquipped);
/**
* Delegate triggered when an equipment's active state changes.
* 装备激活状态更改时触发的委托。
* @param Equipment The equipment instance. 装备实例。
* @param SlotTag The slot tag associated with the equipment. 与装备关联的槽标签。
* @param bActive Whether the equipment is active. 装备是否激活。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_Equipment_ActiveStateChangedSignature, UObject *, Equipment, FGameplayTag, SlotTag, bool, bActive);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_Equipment_GroupStateChangedSignature, UObject *, Equipment, FGameplayTag, SlotTag, FGameplayTag, GroupTag);
/**
* Dynamic delegate for equipment system initialization events.
* 装备系统初始化事件的动态委托。
*/
UDELEGATE()
DECLARE_DYNAMIC_DELEGATE(FGIS_EquipmentSystem_Initialized_DynamicEvent);
/**
* Manager of equipment instances for a pawn.
* 管理棋子装备实例的组件。
*/
UCLASS(ClassGroup = (GIS), meta = (BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_EquipmentSystemComponent : public UPawnComponent
{
GENERATED_BODY()
friend FGIS_EquipmentContainer;
friend FGIS_EquipmentEntry;
public:
/**
* Sets default values for this component's properties.
* 为组件的属性设置默认值。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_EquipmentSystemComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
//~UObject interface
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Replicates subobjects for this component.
* 为此组件复制子对象。
* @param Channel The actor channel. 演员通道。
* @param Bunch The replication data bunch. 复制数据束。
* @param RepFlags The replication flags. 复制标志。
* @return True if subobjects were replicated, false otherwise. 如果子对象被复制则返回true否则返回false。
*/
virtual bool ReplicateSubobjects(class UActorChannel* Channel, class FOutBunch* Bunch, FReplicationFlags* RepFlags) override;
//~End of UObject interface
//~UActorComponent interface
/**
* Called when the component is registered.
* 组件注册时调用。
*/
virtual void OnRegister() override;
/**
* Initializes the component.
* 初始化组件。
*/
virtual void InitializeComponent() override;
/**
* Prepares the component for replication.
* 为组件的复制做准备。
*/
virtual void ReadyForReplication() override;
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* Updates the component each frame.
* 每帧更新组件。
* @param DeltaTime Time since the last tick. 上次tick以来的时间。
* @param TickType The type of tick. tick类型。
* @param ThisTickFunction The tick function. tick函数。
*/
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
/**
* Uninitializes the component.
* 取消初始化组件。
*/
virtual void UninitializeComponent() override;
/**
* Called when the game ends.
* 游戏结束时调用。
* @param EndPlayReason The reason the game ended. 游戏结束的原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
//~End of UActorComponent interface
#pragma region Equipment System
/**
* Gets the equipment system component from the specified actor.
* 从指定演员获取装备系统组件。
* @param Actor The actor to query. 要查询的演员。
* @return The equipment system component, or nullptr if not found. 装备系统组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem", Meta = (DefaultToSelf = "Actor"))
static UGIS_EquipmentSystemComponent* GetEquipmentSystemComponent(const AActor* Actor);
/**
* Finds the equipment system component on the specified actor.
* 在指定演员上查找装备系统组件。
* @param Actor The actor to search for the component. 要查找组件的演员。
* @param Component The found equipment system component (output). 找到的装备系统组件(输出)。
* @return True if the component was found, false otherwise. 如果找到组件则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem", Meta = (DefaultToSelf = "Actor", ExpandBoolAsExecs = "ReturnValue"))
static bool FindEquipmentSystemComponent(const AActor* Actor, UGIS_EquipmentSystemComponent*& Component);
/**
* Finds a typed equipment system component on the specified actor.
* 在指定演员上查找类型化的装备系统组件。
* @param Actor The actor to search for the component. 要查找组件的演员。
* @param DesiredClass The desired class of the component. 组件的期望类。
* @param Component The found equipment system component (output). 找到的装备系统组件(输出)。
* @return True if the component was found, false otherwise. 如果找到组件则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem",
meta = (DefaultToSelf = "Actor", DynamicOutputParam = "Component", DeterminesOutputType = "DesiredClass", ExpandBoolAsExecs = "ReturnValue"))
static bool FindTypedEquipmentSystemComponent(AActor* Actor, TSubclassOf<UGIS_EquipmentSystemComponent> DesiredClass, UGIS_EquipmentSystemComponent*& Component);
/**
* Initializes the equipment system.
* 初始化装备系统。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void InitializeEquipmentSystem();
/**
* Initializes the equipment system with a specified inventory system.
* 使用指定的库存系统初始化装备系统。
* @param InventorySystem The inventory system to associate with. 要关联的库存系统。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void InitializeEquipmentSystemWithInventory(UGIS_InventorySystemComponent* InventorySystem);
/**
* Resets the equipment system.
* 重置装备系统。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void ResetEquipmentSystem();
/**
* Gets the target collection tag for equipment monitoring.
* 获取用于装备监控的目标集合标签。
* @return The target collection tag. 目标集合标签。
*/
FGameplayTag GetTargetCollectionTag() const { return TargetCollectionTag; };
/**
* Checks if the equipment system is initialized.
* 检查装备系统是否已初始化。
* @return True if initialized, false otherwise. 如果已初始化则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|InventorySystem")
bool IsEquipmentSystemInitialized() const;
/**
* Binds a delegate to be called when the equipment system is initialized.
* 绑定一个委托,在装备系统初始化时调用。
* @param Delegate The delegate to bind. 要绑定的委托。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|InventorySystem")
void BindToEquipmentSystemInitialized(FGIS_EquipmentSystem_Initialized_DynamicEvent Delegate);
/**
* Removes all equipment instances from the system.
* 从系统中移除所有装备实例。
*/
virtual void RemoveAllEquipments();
/**
* Equips an item to a specific slot.
* 将道具装备到指定槽。
* @param Item The item instance to equip. 要装备的道具实例。
* @param SlotTag The slot tag to equip the item to. 装备道具的槽标签。
*/
virtual void EquipItemToSlot(UGIS_ItemInstance* Item, const FGameplayTag& SlotTag);
/**
* Unequips an item from a specific slot.
* 从指定槽卸下装备。
* @param SlotTag The slot tag to unequip. 要卸下的槽标签。
*/
virtual void UnequipBySlot(FGameplayTag SlotTag);
/**
* Unequips an item by its ID.
* 通过道具ID卸下装备。
* @param ItemId The ID of the item to unequip. 要卸下的道具ID。
*/
virtual void UnequipByItem(const FGuid& ItemId);
/**
* Checks if the owning actor has authority.
* 检查拥有者演员是否具有权限。
* @return True if the owner has authority, false otherwise. 如果拥有者有权限则返回true否则返回false。
*/
bool OwnerHasAuthority() const;
protected:
/**
* Called when the target collection's item stacks change.
* 目标集合的道具堆栈更改时调用。
* @param Message The update message containing stack details. 包含堆栈详细信息的更新消息。
*/
UFUNCTION()
virtual void OnTargetCollectionChanged(const FGIS_InventoryStackUpdateMessage& Message);
/**
* Called when the target collection is removed.
* 目标集合移除时调用。
* @param Collection The removed collection. 移除的集合。
*/
UFUNCTION()
virtual void OnTargetCollectionRemoved(UGIS_ItemCollection* Collection);
/**
* Called when the equipment system is initialized.
* 装备系统初始化时调用。
*/
UFUNCTION(BlueprintNativeEvent, Category = "GIS|EquipmentSystem")
void OnEquipmentSystemInitialized();
/**
* List of delegates for equipment system initialization.
* 装备系统初始化的委托列表。
*/
UPROPERTY()
TArray<FGIS_EquipmentSystem_Initialized_DynamicEvent> InitializedDelegates;
#pragma endregion
#pragma region Equipments Query
public:
/**
* Gets all equipment instances matching the specified conditions.
* 获取匹配指定条件的所有装备实例。
* @param InstanceType The type of equipment instance to query. 要查询的装备实例类型。
* @param SlotQuery The gameplay tag query for slots. 槽的游戏标签查询。
* @return Array of matching equipment instances, or empty if none found. 匹配的装备实例数组,如果未找到则返回空。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem", meta = (DeterminesOutputType = InstanceType, DynamicOutputParam = ReturnValue))
TArray<UObject*> GetEquipments(UPARAM(meta = (MustImplement = "/Script/GenericInventorySystem.GIS_EquipmentInterface", AllowAbstract = "false"))
TSubclassOf<UObject>
InstanceType,
UPARAM(meta=(Categories="GIS.Slots")) FGameplayTagQuery SlotQuery) const;
/**
* Gets all active equipment instances matching the specified conditions.
* 获取匹配指定条件的激活装备实例。
* @param InstanceType The type of equipment instance to query. 要查询的装备实例类型。
* @param SlotQuery The gameplay tag query for slots. 槽的游戏标签查询。
* @return Array of active equipment instances, or empty if none found. 激活的装备实例数组,如果未找到则返回空。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem",
meta = (DeterminesOutputType = InstanceType, DynamicOutputParam = ReturnValue))
TArray<UObject*> GetActiveEquipments(UPARAM(meta = (MustImplement = "/Script/GenericInventorySystem.GIS_EquipmentInterface", AllowAbstract = "false"))
TSubclassOf<UObject>
InstanceType,
UPARAM(meta=(Categories="GIS.Slots")) FGameplayTagQuery SlotQuery) const;
/**
* Gets the first equipment instance matching the specified query.
* 获取匹配指定查询的第一个装备实例。
* @param InstanceType The type of equipment instance to query. 要查询的装备实例类型。
* @param SlotQuery The gameplay tag query for slots. 槽的游戏标签查询。
* @return The first matching equipment instance, or nullptr if none found. 第一个匹配的装备实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem", meta = (DeterminesOutputType = InstanceType, DynamicOutputParam = ReturnValue))
UObject* GetEquipment(UPARAM(meta = (MustImplement = "/Script/GenericInventorySystem.GIS_EquipmentInterface", AllowAbstract = "false"))
TSubclassOf<UObject>
InstanceType,
UPARAM(meta=(Categories="GIS.Slots")) FGameplayTagQuery SlotQuery) const;
/**
* Gets the first active equipment instance matching the specified query.
* 获取匹配指定查询的第一个激活装备实例。
* @param InstanceType The type of equipment instance to query. 要查询的装备实例类型。
* @param SlotQuery The gameplay tag query for slots. 槽的游戏标签查询。
* @return The first active equipment instance, or nullptr if none found. 第一个激活的装备实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem", meta = (DeterminesOutputType = InstanceType, DynamicOutputParam = ReturnValue))
UObject* GetActiveEquipment(UPARAM(meta = (MustImplement = "/Script/GenericInventorySystem.GIS_EquipmentInterface", AllowAbstract = "false"))
TSubclassOf<UObject>
InstanceType,
UPARAM(meta=(Categories="GIS.Slots")) FGameplayTagQuery SlotQuery) const;
/**
* Gets the active equipment within specified equipment group.
* 获取指定组中的激活装备。
* @param GroupTag The equipment group to look for. 要查询的装备组。
* @param bExactMatch If true, the group tag has to be exactly present. 如果为真,对组标签进行绝对匹配。
* @return active equipment in group. 组中激活的装备。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem")
UObject* GetActiveEquipmentInGroup(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag, bool bExactMatch = true) const;
/**
* Gets the equipment instance that spawned the specified equipment actor.
* 获取生成指定装备演员的装备实例。
* @param EquipmentActor The equipment actor to query. 要查询的装备演员。
* @return The equipment instance, or nullptr if not found. 装备实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem", meta = (DefaultToSelf = "EquipmentActor"))
UGIS_EquipmentInstance* GetEquipmentInstanceOfActor(AActor* EquipmentActor) const;
/**
* Gets the typed equipment instance that spawned the specified equipment actor.
* 获取生成指定装备演员的类型化装备实例。
* @param InstanceType The desired type of equipment instance. 期望的装备实例类型。
* @param EquipmentActor The equipment actor to query. 要查询的装备演员。
* @return The typed equipment instance, or nullptr if not found. 类型化的装备实例如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "GIS|EquipmentSystem",
meta = (DefaultToSelf = "EquipmentActor", DeterminesOutputType = InstanceType, DynamicOutputParam = ReturnValue))
UGIS_EquipmentInstance* GetTypedEquipmentInstanceOfActor(TSubclassOf<UGIS_EquipmentInstance> InstanceType, AActor* EquipmentActor) const;
/**
* Gets the equipment instance in a specific slot.
* 获取特定槽中的装备实例。
* @param SlotTag The slot tag to query. 要查询的槽标签。
* @return The equipment instance in the slot, or nullptr if none. 槽中的装备实例如果没有则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
UObject* GetEquipmentInSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag SlotTag) const;
/**
* Gets the equipment instance associated with a specific item instance.
* 获取与特定道具实例关联的装备实例。
* @param Item The item instance to query. 要查询的道具实例。
* @return The equipment instance, or nullptr if none. 装备实例如果没有则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
UObject* GetEquipmentByItem(const UGIS_ItemInstance* Item);
#pragma endregion
#pragma region Equipments Activation/Deactivation
/**
* Sets the active state of equipment in a specific slot.
* 设置特定槽中装备的激活状态。
* @param SlotTag The slot tag of the equipment. 装备的槽标签。
* @param NewActiveState The new active state. 新的激活状态。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void SetEquipmentActiveState(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag SlotTag, bool NewActiveState);
/**
* Server-side function to set the active state of an equipment in a specific slot.
* 服务器端函数,设置特定槽中装备的激活状态。
* @param SlotTag The slot tag of the equipment. 装备的槽标签。
* @param NewActiveState The new active state. 新的激活状态。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
void ServerSetEquipmentActiveState(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag SlotTag, bool NewActiveState);
virtual void ServerSetEquipmentActiveState_Implementation(FGameplayTag SlotTag, bool NewActiveState);
protected:
/**
* Directly update the active state and group state for equipment entry at Idx.
* 直接设置装备的激活状态和分组。
* @param Idx The index of the equipment entry. 装备条目索引。
* @param NewActiveState The new active state. 新的激活状态。
* @param NewGroup The new group state. 新的组状态。
*
*/
virtual void UpdateEquipmentState(int32 Idx, bool NewActiveState, FGameplayTag NewGroup);
#pragma endregion
#pragma region Events
public:
/**
* Event triggered when the equipment system is initialized.
* 装备系统初始化时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Equipment_InitializedSignature OnEquipmentSystemInitializedEvent;
/**
* Event triggered when an equipment's state changes.
* 装备状态更改时触发的事件。
* @attention Called after equipping, before unequipping.
* @attention 在装备后、卸下前调用。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Equipment_StateChangedSignature OnEquipmentStateChangedEvent;
/**
* Event triggered when an equipment's active state changes.
* 装备激活状态更改时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Equipment_ActiveStateChangedSignature OnEquipmentActiveStateChangedEvent;
UPROPERTY(BlueprintAssignable)
FGIS_Equipment_GroupStateChangedSignature OnEquipmentGroupStateChangedEvent;
#pragma endregion
#pragma region Slot Query
/**
* Checks if a specific slot is equipped.
* 检查特定槽是否已装备。
* @param SlotTag The slot tag to check. 要检查的槽标签。
* @return True if the slot is equipped, false otherwise. 如果槽已装备则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
bool IsSlotEquipped(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag SlotTag) const;
/**
* Gets the slot where the equipment instance was equipped to.
* 获取特定装备实例所装备的位置。
* @param Equipment The equipment to look for. 与要查询装备实例。
* @return Invalid slot if not found. 如果没查到则返回无效标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
FGameplayTag GetSlotByEquipment(UObject* Equipment) const;
/**
* Gets the slot where the equipment instance associated with a specific item instance was equipped to.
* 获取与特定物品实例关联的装备实例所装备的位置。
* @param Item The item instance which the equipment instance was associated with. 与要查询装备实例关联的道具实例。
* @return Invalid slot if not found. 如果没查到则返回无效标签。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
FGameplayTag GetSlotByItem(const UGIS_ItemInstance* Item) const;
/**
* Converts a slot tag to the corresponding equipment entry index.
* 将槽标签转换为对应的装备条目索引。
* @param InSlotTag The slot tag to convert. 要转换的槽标签。
* @return The equipment entry index, or INDEX_NONE if not found. 装备条目索引如果未找到则返回INDEX_NONE。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
int32 SlotTagToEquipmentInex(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag InSlotTag) const;
/**
* Converts an item ID to the corresponding equipment entry index.
* 将道具ID转换为对应的装备条目索引。
* @param InItemId The item ID to convert. 要转换的道具ID。
* @return The equipment entry index, or INDEX_NONE if not found. 装备条目索引如果未找到则返回INDEX_NONE。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category = "GIS|EquipmentSystem")
int32 ItemIdToEquipmentInex(FGuid InItemId) const;
#pragma endregion
#pragma region Equipment Entries
protected:
/**
* Adds an equipment entry to the system.
* 将装备条目添加到系统中。
* @param NewEntry The new equipment entry to add. 要添加的新装备条目。
*/
virtual void AddEquipmentEntry(const FGIS_EquipmentEntry& NewEntry);
/**
* Ticks all the equipment instances in this container.
* 更新所有装备实例。
* @param DeltaTime The time between frames. 每帧的间隔时间(秒)
*/
virtual void TickEquipmentEntries(float DeltaTime);
/**
* Removes an equipment entry by its index.
* 通过索引移除装备条目。
* @param Idx The index of the equipment entry to remove. 要移除的装备条目索引。
*/
virtual void RemoveEquipmentEntry(int32 Idx);
/**
* Creates an equipment instance for the specified item.
* 为指定道具创建装备实例。
* @attention The returned instance must implement GIS_EquipmentInterface.
* @attention 返回的实例必须实现GIS_EquipmentInterface。
* @param Owner The owning actor of the created equipment instance. 创建的装备实例的所属演员。
* @param ItemInstance The item instance containing equipment-related data. 包含装备相关数据的道具实例。
* @return The created equipment instance (UObject or AActor based on design). 创建的装备实例根据设计为UObject或AActor
*/
UFUNCTION(BlueprintNativeEvent, Category = "GIS|EquipmentSystem")
UObject* CreateEquipmentInstance(AActor* Owner, UGIS_ItemInstance* ItemInstance) const;
/**
* Called when an equipment entry is added.
* 装备条目添加时调用。
* @param Entry The added equipment entry. 添加的装备条目。
* @param Idx The index of the added entry. 添加条目的索引。
*/
virtual void OnEquipmentEntryAdded(const FGIS_EquipmentEntry& Entry, int32 Idx);
/**
* Called when an equipment entry is changed.
* 装备条目更改时调用。
* @param Entry The changed equipment entry. 更改的装备条目。
* @param Idx The index of the changed entry. 更改条目的索引。
*/
virtual void OnEquipmentEntryChanged(const FGIS_EquipmentEntry& Entry, int32 Idx);
/**
* Called when an equipment entry is removed.
* 装备条目移除时调用。
* @param Entry The removed equipment entry. 移除的装备条目。
* @param Idx The index of the removed entry. 移除条目的索引。
*/
virtual void OnEquipmentEntryRemoved(const FGIS_EquipmentEntry& Entry, int32 Idx);
/**
* Adds a replicated equipment object to the system.
* 将复制的装备对象添加到系统中。
* @param Instance The equipment instance to add. 要添加的装备实例。
*/
virtual void AddReplicatedEquipmentObject(TObjectPtr<UObject> Instance);
/**
* Removes a replicated equipment object from the system.
* 从系统中移除复制的装备对象。
* @param Instance The equipment instance to remove. 要移除的装备实例。
*/
virtual void RemoveReplicatedEquipmentObject(TObjectPtr<UObject> Instance);
/**
* Processes pending equipment entries.
* 处理待处理的装备条目。
*/
virtual void ProcessPendingEquipments();
/**
* List of pending replicated equipment objects.
* 待复制的装备对象列表。
*/
TArray<TObjectPtr<UObject>> PendingReplicatedEquipments;
/**
* Map of pending equipment entries.
* 待处理装备条目的映射。
*/
TMap<int32, FGIS_EquipmentEntry> PendingEquipmentEntries;
#pragma endregion
#pragma region Equipment Groups
public:
/**
* Gets the layout of an equipment group.
* 获取装备组的布局。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @return Map of indices to slot tags in the group. 组内索引到槽标签的映射。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual TMap<int32, FGameplayTag> GetLayoutOfGroup(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag) const;
/**
* Gets the layout of an equipment group.
* 获取装备组的布局。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @return Map of indices to slot tags in the group. 组内索引到槽标签的映射。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual TMap<FGameplayTag, int32> GetSlottedLayoutOfGroup(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag) const;
/**
* Get the matching equipment group tag for equipment slot. 获取装备槽所在的装备组。
* @param SlotTag The equipment slot to check. 要检查的装备槽。
* @return The equipment group tag, none if not groupped. 装备组标签如果没有组返回None
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem")
FGameplayTag FindMatchingGroupForSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag SlotTag) const;
/**
* Gets all equipment instances in an equipment group.
* 获取装备组中的所有装备实例。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @return Map of indices to equipment instances in the group. 组内索引到装备实例的映射。
*/
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual TMap<int32, UObject*> GetEquipmentsOfGroup(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag) const;
UFUNCTION(BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual TMap<FGameplayTag, UObject*> GetSlottedEquipmentsOfGroup(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag) const;
/**
* Sets the active slot within an equipment group.
* 设置装备组中的激活槽。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @param NewSlot The new active slot. 新的激活槽。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void SetGroupActiveSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag, FGameplayTag NewSlot);
/**
* Server-side function to set the active slot within an equipment group.
* 服务器端函数,设置装备组中的激活槽位。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @param NewSlot The new active slot. 新的激活槽位。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual void ServerSetGroupActiveSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag, FGameplayTag NewSlot);
/**
* Cycles the active index within an equipment group in the specified direction.
* 按指定方向在装备组中循环激活索引。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @param bDirection The cycle direction (true for right, false for left). 循环方向true为右false为左
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "GIS|EquipmentSystem")
virtual void CycleGroupActiveSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag, bool bDirection = true);
virtual FGameplayTag CycleGroupNextSlot(FGameplayTag GroupTag, FGameplayTag PrevSlot, bool bDirection = true);
/**
* Server-side function to cycle the active slot within an equipment group.
* 服务器端函数,按指定方向在装备组中循环激活槽位。
* @param GroupTag The tag of the equipment group. 装备组的标签。
* @param bDirection The cycle direction (true for right, false for left). 循环方向true为右false为左
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category = "GIS|EquipmentSystem")
virtual void ServerCycleGroupActiveSlot(UPARAM(meta=(Categories="GIS.Slots")) FGameplayTag GroupTag, bool bDirection = true);
protected:
#pragma endregion
#pragma region Properties
/**
* Whether to initialize the equipment system automatically on BeginPlay.
* 是否在BeginPlay时自动初始化装备系统。
*/
UPROPERTY(EditDefaultsOnly, Category = "EquipmentSystem")
bool bInitializeOnBeginPlay = false;
/**
* Indicates if the equipment system is initialized.
* 指示装备系统是否已初始化。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "EquipmentSystem", ReplicatedUsing = OnEquipmentSystemInitialized)
bool bEquipmentSystemInitialized = false;
/**
* The target collection tag for monitoring equipment-related items.
* 用于监控装备相关道具的目标集合标签。
* @attention Monitors the specified item slot collection in the actor's inventory and generates/removes equipment instances based on changes.
* @attention 监听同一演员库存中的指定道具槽集合,并根据变化生成/移除装备实例。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "EquipmentSystem", meta = (AllowPrivateAccess = True, Categories = "GIS.Collection"))
FGameplayTag TargetCollectionTag;
/**
* Container for the equipment entries.
* 装备条目的容器。
*/
UPROPERTY(VisibleInstanceOnly, Category = "EquipmentSystem", Replicated, meta = (ShowOnlyInnerProperties))
FGIS_EquipmentContainer Container;
/**
* The definition of the target collection where equipment groups are defined.
* 定义装备组的目标集合定义。
*/
UPROPERTY(VisibleInstanceOnly, Category = "EquipmentSystem", Replicated)
TObjectPtr<const UGIS_ItemSlotCollectionDefinition> TargetCollectionDefinition;
// /**
// * Container for group active indices.
// * 组激活索引的容器。
// */
// UPROPERTY(VisibleInstanceOnly, Category = "EquipmentSystem", Replicated, meta = (ShowOnlyInnerProperties))
// FGIS_EquipmentGroupContainer GroupActiveIndexContainer;
/**
* Track which slot was equipped to which group.
*/
UPROPERTY(VisibleInstanceOnly, Category = "EquipmentSystem")
TMap<FGameplayTag, FGameplayTag> GroupActiveSlots;
/**
* The associated inventory system component.
* 关联的库存系统组件。
*/
UPROPERTY()
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The target item slot collection.
* 目标道具槽集合。
*/
UPROPERTY()
TObjectPtr<UGIS_ItemSlotCollection> TargetCollection;
/**
* Mapping of slot tags to equipment entry indices.
* 槽标签到装备条目索引的映射。
*/
UPROPERTY(VisibleInstanceOnly, Category = "EquipmentSystem", meta = (ForceInlineRow), Transient)
TMap<FGameplayTag, TObjectPtr<UObject>> SlotToInstanceMap;
#pragma endregion
};

View File

@@ -0,0 +1,105 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "GameplayTagContainer.h"
#include "GIS_CurrencyEntry.h"
#include "GIS_CurrencyContainer.generated.h"
class UGIS_CurrencySystemComponent;
class UGIS_CurrencyDefinition;
struct FGIS_CurrencyContainer;
/**
* Container for storing currency entries.
* 用于存储货币条目的容器。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_CurrencyContainer : public FFastArraySerializer
{
GENERATED_BODY()
/**
* Default constructor for the currency container.
* 货币容器的默认构造函数。
*/
FGIS_CurrencyContainer()
{
};
/**
* Constructor for the currency container with an owning component.
* 使用拥有组件构造货币容器。
* @param InOwner The owning currency system component. 拥有此容器的货币系统组件。
*/
FGIS_CurrencyContainer(UGIS_CurrencySystemComponent* InOwner)
: OwningComponent(InOwner)
{
}
//~FFastArraySerializer contract
/**
* Called before entries are removed during replication.
* 复制期间移除条目前调用。
* @param RemovedIndices The indices of entries to remove. 要移除的条目索引。
* @param FinalSize The final size of the entries array after removal. 移除后条目数组的最终大小。
*/
void PreReplicatedRemove(const TArrayView<int32> RemovedIndices, int32 FinalSize);
/**
* Called after entries are added during replication.
* 复制期间添加条目后调用。
* @param AddedIndices The indices of added entries. 添加的条目索引。
* @param FinalSize The final size of the entries array after addition. 添加后条目数组的最终大小。
*/
void PostReplicatedAdd(const TArrayView<int32> AddedIndices, int32 FinalSize);
/**
* Called after entries are changed during replication.
* 复制期间条目更改后调用。
* @param ChangedIndices The indices of changed entries. 更改的条目索引。
* @param FinalSize The final size of the entries array after change. 更改后条目数组的最终大小。
*/
void PostReplicatedChange(const TArrayView<int32> ChangedIndices, int32 FinalSize);
//~End of FFastArraySerializer contract
/**
* Handles delta serialization for network replication.
* 处理网络复制的增量序列化。
* @param DeltaParms The serialization parameters. 序列化参数。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
bool NetDeltaSerialize(FNetDeltaSerializeInfo& DeltaParms)
{
return FastArrayDeltaSerialize<FGIS_CurrencyEntry, FGIS_CurrencyContainer>(Entries, DeltaParms, *this);
}
/**
* The owning currency system component.
* 拥有此容器的货币系统组件。
*/
UPROPERTY()
TObjectPtr<UGIS_CurrencySystemComponent> OwningComponent{nullptr};
/**
* Array of currency entries.
* 货币条目数组。
*/
UPROPERTY(VisibleAnywhere, Category="Currency", meta=(DisplayName="Currencies", TitleProperty="{Definition}->{Value}"))
TArray<FGIS_CurrencyEntry> Entries;
};
/**
* Traits for the currency container to enable network delta serialization.
* 货币容器的特性,用于启用网络增量序列化。
*/
template <>
struct TStructOpsTypeTraits<FGIS_CurrencyContainer> : TStructOpsTypeTraitsBase2<FGIS_CurrencyContainer>
{
enum
{
WithNetDeltaSerializer = true,
};
};

View File

@@ -0,0 +1,127 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/DataAsset.h"
#include "Engine/Texture2D.h"
#include "GIS_CurrencyDefinition.generated.h"
class UGIS_CurrencyDefinition;
/**
* Struct to represent a currency exchange rate.
* 表示货币汇率的结构体。
*/
struct FGIS_CurrencyExchangeRate
{
/**
* The currency definition for the exchange rate.
* 汇率的货币定义。
*/
TObjectPtr<const UGIS_CurrencyDefinition> Currency;
/**
* The exchange rate value.
* 汇率值。
*/
float ExchangeRate;
/**
* Constructor for the currency exchange rate.
* 货币汇率的构造函数。
* @param InCurrency The currency definition. 货币定义。
* @param InExchangeRate The exchange rate value. 汇率值。
*/
FGIS_CurrencyExchangeRate(const UGIS_CurrencyDefinition* InCurrency, float InExchangeRate);
};
/**
* Defines properties for a currency type in the inventory system.
* 定义库存系统中货币类型的属性。
*/
UCLASS(BlueprintType)
class GENERICINVENTORYSYSTEM_API UGIS_CurrencyDefinition : public UDataAsset
{
GENERATED_BODY()
public:
/**
* The display name of the currency for UI purposes.
* 货币的UI显示名称。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Common")
FText DisplayName;
/**
* The description of the currency for UI purposes.
* 货币的UI描述。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Common")
FText Description;
/**
* The icon for the currency for UI display.
* 货币的UI图标。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Common")
TSoftObjectPtr<UTexture2D> Icon;
/**
* The maximum amount allowed for this currency (0 for unlimited).
* 货币的最大数量0表示无限制
* @details If the amount exceeds this value, it will attempt to convert to another currency.
* @细节 如果数量超过此值,将尝试转换为其他货币。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Common", meta=(ClampMin=0))
float MaxAmount{0};
/**
* The parent currency used to compute exchange rates.
* 用于计算汇率的父级货币。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Exchange")
TObjectPtr<const UGIS_CurrencyDefinition> ParentCurrency;
/**
* The exchange rate to the parent currency (e.g., 100 cents = 1 dollar).
* 相对于父级货币的汇率例如100分=1美元
* @details If this currency is a 10-unit note and the parent is a 100-unit note, set to 10 for 1:10 exchange.
* @细节 如果此货币是10元钞父级是100元钞设置值为10表示1个100元钞可兑换10个10元钞。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Exchange", meta=(ClampMin=1))
float ExchangeRateToParent{1};
/**
* The currency to convert to when this currency exceeds MaxAmount.
* 当货币数量超过最大值时转换到的溢出货币。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Exchange")
TObjectPtr<const UGIS_CurrencyDefinition> OverflowCurrency;
/**
* The currency to convert fractional remainders to.
* 分数余数转换到的分数货币。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Exchange")
TObjectPtr<const UGIS_CurrencyDefinition> FractionCurrency;
/**
* Attempts to get the exchange rate to another currency.
* 尝试获取针对其他货币的汇率。
* @param OtherCurrency The currency to compare with. 要比较的其他货币。
* @param ExchangeRate The resulting exchange rate (output). 输出的汇率。
* @return True if the exchange rate was found, false otherwise. 如果找到汇率则返回true否则返回false。
* @details Returns the rate as "1 this currency = ExchangeRate other currency".
* @细节 以“1个当前货币 = 汇率个其他货币”的形式返回汇率。
*/
bool TryGetExchangeRateTo(const UGIS_CurrencyDefinition* OtherCurrency, double& ExchangeRate) const;
/**
* Gets the exchange rate to the root currency.
* 获取相对于根货币的汇率。
* @param AdditionalExchangeRate An external exchange rate for recursive calculations. 用于递归计算的外部汇率。
* @return The exchange rate to the root currency. 相对于根货币的汇率。
*/
FGIS_CurrencyExchangeRate GetRootExchangeRate(double AdditionalExchangeRate = 1) const;
};

View File

@@ -0,0 +1,94 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Net/Serialization/FastArraySerializer.h"
#include "UObject/Object.h"
#include "GIS_CurrencyEntry.generated.h"
class UGIS_CurrencyDefinition;
/**
* Represents a currency and its associated amount.
* 表示一种货币及其数量。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_CurrencyEntry : public FFastArraySerializerItem
{
GENERATED_BODY()
/**
* Default constructor for the currency entry.
* 货币条目的默认构造函数。
*/
FGIS_CurrencyEntry();
/**
* Constructor for the currency entry with specified definition and amount.
* 使用指定货币定义和数量构造货币条目。
* @param InDefinition The currency definition. 货币定义。
* @param InAmount The amount of the currency. 货币数量。
*/
FGIS_CurrencyEntry(const TObjectPtr<const UGIS_CurrencyDefinition>& InDefinition, float InAmount);
/**
* Constructor for the currency entry with specified amount and definition (alternative order).
* 使用指定数量和货币定义构造货币条目(参数顺序相反)。
* @param InAmount The amount of the currency. 货币数量。
* @param InDefinition The currency definition. 货币定义。
*/
FGIS_CurrencyEntry(float InAmount, const TObjectPtr<const UGIS_CurrencyDefinition>& InDefinition);
/**
* Referenced currency definition.
* 引用的货币定义。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
TObjectPtr<const UGIS_CurrencyDefinition> Definition;
/**
* The amount of the currency.
* 货币的数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
float Amount;
/**
* The previous amount of the currency (not replicated).
* 货币的前一数量(不复制)。
*/
UPROPERTY(NotReplicated)
float PrevAmount = 0;
/**
* Checks if this currency entry is equal to another.
* 检查此货币条目是否与另一个相等。
* @param Other The other currency entry to compare with. 要比较的另一个货币条目。
* @return True if the entries are equal, false otherwise. 如果条目相等则返回true否则返回false。
*/
bool Equals(const FGIS_CurrencyEntry& Other) const;
/**
* Converts the currency entry to a string representation.
* 将货币条目转换为字符串表示。
* @return The string representation of the currency entry. 货币条目的字符串表示。
*/
FString ToString() const;
/**
* Equality operator to compare two currency entries.
* 比较两个货币条目的相等性运算符。
* @param Rhs The right-hand side currency entry to compare with. 要比较的右侧货币条目。
* @return True if the entries are equal, false otherwise. 如果条目相等则返回true否则返回false。
*/
bool operator==(const FGIS_CurrencyEntry& Rhs) const;
/**
* Inequality operator to compare two currency entries.
* 比较两个货币条目的不等性运算符。
* @param Rhs The right-hand side currency entry to compare with. 要比较的右侧货币条目。
* @return True if the entries are not equal, false otherwise. 如果条目不相等则返回true否则返回false。
*/
bool operator!=(const FGIS_CurrencyEntry& Rhs) const;
};

View File

@@ -0,0 +1,375 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CurrencyContainer.h"
#include "GIS_CurrencyDefinition.h"
#include "Components/ActorComponent.h"
#include "GIS_CurrencySystemComponent.generated.h"
class UGIS_InventorySubsystem;
/**
* Delegate triggered when a currency amount changes.
* 货币数量变化时触发的委托。
* @param Currency The currency definition that changed. 发生变化的货币定义。
* @param OldAmount The previous amount of the currency. 之前的货币数量。
* @param NewAmount The new amount of the currency. 新的货币数量。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FGIS_CurrencyChangedSignature, const UGIS_CurrencyDefinition*, Currency, float, OldAmount, float, NewAmount);
/**
* Currency system component for managing an actor's currencies.
* 管理演员货币的货币系统组件。
* @details This component serves as a wrapper for the CurrencyContainer, handling currency-related operations.
* @细节 该组件作为CurrencyContainer的包装器处理与货币相关的操作。
*/
UCLASS(ClassGroup=(GIS), BlueprintType, Blueprintable, meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_CurrencySystemComponent : public UActorComponent
{
GENERATED_BODY()
friend FGIS_CurrencyContainer;
public:
/**
* Constructor for the currency system component.
* 货币系统组件的构造函数。
*/
UGIS_CurrencySystemComponent();
/**
* Gets the currency system component from an actor.
* 从一个演员获取货币系统组件。
* @param Actor The actor to query for the currency system component. 要查询货币系统组件的演员。
* @return The currency system component, or nullptr if not found. 货币系统组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|Inventory", Meta = (DefaultToSelf="Actor"))
static UGIS_CurrencySystemComponent* GetCurrencySystemComponent(const AActor* Actor);
/**
* Gets the properties that should be replicated for this component.
* 获取需要为此组件复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<class FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Initializes the component.
* 初始化组件。
*/
virtual void InitializeComponent() override;
/**
* Gets all currency information.
* 获取所有货币信息。
* @return Array of currency entries containing currency types and amounts. 包含货币类型和数量的货币条目数组。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual TArray<FGIS_CurrencyEntry> GetAllCurrencies() const;
/**
* Sets all currency information.
* 设置所有货币信息。
* @param InCurrencyInfos The array of currency entries to set. 要设置的货币条目数组。
*/
virtual void SetCurrencies(const TArray<FGIS_CurrencyEntry>& InCurrencyInfos);
/**
* Clears all currency information.
* 清空所有货币信息。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual void EmptyCurrencies();
/**
* Gets information for a specific currency.
* 获取指定货币的信息。
* @param CurrencyDefinition The currency definition to query. 要查询的货币定义。
* @param OutCurrencyInfo The currency information (output). 货币信息(输出)。
* @return True if the currency is found, false otherwise. 如果找到货币则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|CurrencySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool GetCurrency(TSoftObjectPtr<const UGIS_CurrencyDefinition> CurrencyDefinition, FGIS_CurrencyEntry& OutCurrencyInfo) const;
/**
* Gets information for multiple specified currencies.
* 获取多个指定货币的信息。
* @param CurrencyDefinitions The array of currency definitions to query. 要查询的货币定义数组。
* @param OutCurrencyInfos The array of currency information (output). 货币信息数组(输出)。
* @return True if all specified currencies are found, false otherwise. 如果找到所有指定货币则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|CurrencySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool GetCurrencies(TArray<TSoftObjectPtr<UGIS_CurrencyDefinition>> CurrencyDefinitions, TArray<FGIS_CurrencyEntry>& OutCurrencyInfos) const;
/**
* Adds a currency and its amount.
* 添加货币及其数量。
* @param CurrencyInfo The currency information to add. 要添加的货币信息。
* @return True if the currency was added successfully, false otherwise. 如果货币添加成功则返回true否则返回false。
* @details Adds the specified amount to an existing currency or creates a new entry if the currency doesn't exist.
* @细节 如果当前没有该货币,则以指定数量新增货币;如果已有,则在原始数量上累加。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool AddCurrency(FGIS_CurrencyEntry CurrencyInfo);
/**
* Removes a currency and its amount.
* 移除指定数量的货币。
* @param CurrencyInfo The currency information to remove. 要移除的货币信息。
* @return True if the currency was removed successfully, false if the currency doesn't exist. 如果货币移除成功则返回true如果货币不存在则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool RemoveCurrency(FGIS_CurrencyEntry CurrencyInfo);
/**
* Checks if the specified currency amount is available.
* 检查是否拥有指定数量的货币。
* @param CurrencyInfo The currency information to check. 要检查的货币信息。
* @return True if the specified amount is available, false otherwise. 如果有足够数量的货币则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool HasCurrency(FGIS_CurrencyEntry CurrencyInfo) const;
/**
* Checks if multiple specified currency amounts are available.
* 检查是否拥有多个指定数量的货币。
* @param CurrencyInfos The array of currency information to check. 要检查的货币信息数组。
* @return True if all specified amounts are available, false otherwise. 如果所有货币数量都满足则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool HasCurrencies(const TArray<FGIS_CurrencyEntry>& CurrencyInfos);
/**
* Adds multiple currencies.
* 添加多个货币。
* @param CurrencyInfos The array of currency information to add. 要添加的货币信息数组。
* @return True if all currencies were added successfully, false otherwise. 如果所有货币都添加成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool AddCurrencies(const TArray<FGIS_CurrencyEntry>& CurrencyInfos);
/**
* Removes multiple currencies.
* 移除多个货币。
* @param CurrencyInfos The array of currency information to remove. 要移除的货币信息数组。
* @return True if all currencies were removed successfully, false otherwise. 如果所有货币都移除成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|CurrencySystem")
virtual bool RemoveCurrencies(const TArray<FGIS_CurrencyEntry>& CurrencyInfos);
/**
* Called when the actor begins play.
* 演员开始播放时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the actor ends play.
* 演员结束播放时调用。
* @param EndPlayReason The reason for ending play. 结束播放的原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
/**
* Event triggered when a currency amount changes.
* 货币数量变化时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_CurrencyChangedSignature OnCurrencyChangedEvent;
#pragma region Static Calculations
#if 0
/**
* Finds the index of a currency in a list.
* 查找包含指定货币的索引。
* @param Currency The currency definition to find. 要查找的货币定义。
* @param List The list of currency entries to search. 要搜索的货币条目列表。
* @return The index of the currency, or -1 if not found. 货币的索引,如果未找到则返回-1。
*/
static int32 FindIndexWithCurrency(const UGIS_CurrencyDefinition* Currency, const TArray<FGIS_CurrencyEntry>& List);
/**
* Finds or creates an index for a currency in a list.
* 查找或创建包含指定货币的索引。
* @param Currency The currency definition to find or create. 要查找或创建的货币定义。
* @param Result The list of currency entries (modified). 货币条目列表(可修改)。
* @return The index of the currency. 货币的索引。
*/
static int32 FindOrCreateCurrencyIndex(const UGIS_CurrencyDefinition* Currency, TArray<FGIS_CurrencyEntry>& Result);
/**
* Performs discrete addition of two currency lists.
* 执行两个货币列表的离散加法。
* @param Lhs The first currency list. 第一个货币列表。
* @param Rhs The second currency list. 第二个货币列表。
* @return The combined currency list. 合并后的货币列表。
*/
static TArray<FGIS_CurrencyEntry> DiscreteAddition(const TArray<FGIS_CurrencyEntry>& Lhs, const TArray<FGIS_CurrencyEntry>& Rhs);
/**
* Adds a single currency and amount to a currency list.
* 将单一货币和数量添加到货币列表。
* @param CurrencyAmounts The currency list to modify. 要修改的货币列表。
* @param Currency The currency definition to add. 要添加的货币定义。
* @param Amount The amount to add. 要添加的数量。
* @return The updated currency list. 更新后的货币列表。
*/
static TArray<FGIS_CurrencyEntry> DiscreteAddition(const TArray<FGIS_CurrencyEntry>& CurrencyAmounts,
const UGIS_CurrencyDefinition* Currency, float Amount);
/**
* Sets the fractional part of a currency to its maximum value.
* 将货币的小数部分设置为最大值。
* @param CurrencyAmounts The currency list to modify. 要修改的货币列表。
* @param Currency The currency definition to adjust. 要调整的货币定义。
* @return The updated currency list. 更新后的货币列表。
*/
static TArray<FGIS_CurrencyEntry> SetAllFractionToMax(const TArray<FGIS_CurrencyEntry>& CurrencyAmounts, const UGIS_CurrencyDefinition* Currency);
/**
* Converts an amount to discrete currency units.
* 将数量转换为离散的货币单位。
* @param Currency The currency definition to convert. 要转换的货币定义。
* @param Amount The amount to convert. 要转换的数量。
* @return The discrete currency entries. 离散的货币条目。
*/
static TArray<FGIS_CurrencyEntry> ConvertToDiscrete(const UGIS_CurrencyDefinition* Currency, double Amount);
/**
* Converts overflow amounts, ignoring fractional parts.
* 转换溢出金额,忽略小数部分。
* @param Currency The currency definition to convert. 要转换的货币定义。
* @param Amount The amount to convert. 要转换的数量。
* @return The overflow currency entries. 溢出的货币条目。
*/
static TArray<FGIS_CurrencyEntry> ConvertOverflow(const UGIS_CurrencyDefinition* Currency, double Amount);
/**
* Converts the fractional part of an amount to currency units.
* 将金额的小数部分转换为货币单位。
* @param Currency The currency definition to convert. 要转换的货币定义。
* @param Amount The amount to convert. 要转换的数量。
* @return The fractional currency entries. 小数部分的货币条目。
*/
static TArray<FGIS_CurrencyEntry> ConvertFraction(const UGIS_CurrencyDefinition* Currency, double Amount);
/**
* Gets the maximum amount for a currency in discrete units.
* 获取货币的最大金额(以离散单位计)。
* @param Currency The currency definition to query. 要查询的货币定义。
* @return The maximum currency entries. 最大货币条目。
*/
static TArray<FGIS_CurrencyEntry> MaxedOutAmount(const UGIS_CurrencyDefinition* Currency);
#endif
#pragma endregion
protected:
/**
* Called when a currency entry is added.
* 货币条目添加时调用。
* @param Entry The added currency entry. 添加的货币条目。
* @param Idx The index of the added entry. 添加条目的索引。
*/
virtual void OnCurrencyEntryAdded(const FGIS_CurrencyEntry& Entry, int32 Idx);
/**
* Called when a currency entry is removed.
* 货币条目移除时调用。
* @param Entry The removed currency entry. 移除的货币条目。
* @param Idx The index of the removed entry. 移除条目的索引。
*/
virtual void OnCurrencyEntryRemoved(const FGIS_CurrencyEntry& Entry, int32 Idx);
/**
* Called when a currency entry is updated.
* 货币条目更新时调用。
* @param Entry The updated currency entry. 更新的货币条目。
* @param Idx The index of the updated entry. 更新条目的索引。
* @param OldAmount The previous amount of the currency. 之前的货币数量。
* @param NewAmount The new amount of the currency. 新的货币数量。
*/
virtual void OnCurrencyEntryUpdated(const FGIS_CurrencyEntry& Entry, int32 Idx, float OldAmount, float NewAmount);
/**
* Called when a currency amount changes.
* 货币数量变化时调用。
* @param Tag The currency definition that changed. 发生变化的货币定义。
* @param OldValue The previous amount of the currency. 之前的货币数量。
* @param NewValue The new amount of the currency. 新的货币数量。
*/
virtual void OnCurrencyChanged(TObjectPtr<const UGIS_CurrencyDefinition> Tag, float OldValue, float NewValue);
/**
* Adds initial currencies to the component.
* 向组件添加初始货币。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|CurrencySystem")
void AddInitialCurrencies();
/**
* Internal function to get information for a specific currency.
* 获取指定货币信息的内部函数。
* @param CurrencyTag The currency definition to query. 要查询的货币定义。
* @param OutCurrencyInfo The currency information (output). 货币信息(输出)。
* @return True if the currency is found, false otherwise. 如果找到货币则返回true否则返回false。
*/
virtual bool GetCurrencyInternal(const TObjectPtr<const UGIS_CurrencyDefinition>& CurrencyTag, FGIS_CurrencyEntry& OutCurrencyInfo) const;
/**
* Internal function to get information for multiple currencies.
* 获取多个货币信息的内部函数。
* @param Currencies The array of currency definitions to query. 要查询的货币定义数组。
* @param OutCurrencies The array of currency information (output). 货币信息数组(输出)。
* @return True if all currencies are found, false otherwise. 如果找到所有货币则返回true否则返回false。
*/
virtual bool GetCurrenciesInternal(const TArray<TObjectPtr<const UGIS_CurrencyDefinition>>& Currencies, TArray<FGIS_CurrencyEntry>& OutCurrencies) const;
/**
* Internal function to add a currency.
* 添加货币的内部函数。
* @param CurrencyInfo The currency information to add. 要添加的货币信息。
* @param bNotify Whether to trigger notifications for the addition. 是否触发添加通知。
* @return True if the currency was added successfully, false otherwise. 如果货币添加成功则返回true否则返回false。
*/
virtual bool AddCurrencyInternal(const FGIS_CurrencyEntry& CurrencyInfo, bool bNotify = true);
/**
* Internal function to remove a currency.
* 移除货币的内部函数。
* @param CurrencyInfo The currency information to remove. 要移除的货币信息。
* @param bNotify Whether to trigger notifications for the removal. 是否触发移除通知。
* @return True if the currency was removed successfully, false otherwise. 如果货币移除成功则返回true否则返回false。
*/
virtual bool RemoveCurrencyInternal(const FGIS_CurrencyEntry& CurrencyInfo, bool bNotify = true);
/**
* Internal function to check if a currency amount is available.
* 检查货币数量是否可用的内部函数。
* @param CurrencyInfo The currency information to check. 要检查的货币信息。
* @return True if the specified amount is available, false otherwise. 如果有足够数量的货币则返回true否则返回false。
*/
virtual bool HasCurrencyInternal(const FGIS_CurrencyEntry& CurrencyInfo) const;
/**
* Default currencies to initialize the component with.
* 初始化组件的默认货币。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Currency")
TArray<FGIS_CurrencyEntry> DefaultCurrencies;
/**
* Container for currency entries.
* 货币条目的容器。
*/
UPROPERTY(VisibleAnywhere, Replicated, Category="Currency", meta=(ShowOnlyInnerProperties))
FGIS_CurrencyContainer Container;
/**
* Local cache mapping currency definitions to their amounts.
* 货币定义到其数量的本地缓存映射。
*/
UPROPERTY()
TMap<TObjectPtr<const UGIS_CurrencyDefinition>, float> CurrencyMap;
};

View File

@@ -0,0 +1,82 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Items/GIS_ItemInfo.h"
#include "UObject/Interface.h"
#include "GIS_ShopCondition.generated.h"
class UGIS_CurrencySystemComponent;
class UGIS_ShopSystemComponent;
class UGIS_InventorySystemComponent;
// This class does not need to be modified.
/**
* Interface for defining custom buy condition checks.
* 定义自定义购买条件检查的接口。
*/
UINTERFACE()
class UGIS_ShopBuyCondition : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for actors or components to implement custom buy condition logic.
* 供Actor或组件实现自定义购买条件逻辑的接口。
* @details Allows checking if an item can be bought based on shop, inventory, and currency conditions.
* @细节 允许根据商店、库存和货币条件检查道具是否可以购买。
*/
class GENERICINVENTORYSYSTEM_API IGIS_ShopBuyCondition
{
GENERATED_BODY()
public:
/**
* Checks if an item can be bought.
* 检查道具是否可以购买。
* @param Shop The shop system component. 商店系统组件。
* @param BuyerInventory The inventory of the buyer. 购买者的库存。
* @param CurrencySystem The currency system component. 货币系统组件。
* @param ItemInfo Information about the item to buy. 要购买的道具信息。
* @return True if the item can be bought, false otherwise. 如果道具可以购买则返回true否则返回false。
*/
virtual bool CanBuy(const UGIS_ShopSystemComponent* Shop, UGIS_InventorySystemComponent* BuyerInventory, UGIS_CurrencySystemComponent* CurrencySystem,
FGIS_ItemInfo ItemInfo) = 0;
};
// This class does not need to be modified.
/**
* Interface for defining custom sell condition checks.
* 定义自定义出售条件检查的接口。
*/
UINTERFACE()
class UGIS_ShopSellCondition : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for actors or components to implement custom sell condition logic.
* 供Actor或组件实现自定义出售条件逻辑的接口。
* @details Allows checking if an item can be sold based on shop, inventory, and currency conditions.
* @细节 允许根据商店、库存和货币条件检查道具是否可以出售。
*/
class GENERICINVENTORYSYSTEM_API IGIS_ShopSellCondition
{
GENERATED_BODY()
public:
/**
* Checks if an item can be sold.
* 检查道具是否可以出售。
* @param Shop The shop system component. 商店系统组件。
* @param SellerInventory The inventory of the seller. 出售者的库存。
* @param CurrencySystem The currency system component. 货币系统组件。
* @param ItemInfo Information about the item to sell. 要出售的道具信息。
* @return True if the item can be sold, false otherwise. 如果道具可以出售则返回true否则返回false。
*/
virtual bool CanSell(const UGIS_ShopSystemComponent* Shop, UGIS_InventorySystemComponent* SellerInventory, UGIS_CurrencySystemComponent* CurrencySystem,
FGIS_ItemInfo ItemInfo) = 0;
};

View File

@@ -0,0 +1,254 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CurrencyEntry.h"
#include "GIS_InventoryTags.h"
#include "Items/GIS_ItemInfo.h"
#include "Components/ActorComponent.h"
#include "GIS_ShopSystemComponent.generated.h"
class UGIS_CurrencySystemComponent;
class IGIS_ShopSellCondition;
class IGIS_ShopBuyCondition;
/**
* Component responsible for managing shop functionality, including buying and selling items.
* 负责管理商店功能的组件,包括购买和出售道具。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_ShopSystemComponent : public UActorComponent
{
GENERATED_BODY()
public:
/**
* Constructor for the shop system component.
* 商店系统组件的构造函数。
*/
UGIS_ShopSystemComponent();
/**
* Gets the shop system component from an actor.
* 从一个演员获取商店系统组件。
* @param Actor The actor to query for the shop system component. 要查询商店系统组件的演员。
* @return The shop system component, or nullptr if not found. 商店系统组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ShopSystem", Meta = (DefaultToSelf="Actor"))
static UGIS_ShopSystemComponent* GetShopSystemComponent(const AActor* Actor);
/**
* Gets the shop's inventory.
* 获取商店的库存。
* @return The shop's inventory component, or nullptr if not set. 商店的库存组件如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|ShopSystem")
virtual UGIS_InventorySystemComponent* GetInventory() const;
/**
* Attempts to buy an item from the shop.
* 尝试从商店购买道具。
* @param BuyerInventory The buyer's inventory component. 买家的库存组件。
* @param CurrencySystem The buyer's currency system component (to deduct currency). 买家的货币系统组件(用于扣除货币)。
* @param ItemInfo The item information to buy. 要购买的道具信息。
* @return True if the purchase was successful, false otherwise. 如果购买成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool BuyItem(UGIS_InventorySystemComponent* BuyerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo);
/**
* Attempts to sell an item to the shop.
* 尝试向商店出售道具。
* @param SellerInventory The seller's inventory component. 卖家的库存组件。
* @param CurrencySystem The seller's currency system component (to add currency). 卖家的货币系统组件(用于添加货币)。
* @param ItemInfo The item information to sell. 要出售的道具信息。
* @return True if the sale was successful, false otherwise. 如果出售成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool SellItem(UGIS_InventorySystemComponent* SellerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo);
/**
* Checks if a buyer can purchase an item from the shop.
* 检查买家是否可以从商店购买道具。
* @param BuyerInventory The buyer's inventory component. 买家的库存组件。
* @param CurrencySystem The buyer's currency system component (to check currency availability). 买家的货币系统组件(用于检查货币是否足够)。
* @param ItemInfo The item information to buy. 要购买的道具信息。
* @return True if the buyer can purchase the item, false otherwise. 如果买家可以购买道具则返回true否则返回false。
* @details Used for custom checks such as content locking or other game mechanics. 可用于自定义检查,如内容锁定或其他游戏机制。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool CanBuyerBuyItem(UGIS_InventorySystemComponent* BuyerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo) const;
/**
* Checks if a seller can sell an item to the shop.
* 检查卖家是否可以向商店出售道具。
* @param SellerInventory The seller's inventory component. 卖家的库存组件。
* @param CurrencySystem The seller's currency system component. 卖家的货币系统组件。
* @param ItemInfo The item information to sell. 要出售的道具信息。
* @return True if the seller can sell the item, false otherwise. 如果卖家可以出售道具则返回true否则返回false。
* @details Used for custom checks such as content locking or other game mechanics. 可用于自定义检查,如内容锁定或其他游戏机制。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool CanSellerSellItem(UGIS_InventorySystemComponent* SellerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo) const;
/**
* Checks if the specified item is available for purchase from the shop.
* 检查指定道具是否可从商店购买。
* @param ItemInfo The item information to check. 要检查的道具信息。
* @return True if the item is buyable, false otherwise. 如果道具可购买则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool IsItemBuyable(const FGIS_ItemInfo& ItemInfo) const;
/**
* Checks if the shop can buy the specified item from a seller.
* 检查商店是否可以从卖家购买指定道具。
* @param ItemInfo The item information to check. 要检查的道具信息。
* @return True if the item is sellable, false otherwise. 如果道具可出售则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|ShopSystem")
virtual bool IsItemSellable(const FGIS_ItemInfo& ItemInfo) const;
/**
* Gets the buy price modifier for the buyer.
* 获取买家的购买价格浮动。
* @param BuyerInventory The buyer's inventory component. 买家的库存组件。
* @return The buy price modifier. 购买价格浮动值。
* @details Can be overridden to implement a dynamic pricing system based on game mechanics. 可覆写以基于游戏机制实现动态价格系统。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|ShopSystem")
float GetBuyModifierForBuyer(UGIS_InventorySystemComponent* BuyerInventory) const;
/**
* Gets the sell price modifier for the seller.
* 获取卖家的出售价格浮动。
* @param SellerInventory The seller's inventory component. 卖家的库存组件。
* @return The sell price modifier. 出售价格浮动值。
* @details Can be overridden to implement a dynamic pricing system based on game mechanics, such as supply shortages. 可覆写以基于游戏机制(如缺货)实现动态价格系统。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|ShopSystem")
float GetSellModifierForSeller(UGIS_InventorySystemComponent* SellerInventory) const;
/**
* Gets the buy value (currency cost) of an item for the buyer.
* 获取买家购买道具的货币价格。
* @param Buyer The buyer's inventory component. 买家的库存组件。
* @param ItemInfo The item information to buy. 要购买的道具信息。
* @param BuyValue The required currency for the purchase (output). 购买所需的货币(输出)。
* @return True if the buyer can afford the item, false otherwise. 如果买家买得起则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, BlueprintNativeEvent, Category="GIS|ShopSystem", meta=(ExpandBoolAsExecs="ReturnValue"))
bool TryGetBuyValueForBuyer(UGIS_InventorySystemComponent* Buyer, const FGIS_ItemInfo& ItemInfo, TArray<FGIS_CurrencyEntry>& BuyValue) const;
/**
* Gets the sell value (currency gained) of an item for the seller.
* 获取卖家出售道具的货币价格。
* @param Seller The seller's inventory component. 卖家的库存组件。
* @param ItemInfo The item information to sell. 要出售的道具信息。
* @param SellValue The currency gained from the sale (output). 出售获得的货币(输出)。
* @return True if the currency value is valid, false otherwise. 如果货币价格有效则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, BlueprintNativeEvent, Category="GIS|ShopSystem", meta=(ExpandBoolAsExecs="ReturnValue"))
bool TryGetSellValueForSeller(UGIS_InventorySystemComponent* Seller, const FGIS_ItemInfo& ItemInfo, TArray<FGIS_CurrencyEntry>& SellValue) const;
/**
* Called when the actor begins play.
* 演员开始播放时调用。
*/
virtual void BeginPlay() override;
/**
* Called when the actor ends play.
* 演员结束播放时调用。
* @param EndPlayReason The reason for ending play. 结束播放的原因。
*/
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
protected:
/**
* Internal check for whether a seller can sell an item to the shop.
* 检查卖家是否可以向商店出售道具的内部函数。
* @param SellerInventory The seller's inventory component. 卖家的库存组件。
* @param CurrencySystem The seller's currency system component. 卖家的货币系统组件。
* @param ItemInfo The item information to sell. 要出售的道具信息。
* @return True if the seller can sell the item, false otherwise. 如果卖家可以出售道具则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|ShopSystem")
bool CanSellerSellItemInternal(UGIS_InventorySystemComponent* SellerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo) const;
/**
* Internal check for whether a buyer can purchase an item from the shop.
* 检查买家是否可以从商店购买道具的内部函数。
* @param BuyerInventory The buyer's inventory component. 买家的库存组件。
* @param CurrencySystem The buyer's currency system component. 买家的货币系统组件。
* @param ItemInfo The item information to buy. 要购买的道具信息。
* @return True if the buyer can purchase the item, false otherwise. 如果买家可以购买道具则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|ShopSystem")
bool CanBuyerBuyItemInternal(UGIS_InventorySystemComponent* BuyerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo) const;
/**
* Internal function to handle selling an item to the shop.
* 处理向商店出售道具的内部函数。
* @param SellerInventory The seller's inventory component. 卖家的库存组件。
* @param CurrencySystem The seller's currency system component. 卖家的货币系统组件。
* @param ItemInfo The item information to sell. 要出售的道具信息。
* @return True if the sale was successful, false otherwise. 如果出售成功则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|ShopSystem")
bool SellItemInternal(UGIS_InventorySystemComponent* SellerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo);
/**
* Internal function to handle buying an item from the shop.
* 处理从商店购买道具的内部函数。
* @param BuyerInventory The buyer's inventory component. 买家的库存组件。
* @param CurrencySystem The buyer's currency system component. 买家的货币系统组件。
* @param ItemInfo The item information to buy. 要购买的道具信息。
* @return True if the purchase was successful, false otherwise. 如果购买成功则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|ShopSystem")
bool BuyItemInternal(UGIS_InventorySystemComponent* BuyerInventory, UGIS_CurrencySystemComponent* CurrencySystem, const FGIS_ItemInfo& ItemInfo);
/**
* The target item collection to add items to when purchased.
* 购买时道具添加到的目标道具集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Shop", meta=(Categories="GIS.Collection"))
FGameplayTag TargetItemCollectionToAddOnBuy = GIS_CollectionTags::Main;
/**
* Controls the buy price modifier for this shop.
* 控制此商店的购买价格浮动。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Shop", meta=(ClampMin=0))
float BuyPriceModifier = 0;
/**
* Controls the sell price modifier for this shop.
* 控制此商店的出售价格浮动。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Shop", meta=(ClampMin=0))
float SellPriceModifer = 0;
/**
* The inventory component associated with the shop.
* 与商店关联的库存组件。
*/
UPROPERTY()
TObjectPtr<UGIS_InventorySystemComponent> OwningInventory;
/**
* List of conditions for buying items from the shop.
* 商店购买道具的条件列表。
*/
UPROPERTY()
TArray<TScriptInterface<IGIS_ShopBuyCondition>> BuyConditions;
/**
* List of conditions for selling items to the shop.
* 向商店出售道具的条件列表。
*/
UPROPERTY()
TArray<TScriptInterface<IGIS_ShopSellCondition>> SellConditions;
};

View File

@@ -0,0 +1,149 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_SerializationStructLibrary.h"
#include "UObject/Object.h"
#include "GIS_InventoryFactory.generated.h"
class UGIS_ItemDefinition;
class UGIS_InventorySystemComponent;
class UGIS_ItemInstance;
/**
* Inventory Factory class for managing low level operation in GIS.
* 库存工厂类用于管理GIS中的底层操作。
* @details Extend this class to have full control over how serialization works.
* @细节 拓展此类以完全控制序列化的运作。
*/
UCLASS(BlueprintType, Blueprintable)
class GENERICINVENTORYSYSTEM_API UGIS_InventoryFactory : public UObject
{
GENERATED_BODY()
public:
UGIS_InventoryFactory();
/**
* Creates a new item instance for an actor.
* 为演员创建新的道具实例。
* @param Owner The actor that will own this item (used for network replication). 将拥有此道具的演员(用于网络复制)。
* @param ItemDefinition The definition of the item to create. 要创建的道具定义。
* @return The newly created item instance, or nullptr if creation failed. 新创建的道具实例如果创建失败则返回nullptr。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
UGIS_ItemInstance* CreateItem(AActor* Owner, const UGIS_ItemDefinition* ItemDefinition);
virtual UGIS_ItemInstance* CreateItem_Implementation(AActor* Owner, const UGIS_ItemDefinition* ItemDefinition);
/**
* Duplicates an existing item to create a new one.
* 复制现有道具以创建新道具。
* @param Owner The actor that will own the new item. 将拥有新道具的演员。
* @param SrcItem The item to duplicate from. 要复制的原始道具。
* @param bGenerateNewId If true, will generate new id while copying. 如果为真会在复制时生成新的id
* @return The newly created item instance, or nullptr if duplication failed. 新创建的道具实例如果复制失败则返回nullptr。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
UGIS_ItemInstance* DuplicateItem(AActor* Owner, UGIS_ItemInstance* SrcItem, bool bGenerateNewId = true);
virtual UGIS_ItemInstance* DuplicateItem_Implementation(AActor* Owner, UGIS_ItemInstance* SrcItem, bool bGenerateNewId = true);
// /**
// * Create and restore an item instance from item record.
// * 从item记录录中创建并恢复道具实例。
// * @param Owner The actor that will own the new item. 将拥有新道具的演员。
// * @param InRecord The record of item. 道具记录
// * @return The newly created item instance, or nullptr if restoring failed. 新创建的道具实例如果恢复失败则返回nullptr。
// */
/**
* Serializes an item instance into a record.
* 将道具实例序列化为记录。
* @param Item The item instance to serialize. 要序列化的道具实例。
* @param Record The resulting item record (output). 输出的道具记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
bool SerializeItem(UGIS_ItemInstance* Item, FGIS_ItemRecord& Record);
/**
* Deserializes an item from an item record.
* 从道具记录反序列化道具。
* @param Owner The actor owning the item instance (generally inventory system component's owner). 拥有此道具实例的演员通常是库存系统组件的Owner。
* @param Record The item record to deserialize. 要反序列化的道具记录。
* @return The deserialized item instance, or nullptr if deserialization failed. 反序列化的道具实例如果失败则返回nullptr。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
UGIS_ItemInstance* DeserializeItem(AActor* Owner, const FGIS_ItemRecord& Record);
/**
* Creates a new collection instance for an actor.
* 为演员创建新的集合实例。
* @param Owner The actor that will own this collection (used for network replication). 将拥有此集合的演员(用于网络复制)。
* @param Definition The definition of the collection to create. 要创建的集合定义。
* @return The newly created collection instance, or nullptr if creation failed. 新创建的集合实例如果创建失败则返回nullptr。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
UGIS_ItemCollection* CreateCollection(AActor* Owner, const UGIS_ItemCollectionDefinition* Definition);
/**
* Serializes an item collection into a record.
* 将道具集合序列化为记录。
* @param Collection The item collection to serialize. 要序列化的道具集合。
* @param Record The resulting collection record (output). 输出的集合记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
bool SerializeCollection(UGIS_ItemCollection* Collection, FGIS_CollectionRecord& Record);
/**
* Deserializes a collection from a collection record.
* 从集合记录反序列化集合。
* @param InventorySystem The inventory system component to associate with the collection. 与集合关联的库存系统组件。
* @param Record The collection record to deserialize. 要反序列化的集合记录。
* @param ItemsMap A map of item IDs to item instances (output). 道具ID到道具实例的映射输出
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
void DeserializeCollection(UGIS_InventorySystemComponent* InventorySystem, const FGIS_CollectionRecord& Record, TMap<FGuid, UGIS_ItemInstance*>& ItemsMap);
/**
* Serializes an entire inventory into a record.
* 将整个库存序列化为记录。
* @param InventorySystem The inventory system component to serialize. 要序列化的库存系统组件。
* @param Record The resulting inventory record. 输出的库存记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
bool SerializeInventory(UGIS_InventorySystemComponent* InventorySystem, FGIS_InventoryRecord& Record);
/**
* Deserializes an inventory from an inventory record.
* 从库存记录反序列化库存。
* @param InventorySystem The inventory system component to populate. 要填充的库存系统组件。
* @param InRecord The inventory record to deserialize. 要反序列化的库存记录。
*/
UFUNCTION(BlueprintNativeEvent, Category="GIS|Factory")
void DeserializeInventory(UGIS_InventorySystemComponent* InventorySystem, const FGIS_InventoryRecord& InRecord);
protected:
// virtual TArray<FGIS_ItemFragmentStateRecord> FilterSerializableFragmentStates(const UGIS_ItemInstance* ItemInstance);
// virtual TArray<FGIS_ItemFragmentStateRecord> FilterCompatibleFragmentStateRecords(const UGIS_ItemDefinition* ItemDefinition, const FGIS_ItemRecord& Record);
/**
* The default class used to construct item instances.
* 用于构造道具实例的默认类。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Factory", NoClear)
TSoftClassPtr<UGIS_ItemInstance> DefaultItemInstanceClass;
#if WITH_EDITOR
/**
* Validates the data for this factory in the editor.
* 在编辑器中验证工厂的数据。
* @param Context The data validation context. 数据验证上下文。
* @return The result of the data validation. 数据验证的结果。
*/
virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
#endif
};

View File

@@ -0,0 +1,82 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_CurrencyEntry.h"
#include "Items/GIS_ItemInfo.h"
#include "Items/GIS_ItemStack.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "GIS_InventoryFunctionLibrary.generated.h"
/**
* Blueprint function library for inventory-related utility functions.
* 用于库存相关实用功能的蓝图函数库。
*/
UCLASS()
class GENERICINVENTORYSYSTEM_API UGIS_InventoryFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/**
* Multiplies the amounts of item definitions by a multiplier.
* 将道具定义的数量乘以一个倍数。
* @param ItemAmounts The array of item definitions with amounts. 包含数量的道具定义数组。
* @param Multiplier The multiplier to apply (default is 1). 要应用的倍数默认为1
* @return The modified array of item definitions with multiplied amounts. 修改后的包含乘以倍数的道具定义数组。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
static TArray<FGIS_ItemDefinitionAmount> MultiplyItemAmounts(const TArray<FGIS_ItemDefinitionAmount>& ItemAmounts, int32 Multiplier = 1);
/**
* Multiplies the amounts of currencies by a multiplier.
* 将货币数量乘以一个倍数。
* @param Currencies The array of currency entries. 货币条目数组。
* @param Multiplier The multiplier to apply (default is 1). 要应用的倍数默认为1
* @return The modified array of currency entries with multiplied amounts. 修改后的包含乘以倍数的货币条目数组。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
static TArray<FGIS_CurrencyEntry> MultiplyCurrencies(const TArray<FGIS_CurrencyEntry>& Currencies, float Multiplier = 1.0f);
/**
* Filters item infos based on a gameplay tag query.
* 根据游戏标签查询过滤道具信息。
* @param ItemInfos The array of item infos to filter. 要过滤的道具信息数组。
* @param Query The gameplay tag query to apply. 要应用的游戏标签查询。
* @return The filtered array of item infos. 过滤后的道具信息数组。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
static TArray<FGIS_ItemInfo> FilterItemInfosByTagQuery(const TArray<FGIS_ItemInfo>& ItemInfos, const FGameplayTagQuery& Query);
/**
* Filters item stacks based on a gameplay tag query.
* 根据游戏标签查询过滤道具堆栈。
* @param ItemStacks The item stacks to filter. 要过滤的道具堆栈。
* @param TagQuery The tag query for item tags. 用于道具标签的标签查询。
* @return The filtered array of item stacks matching the tag query. 匹配标签查询的过滤后的道具堆栈数组。
*/
// UFUNCTION(BlueprintPure, Category = "GIS")
static TArray<FGIS_ItemStack> FilterItemStacksByTagQuery(const TArray<FGIS_ItemStack>& ItemStacks, const FGameplayTagQuery& TagQuery);
/**
* Filters item stacks based on an item definition.
* 根据道具定义过滤道具堆栈。
* @param ItemStacks The item stacks to filter. 要过滤的道具堆栈。
* @param Definition The item definition to filter by. 用于过滤的道具定义。
* @return The filtered array of item stacks matching the definition. 匹配定义的过滤后的道具堆栈数组。
*/
// UFUNCTION(BlueprintPure, Category = "GIS")
static TArray<FGIS_ItemStack> FilterItemStacksByDefinition(const TArray<FGIS_ItemStack>& ItemStacks, const UGIS_ItemDefinition* Definition);
/**
* Filters item stacks based on collection tags.
* 根据集合标签过滤道具堆栈。
* @param ItemStacks The item stacks to filter. 要过滤的道具堆栈。
* @param CollectionTags The collection tags to search. 要搜索的集合标签。
* @return The filtered array of item stacks matching the collection tags. 匹配集合标签的过滤后的道具堆栈数组。
*/
// UFUNCTION(BlueprintPure, Category = "GIS")
static TArray<FGIS_ItemStack> FilterItemStacksByCollectionTags(const TArray<FGIS_ItemStack>& ItemStacks, const FGameplayTagContainer& CollectionTags);
};

View File

@@ -0,0 +1,236 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Items/GIS_ItemInfo.h"
#include "NativeGameplayTags.h"
#include "GIS_InventoryMeesages.generated.h"
class UGIS_InventorySystemComponent;
class UGIS_ItemCollection;
class UGIS_ItemInstance;
/**
* Message struct for general inventory updates.
* 通用库存更新的消息结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryUpdateMessage
{
GENERATED_BODY()
/**
* The inventory system component associated with the update.
* 与更新关联的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
};
/**
* Message struct for item stack additions or removals in the inventory.
* 库存中道具堆栈添加或移除的消息结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryStackUpdateMessage
{
GENERATED_BODY()
/**
* The inventory system component associated with the stack update.
* 与堆栈更新关联的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The type of change to the item stack (e.g., added, removed, changed).
* 道具堆栈的变更类型(例如,添加、移除、变更)。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
EGIS_ItemStackChangeType ChangeType{EGIS_ItemStackChangeType::Changed};
/**
* The changed item instance.
* 变更的道具实例。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_ItemInstance> Instance = nullptr;
/**
* The unique ID of the changed stack.
* 变更堆栈的唯一ID。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGuid StackId;
/**
* The unique ID of the collection containing the changed stack.
* 包含变更堆栈的集合的唯一ID。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="GIS")
FGuid CollectionId;
/**
* The new amount of the item instance in the stack.
* 道具实例在堆栈中的当前数量。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
int32 NewCount = 0;
/**
* The change in amount of the item instance in the stack (difference from previous amount).
* 道具实例在堆栈中的数量变化(与之前数量的差值)。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
int32 Delta = 0;
};
/**
* Message struct for adding item info to the inventory.
* 将道具信息添加到库存的消息结构体。
* @details The ItemInfo is the source of the amount being added, and the ItemStack is the result.
* @细节 ItemInfo是添加数量的来源ItemStack是添加的结果。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryAddItemInfoMessage
{
GENERATED_BODY()
/**
* The inventory system component associated with the item addition.
* 与道具添加关联的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The item info being added.
* 正在添加的道具信息。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo ItemInfo;
/**
* The unique ID of the stack where the item is added.
* 添加道具的堆栈的唯一ID。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGuid StackId;
/**
* The unique ID of the collection where the item is added.
* 添加道具的集合的唯一ID。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGuid CollectionId;
/**
* The gameplay tag of the collection where the item is added.
* 添加道具的集合的游戏标签。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGameplayTag CollectionTag;
};
/**
* Message struct for when item info addition is rejected by the inventory.
* 道具信息添加被库存拒绝时的消息结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryAddItemInfoRejectedMessage
{
GENERATED_BODY()
/**
* The inventory system component that rejected the item info.
* 拒绝道具信息的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The collection that rejected the item info.
* 拒绝道具信息的集合。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_ItemCollection> Collection;
/**
* The original item info that was attempted to be added.
* 尝试添加的原始道具信息。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo OriginalItemInfo;
/**
* The portion of the item info that was successfully added.
* 成功添加的道具信息部分。
* @attention May be empty if no items were added. 如果没有添加任何道具,可能为空。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo ItemInfoAdded;
/**
* The portion of the item info that was rejected due to reasons like overflow or collection restrictions.
* 由于溢出或集合限制等原因被拒绝的道具信息部分。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo RejectedItemInfo;
/**
* The item info returned to the incoming collection if the "return overflow" option is enabled.
* 如果启用了“返回溢出”选项,则返回到输入集合的道具信息。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo ReturnedItemInfo;
};
/**
* Message struct for removing item info from the inventory.
* 从库存中移除道具信息的消息结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryRemoveItemInfoMessage
{
GENERATED_BODY()
/**
* The inventory system component associated with the item removal.
* 与道具移除关联的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The item info being removed.
* 正在移除的道具信息。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
FGIS_ItemInfo ItemInfo;
};
/**
* Message struct for collection updates in the inventory.
* 库存中集合更新的消息结构体。
*/
USTRUCT(BlueprintType)
struct FGIS_InventoryCollectionUpdateMessage
{
GENERATED_BODY()
/**
* The inventory system component associated with the collection update.
* 与集合更新关联的库存系统组件。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
/**
* The collection that was updated.
* 已更新的集合。
*/
UPROPERTY(BlueprintReadOnly, Category="GIS")
TObjectPtr<UGIS_ItemCollection> Collection;
};

View File

@@ -0,0 +1,148 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_SerializationStructLibrary.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "GIS_InventorySubsystem.generated.h"
class UGIS_InventorySystemComponent;
class UDataTable;
class UGIS_InventoryFactory;
/**
* Subsystem for managing inventory-related operations, such as item creation.
* 用于管理库存相关操作(如道具创建)的子系统。
*/
UCLASS(Config=Game, DefaultConfig)
class GENERICINVENTORYSYSTEM_API UGIS_InventorySubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
/**
* Gets the inventory subsystem instance from a world context object.
* 从世界上下文对象获取库存子系统实例。
* @param WorldContextObject The object providing the world context. 提供世界上下文的对象。
* @return The inventory subsystem instance, or nullptr if not found. 库存子系统实例如果未找到则返回nullptr。
*/
static UGIS_InventorySubsystem* Get(const UObject* WorldContextObject);
/**
* Initializes the subsystem.
* 初始化子系统。
* @param Collection The subsystem collection. 子系统集合。
*/
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
/**
* Deinitializes the subsystem.
* 反初始化子系统。
*/
virtual void Deinitialize() override;
/**
* Creates an item instance from a definition.
* 从道具定义创建道具实例。
* @param Owner The actor that will own this item (required for network replication). 将拥有此道具的演员(网络复制所需)。
* @param ItemDefinition The item definition to create the instance from. 用于创建实例的道具定义。
* @return The newly created item instance, or nullptr if creation failed. 新创建的道具实例如果创建失败则返回nullptr。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
UGIS_ItemInstance* CreateItem(AActor* Owner, TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition);
/**
* Creates an item instance from a definition (C++ version).
* 从道具定义创建道具实例C++版本)。
* @param Owner The actor that will own this item. 将拥有此道具的演员。
* @param ItemDefinition The item definition to create the instance from. 用于创建实例的道具定义。
* @return The newly created item instance, or nullptr if creation failed. 新创建的道具实例如果创建失败则返回nullptr。
*/
UGIS_ItemInstance* CreateItem(AActor* Owner, const UGIS_ItemDefinition* ItemDefinition);
/**
* Creates a new item by duplicating an existing item.
* 通过复制现有道具创建新道具。
* @param Owner The actor that will own the duplicated item. 将拥有复制道具的演员。
* @param FromItem The original item to duplicate. 要复制的原始道具。
* @attention The duplicated item will have a new unique ID. 复制的道具将具有新的唯一ID。
* @return The duplicated item instance, or nullptr if duplication failed. 复制的道具实例如果复制失败则返回nullptr。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
UGIS_ItemInstance* DuplicateItem(AActor* Owner, UGIS_ItemInstance* FromItem, bool bGenerateNewId = true);
/**
* Serializes an item instance into a record.
* 将道具实例序列化为记录。
* @param Item The item instance to serialize. 要序列化的道具实例。
* @param Record The resulting item record (output). 输出的道具记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
bool SerializeItem(UGIS_ItemInstance* Item, FGIS_ItemRecord& Record);
/**
* Deserializes an item from an item record.
* 从道具记录反序列化道具。
* @param Owner The actor owning the item instance (generally inventory system component's owner). 拥有此道具实例的演员通常是库存系统组件的Owner。
* @param Record The item record to deserialize. 要反序列化的道具记录。
* @return The deserialized item instance, or nullptr if deserialization failed. 反序列化的道具实例如果失败则返回nullptr。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
UGIS_ItemInstance* DeserializeItem(AActor* Owner, const FGIS_ItemRecord& Record);
/**
* Serializes an item collection into a record.
* 将道具集合序列化为记录。
* @param ItemCollection The item collection to serialize. 要序列化的道具集合。
* @param Record The resulting collection record (output). 输出的集合记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
bool SerializeCollection(UGIS_ItemCollection* ItemCollection, FGIS_CollectionRecord& Record);
/**
* Deserializes a collection from a collection record.
* 从集合记录反序列化集合。
* @param InventorySystem The inventory system component to associate with the collection. 与集合关联的库存系统组件。
* @param Record The collection record to deserialize. 要反序列化的集合记录。
* @param ItemsMap A map of item IDs to item instances (output). 道具ID到道具实例的映射输出
*/
UFUNCTION(BlueprintCallable, Category="GIS")
void DeserializeCollection(UGIS_InventorySystemComponent* InventorySystem, const FGIS_CollectionRecord& Record, TMap<FGuid, UGIS_ItemInstance*>& ItemsMap);
/**
* Serializes an entire inventory into a record.
* 将整个库存序列化为记录。
* @param InventorySystem The inventory system component to serialize. 要序列化的库存系统组件。
* @param Record The resulting inventory record. 输出的库存记录。
* @return True if serialization was successful, false otherwise. 如果序列化成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
bool SerializeInventory(UGIS_InventorySystemComponent* InventorySystem, FGIS_InventoryRecord& Record);
/**
* Deserializes an inventory from an inventory record.
* 从库存记录反序列化库存。
* @param InventorySystem The inventory system component to populate. 要填充的库存系统组件。
* @param Record The inventory record to deserialize. 要反序列化的库存记录。
*/
UFUNCTION(BlueprintCallable, Category="GIS")
void DeserializeInventory(UGIS_InventorySystemComponent* InventorySystem, const FGIS_InventoryRecord& Record);
protected:
/**
* Initializes the item factory for the subsystem.
* 初始化子系统的道具工厂。
*/
virtual void InitializeFactory();
/**
* The item factory used to create item instances.
* 用于创建道具实例的道具工厂。
*/
UPROPERTY()
TObjectPtr<UGIS_InventoryFactory> Factory;
};

View File

@@ -0,0 +1,916 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CollectionContainer.h"
#include "GIS_CoreStructLibray.h"
#include "GIS_InventoryMeesages.h"
#include "Items/GIS_ItemInfo.h"
#include "GIS_SerializationStructLibrary.h"
#include "Components/ActorComponent.h"
#include "GIS_InventorySystemComponent.generated.h"
class UGIS_CurrencySystemComponent;
class UGIS_ItemCollectionDefinition;
class UGIS_ItemCollection;
/**
* Delegate triggered when the inventory system is initialized.
* 库存系统初始化时触发的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FGIS_Inventory_InitializedSignature);
/**
* Delegate triggered when an item stack in the inventory is updated.
* 库存中的道具堆栈更新时触发的委托。
* @param Message The update message containing stack details. 包含堆栈详细信息的更新消息。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Inventory_StackUpdateSignature, const FGIS_InventoryStackUpdateMessage&, Message);
/**
* Delegate triggered when an item is added to the inventory (server-side only).
* 道具添加到库存时触发的委托(仅限服务器端)。
* @param Message The message containing details of the added item. 包含添加道具详细信息的消息。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Inventory_AddItemInfoSignature, const FGIS_InventoryAddItemInfoMessage&, Message);
/**
* Delegate triggered when an item addition is rejected (server-side only).
* 道具添加被拒绝时触发的委托(仅限服务器端)。
* @param Message The message containing details of the rejected item. 包含拒绝道具详细信息的消息。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Inventory_AddItemInfoRejectedSignature, const FGIS_InventoryAddItemInfoRejectedMessage&, Message);
/**
* Delegate triggered when an item is removed from the inventory (server-side only).
* 道具从库存移除时触发的委托(仅限服务器端)。
* @param Message The message containing details of the removed item. 包含移除道具详细信息的消息。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Inventory_RemoveItemInfoSignature, const FGIS_InventoryRemoveItemInfoMessage&, Message);
/**
* Delegate triggered when a collection is added or removed from the inventory.
* 集合添加或移除时触发的委托。
* @param Collection The item collection involved. 涉及的道具集合。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_Inventory_CollectionSignature, UGIS_ItemCollection*, Collection);
/**
* Dynamic delegate for inventory system initialization events.
* 库存系统初始化事件的动态委托。
*/
UDELEGATE()
DECLARE_DYNAMIC_DELEGATE(FGIS_InventorySystem_Initialized_DynamicEvent);
/**
* Inventory system component for managing items and collections.
* 管理道具和集合的库存系统组件。
*/
UCLASS(ClassGroup=(GIS), BlueprintType, Blueprintable, meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_InventorySystemComponent : public UActorComponent /*, public IGameFrameworkInitStateInterface*/
{
GENERATED_BODY()
friend FGIS_ItemStackContainer;
friend FGIS_CollectionContainer;
public:
/**
* Sets default values for this component's properties.
* 为组件的属性设置默认值。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_InventorySystemComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
//~UObject interface
/**
* Gets the properties that should be replicated for this object.
* 获取需要为此对象复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Replicates subobjects for this component.
* 为此组件复制子对象。
* @param Channel The actor channel. 演员通道。
* @param Bunch The replication data bunch. 复制数据束。
* @param RepFlags The replication flags. 复制标志。
* @return True if subobjects were replicated, false otherwise. 如果子对象被复制则返回true否则返回false。
*/
virtual bool ReplicateSubobjects(class UActorChannel* Channel, class FOutBunch* Bunch, FReplicationFlags* RepFlags) override;
//~End of UObject interface
//~UActorComponent interface
/**
* Called when the component is registered.
* 组件注册时调用。
*/
virtual void OnRegister() override;
/**
* Initializes the component.
* 初始化组件。
*/
virtual void InitializeComponent() override;
/**
* Prepares the component for replication.
* 为组件的复制做准备。
*/
virtual void ReadyForReplication() override;
/**
* Called when the game starts.
* 游戏开始时调用。
*/
virtual void BeginPlay() override;
/**
* Updates the component each frame.
* 每帧更新组件。
* @param DeltaTime Time since the last tick. 上次tick以来的时间。
* @param TickType The type of tick. tick类型。
* @param ThisTickFunction The tick function. tick函数。
*/
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
//~End of UActorComponent interface
#pragma region Inventory
/**
* Finds the inventory system component on the specified actor.
* 在指定演员上查找库存系统组件。
* @param Actor The actor to search for the component. 要查找组件的演员。
* @param Inventory The found inventory component (output). 找到的库存组件(输出)。
* @return True if the component was found, false otherwise. 如果找到组件则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem", Meta = (DefaultToSelf="Actor", ExpandBoolAsExecs = "ReturnValue"))
static bool FindInventorySystemComponent(const AActor* Actor, UGIS_InventorySystemComponent*& Inventory);
/**
* Gets the inventory system component from the specified actor.
* 从指定演员获取库存系统组件。
* @param Actor The actor to query. 要查询的演员。
* @return The inventory system component, or nullptr if not found. 库存系统组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem", Meta = (DefaultToSelf="Actor"))
static UGIS_InventorySystemComponent* GetInventorySystemComponent(const AActor* Actor);
/**
* Static helper to find the inventory system component on an actor.
* 在演员上查找库存系统组件的静态辅助函数。
* @param Actor The actor to query. 要查询的演员。
* @return The inventory system component, or nullptr if not found. 库存系统组件如果未找到则返回nullptr。
*/
static UGIS_InventorySystemComponent* FindInventorySystemComponent(const AActor* Actor);
/**
* Initializes the inventory system.
* 初始化库存系统。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual void InitializeInventorySystem();
/**
* Initializes the inventory system with a specific record.
* 使用特定记录初始化库存系统。
* @param InventoryRecord The inventory record to initialize with. 初始化使用的库存记录。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual void InitializeInventorySystemWithRecord(const FGIS_InventoryRecord& InventoryRecord);
/**
* Resets the inventory system.
* 重置库存系统。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual void ResetInventorySystem();
/**
* Checks if the inventory system is initialized.
* 检查库存系统是否已初始化。
* @return True if initialized, false otherwise. 如果已初始化则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
bool IsInventoryInitialized() const;
/**
* Binds a delegate to be called when the inventory system is initialized.
* 绑定一个委托,在库存系统初始化时调用。
* @param Delegate The delegate to bind. 要绑定的委托。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
void BindToInventorySystemInitialized(FGIS_InventorySystem_Initialized_DynamicEvent Delegate);
/**
* Gets the associated currency system of this inventory.
* 获取库存关联的货币系统。
* @return The currency system component. 货币系统组件。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
UGIS_CurrencySystemComponent* GetCurrencySystem() const;
/**
* Loads the default loadouts for the inventory.
* 为库存加载默认装备。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual void LoadDefaultLoadouts();
/**
* Server-side function to load default loadouts.
* 服务器端函数,用于加载默认装备。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|InventorySystem")
virtual void ServerLoadDefaultLoadouts();
protected:
/**
* Called when the inventory system is initialized.
* 库存系统初始化时调用。
*/
UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category="GIS|InventorySystem")
void OnInventorySystemInitialized();
/**
* List of delegates for inventory system initialization.
* 库存系统初始化的委托列表。
*/
UPROPERTY()
TArray<FGIS_InventorySystem_Initialized_DynamicEvent> InitializedDelegates;
#pragma endregion
#pragma region InitState
// /**
// * The name of this overall feature.
// * 此功能的整体名称。
// */
// static const FName NAME_ActorFeatureName;
//
// /**
// * Gets the feature name for the init state interface.
// * 获取初始化状态接口的功能名称。
// * @return The feature name. 功能名称。
// */
// virtual FName GetFeatureName() const override;
//
// /**
// * Determines if the component can change its initialization state.
// * 确定组件是否可以更改其初始化状态。
// * @param Manager The component manager. 组件管理器。
// * @param CurrentState The current state. 当前状态。
// * @param DesiredState The desired state. 期望状态。
// * @return True if the state change is allowed, false otherwise. 如果允许状态更改则返回true否则返回false。
// */
// virtual bool CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState) const override;
//
// /**
// * Handles a change in initialization state.
// * 处理初始化状态的更改。
// * @param Manager The component manager. 组件管理器。
// * @param CurrentState The current state. 当前状态。
// * @param DesiredState The desired state. 期望状态。
// */
// virtual void HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState) override;
//
// /**
// * Called when the actor's initialization state changes.
// * 演员的初始化状态更改时调用。
// * @param Params The state change parameters. 状态更改参数。
// */
// virtual void OnActorInitStateChanged(const FActorInitStateChangedParams& Params) override;
//
// /**
// * Checks if the component has reached a specific initialization state.
// * 检查组件是否已达到特定初始化状态。
// * @param State The state to check. 要检查的状态。
// * @return True if the state has been reached, false otherwise. 如果已达到状态则返回true否则返回false。
// */
// virtual bool HasReachedInitState(FGameplayTag State) const override;
//
// /**
// * Checks the default initialization state.
// * 检查默认初始化状态。
// */
// virtual void CheckDefaultInitialization() override;
//
// /**
// * Checks the initialization state of the inventory system.
// * 检查库存系统的初始化状态。
// */
// UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
// virtual void CheckInventoryInitialization();
//
// /**
// * The current initialization state of the component.
// * 组件的当前初始化状态。
// */
// UPROPERTY(VisibleAnywhere, Category="InventorySystem")
// FGameplayTag CurrentInitState{FGameplayTag::EmptyTag};
private:
#pragma endregion
#pragma region Events
public:
/**
* Event triggered when the inventory system is initialized.
* 库存系统初始化时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_InitializedSignature OnInventorySystemInitializedEvent;
/**
* Event triggered when any item stack in collections changes (both server and client).
* 集合中的道具堆栈更改时触发的事件(服务器和客户端均触发)。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_StackUpdateSignature OnInventoryStackUpdate;
/**
* Event triggered when a collection is added to the inventory.
* 集合添加到库存时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_CollectionSignature OnCollectionAddedEvent;
/**
* Event triggered when a collection is removed from the inventory.
* 集合从库存移除时触发的事件。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_CollectionSignature OnCollectionRemovedEvent;
/**
* Event triggered when an item is added to the inventory (server-side only).
* 道具添加到库存时触发的事件(仅限服务器端)。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_AddItemInfoSignature OnInventoryAddItemInfo;
/**
* Event triggered when an item addition is rejected (server-side only).
* 道具添加被拒绝时触发的事件(仅限服务器端)。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_AddItemInfoRejectedSignature OnInventoryAddItemInfo_Rejected;
/**
* Event triggered when an item is removed from the inventory (server-side only).
* 道具从库存移除时触发的事件(仅限服务器端)。
*/
UPROPERTY(BlueprintAssignable)
FGIS_Inventory_RemoveItemInfoSignature OnInventoryRemoveItemInfo;
#pragma endregion
#pragma region Items
/**
* Checks if an item can be added to the inventory.
* 检查道具是否可以添加到库存。
* @param InItemInfo The item info to check. 要检查的道具信息。
* @param OutItemInfo The resulting item info (output). 结果道具信息(输出)。
* @return True if the item can be added, false otherwise. 如果道具可以添加则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual bool CanAddItem(const FGIS_ItemInfo& InItemInfo, FGIS_ItemInfo& OutItemInfo) const;
/**
* Adds an item to the inventory.
* 将道具添加到库存。
* @param ItemInfo The item info specifying the item, collection, and stack details. 指定道具、集合和堆栈详细信息的道具信息。
* @return The number of items added, or 0 if none were added. 添加的道具数量如果未添加则返回0。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem", meta=(AutoCreateRefTerm="ItemInfo"))
virtual FGIS_ItemInfo AddItem(const FGIS_ItemInfo& ItemInfo);
/**
* Adds a group of items to the inventory.
* 将一组道具添加到库存。
* @param ItemInfos The array of item infos to add. 要添加的道具信息数组。
* @return The array of actually added item infos. 实际添加的道具信息数组。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual TArray<FGIS_ItemInfo> AddItems(TArray<FGIS_ItemInfo> ItemInfos);
/**
* Adds an item to a specific collection by its definition.
* 通过道具定义将道具添加到指定集合。
* @param CollectionTag The tag of the target collection. 目标集合的标签。
* @param ItemDefinition The item definition to add. 要添加的道具定义。
* @param NewAmount The amount of the item to add. 要添加的道具数量。
* @return The actually added item info. 实际添加的道具信息。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual FGIS_ItemInfo AddItemByDefinition(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, const int32 NewAmount);
/**
* Server-side function to add an item to a specific collection by its definition.
* 服务器端函数,通过道具定义将道具添加到指定集合。
* @param CollectionTag The tag of the target collection. 目标集合的标签。
* @param ItemDefinition The item definition to add. 要添加的道具定义。
* @param NewAmount The amount of the item to add. 要添加的道具数量。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|InventorySystem")
void ServerAddItemByDefinition(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, const TSoftObjectPtr<UGIS_ItemDefinition>& ItemDefinition, const int32 NewAmount);
/**
* Checks if an item can be moved within the inventory.
* 检查道具是否可以在库存内移动。
* @param ItemInfo The item info specifying the source and target collection. 指定源集合和目标集合的道具信息。
* @return True if the item can be moved, false otherwise. 如果道具可以移动则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem", meta=(AutoCreateRefTerm="ItemInfo"))
virtual bool CanMoveItem(const FGIS_ItemInfo& ItemInfo) const;
/**
* Moves an item within the inventory.
* 在库存内移动道具。
* @param ItemInfo The item info specifying the source and target collection. 指定源集合和目标集合的道具信息。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem", meta=(AutoCreateRefTerm="ItemInfo"))
virtual void MoveItem(const FGIS_ItemInfo& ItemInfo);
/**
* Server-side function to move an item within the inventory.
* 服务器端函数,在库存内移动道具。
* @param ItemInfo The item info specifying the source and target collection. 指定源集合和目标集合的道具信息。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|InventorySystem")
virtual void ServerMoveItem(const FGIS_ItemInfo& ItemInfo);
/**
* Checks if an item can be removed from the inventory.
* 检查道具是否可以从库存移除。
* @param ItemInfo The item info to check. 要检查的道具信息。
* @return True if the item can be removed, false otherwise. 如果道具可以移除则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
bool CanRemoveItem(const FGIS_ItemInfo& ItemInfo) const;
/**
* Removes an item from the inventory.
* 从库存移除道具。
* @param ItemInfo The item info specifying the item and amount to remove. 指定要移除的道具和数量的道具信息。
* @return The item info of the actually removed items. 实际移除的道具信息。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
FGIS_ItemInfo RemoveItem(const FGIS_ItemInfo& ItemInfo);
/**
* Server-side function to remove an item from the inventory.
* 服务器端函数,从库存移除道具。
* @param ItemInfo The item info specifying the item and amount to remove. 指定要移除的道具和数量的道具信息。
*/
UFUNCTION(Server, Reliable, BlueprintCallable, Category="GIS|InventorySystem")
void ServerRemoveItem(FGIS_ItemInfo ItemInfo);
/**
* Implementation of the server-side item removal.
* 服务器端道具移除的实现。
* @param ItemInfo The item info specifying the item and amount to remove. 指定要移除的道具和数量的道具信息。
*/
virtual void ServerRemoveItem_Implementation(FGIS_ItemInfo ItemInfo);
/**
* Removes an item from the inventory by its definition.
* 通过道具定义从库存移除道具。
* @param ItemDefinition The item definition to remove. 要移除的道具定义。
* @param Amount The amount to remove. 要移除的数量。
* @return The item info of the actually removed items. 实际移除的道具信息。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual FGIS_ItemInfo RemoveItemByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, const int32 Amount);
/**
* Removes all items from the inventory.
* 从库存移除所有道具。
* @param RemoveItemsFromIgnoredCollections Whether to remove items from ignored collections. 是否移除忽略集合中的道具。
* @param DisableEventsWhileRemoving Whether to disable events during removal. 是否在移除期间禁用事件。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual void RemoveAllItems(bool RemoveItemsFromIgnoredCollections = false, bool DisableEventsWhileRemoving = true);
#pragma endregion
#pragma region Item Queries
/**
* Gets the amount of a specific item in the inventory.
* 获取库存中特定道具的数量。
* @param Item The item instance to check. 要检查的道具实例。
* @param SimilarItem Whether to count similar items or exact matches. 是否统计相似道具或精确匹配。
* @return The amount of the item in the inventory. 库存中的道具数量。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual int32 GetItemAmount(UGIS_ItemInstance* Item, bool SimilarItem = true) const;
/**
* Gets the total amount of items with the specified definition in all collections.
* 获取所有集合中具有指定定义的道具总数。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param Unique Whether to count unique items or total amounts. 是否统计唯一道具或总数量。
* @return The number of items with the specified definition. 具有指定定义的道具数量。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual int32 GetItemAmountByDefinition(TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, bool Unique) const;
/**
* Gets item info for a specific item in a collection.
* 获取集合中特定道具的道具信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param OutItemInfo The item info (output). 道具信息(输出)。
* @return True if the item was found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
virtual bool GetItemInfoInCollection(UGIS_ItemInstance* Item, UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, FGIS_ItemInfo& OutItemInfo) const;
/**
* Finds item info for a specific item in a collection.
* 在集合中查找特定道具的道具信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param OutItemInfo The item info (output). 道具信息(输出)。
* @return True if the item was found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|InventorySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool FindItemInfoInCollection(UGIS_ItemInstance* Item, UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, FGIS_ItemInfo& OutItemInfo) const;
/**
* Gets all item infos in a specified collection.
* 获取指定集合中的所有道具信息。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param OutItemInfos The array of item infos (output). 道具信息数组(输出)。
* @return True if any items were found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
virtual bool GetAllItemInfosInCollection(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, TArray<FGIS_ItemInfo>& OutItemInfos) const;
/**
* Finds all item infos in a specified collection.
* 查找指定集合中的所有道具信息。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param OutItemInfos The array of item infos (output). 道具信息数组(输出)。
* @return True if any items were found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|InventorySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool FindAllItemInfosInCollection(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, TArray<FGIS_ItemInfo>& OutItemInfos) const;
/**
* Retrieves information about an item instance in the inventory.
* 检索库存中指定道具实例的信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param ItemInfo The item info (output). 道具信息(输出)。
* @return True if the item was found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
virtual bool GetItemInfo(UGIS_ItemInstance* Item, FGIS_ItemInfo& ItemInfo) const;
/**
* Finds information about an item instance in the inventory.
* 查找库存中指定道具实例的信息。
* @param Item The item instance to query. 要查询的道具实例。
* @param ItemInfo The item info (output). 道具信息(输出)。
* @return True if the item was found, false otherwise. 如果找到道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|InventorySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool FindItemInfo(UGIS_ItemInstance* Item, FGIS_ItemInfo& ItemInfo) const;
/**
* Retrieves the first item info matching the specified definition.
* 检索匹配指定定义的第一个道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfo The first matching item info (output). 匹配的第一个道具信息(输出)。
* @return True if a matching item was found, false otherwise. 如果找到匹配的道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
virtual bool GetItemInfoByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, FGIS_ItemInfo& OutItemInfo) const;
/**
* Finds the first item info matching the specified definition.
* 查找匹配指定定义的第一个道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfo The first matching item info (output). 匹配的第一个道具信息(输出)。
* @return True if a matching item was found, false otherwise. 如果找到匹配的道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|InventorySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
bool FindItemInfoByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, FGIS_ItemInfo& OutItemInfo) const;
/**
* Retrieves all item infos matching the specified definition across all collections.
* 检索所有集合中匹配指定定义的道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfos The array of matching item infos (output). 匹配的道具信息数组(输出)。
* @return True if any matching items were found, false otherwise. 如果找到匹配的道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem")
virtual bool GetItemInfosByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, TArray<FGIS_ItemInfo>& OutItemInfos) const;
/**
* Finds all item infos matching the specified definition across all collections.
* 查找所有集合中匹配指定定义的道具信息。
* @param ItemDefinition The item definition to query. 要查询的道具定义。
* @param OutItemInfos The array of matching item infos (output). 匹配的道具信息数组(输出)。
* @return True if any matching items were found, false otherwise. 如果找到匹配的道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure=false, Category="GIS|InventorySystem", meta=(ExpandBoolAsExecs="ReturnValue"))
virtual bool FindItemInfosByDefinition(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, TArray<FGIS_ItemInfo>& OutItemInfos) const;
/**
* Gets all item infos from the inventory.
* 获取库存中的所有道具信息。
* @return The array of all item infos in the inventory. 库存中的所有道具信息数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual TArray<FGIS_ItemInfo> GetItemInfos() const;
/**
* Checks if the inventory has enough items of a specific definition.
* 检查库存中是否有足够多的指定道具。
* @param ItemDefinition The item definition to check. 要检查的道具定义。
* @param Amount The required amount. 所需数量。
* @return True if there are enough items, false otherwise. 如果道具数量足够则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual bool HasEnoughItem(const TSoftObjectPtr<UGIS_ItemDefinition> ItemDefinition, int32 Amount) const;
#pragma endregion
#pragma region Collections
/**
* Gets all collections in the inventory.
* 获取库存中的所有集合。
* @return The array of item collections. 道具集合数组。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual TArray<UGIS_ItemCollection*> GetItemCollections() const;
/**
* Checks if all default collections have been created.
* 检查是否已创建所有默认集合。
* @return True if all default collections are created, false otherwise. 如果所有默认集合都已创建则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual bool IsDefaultCollectionCreated() const;
/**
* Determines the target collection for an item.
* 确定道具的目标集合。
* @param ItemInfo The item info to determine the collection for. 要确定集合的道具信息。
* @return The target item collection. 目标道具集合。
*/
UGIS_ItemCollection* DetermineTargetCollection(const FGIS_ItemInfo& ItemInfo) const;
/**
* Gets the default item collection.
* 获取默认道具集合。
* @return The default item collection. 默认道具集合。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual UGIS_ItemCollection* GetDefaultCollection() const;
/**
* Gets the number of collections in the inventory.
* 获取库存中的集合数量。
* @return The number of collections. 集合数量。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
int32 GetCollectionCount() const;
/**
* Gets a collection by its tag.
* 通过标签获取集合。
* @param CollectionTag The tag of the collection. 集合的标签。
* @return The collection with the specified tag. 具有指定标签的集合。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
UGIS_ItemCollection* GetCollectionByTag(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag) const;
/**
* Gets a collection by matching tags.
* 通过匹配标签获取集合。
* @param Tags The tags to match. 要匹配的标签。
* @return The collection matching the tags. 匹配标签的集合。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
virtual UGIS_ItemCollection* GetCollectionByTags(FGameplayTagContainer Tags);
/**
* Gets a collection by its ID.
* 通过ID获取集合。
* @param CollectionId The ID of the collection. 集合的ID。
* @return The collection with the specified ID. 具有指定ID的集合。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|InventorySystem")
UGIS_ItemCollection* GetCollectionById(FGuid CollectionId) const;
/**
* Gets a typed collection by its tag.
* 通过标签获取类型化的集合。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param DesiredClass The desired class of the collection. 集合的期望类。
* @return The typed collection with the specified tag. 具有指定标签的类型化集合。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem", meta=(DeterminesOutputType="DesiredClass", DynamicOutputParam="ReturnValue"))
UGIS_ItemCollection* GetTypedCollectionByTag(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, TSubclassOf<UGIS_ItemCollection> DesiredClass) const;
/**
* Finds a typed collection by its tag.
* 通过标签查找类型化的集合。
* @param CollectionTag The tag of the collection. 集合的标签。
* @param DesiredClass The desired class of the collection. 集合的期望类。
* @param OutCollection The found collection (output). 找到的集合(输出)。
* @return True if the collection was found, false otherwise. 如果找到集合则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, Category="GIS|InventorySystem", meta=(DeterminesOutputType="DesiredClass", DynamicOutputParam="OutCollection", ExpandBoolAsExecs="ReturnValue"))
bool FindTypedCollectionByTag(UPARAM(meta=(Categories="GIS.Collection"))
const FGameplayTag CollectionTag, TSubclassOf<UGIS_ItemCollection> DesiredClass, UGIS_ItemCollection*& OutCollection);
/**
* Adds a collection to the inventory by its definition.
* 通过定义将集合添加到库存。
* @param CollectionDefinition The collection definition to add. 要添加的集合定义。
* @return The added collection instance. 添加的集合实例。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|InventorySystem")
virtual UGIS_ItemCollection* AddCollectionByDefinition(TSoftObjectPtr<const UGIS_ItemCollectionDefinition> CollectionDefinition);
/**
* Removes a collection entry by its index.
* 通过索引移除集合条目。
* @param Idx The index of the collection entry to remove. 要移除的集合条目索引。
*/
virtual void RemoveCollectionEntry(int32 Idx);
/**
* Adds a collection entry to the inventory.
* 将集合条目添加到库存。
* @param NewEntry The new collection entry to add. 要添加的新集合条目。
* @return True if the entry was added, false otherwise. 如果条目被添加则返回true否则返回false。
*/
virtual bool AddCollectionEntry(const FGIS_CollectionEntry& NewEntry);
/**
* Creates and initializes a new item collection from a definition.
* 从定义创建并初始化新的道具集合。
* @param CollectionDefinition The collection definition. 集合定义。
* @return The newly created uninitialized item collection instance. 新创建的未初始化道具集合实例。
*/
virtual UGIS_ItemCollection* CreateCollectionInstance(const UGIS_ItemCollectionDefinition* CollectionDefinition);
/**
* Checks if a collection should be ignored when searching for items.
* 检查集合在搜索道具时是否应被忽略。
* @param ItemCollection The collection to check. 要检查的集合。
* @return True if the collection should be ignored, false otherwise. 如果集合应被忽略则返回true否则返回false。
*/
virtual bool IsIgnoredCollection(UGIS_ItemCollection* ItemCollection) const;
protected:
/**
* Called when a collection is added to the inventory.
* 集合添加到库存时调用。
* @param Entry The added collection entry. 添加的集合条目。
*/
virtual void OnCollectionAdded(const FGIS_CollectionEntry& Entry);
/**
* Called when a collection is removed from the inventory.
* 集合从库存移除时调用。
* @param Entry The removed collection entry. 移除的集合条目。
*/
virtual void OnCollectionRemoved(const FGIS_CollectionEntry& Entry);
/**
* Called when a collection is updated.
* 集合更新时调用。
* @param Entry The updated collection entry. 更新的集合条目。
*/
virtual void OnCollectionUpdated(const FGIS_CollectionEntry& Entry);
/**
* Processes pending collections in the inventory.
* 处理库存中的待处理集合。
*/
virtual void ProcessPendingCollections();
/**
* Map of pending collection entries.
* 待处理集合条目的映射。
*/
UPROPERTY(VisibleAnywhere, Category="InventorySystem", Transient)
TMap<FGuid, FGIS_CollectionEntry> PendingCollections;
#pragma endregion
#pragma region Properties
/**
* Predefined collections for the inventory.
* 库存的预定义集合。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="InventorySystem")
TArray<TObjectPtr<const UGIS_ItemCollectionDefinition>> CollectionDefinitions;
/**
* Default items for initial collections.
* 默认集合的默认道具。
*/
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="InventorySystem", meta=(TitleProperty="Tag"))
TArray<FGIS_DefaultLoadout> DefaultLoadouts;
/**
* Container for the inventory's collections.
* 库存集合的容器。
*/
UPROPERTY(VisibleAnywhere, Replicated, Category="InventorySystem", meta=(ShowOnlyInnerProperties))
FGIS_CollectionContainer CollectionContainer;
/**
* Cached map for O(1) collection lookups by ID.
* 按ID进行O(1)集合查找的缓存映射。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="InventorySystem", Transient, meta=(ForceInlineRow))
TMap<FGuid, TObjectPtr<UGIS_ItemCollection>> CollectionIdToInstanceMap;
/**
* Cached map for O(1) collection lookups by tag (commented out).
* 按标签进行O(1)集合查找的缓存映射(已注释)。
*/
// UPROPERTY()
// TMap<FGameplayTag, TObjectPtr<UGIS_ItemCollection>> CollectionTagToInstanceMap;
/**
* Whether to use the initialization state chain.
* 是否使用初始化状态链。
*/
// UPROPERTY(EditAnywhere, Category="InventorySystem")
// bool bUseInitStateChain = false;
/**
* Whether to initialize the inventory on BeginPlay.
* 是否在BeginPlay时初始化库存。
*/
UPROPERTY(EditAnywhere, Category="InventorySystem")
bool bInitializeOnBeginplay = false;
/**
* Indicates if the inventory system is initialized.
* 指示库存系统是否已初始化。
*/
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="InventorySystem", ReplicatedUsing=OnInventorySystemInitialized)
bool bInventorySystemInitialized{false};
/**
* Collections with these tags will be ignored when searching for items.
* 搜索道具时将忽略具有这些标签的集合。
*/
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="InventorySystem")
FGameplayTagContainer IgnoredCollections;
/**
* The associated currency system component.
* 关联的货币系统组件。
*/
UPROPERTY()
UGIS_CurrencySystemComponent* CurrencySystem;
#pragma endregion
#pragma region Editor
#if WITH_EDITOR
/**
* Called after the component is loaded in the editor.
* 编辑器中组件加载后调用。
*/
virtual void PostLoad() override;
/**
* Called before the component is saved in the editor.
* 编辑器中组件保存前调用。
* @param SaveContext The save context. 保存上下文。
*/
virtual void PreSave(FObjectPreSaveContext SaveContext) override;
/**
* Validates the component's data in the editor.
* 在编辑器中验证组件的数据。
* @param Context The validation context. 验证上下文。
* @return The result of the data validation. 数据验证的结果。
*/
virtual EDataValidationResult IsDataValid(FDataValidationContext& Context) const override;
#endif
#pragma endregion
};

View File

@@ -0,0 +1,96 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Engine/DeveloperSettings.h"
#include "GIS_InventorySystemSettings.generated.h"
class UGIS_InventoryFactory;
/**
* Structure representing a mapping of asset path prefix to item definition schema.
* 表示资产路径前缀到道具定义模式的映射结构体。
*/
USTRUCT()
struct GENERICINVENTORYSYSTEM_API FGIS_ItemDefinitionSchemaEntry
{
GENERATED_BODY()
/**
* The path prefix for assets to apply this schema (e.g., "/Game/ActionRPG").
* 应用此模式的资产路径前缀(例如,"/Game/ActionRPG")。
*/
UPROPERTY(config, EditAnywhere, Category="Settings", meta=(ContentDir))
FString PathPrefix;
/**
* The schema to apply for assets under this path prefix.
* 对此路径前缀下的资产应用的模式。
*/
UPROPERTY(config, EditAnywhere, Category="Settings", meta=(AllowedClasses="/Script/GenericInventorySystem.GIS_ItemDefinitionSchema"))
FSoftObjectPath Schema;
};
/**
* Settings for the Generic Inventory System.
* 通用库存系统的设置。
*/
UCLASS(Config=Game, defaultconfig)
class GENERICINVENTORYSYSTEM_API UGIS_InventorySystemSettings : public UDeveloperSettings
{
GENERATED_BODY()
public:
/**
* Constructor for the inventory system settings.
* 库存系统设置的构造函数。
*/
UGIS_InventorySystemSettings();
/**
* Gets the category name for these settings.
* 获取这些设置的类别名称。
* @return The category name. 类别名称。
*/
virtual FName GetCategoryName() const override;
/**
* Gets the inventory system settings instance.
* 获取库存系统设置实例。
* @return The inventory system settings. 库存系统设置。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|Settings", meta=(DisplayName="Get Inventory System Settings"))
static const UGIS_InventorySystemSettings* Get();
/**
* Gets the item definition schema for a given asset path.
* 获取给定资产路径的道具定义模式。
* @param AssetPath The path of the asset to find a schema for. 要查找模式的资产路径。
* @return The schema to use, or nullptr if none found. 要使用的模式如果未找到则返回nullptr。
*/
const class UGIS_ItemDefinitionSchema* GetItemDefinitionSchemaForAsset(const FString& AssetPath) const;
/**
* Inventory Factory class for managing low level operation in GIS.
* 库存工厂类用于管理GIS中的底层操作。
*/
UPROPERTY(config, Category="Settings", EditDefaultsOnly, NoClear)
TSoftClassPtr<UGIS_InventoryFactory> InventoryFactoryClass;
/**
* Array of path-to-schema mappings for item definition validation.
* 用于道具定义验证的路径到模式的映射数组。
* @details Assets under the specified path prefix will use the corresponding schema. If no match is found, the default schema is used.
* @细节 指定路径前缀下的资产将使用对应的模式。如果未找到匹配,则使用默认模式。
*/
UPROPERTY(config, EditAnywhere, Category="Settings")
TArray<FGIS_ItemDefinitionSchemaEntry> ItemDefinitionSchemaMap;
/**
* The default schema to enforce item definition layout consistency when no path-specific schema is found.
* 当未找到路径特定模式时,用于强制道具定义布局一致性的默认模式。
*/
UPROPERTY(config, EditAnywhere, Category="Settings", meta=(AllowedClasses="/Script/GenericInventorySystem.GIS_ItemDefinitionSchema"))
FSoftObjectPath DefaultItemDefinitionSchema;
};

View File

@@ -0,0 +1,72 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "NativeGameplayTags.h"
/**
* Namespace for collection-related gameplay tags.
* 集合相关游戏标签的命名空间。
*/
namespace GIS_CollectionTags
{
/** Main inventory collection tag. 主要库存集合标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Main)
/** Hidden inventory collection tag. 隐藏库存集合标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Hidden)
/** Equipped items collection tag. 已装备道具集合标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Equipped)
/** Quick bar collection tag. 快捷栏集合标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(QuickBar);
}
/**
* Namespace for inventory initialization state tags.
* 库存初始化状态标签的命名空间。
*/
namespace GIS_InventoryInitState
{
/** Tag indicating the inventory has been spawned. 指示库存已生成的标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Spawned);
/** Tag indicating data is available for the inventory. 指示库存数据可用的标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(DataAvailable);
/** Tag indicating the inventory data is initialized. 指示库存数据已初始化的标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(DataInitialized);
/** Tag indicating the inventory is ready for gameplay. 指示库存已准备好用于游戏的标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(GameplayReady);
}
// namespace GIS_MessageTags
// {
// /** Tag for item stack updates. 道具堆叠更新标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(ItemStackUpdate);
// /** Tag for inventory updates. 库存更新标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(InventoryUpdate);
// /** Tag for collection updates. 集合更新标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(CollectionUpdate);
// /** Tag for adding item information to the inventory. 添加道具信息到库存的标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(InventoryAddItemInfo);
// /** Tag for rejected item addition to the inventory. 拒绝添加道具到库存的标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(InventoryAddItemInfoRejected)
// /** Tag for removing item information from the inventory. 从库存移除道具信息的标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(InventoryRemoveItemInfo);
// /** Tag for quick bar slots changes. 快捷栏槽位更改标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(QuickBarSlotsChanged);
// /** Tag for quick bar active index changes. 快捷栏激活索引更改标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(QuickBarActiveIndexChanged);
// }
/**
* Namespace for attribute-related gameplay tags.
* 属性相关游戏标签的命名空间。
*/
namespace GIS_AttributeTags
{
/** Tag for the testing attribute. 用于测试属性的标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(Dummy);
// /** Tag for the current enhancement level of an item. 道具当前强化等级标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(EnhancedLevel);
// /** Tag for the maximum enhancement level of an item. 道具最大强化等级标签。 */
// GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(MaxEnhancedLevel);
/** Tag for the stack size limit of an item. 道具堆叠数量限制标签。 */
GENERICINVENTORYSYSTEM_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(StackSizeLimit);
}

View File

@@ -0,0 +1,52 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
DECLARE_STATS_GROUP(TEXT("GIS"), STATGROUP_GIS, STATCAT_Advanced)
/**
* Gets the context string for logging purposes.
* 获取用于日志记录的上下文字符串。
* @param ContextObject The object providing the context (optional). 提供上下文的对象(可选)。
* @return The context string. 上下文字符串。
*/
GENERICINVENTORYSYSTEM_API FString GetGISLogContextString(const UObject* ContextObject = nullptr);
/**
* Log category for general inventory system messages.
* 通用库存系统消息的日志类别。
*/
GENERICINVENTORYSYSTEM_API DECLARE_LOG_CATEGORY_EXTERN(LogGIS, Log, All);
/**
* Macro for logging inventory system messages.
* 用于记录库存系统消息的宏。
* @details Logs messages with function name and formatted message. 记录包含函数名和格式化消息的日志。
*/
#define GIS_LOG(Verbosity, Format, ...) \
{ \
UE_LOG(LogGIS, Verbosity, TEXT("%S: %s"),__FUNCTION__, *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
/**
* Macro for context-based logging for inventory system.
* 用于库存系统的基于上下文的日志记录宏。
* @details Logs messages with function name, context, and formatted message. 记录包含函数名、上下文和格式化消息的日志。
*/
#define GIS_CLOG(Verbosity, Format, ...) \
{ \
UE_LOG(LogGIS, Verbosity, TEXT("%S: ctx(%s) %s"),__FUNCTION__, *GetGISLogContextString(this), *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}
/**
* Macro for context-based logging with an explicit owner.
* 使用显式拥有者进行基于上下文的日志记录宏。
* @details Logs messages with function name, owner context, and formatted message. 记录包含函数名、拥有者上下文和格式化消息的日志。
*/
#define GIS_OWNED_CLOG(LogOwner, Verbosity, Format, ...) \
{ \
UE_LOG(LogGIS, Verbosity, TEXT("%S: ctx(%s) %s"),__FUNCTION__, *GetGISLogContextString(LogOwner), *FString::Printf(TEXT(Format), ##__VA_ARGS__)) \
}

View File

@@ -0,0 +1,27 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "Modules/ModuleManager.h"
/**
* Module class for the Generic Inventory System.
* 通用库存系统的模块类。
* @details Implements the module interface for initializing and shutting down the inventory system.
* @细节 实现模块接口以初始化和关闭库存系统。
*/
class FGenericInventorySystemModule : public IModuleInterface
{
public:
/**
* Called when the module is loaded into memory.
* 模块加载到内存时调用。
*/
virtual void StartupModule() override;
/**
* Called when the module is unloaded from memory.
* 模块从内存中卸载时调用。
*/
virtual void ShutdownModule() override;
};

View File

@@ -0,0 +1,42 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_PickupComponent.h"
#include "GIS_CurrencyPickupComponent.generated.h"
class UGIS_CurrencySystemComponent;
/**
* Component for picking up currencies into the currency system.
* 用于将货币拾取到货币系统的组件。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_CurrencyPickupComponent : public UGIS_PickupComponent
{
GENERATED_BODY()
public:
/**
* Called when the game starts to initialize the component.
* 游戏开始时调用以初始化组件。
*/
virtual void BeginPlay() override;
/**
* Performs the pickup logic, adding currencies to the picker's currency system.
* 执行拾取逻辑,将货币添加到拾取者的货币系统。
* @param Picker The inventory system component of the actor performing the pickup. 执行拾取的演员的库存系统组件。
* @return True if the pickup was successful, false otherwise. 如果拾取成功则返回true否则返回false。
*/
virtual bool Pickup(UGIS_InventorySystemComponent* Picker) override;
protected:
/**
* The currency system component associated with this pickup.
* 与此拾取关联的货币系统组件。
*/
UPROPERTY()
UGIS_CurrencySystemComponent* OwningCurrencySystem;
};

View File

@@ -0,0 +1,66 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_PickupComponent.h"
#include "GIS_InventoryPickupComponent.generated.h"
class UGIS_ItemCollection;
/**
* Component for picking up an entire inventory into a specified collection.
* 用于将整个库存拾取到指定集合的组件。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_InventoryPickupComponent : public UGIS_PickupComponent
{
GENERATED_BODY()
public:
/**
* Called when the game starts to initialize the component.
* 游戏开始时调用以初始化组件。
*/
virtual void BeginPlay() override;
/**
* Performs the pickup logic, transferring the inventory to the picker's collection.
* 执行拾取逻辑,将库存转移到拾取者的集合。
* @param Picker The inventory system component of the actor picking up the inventory. 拾取库存的演员的库存系统组件。
* @return True if the pickup was successful, false otherwise. 如果拾取成功则返回true否则返回false。
*/
virtual bool Pickup(UGIS_InventorySystemComponent* Picker) override;
/**
* Gets the owning inventory system component.
* 获取拥有的库存系统组件。
* @return The inventory system component, or nullptr if not set. 库存系统组件如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|Pickup")
UGIS_InventorySystemComponent* GetOwningInventory() const;
protected:
/**
* Adds the pickup inventory to the specified destination collection.
* 将拾取的库存添加到指定的目标集合。
* @param DestCollection The destination collection to add the inventory to. 要添加库存的目标集合。
* @return True if the addition was successful, false otherwise. 如果添加成功则返回true否则返回false。
*/
bool AddPickupToCollection(UGIS_ItemCollection* DestCollection);
/**
* Specifies the collection in the picker's inventory to add the items to (defaults to Item.Collection.Main if not set).
* 指定拾取者库存中要添加道具的集合如果未设置默认为Item.Collection.Main
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Pickup", meta=(Categories="GIS.Collection"))
FGameplayTag CollectionTag;
/**
* The inventory system component associated with this pickup.
* 与此拾取关联的库存系统组件。
*/
UPROPERTY()
TObjectPtr<UGIS_InventorySystemComponent> Inventory;
};

View File

@@ -0,0 +1,75 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameplayTagContainer.h"
#include "GIS_PickupComponent.h"
#include "GIS_ItemPickupComponent.generated.h"
class UGIS_InventorySystemComponent;
class UGIS_WorldItemComponent;
class UGIS_ItemCollection;
/**
* Component for picking up a single item, requiring a WorldItemComponent on the same actor.
* 用于拾取单个道具的组件需要与GIS_WorldItemComponent共存于同一演员。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_ItemPickupComponent : public UGIS_PickupComponent
{
GENERATED_BODY()
public:
/**
* Performs the pickup logic, adding the item to the picker's inventory.
* 执行拾取逻辑,将道具添加到拾取者的库存。
* @param Picker The inventory system component of the actor performing the pickup. 执行拾取的演员的库存系统组件。
* @return True if the pickup was successful, false otherwise. 如果拾取成功则返回true否则返回false。
*/
virtual bool Pickup(UGIS_InventorySystemComponent* Picker) override;
/**
* Gets the associated world item component.
* 获取关联的世界道具组件。
* @return The world item component, or nullptr if not found. 世界道具组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|Pickup")
UGIS_WorldItemComponent* GetWorldItem() const;
protected:
/**
* Specifies the collection in the picker's inventory to add the item to (defaults to Item.Collection.Main if not set).
* 指定拾取者库存中要添加道具的集合如果未设置默认为Item.Collection.Main
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Pickup", meta=(Categories="GIS.Collection"))
FGameplayTag CollectionTag;
/**
* If true, the pickup fails if the full amount cannot be added to the inventory.
* 如果为true当无法将全部数量添加到库存集合时拾取失败。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Pickup")
bool bFailIfFullAmountNotFit = false;
/**
* Called when the game starts to initialize the component.
* 游戏开始时调用以初始化组件。
*/
virtual void BeginPlay() override;
/**
* Attempts to add the item to the picker's inventory collection.
* 尝试将道具添加到拾取者的库存集合。
* @param Picker The inventory system component of the actor performing the pickup. 执行拾取的演员的库存系统组件。
* @return True if the addition was successful, false otherwise. 如果添加成功则返回true否则返回false。
*/
bool TryAddToCollection(UGIS_InventorySystemComponent* Picker);
/**
* The associated world item component.
* 关联的世界道具组件。
*/
UPROPERTY()
TObjectPtr<UGIS_WorldItemComponent> WorldItemComponent;
};

View File

@@ -0,0 +1,31 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "GIS_PickupActorInterface.generated.h"
/**
* Interface for filtering pickup class selection.
* 用于筛选拾取类选择的接口。
* @details Acts as a marker interface for actors that support pickup functionality.
* @细节 作为支持拾取功能的演员的标记接口。
*/
UINTERFACE()
class UGIS_PickupActorInterface : public UInterface
{
GENERATED_BODY()
};
/**
* Interface class for pickup actor functionality.
* 拾取演员功能的接口类。
*/
class GENERICINVENTORYSYSTEM_API IGIS_PickupActorInterface
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
// 在此添加接口函数。此类将被继承以实现该接口。
};

View File

@@ -0,0 +1,70 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "GIS_PickupComponent.generated.h"
class UGIS_InventorySystemComponent;
/**
* Delegate triggered when a pickup action succeeds or fails.
* 拾取动作成功或失败时触发的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FGIS_PickupSignature);
/**
* Base component for handling pickup logic in the inventory system.
* 库存系统中处理拾取逻辑的基组件。
* @details Provides the core functionality for picking up items, currencies, or inventories.
* @细节 提供拾取道具、货币或库存的核心功能。
*/
UCLASS(Abstract, Blueprintable, BlueprintType)
class GENERICINVENTORYSYSTEM_API UGIS_PickupComponent : public UActorComponent
{
GENERATED_BODY()
public:
/**
* Constructor for the pickup component.
* 拾取组件的构造函数。
*/
UGIS_PickupComponent();
/**
* Performs the pickup logic, typically called during interaction.
* 执行拾取逻辑,通常在交互时调用。
* @param Picker The inventory system component of the actor performing the pickup. 执行拾取的演员的库存系统组件。
* @return True if the pickup was successful, false otherwise. 如果拾取成功则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="GIS|Pickup")
virtual bool Pickup(UGIS_InventorySystemComponent* Picker);
/**
* Delegate triggered when the pickup action succeeds.
* 拾取动作成功时触发的委托。
*/
UPROPERTY(BlueprintAssignable, Category="Pickup")
FGIS_PickupSignature OnPickupSuccess;
/**
* Delegate triggered when the pickup action fails.
* 拾取动作失败时触发的委托。
*/
UPROPERTY(BlueprintAssignable, Category="Pickup")
FGIS_PickupSignature OnPickupFail;
protected:
/**
* Notifies listeners of a successful pickup.
* 通知监听者拾取成功。
*/
virtual void NotifyPickupSuccess();
/**
* Notifies listeners of a failed pickup.
* 通知监听者拾取失败。
*/
virtual void NotifyPickupFailed();
};

View File

@@ -0,0 +1,160 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GIS_CoreStructLibray.h"
#include "Items/GIS_ItemInfo.h"
#include "Components/ActorComponent.h"
#include "GIS_WorldItemComponent.generated.h"
class UGIS_ItemInstance;
/**
* Delegate triggered when an item info is set.
* 道具信息设置时触发的委托。
*/
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FGIS_ItemInfoSetSignature, const FGIS_ItemInfo&, ItemInfo);
/**
* Component for generating or referencing items in the world.
* 用于在世界中生成或引用道具的组件。
* @details Used by item pickups to generate item instances or by spawned equipment to hold references to source items.
* @细节 道具拾取使用此组件生成道具实例,或由生成的装备使用以持有源道具的引用。
*/
UCLASS(ClassGroup=(GIS), meta=(BlueprintSpawnableComponent))
class GENERICINVENTORYSYSTEM_API UGIS_WorldItemComponent : public UActorComponent
{
GENERATED_BODY()
public:
/**
* Constructor for the world item component.
* 世界道具组件的构造函数。
* @param ObjectInitializer The object initializer. 对象初始化器。
*/
UGIS_WorldItemComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
/**
* Gets the properties that should be replicated for this component.
* 获取需要为此组件复制的属性。
* @param OutLifetimeProps Array to store the replicated properties. 存储复制属性的数组。
*/
virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
/**
* Gets the world item component from an actor.
* 从演员获取世界道具组件。
* @param Actor The actor to query for the world item component. 要查询世界道具组件的演员。
* @return The world item component, or nullptr if not found. 世界道具组件如果未找到则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|WorldItem", meta=(DefaultToSelf="Actor"))
static UGIS_WorldItemComponent* GetWorldItemComponent(const AActor* Actor);
/**
* Creates an item instance from a definition.
* 从定义创建道具实例。
* @param ItemDefinition The item definition and amount to create the instance from. 用于创建实例的道具定义和数量。
*/
UFUNCTION(BlueprintCallable, Category="GIS|WorldItem")
void CreateItemFromDefinition(FGIS_ItemDefinitionAmount ItemDefinition);
/**
* Checks if the component has a valid item definition.
* 检查组件是否具有有效的道具定义。
* @return True if the component will auto-create and own an item, false otherwise. 如果组件将自动创建并拥有道具则返回true否则返回false。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|WorldItem")
bool HasValidDefinition() const;
/**
* Sets the item info for the component (should be called only once).
* 设置组件的道具信息(应仅调用一次)。
* @param InItem The item instance to set. 要设置的道具实例。
* @param InAmount The amount of the item. 道具数量。
*/
virtual void SetItemInfo(UGIS_ItemInstance* InItem, int32 InAmount);
/**
* Resets the item info for the component.
* 重置组件的道具信息。
*/
void ResetItemInfo();
/**
* Gets the associated item instance.
* 获取关联的道具实例。
* @return The item instance, or nullptr if not set. 道具实例如果未设置则返回nullptr。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|WorldItem")
UGIS_ItemInstance* GetItemInstance();
/**
* Creates a duplicated item instance with a new owner.
* 创建具有新拥有者的重复道具实例。
* @param NewOwner The new owner for the duplicated instance. 重复实例的新拥有者。
* @return The duplicated item instance, or nullptr if not possible. 重复的道具实例如果无法创建则返回nullptr。
*/
UGIS_ItemInstance* GetDuplicatedItemInstance(AActor* NewOwner);
/**
* Gets the item info associated with the component.
* 获取与组件关联的道具信息。
* @return The item info. 道具信息。
*/
FGIS_ItemInfo GetItemInfo() const;
/**
* Gets the amount of the associated item instance.
* 获取关联道具实例的数量。
* @return The item amount. 道具数量。
*/
UFUNCTION(BlueprintCallable, BlueprintPure, Category="GIS|WorldItem")
int32 GetItemAmount() const;
/**
* Called when the game starts to initialize the component.
* 游戏开始时调用以初始化组件。
*/
virtual void BeginPlay() override;
/**
* Gets the owner cast to a specific type.
* 获取特定类型的拥有者。
* @return The owner cast to the specified type, or nullptr if the cast fails. 转换为指定类型的拥有者如果转换失败则返回nullptr。
*/
template <class T>
T* GetTypedOwner()
{
return Cast<T>(GetOwner());
}
/**
* Delegate triggered when a valid item info is set.
* 有效道具信息设置时触发的委托。
*/
UPROPERTY(BlueprintAssignable)
FGIS_ItemInfoSetSignature ItemInfoSetEvent;
protected:
/**
* Item definition used to auto-create an item instance (if set, the component owns the instance).
* 用于自动创建道具实例的道具定义(如果设置,组件拥有该实例)。
*/
UPROPERTY(EditAnywhere, Category="WorldItem")
FGIS_ItemDefinitionAmount Definition;
/**
* The item info associated with this component.
* 与该组件关联的道具信息。
*/
UPROPERTY(VisibleAnywhere, Category="WorldItem", ReplicatedUsing=OnRep_ItemInfo, meta=(ShowInnerProperties))
FGIS_ItemInfo ItemInfo;
/**
* Called when the item info is replicated.
* 道具信息复制时调用。
*/
UFUNCTION()
void OnRep_ItemInfo();
};

View File

@@ -0,0 +1,248 @@
// Copyright 2025 https://yuewu.dev/en All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Templates/SubclassOf.h"
#include "GameplayTagContainer.h"
#include "GIS_CurrencyEntry.h"
#include "GIS_MixinContainer.h"
#include "Runtime/Launch/Resources/Version.h"
#if ENGINE_MINOR_VERSION < 5
#include "InstancedStruct.h"
#else
#include "StructUtils/InstancedStruct.h"
#endif
#include "GIS_SerializationStructLibrary.generated.h"
class UGIS_ItemFragment;
class UGIS_ItemCollectionDefinition;
class UGIS_ItemDefinition;
class UGIS_ItemCollection;
class UGIS_ItemInstance;
/**
* Record of an item instance for serialization.
* 用于序列化的道具实例记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_ItemRecord
{
GENERATED_BODY()
/**
* Unique identifier for the item instance.
* 道具实例的唯一标识符。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGuid ItemId;
/**
* Asset path to the item definition.
* 道具定义的资产路径。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FString DefinitionAssetPath;
/**
* The serialized runtime state of each item fragment.
* 已经序列化的各item fragment 对应的运行时数据。
*/
// UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
// TArray<FGIS_ItemFragmentStateRecord> FragmentStateRecords;
/**
* The serialized runtime state of each item fragment.
* 已经序列化的各item fragment 对应的运行时数据。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
TArray<FGIS_MixinRecord> FragmentStateRecords;
/**
* Binary data for the item instance.
* 道具实例的二进制数据。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
TArray<uint8> ByteData;
/**
* Equality operator to compare item records.
* 比较道具记录的相等性运算符。
* @param Other The other item record to compare with. 要比较的其他道具记录。
* @return True if the item IDs are equal, false otherwise. 如果道具ID相等则返回true否则返回false。
*/
bool operator==(const FGIS_ItemRecord& Other) const;
/**
* Checks if the item record is valid.
* 检查道具记录是否有效。
* @return True if the item ID and definition asset path are valid, false otherwise. 如果道具ID和定义资产路径有效则返回true否则返回false。
*/
bool IsValid() const;
};
/**
* Record for an item stack for serialization.
* 用于序列化的道具堆栈记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_StackRecord
{
GENERATED_BODY()
/**
* Unique identifier for the stack.
* 堆栈的唯一标识符。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGuid Id;
/**
* Unique identifier for the associated item instance.
* 关联道具实例的唯一标识符。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGuid ItemId;
/**
* Unique identifier for the collection containing the stack.
* 包含堆栈的集合的唯一标识符。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
FGuid CollectionId;
/**
* Amount of items in the stack.
* 堆栈中的道具数量。
*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, SaveGame, Category="GIS")
int32 Amount{0};
/**
* Equality operator to compare stack records.
* 比较堆栈记录的相等性运算符。
* @param Other The other stack record to compare with. 要比较的其他堆栈记录。
* @return True if the stack ID, item ID, and collection ID are equal, false otherwise. 如果堆栈ID、道具ID和集合ID相等则返回true否则返回false。
*/
bool operator==(const FGIS_StackRecord& Other) const
{
return ItemId == Other.ItemId && Id == Other.Id && CollectionId == Other.CollectionId;
}
/**
* Checks if the stack record is valid.
* 检查堆栈记录是否有效。
* @return True if the stack ID, item ID, and collection ID are valid, false otherwise. 如果堆栈ID、道具ID和集合ID有效则返回true否则返回false。
*/
bool IsValid() const;
};
/**
* Record of a collection instance for serialization.
* 用于序列化的道具集合记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_CollectionRecord
{
GENERATED_BODY()
/**
* Gameplay tag identifying the collection.
* 标识集合的游戏标签。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
FGameplayTag Tag;
/**
* Unique identifier for the collection.
* 集合的唯一标识符。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
FGuid Id;
/**
* Asset path to the collection definition.
* 集合定义的资产路径。
*/
UPROPERTY(BlueprintReadWrite, SaveGame, Category="GIS")
FString DefinitionAssetPath;
/**
* Array of stack records within the collection.
* 集合中的堆栈记录数组。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
TArray<FGIS_StackRecord> StackRecords;
/**
* Checks if the collection record is valid.
* 检查集合记录是否有效。
* @return True if the collection ID and definition asset path are valid, false otherwise. 如果集合ID和定义资产路径有效则返回true否则返回false。
*/
bool IsValid() const;
};
/**
* Record of an inventory for serialization.
* 用于序列化的库存记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_InventoryRecord
{
GENERATED_BODY()
/**
* Array of collection records within the inventory.
* 库存中的集合记录数组。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
TArray<FGIS_CollectionRecord> CollectionRecords;
/**
* Array of item records within the inventory.
* 库存中的道具记录数组。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
TArray<FGIS_ItemRecord> ItemRecords;
/**
* Checks if the inventory record is valid.
* 检查库存记录是否有效。
* @return True if the inventory contains at least one collection record, false otherwise. 如果库存包含至少一个集合记录则返回true否则返回false。
*/
bool IsValid() const
{
return CollectionRecords.Num() > 0;
}
};
/**
* Record of a currency system for serialization.
* 用于序列化的货币系统记录。
*/
USTRUCT(BlueprintType)
struct GENERICINVENTORYSYSTEM_API FGIS_CurrencyRecord
{
GENERATED_BODY()
/**
* Default constructor for the currency record.
* 货币记录的默认构造函数。
*/
FGIS_CurrencyRecord();
/**
* Unique key for the currency record.
* 货币记录的唯一键。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
FName Key;
/**
* Array of currency entries in the record.
* 记录中的货币条目数组。
*/
UPROPERTY(BlueprintReadOnly, SaveGame, Category="GIS")
TArray<FGIS_CurrencyEntry> Currencies;
};