// © 2024 Long Ly. All rights reserved. Any unauthorized use, reproduction, or distribution of this trademark is strictly prohibited and may result in legal action.


#include "Nodes/AnimNode_SlotCustom.h"

#include "Animation/AnimInstanceProxy.h"
#include "Animation/AnimNode_Inertialization.h"

void FAnimNode_SlotCustom::Update_AnyThread(const FAnimationUpdateContext& context)
{
	DECLARE_SCOPE_HIERARCHICAL_COUNTER_ANIMNODE(Update_AnyThread)
	// Update weights.
	context.AnimInstanceProxy->GetSlotWeight(SlotName, WeightData.SlotNodeWeight, WeightData.SourceWeight, WeightData.TotalNodeWeight);

	// Update cache in AnimInstance.
	context.AnimInstanceProxy->UpdateSlotNodeWeight(SlotName, WeightData.SlotNodeWeight, context.GetFinalBlendWeight());

	UE::Anim::FSlotInertializationRequest inertializationRequest;
	if (context.AnimInstanceProxy->GetSlotInertializationRequest(SlotName, inertializationRequest))
	{
		UE::Anim::IInertializationRequester* inertializationRequestr = context.GetMessage<UE::Anim::IInertializationRequester>();
		if (inertializationRequestr)
		{
			inertializationRequestr->RequestInertialization(inertializationRequest.Get<0>(), inertializationRequest.Get<1>());
		}
		else
		{
			FAnimNode_Inertialization::LogRequestError(context, Source);
		}
	}
	
	const bool shouldUpdateSource = (bAlwaysUpdateSourcePose || FAnimWeight::IsRelevant(WeightData.SourceWeight));
	if (shouldUpdateSource)
	{
		const float SourceWeight = FMath::Max(FAnimWeight::GetSmallestRelevantWeight(), WeightData.SourceWeight);
		Source.Update(context.FractionalWeight(SourceWeight));
	}
#if ANIM_TRACE_ENABLED
	TRACE_ANIM_NODE_VALUE(context, TEXT("Name"), SlotName);
	TRACE_ANIM_NODE_VALUE(context, TEXT("Slot Weight"), WeightData.SlotNodeWeight);
	TRACE_ANIM_NODE_VALUE(context, TEXT("Pose Source"), (WeightData.SourceWeight <= ZERO_ANIMWEIGHT_THRESH));

	context.AnimInstanceProxy->TraceMontageEvaluationData(context, SlotName);
#endif
}
