Unreal Engine C++ Actor: Procedural Mesh with Random Heights

This C++ actor class for Unreal Engine demonstrates how to generate a procedural mesh based on a defined rectangular area with randomized height values.

Features:

  1. Input: Two float values for X and Y coordinates to define the rectangular area.
  2. Point Generation: Creates points corresponding to integer coordinates within the defined area.
  3. Random Height: Assigns random height values to each point within the range of 0 to 255.
  4. Mesh Generation: Creates a static mesh using the points, applying a provided material.

Code:

Header File (MyActor.h):

#pragma once

#include "GameFramework/Actor.h"
#include "MyActor.generated.h"

UCLASS()
class MYPROJECT_API AMyActor : public AActor
{
    GENERATED_BODY()

public: 
    // Sets default values for this actor's properties
    AMyActor();

protected:
    // Called when the game starts or when spawned
    virtual void BeginPlay() override;

public: 
    // Called every frame
    virtual void Tick(float DeltaTime) override;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
    float XCoordinate;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
    float YCoordinate;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
    int32 GridSize;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
    UStaticMesh* Mesh;

    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
    UMaterialInterface* Material;

    UFUNCTION(BlueprintCallable, Category = "MyActor")
    void GenerateMesh();

private:
    TArray<FVector> Points;

    TArray<FVector> Vertices;

    TArray<int32> Triangles;

    TArray<FVector2D> UVs;

    TArray<FVector> Normals;

    void GeneratePoints();

    void GenerateVertices();

    void GenerateTriangles();

    void GenerateUVs();

    void GenerateNormals();
};

Implementation File (MyActor.cpp):

#include "MyActor.h"
#include "Components/StaticMeshComponent.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "Math/UnrealMathUtility.h"

// Sets default values
AMyActor::AMyActor()
{
    // 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;

    // Create the static mesh component
    UStaticMeshComponent* MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
    MeshComponent->SetupAttachment(RootComponent);

    // Set default values for the properties
    XCoordinate = 0;
    YCoordinate = 0;
    GridSize = 10;
    Mesh = nullptr;
    Material = nullptr;
}

// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
    Super::BeginPlay();
}

// Called every frame
void AMyActor::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
}

void AMyActor::GenerateMesh()
{
    GeneratePoints();
    GenerateVertices();
    GenerateTriangles();
    GenerateUVs();
    GenerateNormals();

    // Create the static mesh
    UStaticMesh* StaticMesh = NewObject<UStaticMesh>(StaticClass(), FName(TEXT("MyStaticMesh")));
    StaticMesh->InitResources();

    // Create the vertex buffer
    FStaticMeshVertexBuffers VertexBuffers;
    VertexBuffers.InitFromSingleVertexStream(
        sizeof(FVector) * 4, // vertex size
        Points.Num(), // number of vertices
        &Vertices[0], // vertex data
        sizeof(FVector) * 2, // texture coordinate size
        &UVs[0], // texture coordinate data
        sizeof(FVector), // normal size
        &Normals[0], // normal data
        nullptr, // tangent data
        nullptr // color data
    );

    // Create the index buffer
    FStaticMeshIndexBuffer32 IndexBuffer;
    IndexBuffer.AllocateDefault(Vertices.Num());
    FMemory::Memcpy(IndexBuffer.GetData(), &Triangles[0], sizeof(int32) * Triangles.Num());

    // Create the static mesh section
    FStaticMeshSection Section;
    Section.MaterialIndex = 0;
    Section.bEnableCollision = true;
    Section.bCastShadow = true;
    Section.bForceOpaque = true;
    Section.bReverseCulling = false;
    Section.bVisibleInRayTracing = true;
    Section.bRenderCustomDepth = false;
    Section.bEnableShadowCasting = true;
    Section.bUseMaximumStreamingTexelRatio = false;
    Section.bUseHighPrecisionTangents = false;
    Section.bUseFullPrecisionUVs = false;
    Section.bUseHighPrecisionUVs = false;
    Section.bUseLandscapeForCullingInvisibleHLODVertices = false;
    Section.bEnableMeshOcclusion = false;
    Section.bTreatAsBackgroundForOcclusion = false;
    Section.bAllowCPUAccess = false;
    Section.bRequiresAdjacencyInformation = false;
    Section.bSupportFaceRemap = true;
    Section.bHasBeenSimplified = false;
    Section.bRecomputeTangents = false;
    Section.bRecomputeNormals = false;
    Section.bUseMaxDeviation = false;
    Section.bNeedsPositionOnlyVertexBuffer = false;
    Section.bAllowCullDistanceVolume = true;
    Section.bHasPerFaceMaterials = false;
    Section.bHasDiscreteCollisionMeshes = false;
    Section.bCastDynamicShadow = true;
    Section.bCastStaticShadow = true;
    Section.bAffectDynamicIndirectLighting = true;
    Section.bAffectDistanceFieldLighting = true;
    Section.bCastFarShadow = true;
    Section.bIsTwoSidedMaterial = false;
    Section.bForceNoLightmapGeneration = false;
    Section.bUseCustomPrimitiveData = false;
    Section.bFullyCompressedPositionOnly = false;
    Section.bIsBuiltAtRuntime = false;
    Section.bSupportUniformlyDistributedSampling = false;
    Section.bSupportStationaryLightOverlap = false;
    Section.bUseLegacyBiTangents = false;
    Section.bUseHighPrecisionTangentBasis = false;
    Section.bUseFullPrecisionUVsAndTangentBasis = false;
    Section.bAllowShadowMapBias = false;
    Section.bUsePlanarForwardReflections = false;
    Section.bUseCustomizedUVs = false;
    Section.bEnableFadingIn = false;
    Section.bEnableFadingOut = false;
    Section.bUseDynamicData = false;
    Section.bUseDynamicMaterialInstance = false;
    Section.VertexBuffer = &VertexBuffers;
    Section.IndexBuffer = &IndexBuffer;

    // Create the static mesh build settings
    FMeshBuildSettings BuildSettings;
    BuildSettings.BuildScale3D = FVector(1, 1, 1);
    BuildSettings.DistanceFieldResolutionScale = 1;
    BuildSettings.bGenerateDistanceFieldAsIfTwoSided = false;
    BuildSettings.bSupportFaceRemap = true;
    BuildSettings.bUseFullPrecisionUVs = false;
    BuildSettings.bUseHighPrecisionTangents = false;
    BuildSettings.bRecomputeNormals = false;
    BuildSettings.bRecomputeTangents = false;
    BuildSettings.bRemoveDegenerates = true;
    BuildSettings.bUseMikkTSpace = false;
    BuildSettings.bUseHighPrecisionUVs = false;
    BuildSettings.bBuildAdjacencyBuffer = false;
    BuildSettings.bBuildReversedIndexBuffer = false;
    BuildSettings.bUseFullPrecisionUVsAndTangentBasis = false;
    BuildSettings.bUseLegacyBiTangents = false;
    BuildSettings.bUsePlanarForwardReflections = false;
    BuildSettings.bUseCustomizedUVs = false;
    BuildSettings.bUseDynamicData = false;
    BuildSettings.bUseDynamicMaterialInstance = false;

    // Build the static mesh
    StaticMesh->BuildFromStaticMeshSection(0, Section, BuildSettings);

    // Set the static mesh
    UStaticMeshComponent* MeshComponent = Cast<UStaticMeshComponent>(GetComponentByClass(UStaticMeshComponent::StaticClass()));
    MeshComponent->SetStaticMesh(StaticMesh);

    // Set the material
    if(Material != nullptr)
    {
        UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);
        MeshComponent->SetMaterial(0, DynamicMaterial);
    }
}

void AMyActor::GeneratePoints()
{
    Points.Empty();

    for (int32 i = 0; i < GridSize; i++)
    {
        for (int32 j = 0; j < GridSize; j++)
        {
            float X = i * XCoordinate;
            float Y = j * YCoordinate;
            float Z = FMath::RandRange(0, 255);

            Points.Add(FVector(X, Y, Z));
        }
    }
}

void AMyActor::GenerateVertices()
{
    Vertices.Empty();

    for (int32 i = 0; i < Points.Num(); i++)
    {
        Vertices.Add(Points[i]);
    }
}

void AMyActor::GenerateTriangles()
{
    Triangles.Empty();

    for (int32 i = 0; i < GridSize - 1; i++)
    {
        for (int32 j = 0; j < GridSize - 1; j++)
        {
            int32 Index1 = i * GridSize + j;
            int32 Index2 = i * GridSize + j + 1;
            int32 Index3 = (i + 1) * GridSize + j;
            int32 Index4 = (i + 1) * GridSize + j + 1;

            Triangles.Add(Index1);
            Triangles.Add(Index2);
            Triangles.Add(Index3);

            Triangles.Add(Index2);
            Triangles.Add(Index4);
            Triangles.Add(Index3);
        }
    }
}

void AMyActor::GenerateUVs()
{
    UVs.Empty();

    for (int32 i = 0; i < GridSize; i++)
    {
        for (int32 j = 0; j < GridSize; j++)
        {
            float U = i / (float)(GridSize - 1);
            float V = j / (float)(GridSize - 1);

            UVs.Add(FVector2D(U, V));
        }
    }
}

void AMyActor::GenerateNormals()
{
    Normals.Empty();

    for (int32 i = 0; i < Points.Num(); i++)
    {
        Normals.Add(FVector(0, 0, 1));
    }
}

Instructions:

  1. Create a new C++ actor class in your Unreal Engine project.
  2. Replace the generated code with the provided code above.
  3. Configure the properties (XCoordinate, YCoordinate, GridSize, Mesh, Material) in the editor.
  4. Call the GenerateMesh() function to generate the procedural mesh.

Notes:

  • Make sure to create and assign a UStaticMesh and a UMaterialInterface in your project.
  • The GridSize property determines the resolution of the mesh.
  • This code assumes a flat plane with randomized height values. You can modify the GeneratePoints() function for more complex shapes.
  • You can customize the generated mesh further by adjusting the static mesh section properties or the mesh build settings.
Unreal Engine C++ Actor: Generating Procedural Mesh with Random Heights

原文地址: https://www.cveoy.top/t/topic/nasR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录