1. 概述
之所以寫這個繪製簡單三角形的實例其實是想知道如何在Unreal中通過代碼繪製自定義Mesh,如果你會繪製一個三角形,那麼自然就會繪製複雜的Mesh了。所以這是很多圖形工作者的第一課。
2. 詳論
2.1. 代碼實現
Actor是Unreal的基本顯示對象,有點類似於Unity中的GameObject或者OSG中的Node。因此,我們首先要實現一個繼承自AActor的類
頭文件CustomMeshActor.h:
#pragma once
// clang-format off
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "CustomMeshActor.generated.h"
// clang-format on
UCLASS()
class UESTUDY_API ACustomMeshActor : public AActor {
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ACustomMeshActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
UStaticMesh* CreateMesh();
void CreateGeometry(FStaticMeshRenderData* RenderData);
void CreateMaterial(UStaticMesh* mesh);
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
UStaticMeshComponent* staticMeshComponent;
};
實現CustomMeshActor.cpp:
#include "CustomMeshActor.h"
#include "Output.h"
// Sets default values
ACustomMeshActor::ACustomMeshActor() {
// Set this actor to call Tick() every frame. You can turn this off to
// improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ACustomMeshActor::BeginPlay() {
Super::BeginPlay();
staticMeshComponent = NewObject<UStaticMeshComponent>(this);
staticMeshComponent->SetMobility(EComponentMobility::Stationary);
SetRootComponent(staticMeshComponent);
staticMeshComponent->RegisterComponent();
UStaticMesh* mesh = CreateMesh();
if (mesh) {
staticMeshComponent->SetStaticMesh(mesh);
}
}
UStaticMesh* ACustomMeshActor::CreateMesh() {
UStaticMesh* mesh = NewObject<UStaticMesh>(staticMeshComponent);
mesh->NeverStream = true;
mesh->SetIsBuiltAtRuntime(true);
TUniquePtr<FStaticMeshRenderData> RenderData =
MakeUnique<FStaticMeshRenderData>();
CreateGeometry(RenderData.Get());
CreateMaterial(mesh);
mesh->SetRenderData(MoveTemp(RenderData));
mesh->InitResources();
mesh->CalculateExtendedBounds(); //設置包圍盒之後調用這個函數起效,否則會被視錐體剔除
return mesh;
}
void ACustomMeshActor::CreateMaterial(UStaticMesh* mesh) {
UMaterial* material1 = (UMaterial*)StaticLoadObject(
UMaterial::StaticClass(), nullptr,
TEXT("Material'/Game/Materials/RedColor.RedColor'"));
mesh->AddMaterial(material1);
UMaterial* material2 = (UMaterial*)StaticLoadObject(
UMaterial::StaticClass(), nullptr,
TEXT("Material'/Game/Materials/GreenColor.GreenColor'"));
mesh->AddMaterial(material2);
}
void ACustomMeshActor::CreateGeometry(FStaticMeshRenderData* RenderData) {
RenderData->AllocateLODResources(1);
FStaticMeshLODResources& LODResources = RenderData->LODResources[0];
int vertexNum = 4;
TArray<FVector> xyzList;
xyzList.Add(FVector(0, 0, 50));
xyzList.Add(FVector(100, 0, 50));
xyzList.Add(FVector(100, 100, 50));
xyzList.Add(FVector(0, 100, 50));
TArray<FVector2D> uvList;
uvList.Add(FVector2D(0, 1));
uvList.Add(FVector2D(0, 0));
uvList.Add(FVector2D(1, 0));
uvList.Add(FVector2D(1, 1));
// 設置頂點數據
TArray<FStaticMeshBuildVertex> StaticMeshBuildVertices;
StaticMeshBuildVertices.SetNum(vertexNum);
for (int m = 0; m < vertexNum; m++) {
StaticMeshBuildVertices[m].Position = xyzList[m];
StaticMeshBuildVertices[m].Color = FColor(255, 0, 0);
StaticMeshBuildVertices[m].UVs[0] = uvList[m];
StaticMeshBuildVertices[m].TangentX = FVector(0, 1, 0); //切線
StaticMeshBuildVertices[m].TangentY = FVector(1, 0, 0); //副切線
StaticMeshBuildVertices[m].TangentZ = FVector(0, 0, 1); //法向量
}
LODResources.bHasColorVertexData = false;
//頂點buffer
LODResources.VertexBuffers.PositionVertexBuffer.Init(StaticMeshBuildVertices);
//法線,切線,貼圖座標buffer
LODResources.VertexBuffers.StaticMeshVertexBuffer.Init(
StaticMeshBuildVertices, 1);
//設置索引數組
TArray<uint32> indices;
int numTriangles = 2;
int indiceNum = numTriangles * 3;
indices.SetNum(indiceNum);
indices[0] = 2;
indices[1] = 1;
indices[2] = 0;
indices[3] = 3;
indices[4] = 2;
indices[5] = 0;
LODResources.IndexBuffer.SetIndices(indices,
EIndexBufferStride::Type::AutoDetect);
LODResources.bHasDepthOnlyIndices = false;
LODResources.bHasReversedIndices = false;
LODResources.bHasReversedDepthOnlyIndices = false;
// LODResources.bHasAdjacencyInfo = false;
FStaticMeshLODResources::FStaticMeshSectionArray& Sections =
LODResources.Sections;
{
FStaticMeshSection& section = Sections.AddDefaulted_GetRef();
section.bEnableCollision = false;
section.MaterialIndex = 0;
section.NumTriangles = 1;
section.FirstIndex = 0;
section.MinVertexIndex = 0;
section.MaxVertexIndex = 2;
}
{
FStaticMeshSection& section = Sections.AddDefaulted_GetRef();
section.bEnableCollision = false;
section.MaterialIndex = 0;
section.NumTriangles = 1;
section.FirstIndex = 3;
section.MinVertexIndex = 3;
section.MaxVertexIndex = 5;
}
double boundArray[7] = {0, 0, 0, 200, 200, 200, 200};
//設置包圍盒
FBoxSphereBounds BoundingBoxAndSphere;
BoundingBoxAndSphere.Origin =
FVector(boundArray[0], boundArray[1], boundArray[2]);
BoundingBoxAndSphere.BoxExtent =
FVector(boundArray[3], boundArray[4], boundArray[5]);
BoundingBoxAndSphere.SphereRadius = boundArray[6];
RenderData->Bounds = BoundingBoxAndSphere;
}
// Called every frame
void ACustomMeshActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
然後將這個類對象ACustomMeshActor拖放到場景中,顯示結果如下:
2.2. 解析:Component
-
Actor只是一個空殼,具體的功能是通過各種類型的Component實現的(這一點與Unity不謀而合),這裏使用的是UStaticMeshComponent,這也是Unreal場景中用的最多的Mesh組件。
-
這裏組件初始化是在BeginPlay()中創建的,如果在構造函數中創建,那麼就不能使用NewObject,而應該使用如下方法:
// Sets default values ACustomMeshActor::ACustomMeshActor() { // Set this actor to call Tick() every frame. You can turn this off to // improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; staticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SceneRoot")); staticMeshComponent->SetMobility(EComponentMobility::Static); SetRootComponent(staticMeshComponent); UStaticMesh* mesh = CreateMesh(); if (mesh) { staticMeshComponent->SetStaticMesh(mesh); } }
-
承接2,在BeginPlay()中創建和在構造函數中創建的區別就在於前者是運行時創建,而後者在程序運行之前就創建了,可以在未運行的編輯器狀態下看到靜態網格體和材質。
-
承接2,在構造函數中創建的UStaticMeshComponent移動性被設置成Static了,這時運行會提示“光照需要重建”,也就是靜態對象需要烘焙光照,在工具欄"構建"->"僅構建光照"烘培一下即可。這種方式運行時渲染效率最高。
-
對比4,運行時創建的UStaticMeshComponent移動性可以設置成Stationary,表示這個靜態物體不移動,啓用緩存光照法,並且緩存動態陰影。
2.3. 解析:材質
-
在UE編輯器分別創建了紅色和綠色簡單材質,注意材質是單面還是雙面的,C++代碼設置的要和材質藍圖中設置的要保持一致。最開始我參考的就是參考文獻1中的代碼,代碼中設置成雙面,但是我自己的材質藍圖中用的單面,程序啓動直接崩潰了。
-
如果場景中材質顯示不正確,比如每次瀏覽場景時的效果都不一樣,說明可能法向量沒有設置,我最開始就沒有注意這個問題以爲是光照的問題。
-
單面材質的話,正面是逆時針序還是順時針序?從這個案例來看應該是逆時針。UE是個左手座標系,X軸向前,法向量是(0, 0, 1),從法向量的一邊看過去,頂點順序是(100, 100, 50)->(100, 0, 50)->(0, 0, 50),明顯是逆時針。
2.4. 解析:包圍盒
-
包圍盒參數最好要設置,UE似乎默認實現了視景體裁剪,不在範圍內的物體會不顯示。如果在某些視角場景對象突然不顯示了,可能包圍盒參數沒有設置正確,導致視景體裁剪錯誤地篩選掉了當前場景對象。
FBoxSphereBounds BoundingBoxAndSphere; //... RenderData->Bounds = BoundingBoxAndSphere; //... mesh->CalculateExtendedBounds(); //設置包圍盒之後調用這個函數起效,否則會被視錐體剔除
-
即使是一個平面,包圍盒的三個Size參數之一也不能爲0,否則還是可能會在某些視角場景對象不顯示。
2.5. 解析:Section
Mesh內部是可以進行劃分的,劃分成多少個section就使用多少個材質,比如這裏劃分了兩個section,最後就使用了兩個材質。如下代碼所示:
FStaticMeshLODResources::FStaticMeshSectionArray& Sections =
LODResources.Sections;
{
FStaticMeshSection& section = Sections.AddDefaulted_GetRef();
section.bEnableCollision = false;
section.MaterialIndex = 0;
section.NumTriangles = 1;
section.FirstIndex = 0;
section.MinVertexIndex = 0;
section.MaxVertexIndex = 2;
}
{
FStaticMeshSection& section = Sections.AddDefaulted_GetRef();
section.bEnableCollision = false;
section.MaterialIndex = 0;
section.NumTriangles = 1;
section.FirstIndex = 3;
section.MinVertexIndex = 3;
section.MaxVertexIndex = 5;
}
3. 其他
除了本文介紹的方法之外,也有其他的實現辦法,具體可以參考文獻3-5。實在是沒有時間進行進一步的研究了,因此記錄備份一下。另外,文獻6-7可能對了解UE關於Mesh的內部實現有所幫助,筆者反正是看麻了。不得不說,這麼一個微小的功能涉及到的內容還真不少,看來有的研究了。