UE4c++ ConvertActorsToStaticMesh

news2025/1/20 20:02:57

UE4c++ ConvertActorsToStaticMesh

ConvertActorsToStaticMesh

    • UE4c++ ConvertActorsToStaticMesh
      • 创建Edior模块(最好是放Editor模块毕竟是编辑器代码)
      • 创建UBlueprintFunctionLibrary
        • UTestFunctionLibrary.h
        • UTestFunctionLibrary.cpp:
        • .Build.cs

目标:为了大量生成模型,我们把虚幻带有的方法迁移成函数,并去掉默认弹窗,以便代码调用
在这里插入图片描述
测试调用:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

演示效果:

请添加图片描述

创建Edior模块(最好是放Editor模块毕竟是编辑器代码)

创建UBlueprintFunctionLibrary

UTestFunctionLibrary.h
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "RawMesh.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "TestFunctionLibrary.generated.h"


struct FRawMeshTracker_Copy
{
	FRawMeshTracker_Copy()
		: bValidColors(false)
	{
		FMemory::Memset(bValidTexCoords, 0);
	}

	bool bValidTexCoords[MAX_MESH_TEXTURE_COORDS];
	bool bValidColors;
};

UCLASS()
class TESTEDITOR_API UTestFunctionLibrary : public UBlueprintFunctionLibrary
{
	GENERATED_BODY()

public:
	UFUNCTION(BlueprintCallable)
	static void ConvertActorMeshesToStaticMesh(const TArray<AActor*> InActors,
	                                           const FString& PathString = FString(TEXT("/Game/Meshes/")),
	                                           const FString& InMeshName = FString(TEXT("StaticMesh")));

	static void GetSkinnedAndStaticMeshComponentsFromActors(const TArray<AActor*> InActors,
	                                                        TArray<UMeshComponent*>& OutMeshComponents);

	static bool IsValidSkinnedMeshComponent(USkinnedMeshComponent* InComponent);

	static bool IsValidStaticMeshComponent(UStaticMeshComponent* InComponent);

	template <typename ComponentType>
	static void ProcessMaterials(ComponentType* InComponent, const FString& InPackageName,
	                             TArray<UMaterialInterface*>& OutMaterials)
	{
		const int32 NumMaterials = InComponent->GetNumMaterials();
		for (int32 MaterialIndex = 0; MaterialIndex < NumMaterials; MaterialIndex++)
		{
			UMaterialInterface* MaterialInterface = InComponent->GetMaterial(MaterialIndex);
			AddOrDuplicateMaterial(MaterialInterface, InPackageName, OutMaterials);
		}
	}

	static void AddOrDuplicateMaterial(UMaterialInterface* InMaterialInterface, const FString& InPackageName,
	                                   TArray<UMaterialInterface*>& OutMaterials);


	static void SkinnedMeshToRawMeshes(USkinnedMeshComponent* InSkinnedMeshComponent, int32 InOverallMaxLODs,
	                                   const FMatrix& InComponentToWorld, const FString& InPackageName,
	                                   TArray<FRawMeshTracker_Copy>& OutRawMeshTrackers, TArray<FRawMesh>& OutRawMeshes,
	                                   TArray<UMaterialInterface*>& OutMaterials);



	// Helper function for ConvertMeshesToStaticMesh
	static void StaticMeshToRawMeshes(UStaticMeshComponent* InStaticMeshComponent, int32 InOverallMaxLODs,
	                                  const FMatrix& InComponentToWorld, const FString& InPackageName,
	                                  TArray<FRawMeshTracker_Copy>& OutRawMeshTrackers, TArray<FRawMesh>& OutRawMeshes,
	                                  TArray<UMaterialInterface*>& OutMaterials);

	static UStaticMesh* ConvertMeshesToStaticMesh(const TArray<UMeshComponent*>& InMeshComponents,
	                                              const FTransform& InRootTransform,
	                                              const FString& PathString = FString(TEXT("/Game/Meshes/")),
	                                              const FString& InMeshName = FString(TEXT("StaticMesh")),
	                                              const FString& InPackageName = FString());

};
UTestFunctionLibrary.cpp:
// Fill out your copyright notice in the Description page of Project Settings.


#include "TestFunctionLibrary.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "AssetToolsModule.h"
#include "ContentBrowserModule.h"
#include "Editor.h"
#include "IContentBrowserSingleton.h"
#include "MeshUtilities.h"
#include "SkeletalRenderPublic.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Components/CapsuleComponent.h"
#include "Framework/Notifications/NotificationManager.h"
#include "GameFramework/Character.h"
#include "Rendering/SkeletalMeshRenderData.h"
#include "Subsystems/AssetEditorSubsystem.h"
#include "Widgets/Notifications/SNotificationList.h"

#define LOCTEXT_NAMESPACE "UTestFunctionLibrary"

void UTestFunctionLibrary::ConvertActorMeshesToStaticMesh(const TArray<AActor*> InActors,
	const FString& PathString, const FString& InMeshName)
{
	IMeshUtilities& MeshUtilities = FModuleManager::Get().LoadModuleChecked<IMeshUtilities>("MeshUtilities");

	TArray<UMeshComponent*> MeshComponents;

	GetSkinnedAndStaticMeshComponentsFromActors(InActors, MeshComponents);

	auto GetActorRootTransform = [](AActor* InActor)
	{
		FTransform RootTransform(FTransform::Identity);
		if (const ACharacter* Character = Cast<ACharacter>(InActor))
		{
			RootTransform = Character->GetTransform();
			RootTransform.SetLocation(
				RootTransform.GetLocation() - FVector(
					0.0f, 0.0f, Character->GetCapsuleComponent()->GetScaledCapsuleHalfHeight()));
		}
		else
		{
			// otherwise just use the actor's origin
			RootTransform = InActor->GetTransform();
		}

		return RootTransform;
	};

	// now pick a root transform
	FTransform RootTransform(FTransform::Identity);
	if (InActors.Num() == 1)
	{
		RootTransform = GetActorRootTransform(InActors[0]);
	}
	else
	{
		// multiple actors use the average of their origins, with Z being the min of all origins. Rotation is identity for simplicity
		FVector Location(FVector::ZeroVector);
		float MinZ = FLT_MAX;
		for (AActor* Actor : InActors)
		{
			FTransform ActorTransform(GetActorRootTransform(Actor));
			Location += ActorTransform.GetLocation();
			MinZ = FMath::Min(ActorTransform.GetLocation().Z, MinZ);
		}
		Location /= (float)InActors.Num();
		Location.Z = MinZ;

		RootTransform.SetLocation(Location);
	}
	UStaticMesh* StaticMesh = ConvertMeshesToStaticMesh(MeshComponents, RootTransform, PathString, InMeshName);

	// Also notify the content browser that the new assets exists
	if (StaticMesh != nullptr)
	{
		FContentBrowserModule& ContentBrowserModule = FModuleManager::Get().LoadModuleChecked<
			FContentBrowserModule>("ContentBrowser");
		ContentBrowserModule.Get().SyncBrowserToAssets(TArray<UObject*>({StaticMesh}), true);
	}
}

void UTestFunctionLibrary::GetSkinnedAndStaticMeshComponentsFromActors(const TArray<AActor*> InActors,
	TArray<UMeshComponent*>& OutMeshComponents)
{
	for (AActor* Actor : InActors)
	{
		// add all components from this actor
		TInlineComponentArray<UMeshComponent*> ActorComponents(Actor);
		for (UMeshComponent* ActorComponent : ActorComponents)
		{
			if (ActorComponent->IsA(USkinnedMeshComponent::StaticClass()) || ActorComponent->IsA(
				UStaticMeshComponent::StaticClass()))
			{
				OutMeshComponents.AddUnique(ActorComponent);
			}
		}

		// add all attached actors
		TArray<AActor*> AttachedActors;
		Actor->GetAttachedActors(AttachedActors);
		for (AActor* AttachedActor : AttachedActors)
		{
			TInlineComponentArray<UMeshComponent*> AttachedActorComponents(AttachedActor);
			for (UMeshComponent* AttachedActorComponent : AttachedActorComponents)
			{
				if (AttachedActorComponent->IsA(USkinnedMeshComponent::StaticClass()) || AttachedActorComponent->
					IsA(UStaticMeshComponent::StaticClass()))
				{
					OutMeshComponents.AddUnique(AttachedActorComponent);
				}
			}
		}
	}
}

bool UTestFunctionLibrary::IsValidSkinnedMeshComponent(USkinnedMeshComponent* InComponent)
{
	return InComponent && InComponent->MeshObject && InComponent->IsVisible();
}

bool UTestFunctionLibrary::IsValidStaticMeshComponent(UStaticMeshComponent* InComponent)
{
	return InComponent && InComponent->GetStaticMesh() && InComponent->GetStaticMesh()->GetRenderData() &&
		InComponent->IsVisible();
}

void UTestFunctionLibrary::AddOrDuplicateMaterial(UMaterialInterface* InMaterialInterface,
	const FString& InPackageName, TArray<UMaterialInterface*>& OutMaterials)
{
	if (InMaterialInterface && !InMaterialInterface->GetOuter()->IsA<UPackage>())
	{
		// Convert runtime material instances to new concrete material instances
		// Create new package
		FString OriginalMaterialName = InMaterialInterface->GetName();
		FString MaterialPath = FPackageName::GetLongPackagePath(InPackageName) / OriginalMaterialName;
		FString MaterialName;
		FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
		AssetToolsModule.Get().CreateUniqueAssetName(MaterialPath, TEXT(""), MaterialPath, MaterialName);
		UPackage* MaterialPackage = CreatePackage(*MaterialPath);

		// Duplicate the object into the new package
		UMaterialInterface* NewMaterialInterface = DuplicateObject<UMaterialInterface>(
			InMaterialInterface, MaterialPackage, *MaterialName);
		NewMaterialInterface->SetFlags(RF_Public | RF_Standalone);

		if (UMaterialInstanceDynamic* MaterialInstanceDynamic = Cast<
			UMaterialInstanceDynamic>(NewMaterialInterface))
		{
			UMaterialInstanceDynamic* OldMaterialInstanceDynamic = CastChecked<UMaterialInstanceDynamic>(
				InMaterialInterface);
			MaterialInstanceDynamic->K2_CopyMaterialInstanceParameters(OldMaterialInstanceDynamic);
		}

		NewMaterialInterface->MarkPackageDirty();

		FAssetRegistryModule::AssetCreated(NewMaterialInterface);

		InMaterialInterface = NewMaterialInterface;
	}

	OutMaterials.Add(InMaterialInterface);
}

void UTestFunctionLibrary::SkinnedMeshToRawMeshes(USkinnedMeshComponent* InSkinnedMeshComponent,
	int32 InOverallMaxLODs, const FMatrix& InComponentToWorld, const FString& InPackageName,
	TArray<FRawMeshTracker_Copy>& OutRawMeshTrackers, TArray<FRawMesh>& OutRawMeshes,
	TArray<UMaterialInterface*>& OutMaterials)
	{
		const int32 BaseMaterialIndex = OutMaterials.Num();

		// Export all LODs to raw meshes
		const int32 NumLODs = InSkinnedMeshComponent->GetNumLODs();

		for (int32 OverallLODIndex = 0; OverallLODIndex < InOverallMaxLODs; OverallLODIndex++)
		{
			int32 LODIndexRead = FMath::Min(OverallLODIndex, NumLODs - 1);

			FRawMesh& RawMesh = OutRawMeshes[OverallLODIndex];
			FRawMeshTracker_Copy& RawMeshTracker = OutRawMeshTrackers[OverallLODIndex];
			const int32 BaseVertexIndex = RawMesh.VertexPositions.Num();

			FSkeletalMeshLODInfo& SrcLODInfo = *(InSkinnedMeshComponent->SkeletalMesh->GetLODInfo(LODIndexRead));

			// Get the CPU skinned verts for this LOD
			TArray<FFinalSkinVertex> FinalVertices;
			InSkinnedMeshComponent->GetCPUSkinnedVertices(FinalVertices, LODIndexRead);

			FSkeletalMeshRenderData& SkeletalMeshRenderData = InSkinnedMeshComponent->MeshObject->
				GetSkeletalMeshRenderData();
			FSkeletalMeshLODRenderData& LODData = SkeletalMeshRenderData.LODRenderData[LODIndexRead];

			// Copy skinned vertex positions
			for (int32 VertIndex = 0; VertIndex < FinalVertices.Num(); ++VertIndex)
			{
				RawMesh.VertexPositions.Add(InComponentToWorld.TransformPosition(FinalVertices[VertIndex].Position));
			}

			const uint32 NumTexCoords = FMath::Min(LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetNumTexCoords(),
			                                       (uint32)MAX_MESH_TEXTURE_COORDS);
			const int32 NumSections = LODData.RenderSections.Num();
			FRawStaticIndexBuffer16or32Interface& IndexBuffer = *LODData.MultiSizeIndexContainer.GetIndexBuffer();

			for (int32 SectionIndex = 0; SectionIndex < NumSections; SectionIndex++)
			{
				const FSkelMeshRenderSection& SkelMeshSection = LODData.RenderSections[SectionIndex];
				if (InSkinnedMeshComponent->IsMaterialSectionShown(SkelMeshSection.MaterialIndex, LODIndexRead))
				{
					// Build 'wedge' info
					const int32 NumWedges = SkelMeshSection.NumTriangles * 3;
					for (int32 WedgeIndex = 0; WedgeIndex < NumWedges; WedgeIndex++)
					{
						const int32 VertexIndexForWedge = IndexBuffer.Get(SkelMeshSection.BaseIndex + WedgeIndex);

						RawMesh.WedgeIndices.Add(BaseVertexIndex + VertexIndexForWedge);

						const FFinalSkinVertex& SkinnedVertex = FinalVertices[VertexIndexForWedge];
						const FVector TangentX = InComponentToWorld.TransformVector(SkinnedVertex.TangentX.ToFVector());
						const FVector TangentZ = InComponentToWorld.TransformVector(SkinnedVertex.TangentZ.ToFVector());
						const FVector4 UnpackedTangentZ = SkinnedVertex.TangentZ.ToFVector4();
						const FVector TangentY = (TangentZ ^ TangentX).GetSafeNormal() * UnpackedTangentZ.W;

						RawMesh.WedgeTangentX.Add(TangentX);
						RawMesh.WedgeTangentY.Add(TangentY);
						RawMesh.WedgeTangentZ.Add(TangentZ);

						for (uint32 TexCoordIndex = 0; TexCoordIndex < MAX_MESH_TEXTURE_COORDS; TexCoordIndex++)
						{
							if (TexCoordIndex >= NumTexCoords)
							{
								RawMesh.WedgeTexCoords[TexCoordIndex].AddDefaulted();
							}
							else
							{
								RawMesh.WedgeTexCoords[TexCoordIndex].Add(
									LODData.StaticVertexBuffers.StaticMeshVertexBuffer.GetVertexUV(
										VertexIndexForWedge, TexCoordIndex));
								RawMeshTracker.bValidTexCoords[TexCoordIndex] = true;
							}
						}

						if (LODData.StaticVertexBuffers.ColorVertexBuffer.IsInitialized())
						{
							RawMesh.WedgeColors.Add(
								LODData.StaticVertexBuffers.ColorVertexBuffer.VertexColor(VertexIndexForWedge));
							RawMeshTracker.bValidColors = true;
						}
						else
						{
							RawMesh.WedgeColors.Add(FColor::White);
						}
					}

					int32 MaterialIndex = SkelMeshSection.MaterialIndex;
					// use the remapping of material indices if there is a valid value
					if (SrcLODInfo.LODMaterialMap.IsValidIndex(SectionIndex) && SrcLODInfo.LODMaterialMap[SectionIndex]
						!= INDEX_NONE)
					{
						MaterialIndex = FMath::Clamp<int32>(SrcLODInfo.LODMaterialMap[SectionIndex], 0,
						                                    InSkinnedMeshComponent->SkeletalMesh->GetMaterials().Num());
					}

					// copy face info
					for (uint32 TriIndex = 0; TriIndex < SkelMeshSection.NumTriangles; TriIndex++)
					{
						RawMesh.FaceMaterialIndices.Add(BaseMaterialIndex + MaterialIndex);
						RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false
					}
				}
			}
		}

		ProcessMaterials<USkinnedMeshComponent>(InSkinnedMeshComponent, InPackageName, OutMaterials);
	}

void UTestFunctionLibrary::StaticMeshToRawMeshes(UStaticMeshComponent* InStaticMeshComponent,
	int32 InOverallMaxLODs, const FMatrix& InComponentToWorld, const FString& InPackageName,
	TArray<FRawMeshTracker_Copy>& OutRawMeshTrackers, TArray<FRawMesh>& OutRawMeshes,
	TArray<UMaterialInterface*>& OutMaterials)
	{
		const int32 BaseMaterialIndex = OutMaterials.Num();

		const int32 NumLODs = InStaticMeshComponent->GetStaticMesh()->GetRenderData()->LODResources.Num();

		for (int32 OverallLODIndex = 0; OverallLODIndex < InOverallMaxLODs; OverallLODIndex++)
		{
			int32 LODIndexRead = FMath::Min(OverallLODIndex, NumLODs - 1);

			FRawMesh& RawMesh = OutRawMeshes[OverallLODIndex];
			FRawMeshTracker_Copy& RawMeshTracker = OutRawMeshTrackers[OverallLODIndex];
			const FStaticMeshLODResources& LODResource = InStaticMeshComponent->GetStaticMesh()->GetRenderData()->
				LODResources[LODIndexRead];
			const int32 BaseVertexIndex = RawMesh.VertexPositions.Num();

			for (int32 VertIndex = 0; VertIndex < LODResource.GetNumVertices(); ++VertIndex)
			{
				RawMesh.VertexPositions.Add(InComponentToWorld.TransformPosition(
					LODResource.VertexBuffers.PositionVertexBuffer.VertexPosition((uint32)VertIndex)));
			}

			const FIndexArrayView IndexArrayView = LODResource.IndexBuffer.GetArrayView();
			const FStaticMeshVertexBuffer& StaticMeshVertexBuffer = LODResource.VertexBuffers.StaticMeshVertexBuffer;
			const int32 NumTexCoords = FMath::Min(StaticMeshVertexBuffer.GetNumTexCoords(),
			                                      (uint32)MAX_MESH_TEXTURE_COORDS);
			const int32 NumSections = LODResource.Sections.Num();

			for (int32 SectionIndex = 0; SectionIndex < NumSections; SectionIndex++)
			{
				const FStaticMeshSection& StaticMeshSection = LODResource.Sections[SectionIndex];

				const int32 NumIndices = StaticMeshSection.NumTriangles * 3;
				for (int32 IndexIndex = 0; IndexIndex < NumIndices; IndexIndex++)
				{
					int32 Index = IndexArrayView[StaticMeshSection.FirstIndex + IndexIndex];
					RawMesh.WedgeIndices.Add(BaseVertexIndex + Index);

					RawMesh.WedgeTangentX.Add(
						InComponentToWorld.TransformVector(StaticMeshVertexBuffer.VertexTangentX(Index)));
					RawMesh.WedgeTangentY.Add(
						InComponentToWorld.TransformVector(StaticMeshVertexBuffer.VertexTangentY(Index)));
					RawMesh.WedgeTangentZ.Add(
						InComponentToWorld.TransformVector(StaticMeshVertexBuffer.VertexTangentZ(Index)));

					for (int32 TexCoordIndex = 0; TexCoordIndex < MAX_MESH_TEXTURE_COORDS; TexCoordIndex++)
					{
						if (TexCoordIndex >= NumTexCoords)
						{
							RawMesh.WedgeTexCoords[TexCoordIndex].AddDefaulted();
						}
						else
						{
							RawMesh.WedgeTexCoords[TexCoordIndex].Add(
								StaticMeshVertexBuffer.GetVertexUV(Index, TexCoordIndex));
							RawMeshTracker.bValidTexCoords[TexCoordIndex] = true;
						}
					}

					if (LODResource.VertexBuffers.ColorVertexBuffer.IsInitialized())
					{
						RawMesh.WedgeColors.Add(LODResource.VertexBuffers.ColorVertexBuffer.VertexColor(Index));
						RawMeshTracker.bValidColors = true;
					}
					else
					{
						RawMesh.WedgeColors.Add(FColor::White);
					}
				}

				// copy face info
				for (uint32 TriIndex = 0; TriIndex < StaticMeshSection.NumTriangles; TriIndex++)
				{
					RawMesh.FaceMaterialIndices.Add(BaseMaterialIndex + StaticMeshSection.MaterialIndex);
					RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false
				}
			}
		}

		ProcessMaterials<UStaticMeshComponent>(InStaticMeshComponent, InPackageName, OutMaterials);
	}

UStaticMesh* UTestFunctionLibrary::ConvertMeshesToStaticMesh(const TArray<UMeshComponent*>& InMeshComponents,
	const FTransform& InRootTransform, const FString& PathString, const FString& InMeshName,
	const FString& InPackageName)
	{
		UStaticMesh* StaticMesh = nullptr;

		IMeshUtilities& MeshUtilities = FModuleManager::Get().LoadModuleChecked<IMeshUtilities>("MeshUtilities");
		// Build a package name to use
		FString MeshName;
		FString PackageName;
		if (InPackageName.IsEmpty())
		{
			FString NewNameSuggestion = InMeshName;
			FString PackageNameSuggestion = PathString + NewNameSuggestion;
			FString Name;
			FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
			AssetToolsModule.Get().CreateUniqueAssetName(PackageNameSuggestion, TEXT(""), PackageNameSuggestion, Name);

			// TSharedPtr<SDlgPickAssetPath> PickAssetPathWidget =
			// 	SNew(SDlgPickAssetPath)
			// .Title(LOCTEXT("ConvertToStaticMeshPickName", "Choose New StaticMesh Location"))
			// .DefaultAssetPath(FText::FromString(PackageNameSuggestion));

			//if (PickAssetPathWidget->ShowModal() == EAppReturnType::Ok)
			{
				// Get the full name of where we want to create the mesh asset.
				PackageName = PackageNameSuggestion; //PickAssetPathWidget->GetFullAssetPath().ToString();
				MeshName = FPackageName::GetLongPackageAssetName(PackageName);

				// Check if the user inputed a valid asset name, if they did not, give it the generated default name
				if (MeshName.IsEmpty())
				{
					// Use the defaults that were already generated.
					PackageName = PackageNameSuggestion;
					MeshName = *Name;
				}
			}
		}
		else
		{
			PackageName = InPackageName;
			MeshName = *FPackageName::GetLongPackageAssetName(PackageName);
		}

		if (!PackageName.IsEmpty() && !MeshName.IsEmpty())
		{
			TArray<FRawMesh> RawMeshes;
			TArray<UMaterialInterface*> Materials;

			TArray<FRawMeshTracker_Copy> RawMeshTrackers;

			FMatrix WorldToRoot = InRootTransform.ToMatrixWithScale().Inverse();

			// first do a pass to determine the max LOD level we will be combining meshes into
			int32 OverallMaxLODs = 0;
			for (UMeshComponent* MeshComponent : InMeshComponents)
			{
				USkinnedMeshComponent* SkinnedMeshComponent = Cast<USkinnedMeshComponent>(MeshComponent);
				UStaticMeshComponent* StaticMeshComponent = Cast<UStaticMeshComponent>(MeshComponent);

				if (IsValidSkinnedMeshComponent(SkinnedMeshComponent))
				{
					OverallMaxLODs = FMath::Max(
						SkinnedMeshComponent->MeshObject->GetSkeletalMeshRenderData().LODRenderData.Num(),
						OverallMaxLODs);
				}
				else if (IsValidStaticMeshComponent(StaticMeshComponent))
				{
					OverallMaxLODs = FMath::Max(
						StaticMeshComponent->GetStaticMesh()->GetRenderData()->LODResources.Num(), OverallMaxLODs);
				}
			}

			// Resize raw meshes to accommodate the number of LODs we will need
			RawMeshes.SetNum(OverallMaxLODs);
			RawMeshTrackers.SetNum(OverallMaxLODs);

			// Export all visible components
			for (UMeshComponent* MeshComponent : InMeshComponents)
			{
				FMatrix ComponentToWorld = MeshComponent->GetComponentTransform().ToMatrixWithScale() * WorldToRoot;

				USkinnedMeshComponent* SkinnedMeshComponent = Cast<USkinnedMeshComponent>(MeshComponent);
				UStaticMeshComponent* StaticMeshComponent = Cast<UStaticMeshComponent>(MeshComponent);

				if (IsValidSkinnedMeshComponent(SkinnedMeshComponent))
				{
					SkinnedMeshToRawMeshes(SkinnedMeshComponent, OverallMaxLODs, ComponentToWorld, PackageName,
					                       RawMeshTrackers, RawMeshes, Materials);
				}
				else if (IsValidStaticMeshComponent(StaticMeshComponent))
				{
					StaticMeshToRawMeshes(StaticMeshComponent, OverallMaxLODs, ComponentToWorld, PackageName,
					                      RawMeshTrackers, RawMeshes, Materials);
				}
			}

			uint32 MaxInUseTextureCoordinate = 0;

			// scrub invalid vert color & tex coord data
			check(RawMeshes.Num() == RawMeshTrackers.Num());
			for (int32 RawMeshIndex = 0; RawMeshIndex < RawMeshes.Num(); RawMeshIndex++)
			{
				if (!RawMeshTrackers[RawMeshIndex].bValidColors)
				{
					RawMeshes[RawMeshIndex].WedgeColors.Empty();
				}

				for (uint32 TexCoordIndex = 0; TexCoordIndex < MAX_MESH_TEXTURE_COORDS; TexCoordIndex++)
				{
					if (!RawMeshTrackers[RawMeshIndex].bValidTexCoords[TexCoordIndex])
					{
						RawMeshes[RawMeshIndex].WedgeTexCoords[TexCoordIndex].Empty();
					}
					else
					{
						// Store first texture coordinate index not in use
						MaxInUseTextureCoordinate = FMath::Max(MaxInUseTextureCoordinate, TexCoordIndex);
					}
				}
			}

			// Check if we got some valid data.
			bool bValidData = false;
			for (FRawMesh& RawMesh : RawMeshes)
			{
				if (RawMesh.IsValidOrFixable())
				{
					bValidData = true;
					break;
				}
			}

			if (bValidData)
			{
				// Then find/create it.
				UPackage* Package = CreatePackage(*PackageName);
				check(Package);

				// Create StaticMesh object
				StaticMesh = NewObject<UStaticMesh>(Package, *MeshName, RF_Public | RF_Standalone);
				StaticMesh->InitResources();

				StaticMesh->SetLightingGuid();

				// Determine which texture coordinate map should be used for storing/generating the lightmap UVs
				const uint32 LightMapIndex = FMath::Min(MaxInUseTextureCoordinate + 1,
				                                        (uint32)MAX_MESH_TEXTURE_COORDS - 1);

				// Add source to new StaticMesh
				for (FRawMesh& RawMesh : RawMeshes)
				{
					if (RawMesh.IsValidOrFixable())
					{
						FStaticMeshSourceModel& SrcModel = StaticMesh->AddSourceModel();
						SrcModel.BuildSettings.bRecomputeNormals = false;
						SrcModel.BuildSettings.bRecomputeTangents = false;
						SrcModel.BuildSettings.bRemoveDegenerates = true;
						SrcModel.BuildSettings.bUseHighPrecisionTangentBasis = false;
						SrcModel.BuildSettings.bUseFullPrecisionUVs = false;
						SrcModel.BuildSettings.bGenerateLightmapUVs = true;
						SrcModel.BuildSettings.SrcLightmapIndex = 0;
						SrcModel.BuildSettings.DstLightmapIndex = LightMapIndex;
						SrcModel.SaveRawMesh(RawMesh);
					}
				}

				// Copy materials to new mesh 
				for (UMaterialInterface* Material : Materials)
				{
					StaticMesh->GetStaticMaterials().Add(FStaticMaterial(Material));
				}

				//Set the Imported version before calling the build
				StaticMesh->ImportVersion = EImportStaticMeshVersion::LastVersion;

				// Set light map coordinate index to match DstLightmapIndex
				StaticMesh->SetLightMapCoordinateIndex(LightMapIndex);

				// setup section info map
				for (int32 RawMeshLODIndex = 0; RawMeshLODIndex < RawMeshes.Num(); RawMeshLODIndex++)
				{
					const FRawMesh& RawMesh = RawMeshes[RawMeshLODIndex];
					TArray<int32> UniqueMaterialIndices;
					for (int32 MaterialIndex : RawMesh.FaceMaterialIndices)
					{
						UniqueMaterialIndices.AddUnique(MaterialIndex);
					}

					int32 SectionIndex = 0;
					for (int32 UniqueMaterialIndex : UniqueMaterialIndices)
					{
						StaticMesh->GetSectionInfoMap().Set(RawMeshLODIndex, SectionIndex,
						                                    FMeshSectionInfo(UniqueMaterialIndex));
						SectionIndex++;
					}
				}
				StaticMesh->GetOriginalSectionInfoMap().CopyFrom(StaticMesh->GetSectionInfoMap());

				// Build mesh from source
				StaticMesh->Build(false);
				StaticMesh->PostEditChange();

				StaticMesh->MarkPackageDirty();

				// Notify asset registry of new asset
				FAssetRegistryModule::AssetCreated(StaticMesh);

				// Display notification so users can quickly access the mesh
				if (GIsEditor)
				{
					FNotificationInfo Info(FText::Format(
						LOCTEXT("SkeletalMeshConverted", "Successfully Converted Mesh"),
						FText::FromString(StaticMesh->GetName())));
					Info.ExpireDuration = 8.0f;
					Info.bUseLargeFont = false;
					Info.Hyperlink = FSimpleDelegate::CreateLambda([=]()
					{
						GEditor->GetEditorSubsystem<UAssetEditorSubsystem>()->OpenEditorForAssets(TArray<UObject*>({
							StaticMesh
						}));
					});
					Info.HyperlinkText = FText::Format(
						LOCTEXT("OpenNewAnimationHyperlink", "Open {0}"),
						FText::FromString(StaticMesh->GetName()));
					TSharedPtr<SNotificationItem> Notification = FSlateNotificationManager::Get().AddNotification(Info);
					if (Notification.IsValid())
					{
						Notification->SetCompletionState(SNotificationItem::CS_Success);
					}
				}
			}
		}

		return StaticMesh;
	}
.Build.cs
        PrivateDependencyModuleNames.AddRange(
            new string[]
            {
                "CoreUObject",
                "Engine",
                "Slate",
                "SlateCore",
                "MeshUtilities",
                "RawMesh",
                "Slate",
                "SlateCore",
                "UnrealEd"
            }
        );

最终调用ConvertActorMeshesToStaticMesh方法即可

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1475251.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

探索IP地址定位工具:解读IP数据云的功能与优势

在当今数字化时代&#xff0c;IP地址定位工具成为了许多领域中不可或缺的技术支持&#xff0c;为网络安全、地理定位服务和个性化推荐等提供了重要数据支持。其中&#xff0c;IP数据云作为一种领先的IP地址定位工具&#xff0c;具有一系列功能和优势&#xff0c;本文将对其进行…

k8s service的概念以及创建方法

Service 的功能&#xff1a; Service主要用于提供网络服务&#xff0c;通过Service的定义&#xff0c;能够为客户端应用提供稳定的访问地址&#xff08;域名或IP地址&#xff09;和负载均衡功能&#xff0c;以及屏蔽后端Endpoint的变化&#xff0c;是K8s实现微服务的核心资源。…

如何选择科技公司或者技术团队来开发软件项目呢

最近有客户问我们为什么同样软件项目不同公司报价和工期差异很大&#xff0c;我们给他解释好久才讲清楚&#xff0c;今天整理一下打算写一篇文章来总结一下&#xff0c;有需要开发朋友可以参考&#xff0c;我们下次遇到客户也可以直接转发文章给客户自己看。 我们根据我们自己报…

计算机网络:IP

引言&#xff1a; IP协议是互联网协议族中的核心协议之一&#xff0c;负责为数据包在网络中传输提供路由寻址。它定义了数据包如何在互联网上从源地址传输到目的地址的规则和流程。IP协议使得各种不同类型的网络设备能够相互通信&#xff0c;实现了全球范围内的信息交换。 目录…

人像背景分割SDK,智能图像处理

美摄科技人像背景分割SDK解决方案&#xff1a;引领企业步入智能图像处理新时代 随着科技的不断进步&#xff0c;图像处理技术已成为许多行业不可或缺的一部分。为了满足企业对于高质量、高效率人像背景分割的需求&#xff0c;美摄科技推出了一款领先的人像背景分割SDK&#xf…

Cluster-Level Contrastive Learning for Emotion Recognition in Conversations

对话情绪识别的聚类级对比学习 摘要一、介绍二、相关工作2.1 对话情感识别2.2 对比学习 三、方法3.1 任务定义和模型概述3.2 上下文感知的话语编码器3.3 使用适配器进行知识注入3.4 有监督的集群级对比学习3.4.1情感原型3.4.2集群级别对比学习 3.5 模型训练 四 实验设置4.1 数据…

idea 更新maven java版本变化

今天遇到个问题就是&#xff0c;点击maven的reload&#xff0c;会导致setting 里的java compiler 版本变化 这里的话&#xff0c;应该是settings.xml文件里面的这个限定死了&#xff0c;修改一下或者去掉就可以了 <profile><id>JDK-1.8</id><activatio…

Qt下使用modbus-c库实现PLC线圈/保持寄存器的读写

系列文章目录 提示&#xff1a;这里是该系列文章的所有文章的目录 第一章&#xff1a;Qt下使用ModbusTcp通信协议进行PLC线圈/保持寄存器的读写&#xff08;32位有符号数&#xff09; 第二章&#xff1a;Qt下使用modbus-c库实现PLC线圈/保持寄存器的读写 文章目录 系列文章目录…

如何使用程序通过OCR识别解析PDF中的表格

https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.7/ppstructure/table/README_ch.md#41-%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B Paddle-structure是目前我们能找到的可以做中英文版面分析较好的一个基础模型&#xff0c;其开源版可以识别十类页面元素。这篇文章介绍…

VL817-Q7 USB3.0 HUB芯片 适用于扩展坞 工控机 显示器

VL817-Q7 USB3.1 GEN1 HUB芯片 VL817-Q7 USB3.1 GEN1 HUB芯片 VIA Lab的VL817是一款现代USB 3.1 Gen 1集线器控制器&#xff0c;具有优化的成本结构和完全符合USB标准3.1 Gen 1规范&#xff0c;包括ecn和2017年1月的合规性测试更新。VL817提供双端口和双端口4端口配置&…

windows安装部署node.js并搭建Vue项目

一、官网下载安装包 官网地址&#xff1a;https://nodejs.org/zh-cn/download/ 二、安装程序 1、安装过程 如果有C/C编程的需求&#xff0c;勾选一下下图所示的部分&#xff0c;没有的话除了选择一下node.js安装路径&#xff0c;直接一路next 2、测试安装是否成功 【winR】…

VUE从0到1创建项目及基本路由、页面配置

一、创建项目:(前提已经安装好vue和npm) 目录:E:\personal\project_pro\ windows下,win+R 输入cmd进入命令行: cd E:\personal\project_pro E:# 创建名为test的项目 vue create test# 用上下键选择vue2或vue3,回车确认创建本次选择VUE3 创建好项目后,使用…

css transform 会影响position 定位

比如通过以下代码.实现导航条上的每个li栏目,以不同的时间间隔,从上向下移动进来并显示 .my-navbar ul li {position: relative;opacity: 0;transform: translateY(-30px);transition: transform .6s cubic-bezier(.165,.84,.44,1),opacity .6s cubic-bezier(.165,.84,.44,1);…

书生·浦语大模型全链路开源体系介绍

背景介绍 随着人工智能技术的迅猛发展&#xff0c;大模型技术已成为当今人工智能领域的热门话题。2022 年 11 月 30 日&#xff0c;美国 OpenAI 公司发布了 ChatGPT 通用型对话系统 并引发了全球 的极大关注&#xff0c;上线仅 60 天月活用户数便超过 1 亿&#xff0c;成为历史…

租赁系统|租赁软件提供免押金等多种租赁方式

租赁小程序是一种全新的租赁模式&#xff0c;为用户提供了免押金、多种租赁方式、定制化服务等多项优势&#xff0c;让用户的租赁体验更加美好。让我们来了解一下它的特点和功能。 首先&#xff0c;租赁小程序支持租完即送&#xff0c;无需等待固定租期。它提供了多种租赁方式&…

Rocky Linux 运维工具 ls

一、ls 的简介 ​​ls​ 用于列出当前目录下的文件和目录&#xff0c;以及它们的属性信息。通过 ​ls​命令可以查看文件名、文件大小、创建时间等信息&#xff0c;并方便用户浏览和管理文件。 二、ls 的参数说明 序号参数描述1-a显示所有文件&#xff0c;包括以 ​.​开头的…

辽宁博学优晨教育:视频剪辑培训的领航者

在当今数字化时代&#xff0c;视频剪辑已经成为一项炙手可热的技能。无论是短视频的火爆&#xff0c;还是影视行业的蓬勃发展&#xff0c;都离不开优秀的视频剪辑人才。辽宁博学优晨教育&#xff0c;作为视频剪辑培训的佼佼者&#xff0c;以其正规、专业的教学态度和高质量的培…

Biotin-PEG2-Thiol,生物素-PEG2-巯基,应用于抗体标记、蛋白质富集等领域

您好&#xff0c;欢迎来到新研之家 文章关键词&#xff1a;Biotin-PEG2-Thiol&#xff0c;生物素-PEG2-巯基&#xff0c;Biotin PEG2 Thiol&#xff0c;生物素 PEG2 巯基 一、基本信息 【产品简介】&#xff1a;Biotin PEG2 Thiol can bind with antibodies to prepare biot…

使用docker安装otter

1、使用docker安装otter首先要把docker装好 2、使用docker把镜像拉进去 拉镜像的过程中注意使用docker load -i imagename命令。如果使用docker import imagename命令拉镜像&#xff0c;在安装过程中会报以下错误&#xff1a; 网上查资料说是需要使用docker ps -a --no-trunc…

MySQL:常用的SQL语句

提醒&#xff1a;设定下面的语句是在数据库名为 db_book执行的。 一、创建表 1. 创建t_booktype表 USE db_book; CREATE TABLE t_booktype(id INT AUTO_INCREMENT, bookTypeName VARCHAR(20),bookTypeDesc varchar(200),PRIMARY KEY (id) );2. 创建t_book表 USE db_book; C…