2022-05-31 04:51:18 -04:00
// Copyright Epic Games, Inc. All Rights Reserved.
# include "StateTree.h"
2023-01-19 00:48:07 -05:00
# include "Misc/PackageName.h"
2022-05-31 04:51:18 -04:00
# include "StateTreeLinker.h"
# include "StateTreeTaskBase.h"
# include "StateTreeEvaluatorBase.h"
2022-06-02 12:03:12 -04:00
# include "AssetRegistry/AssetData.h"
2022-09-07 17:12:18 -04:00
# include "Misc/ScopeRWLock.h"
2022-09-15 13:53:23 -04:00
# include "StateTreeDelegates.h"
# include "Logging/LogScopedVerbosityOverride.h"
2022-05-31 04:51:18 -04:00
2022-09-28 01:06:15 -04:00
# include UE_INLINE_GENERATED_CPP_BY_NAME(StateTree)
2022-05-31 04:51:18 -04:00
const FGuid FStateTreeCustomVersion : : GUID ( 0x28E21331 , 0x501F4723 , 0x8110FA64 , 0xEA10DA1E ) ;
FCustomVersionRegistration GRegisterStateTreeCustomVersion ( FStateTreeCustomVersion : : GUID , FStateTreeCustomVersion : : LatestVersion , TEXT ( " StateTreeAsset " ) ) ;
bool UStateTree : : IsReadyToRun ( ) const
{
// Valid tree must have at least one state and valid instance data.
return States . Num ( ) > 0 & & bIsLinked ;
}
2023-03-14 13:35:46 -04:00
FConstStructView UStateTree : : GetNode ( const int32 NodeIndex ) const
{
return Nodes . IsValidIndex ( NodeIndex ) ? Nodes [ NodeIndex ] : FConstStructView ( ) ;
}
const FCompactStateTreeState * UStateTree : : GetStateFromHandle ( const FStateTreeStateHandle StateHandle ) const
{
return States . IsValidIndex ( StateHandle . Index ) ? & States [ StateHandle . Index ] : nullptr ;
}
FStateTreeStateHandle UStateTree : : GetStateHandleFromId ( const FGuid Id ) const
{
const FStateTreeStateIdToHandle * Entry = IDToStateMappings . FindByPredicate ( [ Id ] ( const FStateTreeStateIdToHandle & Entry ) { return Entry . Id = = Id ; } ) ;
return Entry ! = nullptr ? Entry - > Handle : FStateTreeStateHandle : : Invalid ;
}
FGuid UStateTree : : GetStateIdFromHandle ( const FStateTreeStateHandle Handle ) const
{
const FStateTreeStateIdToHandle * Entry = IDToStateMappings . FindByPredicate ( [ Handle ] ( const FStateTreeStateIdToHandle & Entry ) { return Entry . Handle = = Handle ; } ) ;
return Entry ! = nullptr ? Entry - > Id : FGuid ( ) ;
}
2022-09-07 17:12:18 -04:00
TSharedPtr < FStateTreeInstanceData > UStateTree : : GetSharedInstanceData ( ) const
{
// Create a unique index for each thread.
static std : : atomic_int ThreadIndexCounter { 0 } ;
2022-09-09 05:14:55 -04:00
static thread_local int32 ThreadIndex = INDEX_NONE ; // Cannot init directly on WinRT
if ( ThreadIndex = = INDEX_NONE )
{
ThreadIndex = ThreadIndexCounter . fetch_add ( 1 ) ;
}
2022-09-07 17:12:18 -04:00
// If shared instance data for this thread exists, return it.
{
FReadScopeLock ReadLock ( PerThreadSharedInstanceDataLock ) ;
if ( ThreadIndex < PerThreadSharedInstanceData . Num ( ) )
{
return PerThreadSharedInstanceData [ ThreadIndex ] ;
}
}
// Not initialized yet, create new instances up to the index.
FWriteScopeLock WriteLock ( PerThreadSharedInstanceDataLock ) ;
// It is possible that multiple threads are waiting for the write lock,
// which means that execution may get here so that 'ThreadIndex' is already in valid range.
// The loop below is organized to handle that too.
const int32 NewNum = ThreadIndex + 1 ;
PerThreadSharedInstanceData . Reserve ( NewNum ) ;
UStateTree * NonConstThis = const_cast < UStateTree * > ( this ) ;
for ( int32 Index = PerThreadSharedInstanceData . Num ( ) ; Index < NewNum ; Index + + )
{
TSharedPtr < FStateTreeInstanceData > SharedData = MakeShared < FStateTreeInstanceData > ( ) ;
SharedData - > CopyFrom ( * NonConstThis , SharedInstanceData ) ;
PerThreadSharedInstanceData . Add ( SharedData ) ;
}
return PerThreadSharedInstanceData [ ThreadIndex ] ;
}
2022-05-31 04:51:18 -04:00
# if WITH_EDITOR
void UStateTree : : ResetCompiled ( )
{
Schema = nullptr ;
States . Reset ( ) ;
Transitions . Reset ( ) ;
Nodes . Reset ( ) ;
DefaultInstanceData . Reset ( ) ;
SharedInstanceData . Reset ( ) ;
2022-09-19 19:47:11 -04:00
ContextDataDescs . Reset ( ) ;
2022-05-31 04:51:18 -04:00
PropertyBindings . Reset ( ) ;
Parameters . Reset ( ) ;
2023-03-14 13:35:46 -04:00
IDToStateMappings . Reset ( ) ;
2022-05-31 04:51:18 -04:00
ParametersDataViewIndex = FStateTreeIndex8 : : Invalid ;
EvaluatorsBegin = 0 ;
EvaluatorsNum = 0 ;
2023-01-12 09:45:58 -05:00
GlobalTasksBegin = 0 ;
GlobalTasksNum = 0 ;
2023-01-23 12:48:04 -05:00
bHasGlobalTransitionTasks = false ;
2023-01-12 09:45:58 -05:00
2022-05-31 04:51:18 -04:00
ResetLinked ( ) ;
}
void UStateTree : : GetAssetRegistryTags ( TArray < FAssetRegistryTag > & OutTags ) const
{
Deprecating ANY_PACKAGE.
This change consists of multiple changes:
Core:
- Deprecation of ANY_PACKAGE macro. Added ANY_PACKAGE_DEPRECATED macro which can still be used for backwards compatibility purposes (only used in CoreUObject)
- Deprecation of StaticFindObjectFast* functions that take bAnyPackage parameter
- Added UStruct::GetStructPathName function that returns FTopLevelAssetPath representing the path name (package + object FName, super quick compared to UObject::GetPathName) + wrapper UClass::GetClassPathName to make it look better when used with UClasses
- Added (Static)FindFirstObject* functions that find a first object given its Name (no Outer). These functions are used in places I consider valid to do global UObject (UClass) lookups like parsing command line parameters / checking for unique object names
- Added static UClass::TryFindType function which serves a similar purpose as FindFirstObject however it's going to throw a warning (with a callstack / maybe ensure in the future?) if short class name is provided. This function is used in places that used to use short class names but now should have been converted to use path names to catch any potential regressions and or edge cases I missed.
- Added static UClass::TryConvertShortNameToPathName utility function
- Added static UClass::TryFixShortClassNameExportPath utility function
- Object text export paths will now also include class path (Texture2D'/Game/Textures/Grass.Grass' -> /Script/Engine.Texture2D'/Game/Textures/Grass.Grass')
- All places that manually generated object export paths for objects will now use FObjectPropertyBase::GetExportPath
- Added a new startup test that checks for short type names in UClass/FProperty MetaData values
AssetRegistry:
- Deprecated any member variables (FAssetData / FARFilter) or functions that use FNames to represent class names and replaced them with FTopLevelAssetPath
- Added new member variables and new function overloads that use FTopLevelAssetPath to represent class names
- This also applies to a few other modules' APIs to match AssetRegistry changes
Everything else:
- Updated code that used ANY_PACKAGE (depending on the use case) to use FindObject(nullptr, PathToObject), UClass::TryFindType (used when path name is expected, warns if it's a short name) or FindFirstObject (usually for finding types based on user input but there's been a few legitimate use cases not related to user input)
- Updated code that used AssetRegistry API to use FTopLevelAssetPaths and USomeClass::StaticClass()->GetClassPathName() instead of GetFName()
- Updated meta data and hardcoded FindObject(ANY_PACKAGE, "EEnumNameOrClassName") calls to use path names
#jira UE-99463
#rb many.people
[FYI] Marcus.Wassmer
#preflight 629248ec2256738f75de9b32
#codereviewnumbers 20320742, 20320791, 20320799, 20320756, 20320809, 20320830, 20320840, 20320846, 20320851, 20320863, 20320780, 20320765, 20320876, 20320786
#ROBOMERGE-OWNER: robert.manuszewski
#ROBOMERGE-AUTHOR: robert.manuszewski
#ROBOMERGE-SOURCE: CL 20430220 via CL 20433854 via CL 20435474 via CL 20435484
#ROBOMERGE-BOT: UE5 (Release-Engine-Staging -> Main) (v949-20362246)
[CL 20448496 by robert manuszewski in ue5-main branch]
2022-06-01 03:46:59 -04:00
const FString SchemaClassName = Schema ? Schema - > GetClass ( ) - > GetPathName ( ) : TEXT ( " " ) ;
2022-05-31 04:51:18 -04:00
OutTags . Add ( FAssetRegistryTag ( UE : : StateTree : : SchemaTag , SchemaClassName , FAssetRegistryTag : : TT_Alphabetical ) ) ;
Super : : GetAssetRegistryTags ( OutTags ) ;
}
Deprecating ANY_PACKAGE.
This change consists of multiple changes:
Core:
- Deprecation of ANY_PACKAGE macro. Added ANY_PACKAGE_DEPRECATED macro which can still be used for backwards compatibility purposes (only used in CoreUObject)
- Deprecation of StaticFindObjectFast* functions that take bAnyPackage parameter
- Added UStruct::GetStructPathName function that returns FTopLevelAssetPath representing the path name (package + object FName, super quick compared to UObject::GetPathName) + wrapper UClass::GetClassPathName to make it look better when used with UClasses
- Added (Static)FindFirstObject* functions that find a first object given its Name (no Outer). These functions are used in places I consider valid to do global UObject (UClass) lookups like parsing command line parameters / checking for unique object names
- Added static UClass::TryFindType function which serves a similar purpose as FindFirstObject however it's going to throw a warning (with a callstack / maybe ensure in the future?) if short class name is provided. This function is used in places that used to use short class names but now should have been converted to use path names to catch any potential regressions and or edge cases I missed.
- Added static UClass::TryConvertShortNameToPathName utility function
- Added static UClass::TryFixShortClassNameExportPath utility function
- Object text export paths will now also include class path (Texture2D'/Game/Textures/Grass.Grass' -> /Script/Engine.Texture2D'/Game/Textures/Grass.Grass')
- All places that manually generated object export paths for objects will now use FObjectPropertyBase::GetExportPath
- Added a new startup test that checks for short type names in UClass/FProperty MetaData values
AssetRegistry:
- Deprecated any member variables (FAssetData / FARFilter) or functions that use FNames to represent class names and replaced them with FTopLevelAssetPath
- Added new member variables and new function overloads that use FTopLevelAssetPath to represent class names
- This also applies to a few other modules' APIs to match AssetRegistry changes
Everything else:
- Updated code that used ANY_PACKAGE (depending on the use case) to use FindObject(nullptr, PathToObject), UClass::TryFindType (used when path name is expected, warns if it's a short name) or FindFirstObject (usually for finding types based on user input but there's been a few legitimate use cases not related to user input)
- Updated code that used AssetRegistry API to use FTopLevelAssetPaths and USomeClass::StaticClass()->GetClassPathName() instead of GetFName()
- Updated meta data and hardcoded FindObject(ANY_PACKAGE, "EEnumNameOrClassName") calls to use path names
#jira UE-99463
#rb many.people
[FYI] Marcus.Wassmer
#preflight 629248ec2256738f75de9b32
#codereviewnumbers 20320742, 20320791, 20320799, 20320756, 20320809, 20320830, 20320840, 20320846, 20320851, 20320863, 20320780, 20320765, 20320876, 20320786
#ROBOMERGE-OWNER: robert.manuszewski
#ROBOMERGE-AUTHOR: robert.manuszewski
#ROBOMERGE-SOURCE: CL 20430220 via CL 20433854 via CL 20435474 via CL 20435484
#ROBOMERGE-BOT: UE5 (Release-Engine-Staging -> Main) (v949-20362246)
[CL 20448496 by robert manuszewski in ue5-main branch]
2022-06-01 03:46:59 -04:00
void UStateTree : : PostLoadAssetRegistryTags ( const FAssetData & InAssetData , TArray < FAssetRegistryTag > & OutTagsAndValuesToUpdate ) const
{
Super : : PostLoadAssetRegistryTags ( InAssetData , OutTagsAndValuesToUpdate ) ;
static const FName SchemaTag ( TEXT ( " Schema " ) ) ;
FString SchemaTagValue = InAssetData . GetTagValueRef < FString > ( SchemaTag ) ;
if ( ! SchemaTagValue . IsEmpty ( ) & & FPackageName : : IsShortPackageName ( SchemaTagValue ) )
{
FTopLevelAssetPath SchemaTagClassPathName = UClass : : TryConvertShortTypeNameToPathName < UStruct > ( SchemaTagValue , ELogVerbosity : : Warning , TEXT ( " UStateTree::PostLoadAssetRegistryTags " ) ) ;
if ( ! SchemaTagClassPathName . IsNull ( ) )
{
OutTagsAndValuesToUpdate . Add ( FAssetRegistryTag ( SchemaTag , SchemaTagClassPathName . ToString ( ) , FAssetRegistryTag : : TT_Alphabetical ) ) ;
}
}
}
2022-09-24 13:28:43 -04:00
# endif // WITH_EDITOR
2022-09-24 13:28:37 -04:00
void UStateTree : : AddReferencedObjects ( UObject * InThis , FReferenceCollector & Collector )
{
Super : : AddReferencedObjects ( InThis , Collector ) ;
const UStateTree * StateTree = Cast < UStateTree > ( InThis ) ;
check ( StateTree ) ;
FReadScopeLock ReadLock ( StateTree - > PerThreadSharedInstanceDataLock ) ;
for ( const TSharedPtr < FStateTreeInstanceData > & InstanceData : StateTree - > PerThreadSharedInstanceData )
{
if ( InstanceData . IsValid ( ) )
{
GC reachability optimizations. ~1.5x speedup and ~2.5MB memory saved for an internal title.
List of optimizations and changes:
* Token stream structure
* Split token stream into strong-only and a mixed (weak+strong) stream
* Split token stream into a builder and a tighter view class which reduces sizeof(UClass)
* Implemented ref-counted token stream view sharing
* Removed Class and Outer from token stream
* Allow empty token streams (enabled by removing Class/Outer) to avoid touching token stream data
* Placed ARO (AddReferencedObjects) last to reduce per object cache thrashing, improve control flow predicability and avoid reading the last EndOfPointer and EndOfStream tokens
* FPrefetchingObjectIterator that bring in Class/Outer, class' tokenstream view and the first token data ahead of time
* Decode token bitfield once and ahead of time
* Reference queues and batch processing
* Introduced bounded queues: ref arrays -> unvalidated refs -> validated (non-null / non-permanent) refs
* Split all these queues for killable vs immutable references
* Stack-living references still handled synchronously. With removal of Class/Outer (prefetched ahead of time) few instances remain outside of ARO calls.
* Outer queues hold 32 items and get flushed when full.
* AddReferencedObjects (ARO) optimizations
* Misc optimizations in many ARO implementations
* New FReferenceCollector API to queue up ARO references (AddStableReference), old sync API (HandleObjectReference) still available
* New AddPropertyReferences traversal that replaces SerializeBin and PropertyValueIterator
* 4.5x faster than PropertyValueIterator
* Uses CLASSCAST dispatch instead of virtual SerializeItem dispatch.
* Step towards new unified token stream replacement shared by class token processing, structs and ARO
* Replaced StructUtil::AddReferencedObjects with AddPropertyReferences traversal, ~8x speedup and collects more references for CitySample
* Parallelism
* Single long-running task per worker
* Improved work-stealing / load-balancing, workers can steal full blocks, ARO calls and initial references
* Queue up slow ARO calls to improve load balancing and avoid late stragglers. Motivated by certain ARO calls taking over 2ms for a few specific objects.
* Kick tasks manually to avoid ParallelFor end synchronization
* FGCObject
* Initial reference collector runs in parallel with mark phase
* New FGCObject constructor API (AddStableNativeReferencesOnly) to opt-in to initial reference collection, used by StreamableManager
* Same constructor API allows FGCObjects to defer registration until they become active (RegisterLater), reduces number of active GCObjects
* Reduced memory usage
* Allocate reached objects in scratch pages (FWorkBlock) and reuse processed blocks, instead of swapping two big TArray<UObject*> per worker
* Reduced sizeof(UClass)
* Shareable token streams
* Misc optimizations
* New API to test if an object is in the permanent object pool. Old API read two global pointers for every visited reference.
* Fixed signed integer usage in GUObjectArray lookup that led to bad codegen
* FPropertyIterator optimizations
* SerializeBin optimizations
* Other changes
* Moved many helpers into UE::GC namespace
* Replaced TFastReferenceCollector API with simplified CollectReferences call. Needed to break this API any way.
* Introduced FGCInternals to avoid forward-declaring TFastReferenceCollector and depend on the options enum in common headers
* Moved and outlined code from GarbageCollection.h / FastReferenceCollector.h to GarbageCollection.cpp
* Moved GC History and Garbage Reference Tracking into a synchronous TDebugReachabilityProcessor
* Removed PersistentGarbage flag since it wasn't used in practice
* Improved const correctness
#rb robert.millar,robert.manuszewski,pj.kack
#preflight 63945bf45624e6da5ec85f88
#jira UE-169791
[CL 23475562 by johan torp in ue5-main branch]
2022-12-11 23:21:18 -05:00
Collector . AddPropertyReferencesWithStructARO ( FStateTreeInstanceData : : StaticStruct ( ) , InstanceData . Get ( ) , StateTree ) ;
2022-09-24 13:28:37 -04:00
}
}
}
2022-05-31 04:51:18 -04:00
void UStateTree : : PostLoad ( )
{
Super : : PostLoad ( ) ;
const int32 CurrentVersion = GetLinkerCustomVersion ( FStateTreeCustomVersion : : GUID ) ;
if ( CurrentVersion < FStateTreeCustomVersion : : LatestVersion )
{
# if WITH_EDITOR
2022-09-15 13:53:23 -04:00
// Compiled data is in older format, try to compile the StateTree.
if ( UE : : StateTree : : Delegates : : OnRequestCompile . IsBound ( ) )
{
LOG_SCOPE_VERBOSITY_OVERRIDE ( LogStateTree , ELogVerbosity : : Log ) ;
UE_LOG ( LogStateTree , Log , TEXT ( " %s: compiled data is in older format. Trying to compile the asset... " ) , * GetFullName ( ) ) ;
UE : : StateTree : : Delegates : : OnRequestCompile . Execute ( * this ) ;
}
else
{
ResetCompiled ( ) ;
UE_LOG ( LogStateTree , Warning , TEXT ( " %s: compiled data is in older format. Please resave the StateTree asset. " ) , * GetFullName ( ) ) ;
}
2022-09-02 01:15:02 -04:00
# else
2022-09-15 13:53:23 -04:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: compiled data is in older format. Please recompile the StateTree asset. " ) , * GetFullName ( ) ) ;
2022-05-31 04:51:18 -04:00
# endif
return ;
}
if ( ! Link ( ) )
{
2022-09-15 13:53:23 -04:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s failed to link. Asset will not be usable at runtime. " ) , * GetFullName ( ) ) ;
2022-05-31 04:51:18 -04:00
}
}
2022-11-25 15:40:13 -05:00
# if WITH_EDITORONLY_DATA
void UStateTree : : DeclareConstructClasses ( TArray < FTopLevelAssetPath > & OutConstructClasses , const UClass * SpecificSubclass )
{
Super : : DeclareConstructClasses ( OutConstructClasses , SpecificSubclass ) ;
TArray < UClass * > SchemaClasses ;
GetDerivedClasses ( UStateTreeSchema : : StaticClass ( ) , SchemaClasses ) ;
for ( UClass * SchemaClass : SchemaClasses )
{
if ( ! SchemaClass - > HasAnyClassFlags ( CLASS_Abstract | CLASS_Transient ) )
{
OutConstructClasses . Add ( FTopLevelAssetPath ( SchemaClass ) ) ;
}
}
}
# endif
2022-05-31 04:51:18 -04:00
void UStateTree : : Serialize ( FStructuredArchiveRecord Record )
{
Super : : Serialize ( Record ) ;
Record . GetUnderlyingArchive ( ) . UsingCustomVersion ( FStateTreeCustomVersion : : GUID ) ;
// We need to link and rebind property bindings each time a BP is compiled,
// because property bindings may get invalid, and instance data potentially needs refreshed.
if ( Record . GetUnderlyingArchive ( ) . IsModifyingWeakAndStrongReferences ( ) )
{
if ( ! Link ( ) )
{
UE_LOG ( LogStateTree , Error , TEXT ( " %s failed to link. Asset will not be usable at runtime. " ) , * GetName ( ) ) ;
}
}
}
void UStateTree : : ResetLinked ( )
{
bIsLinked = false ;
ExternalDataDescs . Reset ( ) ;
ExternalDataBaseIndex = 0 ;
NumDataViews = 0 ;
2022-09-07 17:12:18 -04:00
FWriteScopeLock WriteLock ( PerThreadSharedInstanceDataLock ) ;
PerThreadSharedInstanceData . Reset ( ) ;
2022-05-31 04:51:18 -04:00
}
bool UStateTree : : Link ( )
{
// Initialize the instance data default value.
// This data will be used to allocate runtime instance on all StateTree users.
ResetLinked ( ) ;
2022-08-29 14:47:43 -04:00
if ( States . Num ( ) > 0 & & Nodes . Num ( ) > 0 )
2022-06-21 06:57:10 -04:00
{
2022-08-29 14:47:43 -04:00
if ( ! DefaultInstanceData . IsValid ( ) )
2022-05-31 04:51:18 -04:00
{
2023-03-09 06:35:16 -05:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: StartTree does not have instance data. Please recompile the StateTree asset. " ) , * GetFullName ( ) ) ;
2022-08-29 14:47:43 -04:00
return false ;
2022-05-31 04:51:18 -04:00
}
2022-12-05 03:19:45 -05:00
2023-03-09 06:35:16 -05:00
// Check that all nodes are valid.
for ( FConstStructView Node : Nodes )
{
if ( ! Node . IsValid ( ) )
{
UE_LOG ( LogStateTree , Error , TEXT ( " %s: State Tree asset was not properly loaded (missing node). See log for loading failures, or recompile the StateTree asset. " ) , * GetFullName ( ) ) ;
return false ;
}
}
if ( ! DefaultInstanceData . AreAllInstancesValid ( ) )
{
UE_LOG ( LogStateTree , Error , TEXT ( " %s: State Tree asset was not properly loaded (missing instance data). See log for loading failures, or recompile the StateTree asset. " ) , * GetFullName ( ) ) ;
return false ;
}
if ( ! SharedInstanceData . AreAllInstancesValid ( ) )
{
UE_LOG ( LogStateTree , Error , TEXT ( " %s: State Tree asset was not properly loaded (missing shared instance data). See log for loading failures, or recompile the StateTree asset. " ) , * GetFullName ( ) ) ;
return false ;
}
2022-08-29 14:47:43 -04:00
// Update property bag structs before resolving binding.
2023-02-10 07:22:48 -05:00
const TArrayView < FStateTreeBindableStructDesc > SourceStructs = PropertyBindings . SourceStructs ;
const TArrayView < FStateTreePropertyCopyBatch > CopyBatches = PropertyBindings . CopyBatches ;
2022-08-29 14:47:43 -04:00
2022-12-05 03:19:45 -05:00
// Reconcile out of date classes.
for ( FStateTreeBindableStructDesc & SourceStruct : SourceStructs )
{
if ( const UClass * SourceClass = Cast < UClass > ( SourceStruct . Struct ) )
{
if ( SourceClass - > HasAnyClassFlags ( CLASS_NewerVersionExists ) )
{
SourceStruct . Struct = SourceClass - > GetAuthoritativeClass ( ) ;
}
}
}
2023-02-10 07:22:48 -05:00
for ( FStateTreePropertyCopyBatch & CopyBatch : CopyBatches )
2022-12-05 03:19:45 -05:00
{
if ( const UClass * TargetClass = Cast < UClass > ( CopyBatch . TargetStruct . Struct ) )
{
if ( TargetClass - > HasAnyClassFlags ( CLASS_NewerVersionExists ) )
{
CopyBatch . TargetStruct . Struct = TargetClass - > GetAuthoritativeClass ( ) ;
}
}
}
2022-08-29 14:47:43 -04:00
if ( ParametersDataViewIndex . IsValid ( ) & & SourceStructs . IsValidIndex ( ParametersDataViewIndex . Get ( ) ) )
2022-05-31 04:51:18 -04:00
{
2022-08-29 14:47:43 -04:00
SourceStructs [ ParametersDataViewIndex . Get ( ) ] . Struct = Parameters . GetPropertyBagStruct ( ) ;
}
for ( const FCompactStateTreeState & State : States )
{
if ( State . Type = = EStateTreeStateType : : Subtree )
2022-05-31 04:51:18 -04:00
{
2022-09-23 19:58:36 -04:00
if ( State . ParameterInstanceIndex . IsValid ( ) = = false )
2022-08-29 14:47:43 -04:00
{
2023-03-09 06:35:16 -05:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: Data for state '%s' is malformed. Please recompile the StateTree asset. " ) , * GetFullName ( ) , * State . Name . ToString ( ) ) ;
2022-08-29 14:47:43 -04:00
return false ;
}
// Subtree is a bind source, update bag struct.
2022-09-23 19:58:36 -04:00
if ( State . ParameterDataViewIndex . IsValid ( ) )
{
2023-02-13 20:06:02 -05:00
const FCompactStateTreeParameters & Params = DefaultInstanceData . GetMutableStruct ( State . ParameterInstanceIndex . Get ( ) ) . Get < FCompactStateTreeParameters > ( ) ;
2022-09-23 19:58:36 -04:00
FStateTreeBindableStructDesc & Desc = SourceStructs [ State . ParameterDataViewIndex . Get ( ) ] ;
Desc . Struct = Params . Parameters . GetPropertyBagStruct ( ) ;
}
2022-05-31 04:51:18 -04:00
}
2022-08-29 14:47:43 -04:00
else if ( State . Type = = EStateTreeStateType : : Linked & & State . LinkedState . IsValid ( ) )
2022-05-31 04:51:18 -04:00
{
2022-08-29 14:47:43 -04:00
const FCompactStateTreeState & LinkedState = States [ State . LinkedState . Index ] ;
2022-05-31 04:51:18 -04:00
2022-08-29 14:47:43 -04:00
if ( State . ParameterInstanceIndex . IsValid ( ) = = false
| | LinkedState . ParameterInstanceIndex . IsValid ( ) = = false )
{
2023-03-09 06:35:16 -05:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: Data for state '%s' is malformed. Please recompile the StateTree asset. " ) , * GetFullName ( ) , * State . Name . ToString ( ) ) ;
2022-08-29 14:47:43 -04:00
return false ;
}
2023-02-13 20:06:02 -05:00
const FCompactStateTreeParameters & Params = DefaultInstanceData . GetMutableStruct ( State . ParameterInstanceIndex . Get ( ) ) . Get < FCompactStateTreeParameters > ( ) ;
2022-08-29 14:47:43 -04:00
// Check that the bag in linked state matches.
2023-02-13 20:06:02 -05:00
const FCompactStateTreeParameters & LinkedStateParams = DefaultInstanceData . GetMutableStruct ( LinkedState . ParameterInstanceIndex . Get ( ) ) . Get < FCompactStateTreeParameters > ( ) ;
2022-08-29 14:47:43 -04:00
if ( LinkedStateParams . Parameters . GetPropertyBagStruct ( ) ! = Params . Parameters . GetPropertyBagStruct ( ) )
{
2023-03-09 06:35:16 -05:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: The parameters on state '%s' does not match the linked state parameters in state '%s'. Please recompile the StateTree asset. " ) , * GetFullName ( ) , * State . Name . ToString ( ) , * LinkedState . Name . ToString ( ) ) ;
2022-08-29 14:47:43 -04:00
return false ;
}
if ( Params . BindingsBatch . IsValid ( ) )
{
2023-02-10 07:22:48 -05:00
FStateTreePropertyCopyBatch & Batch = CopyBatches [ Params . BindingsBatch . Get ( ) ] ;
2022-08-29 14:47:43 -04:00
Batch . TargetStruct . Struct = Params . Parameters . GetPropertyBagStruct ( ) ;
}
2022-07-21 08:19:56 -04:00
}
2022-05-31 04:51:18 -04:00
}
2022-08-29 14:47:43 -04:00
// Resolves property paths used by bindings a store property pointers
if ( ! PropertyBindings . ResolvePaths ( ) )
{
return false ;
}
2022-05-31 04:51:18 -04:00
}
// Resolves nodes references to other StateTree data
FStateTreeLinker Linker ( Schema ) ;
Linker . SetExternalDataBaseIndex ( PropertyBindings . GetSourceStructNum ( ) ) ;
for ( int32 Index = 0 ; Index < Nodes . Num ( ) ; Index + + )
{
2023-01-12 09:45:58 -05:00
FStructView Node = Nodes [ Index ] ;
2023-02-13 20:06:02 -05:00
if ( FStateTreeNodeBase * NodePtr = Node . GetPtr < FStateTreeNodeBase > ( ) )
2022-05-31 04:51:18 -04:00
{
Linker . SetCurrentInstanceDataType ( NodePtr - > GetInstanceDataType ( ) , NodePtr - > DataViewIndex . Get ( ) ) ;
const bool bLinkSucceeded = NodePtr - > Link ( Linker ) ;
if ( ! bLinkSucceeded | | Linker . GetStatus ( ) = = EStateTreeLinkerStatus : : Failed )
{
2023-03-09 06:35:16 -05:00
UE_LOG ( LogStateTree , Error , TEXT ( " %s: node '%s' failed to resolve its references. " ) , * GetFullName ( ) , * NodePtr - > StaticStruct ( ) - > GetName ( ) ) ;
2022-05-31 04:51:18 -04:00
return false ;
}
}
}
// Link succeeded, setup tree to be ready to run
ExternalDataBaseIndex = PropertyBindings . GetSourceStructNum ( ) ;
ExternalDataDescs = Linker . GetExternalDataDescs ( ) ;
NumDataViews = ExternalDataBaseIndex + ExternalDataDescs . Num ( ) ;
bIsLinked = true ;
return true ;
}
# if WITH_EDITOR
void FStateTreeMemoryUsage : : AddUsage ( FConstStructView View )
{
if ( const UScriptStruct * ScriptStruct = View . GetScriptStruct ( ) )
{
EstimatedMemoryUsage = Align ( EstimatedMemoryUsage , ScriptStruct - > GetMinAlignment ( ) ) ;
EstimatedMemoryUsage + = ScriptStruct - > GetStructureSize ( ) ;
}
}
void FStateTreeMemoryUsage : : AddUsage ( const UObject * Object )
{
if ( Object ! = nullptr )
{
check ( Object - > GetClass ( ) ) ;
EstimatedMemoryUsage + = Object - > GetClass ( ) - > GetStructureSize ( ) ;
}
}
TArray < FStateTreeMemoryUsage > UStateTree : : CalculateEstimatedMemoryUsage ( ) const
{
TArray < FStateTreeMemoryUsage > MemoryUsages ;
TArray < TPair < int32 , int32 > > StateLinks ;
2023-03-09 06:35:16 -05:00
if ( ! bIsLinked
| | States . IsEmpty ( )
| | ! Nodes . IsValid ( )
| | ! DefaultInstanceData . IsValid ( ) )
2022-05-31 04:51:18 -04:00
{
return MemoryUsages ;
}
const int32 TreeMemUsageIndex = MemoryUsages . Emplace ( TEXT ( " State Tree Max " ) ) ;
2022-06-29 07:22:15 -04:00
const int32 InstanceMemUsageIndex = MemoryUsages . Emplace ( TEXT ( " Instance Overhead " ) ) ;
2022-05-31 04:51:18 -04:00
const int32 EvalMemUsageIndex = MemoryUsages . Emplace ( TEXT ( " Evaluators " ) ) ;
2023-01-12 09:45:58 -05:00
const int32 GlobalTaskMemUsageIndex = MemoryUsages . Emplace ( TEXT ( " GlobalTask " ) ) ;
2022-05-31 04:51:18 -04:00
const int32 SharedMemUsageIndex = MemoryUsages . Emplace ( TEXT ( " Shared Data " ) ) ;
auto GetRootStateHandle = [ this ] ( const FStateTreeStateHandle InState ) - > FStateTreeStateHandle
{
FStateTreeStateHandle Result = InState ;
while ( Result . IsValid ( ) & & States [ Result . Index ] . Parent . IsValid ( ) )
{
Result = States [ Result . Index ] . Parent ;
}
return Result ;
} ;
auto GetUsageIndexForState = [ & MemoryUsages , this ] ( const FStateTreeStateHandle InStateHandle ) - > int32
{
check ( InStateHandle . IsValid ( ) ) ;
const int32 FoundMemUsage = MemoryUsages . IndexOfByPredicate ( [ InStateHandle ] ( const FStateTreeMemoryUsage & MemUsage ) { return MemUsage . Handle = = InStateHandle ; } ) ;
if ( FoundMemUsage ! = INDEX_NONE )
{
return FoundMemUsage ;
}
const FCompactStateTreeState & CompactState = States [ InStateHandle . Index ] ;
return MemoryUsages . Emplace ( TEXT ( " State " ) + CompactState . Name . ToString ( ) , InStateHandle ) ;
} ;
2022-06-29 07:22:15 -04:00
// Calculate memory usage per state.
TArray < FStateTreeMemoryUsage > TempStateMemoryUsages ;
TempStateMemoryUsages . SetNum ( States . Num ( ) ) ;
2022-05-31 04:51:18 -04:00
for ( int32 Index = 0 ; Index < States . Num ( ) ; Index + + )
{
const FStateTreeStateHandle StateHandle ( ( uint16 ) Index ) ;
const FCompactStateTreeState & CompactState = States [ Index ] ;
const FStateTreeStateHandle ParentHandle = GetRootStateHandle ( StateHandle ) ;
const int32 ParentUsageIndex = GetUsageIndexForState ( ParentHandle ) ;
2022-06-29 07:22:15 -04:00
FStateTreeMemoryUsage & MemUsage = CompactState . Parent . IsValid ( ) ? TempStateMemoryUsages [ Index ] : MemoryUsages [ GetUsageIndexForState ( StateHandle ) ] ;
2022-05-31 04:51:18 -04:00
MemUsage . NodeCount + = CompactState . TasksNum ;
if ( CompactState . Type = = EStateTreeStateType : : Linked )
{
const int32 LinkedUsageIndex = GetUsageIndexForState ( CompactState . LinkedState ) ;
StateLinks . Emplace ( ParentUsageIndex , LinkedUsageIndex ) ;
MemUsage . NodeCount + + ;
MemUsage . AddUsage ( DefaultInstanceData . GetStruct ( CompactState . ParameterInstanceIndex . Get ( ) ) ) ;
}
for ( int32 TaskIndex = CompactState . TasksBegin ; TaskIndex < ( CompactState . TasksBegin + CompactState . TasksNum ) ; TaskIndex + + )
{
2023-03-09 06:35:16 -05:00
if ( const FStateTreeTaskBase * Task = Nodes [ TaskIndex ] . GetPtr < const FStateTreeTaskBase > ( ) )
2022-05-31 04:51:18 -04:00
{
2023-03-09 06:35:16 -05:00
if ( Task - > bInstanceIsObject )
{
MemUsage . NodeCount + + ;
MemUsage . AddUsage ( DefaultInstanceData . GetObject ( Task - > InstanceIndex . Get ( ) ) ) ;
}
else
{
MemUsage . NodeCount + + ;
MemUsage . AddUsage ( DefaultInstanceData . GetStruct ( Task - > InstanceIndex . Get ( ) ) ) ;
}
2022-05-31 04:51:18 -04:00
}
}
}
2022-06-29 07:22:15 -04:00
// Combine max child usage to parents. Iterate backwards to update children first.
for ( int32 Index = States . Num ( ) - 1 ; Index > = 0 ; Index - - )
{
const FStateTreeStateHandle StateHandle ( ( uint16 ) Index ) ;
const FCompactStateTreeState & CompactState = States [ Index ] ;
FStateTreeMemoryUsage & MemUsage = CompactState . Parent . IsValid ( ) ? TempStateMemoryUsages [ Index ] : MemoryUsages [ GetUsageIndexForState ( StateHandle ) ] ;
int32 MaxChildStateMem = 0 ;
int32 MaxChildStateNodes = 0 ;
for ( uint16 ChildState = CompactState . ChildrenBegin ; ChildState < CompactState . ChildrenEnd ; ChildState = States [ ChildState ] . GetNextSibling ( ) )
{
const FStateTreeMemoryUsage & ChildMemUsage = TempStateMemoryUsages [ ChildState ] ;
if ( ChildMemUsage . EstimatedMemoryUsage > MaxChildStateMem )
{
MaxChildStateMem = ChildMemUsage . EstimatedMemoryUsage ;
MaxChildStateNodes = ChildMemUsage . NodeCount ;
}
}
MemUsage . EstimatedMemoryUsage + = MaxChildStateMem ;
MemUsage . NodeCount + = MaxChildStateNodes ;
}
2022-05-31 04:51:18 -04:00
// Accumulate linked states.
for ( int32 Index = StateLinks . Num ( ) - 1 ; Index > = 0 ; Index - - )
{
FStateTreeMemoryUsage & ParentUsage = MemoryUsages [ StateLinks [ Index ] . Get < 0 > ( ) ] ;
const FStateTreeMemoryUsage & LinkedUsage = MemoryUsages [ StateLinks [ Index ] . Get < 1 > ( ) ] ;
const int32 LinkedTotalUsage = LinkedUsage . EstimatedMemoryUsage + LinkedUsage . EstimatedChildMemoryUsage ;
if ( LinkedTotalUsage > ParentUsage . EstimatedChildMemoryUsage )
{
ParentUsage . EstimatedChildMemoryUsage = LinkedTotalUsage ;
ParentUsage . ChildNodeCount = LinkedUsage . NodeCount + LinkedUsage . ChildNodeCount ;
}
}
// Evaluators
FStateTreeMemoryUsage & EvalMemUsage = MemoryUsages [ EvalMemUsageIndex ] ;
for ( int32 EvalIndex = EvaluatorsBegin ; EvalIndex < ( EvaluatorsBegin + EvaluatorsNum ) ; EvalIndex + + )
{
2023-02-13 20:06:02 -05:00
const FStateTreeEvaluatorBase & Eval = Nodes [ EvalIndex ] . Get < const FStateTreeEvaluatorBase > ( ) ;
2022-05-31 04:51:18 -04:00
if ( Eval . bInstanceIsObject = = false )
{
2022-11-30 07:17:26 -05:00
EvalMemUsage . AddUsage ( DefaultInstanceData . GetStruct ( Eval . InstanceIndex . Get ( ) ) ) ;
2022-05-31 04:51:18 -04:00
}
else
{
2022-11-30 07:17:26 -05:00
EvalMemUsage . AddUsage ( DefaultInstanceData . GetObject ( Eval . InstanceIndex . Get ( ) ) ) ;
2022-05-31 04:51:18 -04:00
}
2022-06-29 07:22:15 -04:00
EvalMemUsage . NodeCount + + ;
2022-05-31 04:51:18 -04:00
}
2023-01-12 09:45:58 -05:00
// Global Tasks
FStateTreeMemoryUsage & GlobalTaskMemUsage = MemoryUsages [ GlobalTaskMemUsageIndex ] ;
for ( int32 TaskIndex = GlobalTasksBegin ; TaskIndex < ( GlobalTasksBegin + GlobalTasksNum ) ; TaskIndex + + )
{
2023-02-13 20:06:02 -05:00
const FStateTreeTaskBase & Task = Nodes [ TaskIndex ] . Get < const FStateTreeTaskBase > ( ) ;
2023-01-12 09:45:58 -05:00
if ( Task . bInstanceIsObject = = false )
{
GlobalTaskMemUsage . AddUsage ( DefaultInstanceData . GetStruct ( Task . InstanceIndex . Get ( ) ) ) ;
}
else
{
GlobalTaskMemUsage . AddUsage ( DefaultInstanceData . GetObject ( Task . InstanceIndex . Get ( ) ) ) ;
}
GlobalTaskMemUsage . NodeCount + + ;
}
2022-05-31 04:51:18 -04:00
// Estimate highest combined usage.
FStateTreeMemoryUsage & TreeMemUsage = MemoryUsages [ TreeMemUsageIndex ] ;
// Exec state
TreeMemUsage . AddUsage ( DefaultInstanceData . GetStruct ( 0 ) ) ;
TreeMemUsage . NodeCount + + ;
TreeMemUsage . EstimatedMemoryUsage + = EvalMemUsage . EstimatedMemoryUsage ;
TreeMemUsage . NodeCount + = EvalMemUsage . NodeCount ;
2023-01-12 09:45:58 -05:00
TreeMemUsage . EstimatedMemoryUsage + = GlobalTaskMemUsage . EstimatedMemoryUsage ;
TreeMemUsage . NodeCount + = GlobalTaskMemUsage . NodeCount ;
2022-06-29 07:22:15 -04:00
FStateTreeMemoryUsage & InstanceMemUsage = MemoryUsages [ InstanceMemUsageIndex ] ;
2022-05-31 04:51:18 -04:00
// FStateTreeInstanceData overhead.
2022-06-29 07:22:15 -04:00
InstanceMemUsage . EstimatedMemoryUsage + = sizeof ( FStateTreeInstanceData ) ;
2022-12-05 09:16:27 -05:00
// FInstancedStructContainer overhead.
InstanceMemUsage . EstimatedMemoryUsage + = TreeMemUsage . NodeCount * FInstancedStructContainer : : OverheadPerItem ;
2022-06-29 07:22:15 -04:00
TreeMemUsage . EstimatedMemoryUsage + = InstanceMemUsage . EstimatedMemoryUsage ;
2022-05-31 04:51:18 -04:00
int32 MaxSubtreeUsage = 0 ;
int32 MaxSubtreeNodeCount = 0 ;
for ( const FStateTreeMemoryUsage & MemUsage : MemoryUsages )
{
if ( MemUsage . Handle . IsValid ( ) )
{
const int32 TotalUsage = MemUsage . EstimatedMemoryUsage + MemUsage . EstimatedChildMemoryUsage ;
if ( TotalUsage > MaxSubtreeUsage )
{
MaxSubtreeUsage = TotalUsage ;
MaxSubtreeNodeCount = MemUsage . NodeCount + MemUsage . ChildNodeCount ;
}
}
}
TreeMemUsage . EstimatedMemoryUsage + = MaxSubtreeUsage ;
TreeMemUsage . NodeCount + = MaxSubtreeNodeCount ;
if ( SharedInstanceData . IsValid ( ) )
{
FStateTreeMemoryUsage & SharedMemUsage = MemoryUsages [ SharedMemUsageIndex ] ;
SharedMemUsage . NodeCount = SharedInstanceData . GetNumItems ( ) ;
SharedMemUsage . EstimatedMemoryUsage = SharedInstanceData . GetEstimatedMemoryUsage ( ) ;
}
return MemoryUsages ;
}
# endif // WITH_EDITOR
2022-09-28 01:06:15 -04:00