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的內部實現有所幫助,筆者反正是看麻了。不得不說,這麼一個微小的功能涉及到的內容還真不少,看來有的研究了。