Example #1
1
void UFlareAIBehavior::Simulate()
{
	SCOPE_CYCLE_COUNTER(STAT_FlareAIBehavior_Simulate);

	// See how the player is doing
	TArray<UFlareCompany*> SortedCompany = Game->GetGameWorld()->GetCompanies();
	SortedCompany.Sort(&CompanyValueComparator);
	int32 PlayerCompanyIndex = SortedCompany.IndexOfByKey(GetGame()->GetPC()->GetCompany());
	int32 PlayerArmy = GetGame()->GetPC()->GetCompany()->GetCompanyValue().ArmyCurrentCombatPoints;

	// Pirates hate you
	if (PlayerCompanyIndex > 0 && Company == ST->Pirates)
	{
		Company->GivePlayerReputation(-0.5);
	}

	// Competitors hate you more if you're doing well
	float ReputationLoss = PlayerCompanyIndex / 30.f;
	if (PlayerArmy > 0 && Company != ST->AxisSupplies && Company->GetPlayerReputation() > ReputationLoss)
	{
		Company->GivePlayerReputation(-ReputationLoss);
	}

	// Simulate the day
	if (Company == ST->Pirates)
	{
		SimulatePirateBehavior();
	}
	else
	{
		SimulateGeneralBehavior();
	}

}
bool FLocMetadataValueArray::EqualTo( const FLocMetadataValue& Other ) const
{
	const FLocMetadataValueArray* OtherObj = (FLocMetadataValueArray*) &Other; 

	if( Value.Num() != OtherObj->Value.Num() )
	{
		return false;
	}

	TArray< TSharedPtr<FLocMetadataValue> > Sorted = Value;
	TArray< TSharedPtr<FLocMetadataValue> > OtherSorted = OtherObj->Value;

	Sorted.Sort( FCompareMetadataValue() );
	OtherSorted.Sort( FCompareMetadataValue() );

	for( int32 idx = 0; idx < Sorted.Num(); ++idx )
	{
		if( !(*(Sorted[idx]) == *(OtherSorted[idx]) ) )
		{
			return false;
		}
	}

	return true;
}
bool FLocMetadataValueArray::LessThan( const FLocMetadataValue& Other ) const
{
	const FLocMetadataValueArray* OtherObj = (FLocMetadataValueArray*) &Other;

	TArray< TSharedPtr<FLocMetadataValue> > Sorted = Value;
	TArray< TSharedPtr<FLocMetadataValue> > OtherSorted = OtherObj->Value;

	Sorted.Sort( FCompareMetadataValue() );
	OtherSorted.Sort( FCompareMetadataValue() );

	for( int32 idx = 0; idx < Sorted.Num(); ++idx )
	{
		if( idx >= OtherSorted.Num() )
		{
			return false;
		}
		else if( !( *(Sorted[idx]) == *(OtherSorted[idx]) ) )
		{
			return *(Sorted[idx]) < *(OtherSorted[idx]);
		}
	}

	if( OtherSorted.Num() > Sorted.Num() )
	{
		return true;
	}

	return false;
}
FProfilerManager::FProfilerManager( const ISessionManagerRef& InSessionManager )
	: SessionManager( InSessionManager )
	, CommandList( new FUICommandList() )
	, ProfilerActionManager( this )
	, Settings()

	, ProfilerType( EProfilerSessionTypes::InvalidOrMax )
	, bLivePreview( false )
	, bHasCaptureFileFullyProcessed( false )
{
	FEventGraphSample::InitializePropertyManagement();

#if	0
	// Performance tests.
	static FTotalTimeAndCount CurrentNative(0.0f, 0);
	static FTotalTimeAndCount CurrentPointer(0.0f, 0);
	static FTotalTimeAndCount CurrentShared(0.0f, 0);

	for( int32 Lx = 0; Lx < 16; ++Lx )
	{
		FRandomStream RandomStream( 666 );
		TArray<FEventGraphSample> EventsNative;
		TArray<FEventGraphSample*> EventsPointer;
		TArray<FEventGraphSamplePtr> EventsShared;

		const int32 NumEvents = 16384;
		for( int32 Nx = 0; Nx < NumEvents; ++Nx )
		{
			const double Rnd = RandomStream.FRandRange( 0.0f, 16384.0f );
			const FString EventName = TTypeToString<double>::ToString( Rnd );
			FEventGraphSample NativeEvent( *EventName );
			NativeEvent._InclusiveTimeMS = Rnd;

			FEventGraphSamplePtr SharedEvent = FEventGraphSample::CreateNamedEvent( *EventName );
			SharedEvent->_InclusiveTimeMS = Rnd;

			EventsNative.Add(NativeEvent);
			EventsPointer.Add(SharedEvent.Get());
			EventsShared.Add(SharedEvent);
		}

		{
			FProfilerScopedLogTime ScopedLog( TEXT("1.NativeSorting"), &CurrentNative );
			EventsNative.Sort( FEventGraphSampleLess() );
		}

		{
			FProfilerScopedLogTime ScopedLog( TEXT("2PointerSorting"), &CurrentPointer );
			EventsPointer.Sort( FEventGraphSampleLess() );
		}

		{
			FProfilerScopedLogTime ScopedLog( TEXT("3.SharedSorting"), &CurrentShared );
			FEventArraySorter::Sort( EventsShared, FEventGraphSample::GetEventPropertyByIndex(EEventPropertyIndex::InclusiveTimeMS).Name, EEventCompareOps::Less );
		}
	}
#endif // 0
}
Example #5
0
void NUTUtil::SortUnitTestClassDefList(TArray<UUnitTest*>& InUnitTestClassDefaults)
{
	// @todo #JohnBRefactorLambda: Convert these inline sort functions to lambda's now
	struct FUnitTestDateSort
	{
		FORCEINLINE bool operator()(const UUnitTest& A, const UUnitTest& B) const
		{
			return (A.GetUnitTestDate() < B.GetUnitTestDate());
		}
	};

	struct FUnitTestTypeDateSort
	{
		FUnitTestTypeDateSort(TArray<FString>& InTypeOrder)
			: TypeOrder(InTypeOrder)
		{
		}

		FORCEINLINE bool operator()(const UUnitTest& A, const UUnitTest& B) const
		{
			bool bReturnVal = false;

			if (TypeOrder.IndexOfByKey(A.GetUnitTestType()) < TypeOrder.IndexOfByKey(B.GetUnitTestType()))
			{
				bReturnVal = true;
			}
			else if (TypeOrder.IndexOfByKey(A.GetUnitTestType()) == TypeOrder.IndexOfByKey(B.GetUnitTestType()) &&
						A.GetUnitTestDate() < B.GetUnitTestDate())
			{
				bReturnVal = true;
			}

			return bReturnVal;
		}

		/** The order with which the prioritize types */
		TArray<FString> TypeOrder;
	};


	// First reorder the unit test classes by date, then grab the unit test types by date, then group them by type/date
	TArray<FString> ListTypes;

	InUnitTestClassDefaults.Sort(FUnitTestDateSort());

	for (int i=0; i<InUnitTestClassDefaults.Num(); i++)
	{
		ListTypes.AddUnique(InUnitTestClassDefaults[i]->GetUnitTestType());
	}

	// Now sort again, based both on type and date
	InUnitTestClassDefaults.Sort(FUnitTestTypeDateSort(ListTypes));
}
void FMacErrorReport::FindMostRecentErrorReports(TArray<FString>& ErrorReportPaths, const FTimespan& MaxCrashReportAge)
{
	auto& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();

	FDateTime MinCreationTime = FDateTime::Now() - MaxCrashReportAge;
	auto ReportFinder = MakeDirectoryVisitor([&](const TCHAR* FilenameOrDirectory, bool bIsDirectory)
	{
		if (bIsDirectory)
		{
			auto TimeStamp = PlatformFile.GetTimeStamp(FilenameOrDirectory);
			if (TimeStamp > MinCreationTime)
			{
				ErrorReportPaths.Add(FilenameOrDirectory);
			}
		}
		return true;
	});

	FString AllReportsDirectory = FPaths::GameAgnosticSavedDir() / TEXT("Crashes");

	PlatformFile.IterateDirectory(
		*AllReportsDirectory,
		ReportFinder);

	ErrorReportPaths.Sort([&](const FString& L, const FString& R)
	{
		auto TimeStampL = PlatformFile.GetTimeStamp(*L);
		auto TimeStampR = PlatformFile.GetTimeStamp(*R);

		return TimeStampL > TimeStampR;
	});
}
void FSplineComponentVisualizer::OnDuplicateKey()
{
	const FScopedTransaction Transaction(LOCTEXT("DuplicateSplinePoint", "Duplicate Spline Point"));
	USplineComponent* SplineComp = GetEditedSplineComponent();
	check(SplineComp != nullptr);
	check(LastKeyIndexSelected != INDEX_NONE);
	check(SelectedKeys.Num() > 0);
	check(SelectedKeys.Contains(LastKeyIndexSelected));

	SplineComp->Modify();
	if (AActor* Owner = SplineComp->GetOwner())
	{
		Owner->Modify();
	}

	// Get a sorted list of all the selected indices, highest to lowest
	TArray<int32> SelectedKeysSorted;
	for (int32 SelectedKeyIndex : SelectedKeys)
	{
		SelectedKeysSorted.Add(SelectedKeyIndex);
	}
	SelectedKeysSorted.Sort([](int32 A, int32 B) { return A > B; });

	// Insert duplicates into the list, highest index first, so that the lower indices remain the same
	FInterpCurveVector& SplineInfo = SplineComp->SplineInfo;
	FInterpCurveQuat& SplineRotInfo = SplineComp->SplineRotInfo;
	FInterpCurveVector& SplineScaleInfo = SplineComp->SplineScaleInfo;

	for (int32 SelectedKeyIndex : SelectedKeysSorted)
	{
		// Insert duplicates into arrays.
		// It's necessary to take a copy because copying existing array items by reference isn't allowed (the array may reallocate)
		SplineInfo.Points.Insert(FInterpCurvePoint<FVector>(SplineInfo.Points[SelectedKeyIndex]), SelectedKeyIndex);
		SplineRotInfo.Points.Insert(FInterpCurvePoint<FQuat>(SplineRotInfo.Points[SelectedKeyIndex]), SelectedKeyIndex);
		SplineScaleInfo.Points.Insert(FInterpCurvePoint<FVector>(SplineScaleInfo.Points[SelectedKeyIndex]), SelectedKeyIndex);
	}

	// Repopulate the selected keys
	SelectedKeys.Empty();
	int32 Offset = SelectedKeysSorted.Num();
	for (int32 SelectedKeyIndex : SelectedKeysSorted)
	{
		SelectedKeys.Add(SelectedKeyIndex + Offset);

		if (LastKeyIndexSelected == SelectedKeyIndex)
		{
			LastKeyIndexSelected += Offset;
		}

		Offset--;
	}

	// Unset tangent handle selection
	SelectedTangentHandle = INDEX_NONE;
	SelectedTangentHandleType = ESelectedTangentHandle::None;

	NotifyComponentModified();

//	CachedRotation = SplineComp->GetQuaternionAtSplinePoint(LastKeyIndexSelected, ESplineCoordinateSpace::World);
}
FString UGatherTextFromAssetsCommandlet::FDialogueHelper::ArrayMetaDataToString( const TArray< TSharedPtr< FLocMetadataValue > >& MetadataArray )
{
	FString FinalString;
	if( MetadataArray.Num() > 0 )
	{
		TArray< FString > MetadataStrings;
		for( TSharedPtr< FLocMetadataValue > DataEntry : MetadataArray )
		{
			if( DataEntry->Type == ELocMetadataType::String )
			{
				MetadataStrings.Add(DataEntry->AsString());
			}
		}
		MetadataStrings.Sort();
		for( const FString& StrEntry : MetadataStrings )
		{
			if(FinalString.Len())
			{
				FinalString += TEXT(",");
			}
			FinalString += StrEntry;
		}
	}
	return FinalString;
}
void UGISInventoryBaseComponent::PreLootAction(TArray<class AGISPickupActor*> PickupsIn)
{ 
	TArray<FGISPickupActorDistanceHelper> HelperStruct;
	FVector PawmLocation = PCOwner->GetPawn()->GetActorLocation();
	for (AGISPickupActor* Pickup : PickupsIn)
	{
		if (Pickup)
		{
			if (Pickup->ItemToLoot.Num() > 0)
			{
				float Distance = FVector::Dist(PawmLocation, Pickup->GetActorLocation());
				FGISPickupActorDistanceHelper helper(Distance, Pickup);
				HelperStruct.Add(helper);
			}
		}
	}
	HelperStruct.Sort();

	if (HelperStruct.IsValidIndex(0))
	{
		//don't need to check everything. If closest actor is to far, rest is as well.
		if (HelperStruct[0].Distance > MaxLootingDistance)
			StartLooting(HelperStruct[0].PickupActor.Get());
	}
}
TSharedPtr< FLocMetadataValue > UGatherTextFromAssetsCommandlet::FDialogueHelper::GenSourceTargetMetadata( const FString& SpeakerName, const TArray< FString >& TargetNames, bool bCompact )
{
	/*
	This function can support two different formats.
	
	The first format is compact and results in string entries that will later be combined into something like this
	"Variations": [
		"Jenny -> Audience",
		"Zak -> Audience"
	]

	The second format is verbose and results in object entries that will later be combined into something like this
	"VariationsTest": [
		{
			"Speaker": "Jenny",
			"Targets": [
				"Audience"
			]
		},
		{
			"Speaker": "Zak",
			"Targets": [
				"Audience"
			]
		}
	]
	*/

	TSharedPtr< FLocMetadataValue > Result;
	if( bCompact )
	{
		TArray<FString> SortedTargetNames = TargetNames;
		SortedTargetNames.Sort();
		FString TargetNamesString;
		for( const FString& StrEntry : SortedTargetNames )
		{
			if(TargetNamesString.Len())
			{
				TargetNamesString += TEXT(",");
			}
			TargetNamesString += StrEntry;
		}
		Result = MakeShareable( new FLocMetadataValueString( FString::Printf( TEXT("%s -> %s" ), *SpeakerName, *TargetNamesString ) ) );
	}
	else
	{
		TArray< TSharedPtr< FLocMetadataValue > > TargetNamesMetadataList;
		for( const FString& StrEntry: TargetNames )
		{
			TargetNamesMetadataList.Add( MakeShareable( new FLocMetadataValueString( StrEntry ) ) );
		}

		TSharedPtr< FLocMetadataObject > MetadataObj = MakeShareable( new FLocMetadataObject() );
		MetadataObj->SetStringField( PropertyName_Speaker, SpeakerName );
		MetadataObj->SetArrayField( PropertyName_Targets, TargetNamesMetadataList );

		Result = MakeShareable( new FLocMetadataValueObject( MetadataObj.ToSharedRef() ) );
	}
	return Result;
}
void FObjectMemoryAnalyzer::PrintResults(FOutputDevice& Ar, uint32 PrintFlags)
{
	TArray<FObjectMemoryUsage> Results;
	GetResults(Results);

	Results.Sort(FCompareFSortBySize(ESortKey::InclusiveTotal));

	Ar.Logf( TEXT("%-100s %-10s %-10s %-10s %-10s"), TEXT("Object"), TEXT("InclBytes"), TEXT("ExclBytes"), TEXT("InclResKBytes"), TEXT("ExclResKBytes") );
	
	for( int32 i=0; i < Results.Num(); ++i )
	{
		const FObjectMemoryUsage& Annotation = Results[i];

		if (Annotation.IsRoot() || (Annotation.RootReferencer.Num() == 0 && Annotation.NonRootReferencer.Num() == 0) )
		{
			Ar.Logf( TEXT("%-100s %-10d %-10d %-10d %-10d"), *FString::Printf(TEXT("%s %s"), *Annotation.Object->GetClass()->GetName(), *Annotation.Object->GetName()), 
					 (int32)Annotation.InclusiveMemoryUsage, (int32)Annotation.ExclusiveMemoryUsage, 
					 (int32)(Annotation.InclusiveResourceSize/1024), (int32)(Annotation.ExclusiveResourceSize/1024) );


			if (!!(PrintFlags&EPrintFlags::PrintReferences))
			{
				PrintSubObjects(Ar, TEXT(" -> "), Annotation.Object, PrintFlags);
			}
		}
	}
}
EConvertQueryResult AddSweepResults(bool& OutHasValidBlockingHit, const UWorld* World, int32 NumHits, PxSweepHit* Hits, float CheckLength, const PxFilterData& QueryFilter, TArray<FHitResult>& OutHits, const FVector& StartLoc, const FVector& EndLoc, const PxGeometry& Geom, const PxTransform& QueryTM, float MaxDistance, bool bReturnFaceIndex, bool bReturnPhysMat)
{
	OutHits.Reserve(OutHits.Num() + NumHits);
	EConvertQueryResult ConvertResult = EConvertQueryResult::Valid;
	bool bHadBlockingHit = false;
	const PxVec3 PDir = U2PVector((EndLoc - StartLoc).GetSafeNormal());

	for(int32 i=0; i<NumHits; i++)
	{
		PxSweepHit& PHit = Hits[i];
		checkSlow(PHit.flags & PxHitFlag::eDISTANCE);
		if(PHit.distance <= MaxDistance)
		{
			PHit.faceIndex = FindFaceIndex(PHit, PDir);

			FHitResult& NewResult = OutHits[OutHits.AddDefaulted()];
			if (ConvertQueryImpactHit(World, PHit, NewResult, CheckLength, QueryFilter, StartLoc, EndLoc, &Geom, QueryTM, bReturnFaceIndex, bReturnPhysMat) == EConvertQueryResult::Valid)
			{
				bHadBlockingHit |= NewResult.bBlockingHit;
			}
			else
			{
				// Reject invalid result (this should be rare). Remove from the results.
				OutHits.Pop(/*bAllowShrinking=*/ false);
				ConvertResult = EConvertQueryResult::Invalid;
			}
			
		}
	}

	// Sort results from first to last hit
	OutHits.Sort( FCompareFHitResultTime() );
	OutHasValidBlockingHit = bHadBlockingHit;
	return ConvertResult;
}
Example #13
0
void BuildResourceTableTokenStream(const TArray<uint32>& InResourceMap, int32 MaxBoundResourceTable, TArray<uint32>& OutTokenStream)
{
	// First we sort the resource map.
	TArray<uint32> SortedResourceMap = InResourceMap;
	SortedResourceMap.Sort();

	// The token stream begins with a table that contains offsets per bound uniform buffer.
	// This offset provides the start of the token stream.
	OutTokenStream.AddZeroed(MaxBoundResourceTable+1);
	auto LastBufferIndex = FRHIResourceTableEntry::GetEndOfStreamToken();
	for (int32 i = 0; i < SortedResourceMap.Num(); ++i)
	{
		auto BufferIndex = FRHIResourceTableEntry::GetUniformBufferIndex(SortedResourceMap[i]);
		if (BufferIndex != LastBufferIndex)
		{
			// Store the offset for resources from this buffer.
			OutTokenStream[BufferIndex] = OutTokenStream.Num();
			LastBufferIndex = BufferIndex;
		}
		OutTokenStream.Add(SortedResourceMap[i]);
	}

	// Add a token to mark the end of the stream. Not needed if there are no bound resources.
	if (OutTokenStream.Num())
	{
		OutTokenStream.Add(FRHIResourceTableEntry::GetEndOfStreamToken());
	}
}
Example #14
0
void FAnimTrack::CollapseAnimSegments()
{
	if(AnimSegments.Num() > 0)
	{
		// Sort function
		struct FSortFloatInt
		{
			bool operator()( const TKeyValuePair<float, int32> &A, const TKeyValuePair<float, int32>&B ) const
			{
				return A.Key < B.Key;
			}
		};

		// Create sorted map of start time to segment
		TArray<TKeyValuePair<float, int32>> m;
		for( int32 SegmentInd=0; SegmentInd < AnimSegments.Num(); ++SegmentInd )
		{
			m.Add(TKeyValuePair<float, int32>(AnimSegments[SegmentInd].StartPos, SegmentInd));
		}
		m.Sort(FSortFloatInt());

		//collapse all start times based on sorted map
		FAnimSegment* PrevSegment = &AnimSegments[m[0].Value];
		PrevSegment->StartPos = 0.0f;

		for ( int32 SegmentInd=1; SegmentInd < m.Num(); ++SegmentInd )
		{
			FAnimSegment* CurrSegment = &AnimSegments[m[SegmentInd].Value];
			CurrSegment->StartPos = PrevSegment->StartPos + PrevSegment->GetLength();
			PrevSegment = CurrSegment;
		}
	}
}
Example #15
0
/**
* Dumps capture stack trace summary to the passed in log.
*/
void FScriptStackTracker::DumpStackTraces( int32 StackThreshold, FOutputDevice& Ar )
{
	// Avoid distorting results while we log them.
	check( !bAvoidCapturing );
	bAvoidCapturing = true;

	// Make a copy as sorting causes index mismatch with TMap otherwise.
	TArray<FCallStack> SortedCallStacks = CallStacks;
	// Compare function, sorting callstack by stack count in descending order.
	struct FCompareStackCount
	{
		FORCEINLINE bool operator()( const FCallStack& A, const FCallStack& B ) const { return B.StackCount < A.StackCount; }
	};
	// Sort callstacks in descending order by stack count.
	SortedCallStacks.Sort( FCompareStackCount() );

	// Iterate over each callstack to get total stack count.
	uint64 TotalStackCount = 0;
	for( int32 CallStackIndex=0; CallStackIndex<SortedCallStacks.Num(); CallStackIndex++ )
	{
		const FCallStack& CallStack = SortedCallStacks[CallStackIndex];
		TotalStackCount += CallStack.StackCount;
	}

	// Calculate the number of frames we captured.
	int32 FramesCaptured = 0;
	if( bIsEnabled )
	{
		FramesCaptured = GFrameCounter - StartFrameCounter;
	}
	else
	{
		FramesCaptured = StopFrameCounter - StartFrameCounter;
	}

	// Log quick summary as we don't log each individual so totals in CSV won't represent real totals.
	Ar.Logf(TEXT("Captured %i unique callstacks totalling %i function calls over %i frames, averaging %5.2f calls/frame"), SortedCallStacks.Num(), (int32)TotalStackCount, FramesCaptured, (float) TotalStackCount / FramesCaptured);

	// Iterate over each callstack and write out info in human readable form in CSV format
	for( int32 CallStackIndex=0; CallStackIndex<SortedCallStacks.Num(); CallStackIndex++ )
	{
		const FCallStack& CallStack = SortedCallStacks[CallStackIndex];

		// Avoid log spam by only logging above threshold.
		if( CallStack.StackCount > StackThreshold )
		{
			// First row is stack count.
			FString CallStackString = FString::FromInt((int32)CallStack.StackCount);
			CallStackString += LINE_TERMINATOR;
			CallStackString += CallStack.StackTrace;

			// Finally log with ',' prefix so "Log:" can easily be discarded as row in Excel.
			Ar.Logf(TEXT(",%s"),*CallStackString);
		}
	}

	// Done logging.
	bAvoidCapturing = false;
}
Example #16
0
bool UBlendSpaceBase::GetSamplesFromBlendInput(const FVector &BlendInput, TArray<FBlendSampleData> & OutSampleDataList) const
{
    TArray<FGridBlendSample> RawGridSamples;
    GetRawSamplesFromBlendInput(BlendInput, RawGridSamples);

    OutSampleDataList.Empty();

    // consolidate all samples
    for (int32 SampleNum=0; SampleNum<RawGridSamples.Num(); ++SampleNum)
    {
        FGridBlendSample& GridSample = RawGridSamples[SampleNum];
        float GridWeight = GridSample.BlendWeight;
        FEditorElement& GridElement = GridSample.GridElement;

        for(int Ind = 0; Ind < GridElement.MAX_VERTICES; ++Ind)
        {
            if(GridElement.Indices[Ind] != INDEX_NONE)
            {
                int32 Index = OutSampleDataList.AddUnique(GridElement.Indices[Ind]);
                OutSampleDataList[Index].AddWeight(GridElement.Weights[Ind]*GridWeight);
            }
        }
    }

    /** Used to sort by  Weight. */
    struct FCompareFBlendSampleData
    {
        FORCEINLINE bool operator()( const FBlendSampleData& A, const FBlendSampleData& B ) const {
            return B.TotalWeight < A.TotalWeight;
        }
    };
    OutSampleDataList.Sort( FCompareFBlendSampleData() );

    // remove noisy ones
    int32 TotalSample = OutSampleDataList.Num();
    float TotalWeight = 0.f;
    for (int32 I=0; I<TotalSample; ++I)
    {
        if (OutSampleDataList[I].TotalWeight < ZERO_ANIMWEIGHT_THRESH)
        {
            // cut anything in front of this
            OutSampleDataList.RemoveAt(I, TotalSample-I);
            break;
        }

        TotalWeight += OutSampleDataList[I].TotalWeight;
    }

    for (int32 I=0; I<OutSampleDataList.Num(); ++I)
    {
        // normalize to all weights
        OutSampleDataList[I].TotalWeight /= TotalWeight;
    }

    return (OutSampleDataList.Num()!=0);
}
Example #17
0
bool UBlendSpaceBase::GetSamplesFromBlendInput(const FVector &BlendInput, TArray<FBlendSampleData> & OutSampleDataList) const
{
	static TArray<FGridBlendSample, TInlineAllocator<4> > RawGridSamples;
	check(IsInGameThread() && !RawGridSamples.Num()); // this must be called non-recursively from the gamethread
	GetRawSamplesFromBlendInput(BlendInput, RawGridSamples);

	OutSampleDataList.Reset();
	OutSampleDataList.Reserve(RawGridSamples.Num() * FEditorElement::MAX_VERTICES);

	// consolidate all samples
	for (int32 SampleNum=0; SampleNum<RawGridSamples.Num(); ++SampleNum)
	{
		FGridBlendSample& GridSample = RawGridSamples[SampleNum];
		float GridWeight = GridSample.BlendWeight;
		FEditorElement& GridElement = GridSample.GridElement;

		for(int Ind = 0; Ind < GridElement.MAX_VERTICES; ++Ind)
		{
			if(GridElement.Indices[Ind] != INDEX_NONE)
			{
				int32 Index = OutSampleDataList.AddUnique(GridElement.Indices[Ind]);
				OutSampleDataList[Index].AddWeight(GridElement.Weights[Ind]*GridWeight);
			}
		}
	}

	/** Used to sort by  Weight. */
	struct FCompareFBlendSampleData
	{
		FORCEINLINE bool operator()( const FBlendSampleData& A, const FBlendSampleData& B ) const { return B.TotalWeight < A.TotalWeight; }
	};
	OutSampleDataList.Sort( FCompareFBlendSampleData() );

	// remove noisy ones
	int32 TotalSample = OutSampleDataList.Num();
	float TotalWeight = 0.f;
	for (int32 I=0; I<TotalSample; ++I)
	{
		if (OutSampleDataList[I].TotalWeight < ZERO_ANIMWEIGHT_THRESH)
		{
			// cut anything in front of this 
			OutSampleDataList.RemoveAt(I, TotalSample-I, false); // we won't shrink here, that might screw up alloc optimization at a higher level, if not this is temp anyway
			break;
		}

		TotalWeight += OutSampleDataList[I].TotalWeight;
	}

	for (int32 I=0; I<OutSampleDataList.Num(); ++I)
	{
		// normalize to all weights
		OutSampleDataList[I].TotalWeight /= TotalWeight;
	}
	RawGridSamples.Reset();
	return (OutSampleDataList.Num()!=0);
}
	virtual int32 GetFriendList(TArray< TSharedPtr<FFriendViewModel> >& OutFriendsList) override
	{
		TArray< TSharedPtr< IFriendItem > > FriendItemList = FriendsAndChatManager.Pin()->GetRecentPlayerList();
		FriendItemList.Sort(FCompareGroupByName());
		for(const auto& FriendItem : FriendItemList)
		{
			OutFriendsList.Add(FriendViewModelFactory->Create(FriendItem.ToSharedRef()));
		}
		return 0;
	}
Example #19
0
bool UBehaviorTreeManager::LoadTree(UBehaviorTree& Asset, UBTCompositeNode*& Root, uint16& InstanceMemorySize)
{
	SCOPE_CYCLE_COUNTER(STAT_AI_BehaviorTree_LoadTime);

	for (int32 TemplateIndex = 0; TemplateIndex < LoadedTemplates.Num(); TemplateIndex++)
	{
		FBehaviorTreeTemplateInfo& TemplateInfo = LoadedTemplates[TemplateIndex];
		if (TemplateInfo.Asset == &Asset)
		{
			Root = TemplateInfo.Template;
			InstanceMemorySize = TemplateInfo.InstanceMemorySize;
			return true;
		}
	}

	if (Asset.RootNode)
	{
		FBehaviorTreeTemplateInfo TemplateInfo;
		TemplateInfo.Asset = &Asset;
		TemplateInfo.Template = Cast<UBTCompositeNode>(StaticDuplicateObject(Asset.RootNode, this, TEXT("None")));

		TArray<FNodeInitializationData> InitList;
		uint16 ExecutionIndex = 0;
		InitializeNodeHelper(NULL, TemplateInfo.Template, 0, ExecutionIndex, InitList, Asset, this);

#if USE_BEHAVIORTREE_DEBUGGER
		// fill in information about next nodes in execution index, before sorting memory offsets
		for (int32 Index = 0; Index < InitList.Num() - 1; Index++)
		{
			InitList[Index].Node->InitializeExecutionOrder(InitList[Index + 1].Node);
		}
#endif

		// sort nodes by memory size, so they can be packed better
		// it still won't protect against structures, that are internally misaligned (-> uint8, uint32)
		// but since all Engine level nodes are good... 
		InitList.Sort(FNodeInitializationData::FMemorySort());
		uint16 MemoryOffset = 0;
		for (int32 Index = 0; Index < InitList.Num(); Index++)
		{
			InitList[Index].Node->InitializeNode(InitList[Index].ParentNode, InitList[Index].ExecutionIndex, InitList[Index].SpecialDataSize + MemoryOffset, InitList[Index].TreeDepth);
			MemoryOffset += InitList[Index].DataSize;
		}
		
		TemplateInfo.InstanceMemorySize = MemoryOffset;

		INC_DWORD_STAT(STAT_AI_BehaviorTree_NumTemplates);
		LoadedTemplates.Add(TemplateInfo);
		Root = TemplateInfo.Template;
		InstanceMemorySize = TemplateInfo.InstanceMemorySize;
		return true;
	}

	return false;
}
int32 UPartyBeaconState::GetTeamAssignment(const FPartyReservation& Party)
{
	if (NumTeams > 1)
	{
		TArray<FTeamBalanceInfo> PotentialTeamChoices;
		for (int32 TeamIdx = 0; TeamIdx < NumTeams; TeamIdx++)
		{
			const int32 CurrentPlayersOnTeam = GetNumPlayersOnTeam(TeamIdx);
			if ((CurrentPlayersOnTeam + Party.PartyMembers.Num()) <= NumPlayersPerTeam)
			{
				new (PotentialTeamChoices)FTeamBalanceInfo(TeamIdx, CurrentPlayersOnTeam);
			}
		}

		// Grab one from our list of choices
		if (PotentialTeamChoices.Num() > 0)
		{
			if (TeamAssignmentMethod == ETeamAssignmentMethod::Smallest)
			{
				PotentialTeamChoices.Sort(FSortTeamSizeSmallestToLargest());
				return PotentialTeamChoices[0].TeamIdx;
			}
			else if (TeamAssignmentMethod == ETeamAssignmentMethod::BestFit)
			{
				PotentialTeamChoices.Sort(FSortTeamSizeSmallestToLargest());
				return PotentialTeamChoices[PotentialTeamChoices.Num() - 1].TeamIdx;
			}
			else if (TeamAssignmentMethod == ETeamAssignmentMethod::Random)
			{
				int32 TeamIndex = FMath::Rand() % PotentialTeamChoices.Num();
				return PotentialTeamChoices[TeamIndex].TeamIdx;
			}
		}
		else
		{
			UE_LOG(LogBeacon, Warning, TEXT("UPartyBeaconHost::GetTeamAssignment: couldn't find an open team for party members."));
			return INDEX_NONE;
		}
	}

	return ForceTeamNum;
}
Example #21
0
bool ScanPackages(TArray<FileInfo>& info, IProgressCallback* progress)
{
	info.Empty();
	ScanPackageData data;
	data.PkgInfo = &info;
	data.Progress = progress;
	appEnumGameFiles(ScanPackage, data);
	info.Sort(InfoCmp);

	return !data.Cancelled;
}
void USignificanceManager::GetManagedObjects(TArray<const USignificanceManager::FManagedObjectInfo*>& OutManagedObjects, bool bInSignificanceOrder) const
{
	OutManagedObjects.Reserve(ManagedObjects.Num());
	for (const TPair<FName, TArray<const FManagedObjectInfo*>>& TagToObjectInfoArrayPair : ManagedObjectsByTag)
	{
		OutManagedObjects.Append(TagToObjectInfoArrayPair.Value);
	}
	if (bInSignificanceOrder)
	{
		OutManagedObjects.Sort(PickCompareBySignificance(bSortSignificanceAscending));
	}
}
				static void SortCategoriesRecursively( TArray< FPluginCategoryTreeItemPtr >& Categories )
				{
					// Sort the categories
					Categories.Sort( FPluginCategoryTreeItemSorter() );

					// Sort sub-categories
					for( auto SubCategoryIt( Categories.CreateConstIterator() ); SubCategoryIt; ++SubCategoryIt )
					{
						const auto& SubCategory = *SubCategoryIt;
						SortCategoriesRecursively( SubCategory->AccessSubCategories() );
					}
				}
void FDetailLayoutBuilderImpl::GenerateDetailLayout()
{
	AllRootTreeNodes.Empty();

	// Sort by the order in which categories were edited
	struct FCompareFDetailCategoryImpl
	{
		FORCEINLINE bool operator()( TSharedPtr<FDetailCategoryImpl> A, TSharedPtr<FDetailCategoryImpl> B ) const
		{
			return A->GetSortOrder() < B->GetSortOrder();
		}
	};

	// Merge the two category lists and sort them based on priority
	FCategoryMap AllCategories = CustomCategoryMap;
	AllCategories.Append( DefaultCategoryMap );

	TArray< TSharedRef<FDetailCategoryImpl> > SimpleCategories;
	TArray< TSharedRef<FDetailCategoryImpl> > AdvancedOnlyCategories;

	BuildCategories( CustomCategoryMap, SimpleCategories, AdvancedOnlyCategories );
	BuildCategories( DefaultCategoryMap, SimpleCategories, AdvancedOnlyCategories );

	SimpleCategories.Sort( FCompareFDetailCategoryImpl() );
	AdvancedOnlyCategories.Sort( FCompareFDetailCategoryImpl() );

	/** Merge the two category lists in sorted order */
	for( int32 CategoryIndex = 0; CategoryIndex < SimpleCategories.Num(); ++CategoryIndex )
	{
		AllRootTreeNodes.Add( SimpleCategories[CategoryIndex] );
	}

	for( int32 CategoryIndex = 0; CategoryIndex < AdvancedOnlyCategories.Num(); ++CategoryIndex )
	{
		AllRootTreeNodes.Add( AdvancedOnlyCategories[CategoryIndex] );
	}


}
Example #25
0
void USkeleton::RemoveBonesFromSkeleton( const TArray<FName>& BonesToRemove, bool bRemoveChildBones )
{
	TArray<int32> BonesRemoved = ReferenceSkeleton.RemoveBonesByName(BonesToRemove);
	if(BonesRemoved.Num() > 0)
	{
		BonesRemoved.Sort();
		for(int32 Index = BonesRemoved.Num()-1; Index >=0; --Index)
		{
			BoneTree.RemoveAt(Index);
		}
		HandleSkeletonHierarchyChange();
	}
}
void FGameplayCueTranslationManager::RefreshNameSwaps()
{
	AllNameSwaps.Reset();
	TArray<UGameplayCueTranslator*> CDOList;

	// Gather CDOs
	for( TObjectIterator<UClass> It ; It ; ++It )
	{
		UClass* Class = *It;
		if( !Class->HasAnyClassFlags(CLASS_Abstract | CLASS_Deprecated) )
		{
			if( Class->IsChildOf(UGameplayCueTranslator::StaticClass()) )
			{
				UGameplayCueTranslator* CDO = Class->GetDefaultObject<UGameplayCueTranslator>();
				if (CDO->IsEnabled())
				{
					CDOList.Add(CDO);
				}
			}
		}
	}

	// Sort and get translated names
	CDOList.Sort([](const UGameplayCueTranslator& A, const UGameplayCueTranslator& B) { return (A.GetPriority() > B.GetPriority()); });

	for (UGameplayCueTranslator* CDO : CDOList)
	{
		FNameSwapData& Data = AllNameSwaps[AllNameSwaps.AddDefaulted()];
		CDO->GetTranslationNameSpawns(Data.NameSwaps);
		if (Data.NameSwaps.Num() > 0)
		{
			Data.ClassCDO = CDO;
		}
		else
		{
			AllNameSwaps.Pop(false);
		}
	}

#if WITH_EDITOR
	// Give UniqueID to each rule
	int32 ID=1;
	for (FNameSwapData& GroupData : AllNameSwaps)
	{
		for (FGameplayCueTranslationNameSwap& SwapData : GroupData.NameSwaps)
		{
			SwapData.EditorData.UniqueID = ID++;
		}
	}
#endif
}
void FCollectionContextMenu::MakeSaveDynamicCollectionSubMenu(FMenuBuilder& MenuBuilder, FText InSearchQuery)
{
	auto OnCollectionCreated = FCollectionItem::FCollectionCreatedEvent::CreateSP(this, &FCollectionContextMenu::ExecuteSaveDynamicCollection, InSearchQuery);

	// Create new root level collection
	MakeNewCollectionSubMenu(MenuBuilder, ECollectionStorageMode::Dynamic, SCollectionView::FCreateCollectionPayload(OnCollectionCreated));

	FCollectionManagerModule& CollectionManagerModule = FCollectionManagerModule::GetModule();
	
	TArray<FCollectionNameType> AvailableCollections;
	CollectionManagerModule.Get().GetCollections(AvailableCollections);

	AvailableCollections.Sort([](const FCollectionNameType& One, const FCollectionNameType& Two) -> bool
	{
		return One.Name < Two.Name;
	});

	if (AvailableCollections.Num() > 0)
	{
		MenuBuilder.BeginSection("CollectionReplaceCollection", LOCTEXT("OverwriteDynamicCollectionMenuHeading", "Overwrite Dynamic Collection"));

		for (const FCollectionNameType& AvailableCollection : AvailableCollections)
		{
			// Never display system collections
			if (AvailableCollection.Type == ECollectionShareType::CST_System)
			{
				continue;
			}

			// Can only overwrite dynamic collections
			ECollectionStorageMode::Type StorageMode = ECollectionStorageMode::Static;
			CollectionManagerModule.Get().GetCollectionStorageMode(AvailableCollection.Name, AvailableCollection.Type, StorageMode);
			if (StorageMode != ECollectionStorageMode::Dynamic)
			{
				continue;
			}

			MenuBuilder.AddMenuEntry(
				FText::FromName(AvailableCollection.Name), 
				FText::Format(LOCTEXT("SaveDynamicCollection_OverwriteExistingCollectionToolTip", "Overwrite '{0}' with the current search query"), FText::FromName(AvailableCollection.Name)),
				FSlateIcon(FEditorStyle::GetStyleSetName(), ECollectionShareType::GetIconStyleName(AvailableCollection.Type)),
				FUIAction(
					FExecuteAction::CreateSP( this, &FCollectionContextMenu::ExecuteSaveDynamicCollection, AvailableCollection, InSearchQuery ),
					FCanExecuteAction::CreateSP( this, &FCollectionContextMenu::CanExecuteSaveDynamicCollection, AvailableCollection )
					)
				);
		}

		MenuBuilder.EndSection();
	}
}
AEyeXActorBase* AEyeXPlayerController::FindByBoxedLineTrace(FHitResult& OutHit, const FSceneView* const View, const FVector2D& GazePoint,
	const FCollisionObjectQueryParams& ObjectParams, const FCollisionQueryParams& TraceParams)
{
	UWorld* World = GetWorld();
	if (!World) return nullptr;

	// Set up a box around the gaze point
	FVector2D Corners[4];
	GetBoxCorners(GazePoint, BoxSize * GetApproximatePixelsPerMillimeter(), Corners);

	// First check center point
	AEyeXActorBase* EyeXActor = nullptr;
	FVector Start, End;
	FEyeXUtils::GetStartAndEndOfLineTrace(View, MaxDistance, GazePoint, /*out*/ Start, /*out*/ End);
	if (World->LineTraceSingleByObjectType(OutHit, Start, End, ObjectParams, TraceParams))
	{
		EyeXActor = Cast<AEyeXActorBase>(OutHit.GetActor());
	}
	else
	{
		// If center point missed we perform traces in a box around the gaze point
		// and choose the closest EyeXActor hit by the traces
		TArray<AEyeXActorBase*> EyeXActors;
		for (int i = 0; i < 4; ++i)
		{
			FVector BoxStart, BoxEnd;
			FEyeXUtils::GetStartAndEndOfLineTrace(View, MaxDistance, Corners[i], /*out*/ BoxStart, /*out*/ BoxEnd);
			if (World->LineTraceSingleByObjectType(OutHit, BoxStart, BoxEnd, ObjectParams, TraceParams))
			{
				AEyeXActorBase* Actor = Cast<AEyeXActorBase>(OutHit.GetActor());
				if (!Actor) continue;
				EyeXActors.Add(Actor);
			}

			VisualizeHitTestPoint(bVisualizeDetection, World, BoxStart);
		}

		if (EyeXActors.Num() > 0)
		{
			FEyeXUtils::ActorDistanceComparer Comparer(PlayerCameraManager);
			EyeXActors.Sort(Comparer);
			EyeXActor = EyeXActors[0];
		}
	}

	VisualizeHit(bVisualizeDetection, World, OutHit);
	VisualizeGazePoint(bVisualizeDetection, World, Start);

	return EyeXActor;
}
TArray<FEditorModeInfo> FEditorModeRegistry::GetSortedModeInfo() const
{
	TArray<FEditorModeInfo> ModeInfoArray;
	
	for (const auto& Pair : ModeFactories)
	{
		ModeInfoArray.Add(Pair.Value->GetModeInfo());
	}

	ModeInfoArray.Sort([](const FEditorModeInfo& A, const FEditorModeInfo& B){
		return A.PriorityOrder < B.PriorityOrder;
	});

	return ModeInfoArray;
}
			FRectangleSortHelper(TArray<FIntRect>& InOutSprites)
			{
				// Sort by Y, then by X (top left corner), descending order (so we can use it as a stack from the top row down)
				TArray<FIntRect> SpritesLeft = InOutSprites;
				SpritesLeft.Sort([](const FIntRect& A, const FIntRect& B) { return (A.Min.Y == B.Min.Y) ? (A.Min.X > B.Min.X) : (A.Min.Y > B.Min.Y); });
				InOutSprites.Reset();

				// Start pulling sprites out, the first one in each row will dominate remaining ones and cause them to get labeled
				TArray<FIntRect> DominatedSprites;
				DominatedSprites.Empty(SpritesLeft.Num());
				while (SpritesLeft.Num())
				{
					FIntRect DominatingSprite = SpritesLeft.Pop();
					DominatedSprites.Add(DominatingSprite);

					// Find the sprites that are dominated (intersect the infinite horizontal band described by the dominating sprite)
					for (int32 Index = 0; Index < SpritesLeft.Num();)
					{
						const FIntRect& CurElement = SpritesLeft[Index];
						if ((CurElement.Min.Y <= DominatingSprite.Max.Y) && (CurElement.Max.Y >= DominatingSprite.Min.Y))
						{
							DominatedSprites.Add(CurElement);
							SpritesLeft.RemoveAt(Index, /*Count=*/ 1, /*bAllowShrinking=*/ false);
						}
						else
						{
							++Index;
						}
					}

					// Sort the sprites in the band by X and add them to the result
					DominatedSprites.Sort([](const FIntRect& A, const FIntRect& B) { return (A.Min.X < B.Min.X); });
					InOutSprites.Append(DominatedSprites);
					DominatedSprites.Reset();
				}
			}