uint32 FArchiveObjectCrc32::Crc32(UObject* Object, uint32 CRC)
{
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
	const double StartTime = FPlatformTime::Seconds();
	UE_LOG(LogArchiveObjectCrc32, Log, TEXT("### Calculating CRC for object: %s with outer: %s"), *Object->GetName(), Object->GetOuter() ? *Object->GetOuter()->GetName() : TEXT("NULL"));
#endif
	RootObject = Object;
	if (Object)
	{
		TSet<UObject*> SerializedObjects;

		// Start with the given object
		ObjectsToSerialize.Enqueue(Object);

		// Continue until we no longer have any objects to serialized
		while (ObjectsToSerialize.Dequeue(Object))
		{
			bool bAlreadyProcessed = false;
			SerializedObjects.Add(Object, &bAlreadyProcessed);
			// If we haven't already serialized this object
			if (!bAlreadyProcessed)
			{
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
				UE_LOG(LogArchiveObjectCrc32, Log, TEXT("- Serializing object: %s with outer: %s"), *Object->GetName(), Object->GetOuter() ? *Object->GetOuter()->GetName() : TEXT("NULL"));
#endif
				// Serialize it
				ObjectBeingSerialized = Object;
				if (!CustomSerialize(Object))
				{
					Object->Serialize(*this);
				}
				ObjectBeingSerialized = NULL;

				// Calculate the CRC, compounding it with the checksum calculated from the previous object
				CRC = FCrc::MemCrc32(SerializedObjectData.GetData(), SerializedObjectData.Num(), CRC);
#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
				UE_LOG(LogArchiveObjectCrc32, Log, TEXT("=> object: '%s', total size: %d bytes, checksum: 0x%08x"), *GetPathNameSafe(Object), SerializedObjectData.Num(), CRC);
#endif
				// Cleanup
				MemoryWriter.Seek(0L);
				SerializedObjectData.Empty();
			}
		}

		// Cleanup
		SerializedObjects.Empty();
		RootObject = NULL;
	}

#ifdef DEBUG_ARCHIVE_OBJECT_CRC32
	UE_LOG(LogArchiveObjectCrc32, Log, TEXT("### Finished (%.02f ms), final checksum: 0x%08x"), (FPlatformTime::Seconds() - StartTime) * 1000.0f, CRC);
#endif
	return CRC;
}
Example #2
0
FText STileLayerList::GenerateDuplicatedLayerName(const FString& InputNameRaw, UPaperTileMap* TileMap)
{
	// Create a set of existing names
	TSet<FString> ExistingNames;
	for (UPaperTileLayer* ExistingLayer : TileMap->TileLayers)
	{
		ExistingNames.Add(ExistingLayer->LayerName.ToString());
	}

	FString BaseName = InputNameRaw;
	int32 TestIndex = 0;
	bool bAddNumber = false;

	// See if this is the result of a previous duplication operation, and change the desired name accordingly
	int32 SpaceIndex;
	if (InputNameRaw.FindLastChar(' ', /*out*/ SpaceIndex))
	{
		FString PossibleDuplicationSuffix = InputNameRaw.Mid(SpaceIndex + 1);

		if (PossibleDuplicationSuffix == TEXT("copy"))
		{
			bAddNumber = true;
			BaseName = InputNameRaw.Left(SpaceIndex);
			TestIndex = 2;
		}
		else
		{
			int32 ExistingIndex = FCString::Atoi(*PossibleDuplicationSuffix);

			const FString TestSuffix = FString::Printf(TEXT(" copy %d"), ExistingIndex);

			if (InputNameRaw.EndsWith(TestSuffix))
			{
				bAddNumber = true;
				BaseName = InputNameRaw.Left(InputNameRaw.Len() - TestSuffix.Len());
				TestIndex = ExistingIndex + 1;
			}
		}
	}

	// Find a good name
	FString TestLayerName = BaseName + TEXT(" copy");

	if (bAddNumber || ExistingNames.Contains(TestLayerName))
	{
		do
		{
			TestLayerName = FString::Printf(TEXT("%s copy %d"), *BaseName, TestIndex++);
		} while (ExistingNames.Contains(TestLayerName));
	}

	return FText::FromString(TestLayerName);
}
static bool ParseFramesFromSpriteHash(TSharedPtr<FJsonObject> ObjectBlock, TArray<FSpriteFrame>& OutSpriteFrames, TSet<FName>& FrameNames)
{
	GWarn->BeginSlowTask(NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frame"), true, true);
	bool bLoadedSuccessfully = true;

	// Parse all of the frames
	int32 FrameCount = 0;
	for (auto FrameIt = ObjectBlock->Values.CreateIterator(); FrameIt; ++FrameIt)
	{
		GWarn->StatusUpdate(FrameCount, ObjectBlock->Values.Num(), NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frames"));

		bool bReadFrameSuccessfully = true;

		FSpriteFrame Frame;
		Frame.FrameName = *FrameIt.Key();

		if (FrameNames.Contains(Frame.FrameName))
		{
			bReadFrameSuccessfully = false;
		}
		else
		{
			FrameNames.Add(Frame.FrameName);
		}

		TSharedPtr<FJsonValue> FrameDataAsValue = FrameIt.Value();
		TSharedPtr<FJsonObject> FrameData;
		if (FrameDataAsValue->Type == EJson::Object)
		{
			FrameData = FrameDataAsValue->AsObject();
			bReadFrameSuccessfully = bReadFrameSuccessfully && ParseFrame(FrameData, /*out*/Frame);
		}
		else
		{
			bReadFrameSuccessfully = false;
		}

		if (bReadFrameSuccessfully)
		{
			OutSpriteFrames.Add(Frame);
		}
		else
		{
			UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Frame %s is in an unexpected format"), *Frame.FrameName.ToString());
			bLoadedSuccessfully = false;
		}

		FrameCount++;
	}

	GWarn->EndSlowTask();
	return bLoadedSuccessfully;
}
void FBlueprintNativeCodeGenModule::Convert(UPackage* Package, ESavePackageResult CookResult, const TCHAR* PlatformName)
{
	// Find the struct/enum to convert:
	UStruct* Struct = nullptr;
	UEnum* Enum = nullptr;
	GetFieldFormPackage(Package, Struct, Enum);

	// First we gather information about bound functions.
	UClass* AsClass = Cast<UClass>(Struct);
	UBlueprint* BP = AsClass ? Cast<UBlueprint>(AsClass->ClassGeneratedBy) : nullptr;
	if (BP)
	{
		CollectBoundFunctions(BP);
	}

	if (CookResult != ESavePackageResult::ReplaceCompletely && CookResult != ESavePackageResult::GenerateStub)
	{
		// nothing to convert
		return;
	}

	if (Struct == nullptr && Enum == nullptr)
	{
		ensure(false);
		return;
	}

	if (CookResult == ESavePackageResult::GenerateStub)
	{
		if (ensure(BP))
		{
			ensure(!ToGenerate.Contains(BP));
			AllPotentialStubs.Add(BP);
		}
	}
	else
	{
		check(CookResult == ESavePackageResult::ReplaceCompletely);
		if (AsClass)
		{
			if (ensure(BP))
			{
				ensure(!AllPotentialStubs.Contains(BP));
				ToGenerate.Add(BP);
			}
		}
		else
		{
			UField* ForConversion = Struct ? (UField*)Struct : (UField*)Enum;
			GenerateSingleAsset(ForConversion, PlatformName);
		}
	}
}
FSlateTextureDataPtr FTileThumbnail::UpdateThumbnail()
{
	// No need images for persistent and always loaded levels
	if (TileModel.IsPersistent())
	{
		return ToSlateTextureData(nullptr);
	}
	
	// Load image from a package header
	if (!TileModel.IsVisible() || TileModel.IsSimulating())
	{
		const FName LevelAssetName = TileModel.GetAssetName();
		TSet<FName> ObjectFullNames;
		ObjectFullNames.Add(LevelAssetName);
		FThumbnailMap ThumbnailMap;

		if (ThumbnailTools::ConditionallyLoadThumbnailsFromPackage(TileModel.GetPackageFileName(), ObjectFullNames, ThumbnailMap))
		{
			const FObjectThumbnail* ObjectThumbnail = ThumbnailMap.Find(LevelAssetName);
			return ToSlateTextureData(ObjectThumbnail);
		}
	}
	// Render image from a visible level
	else
	{
		ULevel* TargetLevel = TileModel.GetLevelObject();
		if (TargetLevel)
		{
			FIntPoint RTSize = ThumbnailRenderTarget->GetSizeXY();
			
			// Set persistent world package as transient to avoid package dirtying during thumbnail rendering
			FUnmodifiableObject ImmuneWorld(TargetLevel->OwningWorld);
			
			FObjectThumbnail NewThumbnail;
			// Generate the thumbnail
			ThumbnailTools::RenderThumbnail(
				TargetLevel,
				RTSize.X,
				RTSize.Y,
				ThumbnailTools::EThumbnailTextureFlushMode::NeverFlush,
				ThumbnailRenderTarget,
				&NewThumbnail
				);

			UPackage* MyOutermostPackage = CastChecked<UPackage>(TargetLevel->GetOutermost());
			ThumbnailTools::CacheThumbnail(TileModel.GetAssetName().ToString(), &NewThumbnail, MyOutermostPackage);
			return ToSlateTextureData(&NewThumbnail);
		}
	}

	return ToSlateTextureData(nullptr);
}
FGeometry SWidget::FindChildGeometry( const FGeometry& MyGeometry, TSharedRef<SWidget> WidgetToFind ) const
{
	// We just need to find the one WidgetToFind among our descendants.
	TSet< TSharedRef<SWidget> > WidgetsToFind;
	{
		WidgetsToFind.Add( WidgetToFind );
	}
	TMap<TSharedRef<SWidget>, FArrangedWidget> Result;

	FindChildGeometries( MyGeometry, WidgetsToFind, Result );

	return Result.FindChecked( WidgetToFind ).Geometry;
}
void UKismetUpdateCommandlet::CompileOneBlueprint(UBlueprint* Blueprint)
{
	FString PathName = Blueprint->GetPathName();

	if (!AlreadyCompiledFullPaths.Contains(PathName))
	{
		// Make sure any referenced interfaces are already recompiled
		for (int32 i = 0; i < Blueprint->ImplementedInterfaces.Num(); ++i)
		{
			const FBPInterfaceDescription& InterfaceDesc = Blueprint->ImplementedInterfaces[i];
			if (UBlueprint* InterfaceBP = Cast<UBlueprint>(InterfaceDesc.Interface->ClassGeneratedBy))
			{
				CompileOneBlueprint(InterfaceBP);
			}
		}

		// Make sure any referenced macros are already recompiled
		{
			// Find all macro instances
			TArray<UK2Node_MacroInstance*> MacroNodes;
			FBlueprintEditorUtils::GetAllNodesOfClass<UK2Node_MacroInstance>(Blueprint, /*out*/ MacroNodes);

			// Find all unique macro blueprints that contributed to the used macro instances
			TSet<UBlueprint*> UniqueMacroBlueprints;
			for (int32 i = 0; i < MacroNodes.Num(); ++i)
			{
				UBlueprint* MacroBP = FBlueprintEditorUtils::FindBlueprintForGraphChecked(MacroNodes[i]->GetMacroGraph());
				UniqueMacroBlueprints.Add(MacroBP);
			}

			// Compile each of the unique macro libraries
			for (TSet<UBlueprint*>::TIterator It(UniqueMacroBlueprints); It; ++It)
			{
				UBlueprint* MacroBP = *It;
				CompileOneBlueprint(MacroBP);
			}
		}

		// Refresh and compile this blueprint
		FBlueprintEditorUtils::RefreshAllNodes(Blueprint);

		const bool bIsRegeneratingOnLoad = true;
		FKismetEditorUtilities::CompileBlueprint(Blueprint, bIsRegeneratingOnLoad);

		// Notify the user of errors
		if (Blueprint->Status == BS_Error)
		{
			UE_LOG(LogBlueprintUpdateCommandlet, Warning, TEXT("[REPORT] Error: Failed to compile blueprint '%s'"), *Blueprint->GetName());
		}
	}
}
void FPackageDependencyInfo::ResolveCircularDependenciesInnerFast()
{
    int32 NumReResolves = 0;

    // We have a list of all packages the current package depends on.
    // And we iterate through the list as long as we won't update any package info.
    TSet<FPackageDependencyTrackingInfo*> ToBeProcessed;

    // Find packages that matters.
    for( auto ResolveIt = AllPackages.CreateIterator(); ResolveIt; ++ResolveIt )
    {
        FPackageDependencyTrackingInfo* PkgInfo = *ResolveIt;
        if( PkgInfo && PkgInfo->DependentPackages.Num() )
        {
            ToBeProcessed.Add( PkgInfo );
        }
    }

    do
    {
        NumReResolves = 0;
        // Iterate through all valid packages.
        for( auto ResolveIt = ToBeProcessed.CreateIterator(); ResolveIt; ++ResolveIt )
        {
            const int32 PackageIndex = 0;
            FPackageDependencyTrackingInfo* InPkgInfo = *ResolveIt;

            // Iterate through all dependent packages and update time if necessary.
            for( auto DepPkgIt = InPkgInfo->DependentPackages.CreateIterator(); DepPkgIt; ++DepPkgIt )
            {
                NumResolveIterations++;
                FPackageDependencyTrackingInfo* DepPkgInfo = DepPkgIt.Value();
                if( DepPkgInfo != NULL )
                {
                    if( InPkgInfo->DependentTimeStamp < DepPkgInfo->DependentTimeStamp )
                    {
                        InPkgInfo->DependentTimeStamp = DepPkgInfo->DependentTimeStamp;
                        ResolvedCircularDependencies.Add(InPkgInfo);
                        NumCirculars++;

                        // We updated a timestamp, so we need to run the iteration once again to make sure that other packages will be updated as well.
                        NumReResolves++;
                    }
                }
            }
        }

        NumResolvePasses++;
    }
    while( NumReResolves > 0 );
}
void FPropertyEditorToolkit::ToggleColumnForProperty( const TSharedPtr< FPropertyPath >& PropertyPath )
{
	if ( !PropertyPath.IsValid() )
	{
		return;
	}

	TSharedRef< FPropertyPath > NewPath = PropertyPath->TrimRoot( PropertyTable->GetRootPath()->GetNumProperties() );
	const TSet< TSharedRef< IPropertyTableRow > > SelectedRows = PropertyTable->GetSelectedRows();
	
	for( auto RowIter = SelectedRows.CreateConstIterator(); RowIter; ++RowIter )
	{
		NewPath = NewPath->TrimRoot( (*RowIter)->GetPartialPath()->GetNumProperties() );
		break;
	}

	if ( NewPath->GetNumProperties() == 0 )
	{
		return;
	}

	TSharedPtr< IPropertyTableColumn > ExistingColumn;
	for( auto ColumnIter = PropertyTable->GetColumns().CreateConstIterator(); ColumnIter; ++ColumnIter )
	{
		TSharedRef< IPropertyTableColumn > Column = *ColumnIter;
		const TSharedPtr< FPropertyPath > Path = Column->GetDataSource()->AsPropertyPath();

		if ( Path.IsValid() && FPropertyPath::AreEqual( Path.ToSharedRef(), NewPath ) )
		{
			ExistingColumn = Column;
		}
	}

	if ( ExistingColumn.IsValid() )
	{
		PropertyTable->RemoveColumn( ExistingColumn.ToSharedRef() );
		const TSharedRef< FPropertyPath > ColumnPath = ExistingColumn->GetDataSource()->AsPropertyPath().ToSharedRef();
		for (int Index = PropertyPathsAddedAsColumns.Num() - 1; Index >= 0 ; Index--)
		{
			if ( FPropertyPath::AreEqual( ColumnPath, PropertyPathsAddedAsColumns[ Index ] ) )
			{
				PropertyPathsAddedAsColumns.RemoveAt( Index );
			}
		}
	}
	else
	{
		PropertyTable->AddColumn( NewPath );
		PropertyPathsAddedAsColumns.Add( NewPath );
	}
}
bool FChunkManifestGenerator::SaveManifests(FSandboxPlatformFile* InSandboxFile)
{
	// Always do package dependency work, is required to modify asset registry
	FixupPackageDependenciesForChunks(InSandboxFile);

	if (bGenerateChunks)
	{
		for (auto Platform : Platforms)
		{
			if (!GenerateStreamingInstallManifest(Platform->PlatformName()))
			{
				return false;
			}

			// Generate map for the platform abstraction
			TMultiMap<FString, int32> ChunkMap;	// asset -> ChunkIDs map
			TSet<int32> ChunkIDsInUse;
			const FString PlatformName = Platform->PlatformName();

			// Collect all unique chunk indices and map all files to their chunks
			for (int32 ChunkIndex = 0; ChunkIndex < FinalChunkManifests.Num(); ++ChunkIndex)
			{
				if (FinalChunkManifests[ChunkIndex] && FinalChunkManifests[ChunkIndex]->Num())
				{
					ChunkIDsInUse.Add(ChunkIndex);
					for (auto& Filename : *FinalChunkManifests[ChunkIndex])
					{
						FString PlatFilename = Filename.Value.Replace(TEXT("[Platform]"), *PlatformName);
						ChunkMap.Add(PlatFilename, ChunkIndex);
					}
				}
			}

			// Sort our chunk IDs and file paths
			ChunkMap.KeySort(TLess<FString>());
			ChunkIDsInUse.Sort(TLess<int32>());

			// Platform abstraction will generate any required platform-specific files for the chunks
			if (!Platform->GenerateStreamingInstallManifest(ChunkMap, ChunkIDsInUse))
			{
				return false;
			}
		}


		GenerateAssetChunkInformationCSV(FPaths::Combine(*FPaths::GameLogDir(), TEXT("ChunkLists")));
	}

	return true;
}
void FMovieSceneSequenceInstance::RefreshInstanceMap( const TArray<UMovieSceneTrack*>& Tracks, const TArray<TWeakObjectPtr<UObject>>& RuntimeObjects, FMovieSceneInstanceMap& TrackInstances, IMovieScenePlayer& Player  )
{
	// All the tracks we found during this pass
	TSet< UMovieSceneTrack* > FoundTracks;

	// For every track, check if it has an instance, if not create one, otherwise refresh that instance
	for( int32 TrackIndex = 0; TrackIndex < Tracks.Num(); ++TrackIndex )
	{
		UMovieSceneTrack* Track = Tracks[TrackIndex];

		// A new track has been encountered
		FoundTracks.Add( Track );

		// See if the track has an instance
		TSharedPtr<IMovieSceneTrackInstance> Instance = TrackInstances.FindRef( Track );
		if ( !Instance.IsValid() )
		{
			// The track does not have an instance, create one
			Instance = Track->CreateInstance();
			Instance->RefreshInstance( RuntimeObjects, Player, *this );
			Instance->SaveState(RuntimeObjects, Player, *this);

			TrackInstances.Add( Track, Instance );
		}
		else
		{
			// The track has an instance, refresh it
			Instance->RefreshInstance( RuntimeObjects, Player, *this );
			Instance->SaveState(RuntimeObjects, Player, *this);
		}

	}

	// Remove entries which no longer have a track associated with them
	FMovieSceneInstanceMap::TIterator It = TrackInstances.CreateIterator();
	for( ; It; ++It )
	{
		if( !FoundTracks.Contains( It.Key().Get() ) )
		{
			It.Value()->ClearInstance( Player, *this );

			// This track was not found in the moviescene's track list so it was removed.
			It.RemoveCurrent();
		}
	}

	// Sort based on evaluation order
	TrackInstances.ValueSort(FTrackInstanceEvalSorter());
}
void UMovieSceneParameterSection::GetParameterNames( TSet<FName>& ParameterNames ) const
{
	for ( const FScalarParameterNameAndCurve& ScalarParameterNameAndCurve : ScalarParameterNamesAndCurves )
	{
		ParameterNames.Add( ScalarParameterNameAndCurve.ParameterName );
	}
	for ( const FVectorParameterNameAndCurves& VectorParameterNameAndCurves : VectorParameterNamesAndCurves )
	{
		ParameterNames.Add( VectorParameterNameAndCurves.ParameterName );
	}
	for ( const FColorParameterNameAndCurves& ColorParameterNameAndCurves : ColorParameterNamesAndCurves )
	{
		ParameterNames.Add( ColorParameterNameAndCurves.ParameterName );
	}
}
Example #13
0
void FTimeline::GetAllCurves(TSet<class UCurveBase*>& InOutCurves) const
{
	for (auto& Track : InterpVectors)
	{
		InOutCurves.Add(Track.VectorCurve);
	}
	for (auto& Track : InterpFloats)
	{
		InOutCurves.Add(Track.FloatCurve);
	}
	for (auto& Track : InterpLinearColors)
	{
		InOutCurves.Add(Track.LinearColorCurve);
	}
}
TVector<TColumn> ReadCD(const TString& fileName, const TCdParserDefaults& defaults) {
    CB_ENSURE(NFs::Exists(TString(fileName)), "column description file is not found");
    int columnsCount = defaults.UseDefaultType ? defaults.ColumnCount : 0;

    TVector<TColumn> columns(columnsCount, TColumn{defaults.DefaultColumnType, TString()});
    TSet<int> parsedColumns;

    TString line;
    TIFStream reader(fileName.c_str());
    while (reader.ReadLine(line)) {
        TVector<TString> tokens;
        try {
            Split(line, "\t", tokens);
        } catch (const yexception& e) {
            MATRIXNET_DEBUG_LOG << "Got exception " << e.what() << " while parsing feature descriptions line " << line << Endl;
            break;
        }
        if (tokens.empty()) {
            continue;
        }
        CB_ENSURE(tokens.ysize() == 2 || tokens.ysize() == 3, "Each line should have two or three columns. " << line);
        int index = FromString<int>(tokens[0]);
        CB_ENSURE(index >= 0, "Invalid column index " << index);
        if (defaults.UseDefaultType) {
            CB_ENSURE(index < columnsCount, "Invalid column index " << index);
        }
        CB_ENSURE(!parsedColumns.has(index), "column specified twice in cd file: " << index);
        parsedColumns.insert(index);
        columns.resize(Max(columns.ysize(), index + 1));

        TStringBuf type = tokens[1];
        if (type == "QueryId") {
            type = "GroupId";
        }
        if (type == "Target") {
            type = "Label";
        }
        CB_ENSURE(TryFromString<EColumn>(type, columns[index].Type), "unsupported column type " << type);
        if (tokens.ysize() == 3) {
            columns[index].Id = tokens[2];
        }
    }
    if (!defaults.UseDefaultType) {
        CheckAllFeaturesPresent(columns, parsedColumns);
    }

    return columns;
}
Example #15
0
/*Function which retrieves an arranged list of assets with the same nature (coresponding tags: Item, Stackable, ItemType)
which are placed on top of one another in the world (eg: a stack of plates)
The list is used for picking up multiple items at once in the GrabWithTwoHands() method.
@param AActor* ContainedItem  -->  Actor contained within the stack needed
*/
TSet<AActor*> AMyCharacter::GetStack(AActor* ContainedItem)
{
	//Create an empty array to be populated with proper values
	TSet<AActor*> StackList;
	StackList.Empty();

	//Make sure that the function parameter is logicaly valid and if not return an empty stack and exit the function call
	if (!ContainedItem->ActorHasTag(FName(TEXT("Stackable"))))
	{
		return StackList;
	}

	/*Loop through the list of stackable items created in BeginPlay() and check for matching tags, as well as world positioning, 
	and populate the array with elements which are found to have the center on the same Z axis as the recieved parameter (+/- a small offset)
	*/
	for (const auto Iterator : AllStackableItems)
	{
		if (Iterator->Tags == ContainedItem->Tags)
		{
			if ((ContainedItem->GetActorLocation().X - 2 < Iterator->GetActorLocation().X) &&
				(Iterator->GetActorLocation().X < ContainedItem->GetActorLocation().X + 2) &&
				(ContainedItem->GetActorLocation().Y - 2 < Iterator->GetActorLocation().Y) &&
				(Iterator->GetActorLocation().Y< ContainedItem->GetActorLocation().Y + 2))
			{
				StackList.Add(Iterator);
			}
		}
	}

	//Bubble sort algorithm
	bool swapped = true;
	int j = 0;
	AActor* tmp;
	while (swapped) {
		swapped = false;
		j++;
		for (int i = 0; i < StackList.Num() - j; i++) {
			if (StackList[FSetElementId::FromInteger(i)]->GetActorLocation().Z > StackList[FSetElementId::FromInteger(i + 1)]->GetActorLocation().Z)
			{
				tmp = StackList[FSetElementId::FromInteger(i)];
				StackList[FSetElementId::FromInteger(i)] = StackList[FSetElementId::FromInteger(i + 1)];
				StackList[FSetElementId::FromInteger(i + 1)] = tmp;
				swapped = true;
			}
		}
	}
	return StackList;
}
// Update the drawing policy with the set of hovered pins (which can be empty)
void FConnectionDrawingPolicy::SetHoveredPins(const TSet< TWeakObjectPtr<UEdGraphPin> >& InHoveredPins, const TArray< TSharedPtr<SGraphPin> >& OverridePins, double HoverTime)
{
	HoveredPins.Empty();

	LastHoverTimeEvent = (OverridePins.Num() > 0) ? 0.0 : HoverTime;

	for (auto PinIt = OverridePins.CreateConstIterator(); PinIt; ++PinIt)
	{
		if (SGraphPin* GraphPin = PinIt->Get())
		{
			HoveredPins.Add(GraphPin->GetPinObj());
		}
	}

	// Convert the widget pointer for hovered pins to be EdGraphPin pointers for their connected nets (both ends of any connection)
	for (auto PinIt = InHoveredPins.CreateConstIterator(); PinIt; ++PinIt)
	{
		if (UEdGraphPin* Pin = PinIt->Get())
		{
			if (Pin->LinkedTo.Num() > 0)
			{
				HoveredPins.Add(Pin);

				for (auto LinkIt = Pin->LinkedTo.CreateConstIterator(); LinkIt; ++LinkIt)
				{
					HoveredPins.Add(*LinkIt);
				}
			}
		}
	}
}
void FComponentEditorUtils::PropagateTransformPropertyChange(
	class USceneComponent* InSceneComponentTemplate,
	const FTransformData& OldDefaultTransform,
	const FTransformData& NewDefaultTransform,
	TSet<class USceneComponent*>& UpdatedComponents)
{
	check(InSceneComponentTemplate != nullptr);

	TArray<UObject*> ArchetypeInstances;
	FComponentEditorUtils::GetArchetypeInstances(InSceneComponentTemplate, ArchetypeInstances);
	for(int32 InstanceIndex = 0; InstanceIndex < ArchetypeInstances.Num(); ++InstanceIndex)
	{
		USceneComponent* InstancedSceneComponent = FComponentEditorUtils::GetSceneComponent(ArchetypeInstances[InstanceIndex], InSceneComponentTemplate);
		if(InstancedSceneComponent != nullptr && !UpdatedComponents.Contains(InstancedSceneComponent))
		{
			static const UProperty* RelativeLocationProperty = FindFieldChecked<UProperty>( USceneComponent::StaticClass(), "RelativeLocation" );
			if(RelativeLocationProperty != nullptr)
			{
				PropagateTransformPropertyChange(InstancedSceneComponent, RelativeLocationProperty, OldDefaultTransform.Trans, NewDefaultTransform.Trans, UpdatedComponents);
			}

			static const UProperty* RelativeRotationProperty = FindFieldChecked<UProperty>( USceneComponent::StaticClass(), "RelativeRotation" );
			if(RelativeRotationProperty != nullptr)
			{
				PropagateTransformPropertyChange(InstancedSceneComponent, RelativeRotationProperty, OldDefaultTransform.Rot, NewDefaultTransform.Rot, UpdatedComponents);
			}

			static const UProperty* RelativeScale3DProperty = FindFieldChecked<UProperty>( USceneComponent::StaticClass(), "RelativeScale3D" );
			if(RelativeScale3DProperty != nullptr)
			{
				PropagateTransformPropertyChange(InstancedSceneComponent, RelativeScale3DProperty, OldDefaultTransform.Scale, NewDefaultTransform.Scale, UpdatedComponents);
			}
		}
	}
}
Example #18
0
void UActorComponent::GetUCSModifiedProperties(TSet<const UProperty*>& ModifiedProperties) const
{
	for (const FSimpleMemberReference& MemberReference : UCSModifiedProperties)
	{
		ModifiedProperties.Add(FMemberReference::ResolveSimpleMemberReference<UProperty>(MemberReference));
	}
}
	static void ReplaceStructWithTempDuplicate(
		UUserDefinedStruct* StructureToReinstance, 
		TSet<UBlueprint*>& BlueprintsToRecompile,
		TArray<UUserDefinedStruct*>& ChangedStructs)
	{
		if (StructureToReinstance)
		{
			UUserDefinedStruct* DuplicatedStruct = NULL;
			{
				const FString ReinstancedName = FString::Printf(TEXT("STRUCT_REINST_%s"), *StructureToReinstance->GetName());
				const FName UniqueName = MakeUniqueObjectName(GetTransientPackage(), UUserDefinedStruct::StaticClass(), FName(*ReinstancedName));

				TGuardValue<bool> IsDuplicatingClassForReinstancing(GIsDuplicatingClassForReinstancing, true);
				DuplicatedStruct = (UUserDefinedStruct*)StaticDuplicateObject(StructureToReinstance, GetTransientPackage(), *UniqueName.ToString(), ~RF_Transactional); 
			}

			DuplicatedStruct->Guid = StructureToReinstance->Guid;
			DuplicatedStruct->Bind();
			DuplicatedStruct->StaticLink(true);
			DuplicatedStruct->PrimaryStruct = StructureToReinstance;
			DuplicatedStruct->Status = EUserDefinedStructureStatus::UDSS_Duplicate;
			DuplicatedStruct->SetFlags(RF_Transient);
			DuplicatedStruct->AddToRoot();
			CastChecked<UUserDefinedStructEditorData>(DuplicatedStruct->EditorData)->RecreateDefaultInstance();

			for (auto StructProperty : TObjectRange<UStructProperty>(RF_ClassDefaultObject | RF_PendingKill))
			{
				if (StructProperty && (StructureToReinstance == StructProperty->Struct))
				{
					if (auto OwnerClass = Cast<UBlueprintGeneratedClass>(StructProperty->GetOwnerClass()))
					{
						if (UBlueprint* FoundBlueprint = Cast<UBlueprint>(OwnerClass->ClassGeneratedBy))
						{
							BlueprintsToRecompile.Add(FoundBlueprint);
							StructProperty->Struct = DuplicatedStruct;
						}
					}
					else if (auto OwnerStruct = Cast<UUserDefinedStruct>(StructProperty->GetOwnerStruct()))
					{
						check(OwnerStruct != DuplicatedStruct);
						const bool bValidStruct = (OwnerStruct->GetOutermost() != GetTransientPackage())
							&& !OwnerStruct->HasAnyFlags(RF_PendingKill)
							&& (EUserDefinedStructureStatus::UDSS_Duplicate != OwnerStruct->Status.GetValue());

						if (bValidStruct)
						{
							ChangedStructs.AddUnique(OwnerStruct);
							StructProperty->Struct = DuplicatedStruct;
						}
					}
					else
					{
						UE_LOG(LogK2Compiler, Error, TEXT("ReplaceStructWithTempDuplicate unknown owner"));
					}
				}
			}

			DuplicatedStruct->RemoveFromRoot();
		}
	}
bool UParticleSystemAuditCommandlet::DumpSimpleSet(TSet<FString>& InSet, const TCHAR* InShortFilename, const TCHAR* InObjectClassName)
{
	if (InSet.Num() > 0)
	{
		check(InShortFilename != NULL);
		check(InObjectClassName != NULL);

		FArchive* OutputStream = GetOutputFile(InShortFilename);
		if (OutputStream != NULL)
		{
			UE_LOG(LogParticleSystemAuditCommandlet, Log, TEXT("Dumping '%s' results..."), InShortFilename);
			OutputStream->Logf(TEXT("%s,..."), InObjectClassName);
			for (TSet<FString>::TIterator DumpIt(InSet); DumpIt; ++DumpIt)
			{
				FString ObjName = *DumpIt;
				OutputStream->Logf(TEXT("%s"), *ObjName);
			}

			OutputStream->Close();
			delete OutputStream;
		}
		else
		{
			return false;
		}
	}
	return true;
}
Example #21
0
void FSoundCueEditor::OnSelectedNodesChanged(const TSet<class UObject*>& NewSelection)
{
	TArray<UObject*> Selection;

	if(NewSelection.Num())
	{
		for(TSet<class UObject*>::TConstIterator SetIt(NewSelection);SetIt;++SetIt)
		{
			if (Cast<USoundCueGraphNode_Root>(*SetIt))
			{
				Selection.Add(GetSoundCue());
			}
			else if (USoundCueGraphNode* GraphNode = Cast<USoundCueGraphNode>(*SetIt))
			{
				Selection.Add(GraphNode->SoundNode);
			}
			else
			{
				Selection.Add(*SetIt);
			}
		}
		//Selection = NewSelection.Array();
	}
	else
	{
		Selection.Add(GetSoundCue());
	}

	SetSelection(Selection);
}
bool FGameplayTagContainer::Serialize(FArchive& Ar)
{
	const bool bOldTagVer = Ar.UE4Ver() < VER_UE4_GAMEPLAY_TAG_CONTAINER_TAG_TYPE_CHANGE;
	
	if (bOldTagVer)
	{
		Ar << Tags_DEPRECATED;
	}
	else
	{
		Ar << GameplayTags;
	}
	
	if (Ar.IsLoading())
	{
		UGameplayTagsManager& TagManager = IGameplayTagsModule::GetGameplayTagsManager();

		// If loading old version, add old tags to the new gameplay tags array so they can be saved out with the new version
		// This needs to happen 
		// NOTE: DeprecatedTagNamesNotFoundInTagMap should be removed along with the bOldTagVer when we remove backwards
		// compatibility, and the signature of RedirectTagsForContainer (below) should be changed appropriately as well.
		TSet<FName> DeprecatedTagNamesNotFoundInTagMap;
		if (bOldTagVer)
		{
			for (auto It = Tags_DEPRECATED.CreateConstIterator(); It; ++It)
			{
				const bool bErrorIfNotFound = false;
				FGameplayTag Tag = TagManager.RequestGameplayTag(*It, bErrorIfNotFound);
				if (Tag.IsValid())
				{
					TagManager.AddLeafTagToContainer(*this, Tag);
				}
				else
				{	// For tags not found in the current table, add them to a list to be checked when handling
					// redirection (below).
					DeprecatedTagNamesNotFoundInTagMap.Add(*It);
				}
			}
		}

		// Rename any tags that may have changed by the ini file.  Redirects can happen regardless of version.
		// Regardless of version, want loading to have a chance to handle redirects
		TagManager.RedirectTagsForContainer(*this, DeprecatedTagNamesNotFoundInTagMap);
	}

	return true;
}
TSet<FName> FNativeClassHierarchy::GetGameModules()
{
	FGameProjectGenerationModule& GameProjectModule = FGameProjectGenerationModule::Get();

	// Build up a set of known game modules - used to work out which modules populate Classes_Game
	TSet<FName> GameModules;
	if(GameProjectModule.ProjectHasCodeFiles())
	{
		TArray<FModuleContextInfo> GameModulesInfo = GameProjectModule.GetCurrentProjectModules();
		for(const auto& GameModuleInfo : GameModulesInfo)
		{
			GameModules.Add(FName(*GameModuleInfo.ModuleName));
		}
	}

	return GameModules;
}
void FKismetConnectionDrawingPolicy::ResetIncompatiblePinDrawState(const TSet< TSharedRef<SWidget> >& VisiblePins)
{
	for(auto VisiblePinIterator = VisiblePins.CreateConstIterator(); VisiblePinIterator; ++VisiblePinIterator)
	{
		TSharedPtr<SGraphPin> VisiblePin = StaticCastSharedRef<SGraphPin>(*VisiblePinIterator);
		VisiblePin->SetPinColorModifier(FLinearColor::White);
	}
}
Example #25
0
	static void AppendCollectionToArray(const TSet<FName>& InObjectSet, TArray<FName>& OutObjectArray)
	{
		OutObjectArray.Reserve(OutObjectArray.Num() + InObjectSet.Num());
		for (const FName& ObjectName : InObjectSet)
		{
			OutObjectArray.Add(ObjectName);
		}
	}
bool FChunkManifestGenerator::SaveAssetRegistry(const FString& SandboxPath, const TArray<FName>* IgnorePackageList)
{
    UE_LOG(LogChunkManifestGenerator, Display, TEXT("Saving asset registry."));


    TSet<FName> IgnorePackageSet;
    if (IgnorePackageList != nullptr)
    {
        for (const auto& IgnorePackage : *IgnorePackageList)
        {
            IgnorePackageSet.Add(IgnorePackage);
        }
    }


    // Create asset registry data
    FArrayWriter SerializedAssetRegistry;
    SerializedAssetRegistry.SetFilterEditorOnly(true);
    TMap<FName, FAssetData*> GeneratedAssetRegistryData;
    for (auto& AssetData : AssetRegistryData)
    {
        if (IgnorePackageSet.Contains(AssetData.PackageName))
        {
            continue;
        }

        // Add only assets that have actually been cooked and belong to any chunk
        if (AssetData.ChunkIDs.Num() > 0)
        {
            GeneratedAssetRegistryData.Add(AssetData.ObjectPath, &AssetData);
        }
    }
    AssetRegistry.SaveRegistryData(SerializedAssetRegistry, GeneratedAssetRegistryData);
    UE_LOG(LogChunkManifestGenerator, Display, TEXT("Generated asset registry num assets %d, size is %5.2fkb"), GeneratedAssetRegistryData.Num(), (float)SerializedAssetRegistry.Num() / 1024.f);

    // Save the generated registry for each platform
    for (auto Platform : Platforms)
    {
        FString PlatformSandboxPath = SandboxPath.Replace(TEXT("[Platform]"), *Platform->PlatformName());
        FFileHelper::SaveArrayToFile(SerializedAssetRegistry, *PlatformSandboxPath);
    }

    UE_LOG(LogChunkManifestGenerator, Display, TEXT("Done saving asset registry."));

    return true;
}
Example #27
0
bool FVertexSnappingImpl::SnapLocationToNearestVertex( FVector& Location, const FVector2D& MouseLocation, FLevelEditorViewportClient* ViewportClient, FVector& OutVertexNormal, bool bDrawVertexHelpers )
{
	bool bSnapped = false;

	// Make a box around the actor which is the area we are allowed to snap in
	FBox AllowedSnappingBox = FBox( Location-VertexSnappingConstants::MaxSnappingDistance, Location+VertexSnappingConstants::MaxSnappingDistance );

	FSceneViewFamilyContext ViewFamily(FSceneViewFamily::ConstructionValues(
		ViewportClient->Viewport, 
		ViewportClient->GetScene(),
		ViewportClient->EngineShowFlags )
		.SetRealtimeUpdate( ViewportClient->IsRealtime() ));

	FSceneView* View = ViewportClient->CalcSceneView( &ViewFamily );

	TArray<FSnapActor> ActorsInBox;
	TSet<TWeakObjectPtr<AActor> > ActorsToIgnore;
	// Ignore actors currently being moved
	ActorsToIgnore.Append( ViewportClient->GetDropPreviewActors() );

	GetPossibleSnapActors( AllowedSnappingBox, MouseLocation.IntPoint(), ViewportClient, View, EAxisList::Screen, ActorsToIgnore, ActorsInBox );

	FViewportCursorLocation Cursor(View, ViewportClient, MouseLocation.X, MouseLocation.Y );

	FPlane ActorPlane( Location, Cursor.GetDirection() );

	FVertexSnappingArgs Args
	( 
		ActorPlane, 
		Location,
		ViewportClient,
		View,
		Cursor.GetCursorPos(),
		EAxisList::Screen,
		bDrawVertexHelpers
	);
	
	// Snap to the nearest vertex
	FSnappingVertex ClosestVertex = GetClosestVertex( ActorsInBox, Args );

	Location = ClosestVertex.Position;
	OutVertexNormal = ClosestVertex.Normal;
	bSnapped = true;

	return bSnapped;
}
Example #28
0
	void PurgeAllDelegates()
	{
		for (auto d : Delegates)
		{
			delete d;
		}
		Delegates.Empty();
	}
	virtual FArchive& operator<<(UObject*& Object) override
	{
		if (Object)
		{
			References.Add(Object);
		}
		return *this;
	}
void UEnvironmentQueryGraph::RemoveOrphanedNodes()
{
	UEnvQuery* QueryAsset = CastChecked<UEnvQuery>(GetOuter());

	// Obtain a list of all nodes that should be in the asset
	TSet<UObject*> AllNodes;
	for (int32 Index = 0; Index < Nodes.Num(); ++Index)
	{
		UEnvironmentQueryGraphNode_Option* OptionNode = Cast<UEnvironmentQueryGraphNode_Option>(Nodes[Index]);
		if (OptionNode)
		{
			UEnvQueryOption* OptionInstance = Cast<UEnvQueryOption>(OptionNode->NodeInstance);
			if (OptionInstance)
			{
				AllNodes.Add(OptionInstance);
				if (OptionInstance->Generator)
				{
					AllNodes.Add(OptionInstance->Generator);
				}
			}

			for (int32 SubIdx = 0; SubIdx < OptionNode->Tests.Num(); SubIdx++)
			{
				if (OptionNode->Tests[SubIdx] && OptionNode->Tests[SubIdx]->NodeInstance)
				{
					AllNodes.Add(OptionNode->Tests[SubIdx]->NodeInstance);
				}
			}
		}
	}

	// Obtain a list of all nodes actually in the asset and discard unused nodes
	TArray<UObject*> AllInners;
	const bool bIncludeNestedObjects = false;
	GetObjectsWithOuter(QueryAsset, AllInners, bIncludeNestedObjects);
	for (auto InnerIt = AllInners.CreateConstIterator(); InnerIt; ++InnerIt)
	{
		UObject* Node = *InnerIt;
		const bool bEQSNode =
			Node->IsA(UEnvQueryGenerator::StaticClass()) ||
			Node->IsA(UEnvQueryTest::StaticClass()) ||
			Node->IsA(UEnvQueryOption::StaticClass());

		if (bEQSNode && !AllNodes.Contains(Node))
		{
			Node->SetFlags(RF_Transient);
			Node->Rename(NULL, GetTransientPackage(), REN_DontCreateRedirectors | REN_NonTransactional | REN_ForceNoResetLoaders);
		}
	}
}