Download

Best way to create foliage/forest area in C++

Hi,

I am importing terrain from Cesium (Unreal 4.26).
I want to add trees and plants in certain areas of the terrain. These areas are delimited by geometric shapes (from shapefile).

Based on these two tutorials:

I created a class allowing to place trees inside a zone delimited by a spline.
But it is very slow.

Is there a better method ?
How to take advantage of the power of Unrela Engine for the display of forests without using painting tools but by programming in C ++ zones delimiting forests?

For information, here is my code:

AAdvancedFoliageSpawner::AAdvancedFoliageSpawner()
{
	PrimaryActorTick.bCanEverTick = true;

	NbrDivX = 50;
	NbrDivY = 50;
	
	SplineComponent = CreateDefaultSubobject<USplineComponent>(TEXT("Spline"));
	if (SplineComponent)
	{
		SetRootComponent(SplineComponent);
	}

	ismc = CreateDefaultSubobject<UInstancedStaticMeshComponent>(TEXT("UInstancedStaticMeshComponent"));
	ismc->SetMobility(EComponentMobility::Static);
	ismc->SetCollisionProfileName("NoCollision");
}

void AAdvancedFoliageSpawner::OnConstruction(const FTransform& Transform)
{
	Super::OnConstruction(Transform);

	FVector pMin;
	FVector pMax;
	for (int sPtIndex = 0; sPtIndex < SplineComponent->GetNumberOfSplinePoints(); ++sPtIndex)
	{
		FVector location = SplineComponent->GetLocationAtSplinePoint(sPtIndex, ESplineCoordinateSpace::World);
		
		if (location.X < pMin.X) pMin.X = location.X;
		if (location.Y < pMin.Y) pMin.Y = location.Y;
		if (location.Z < pMin.Z) pMin.Z = location.Z;

		if (location.X > pMax.X) pMax.X = location.X;
		if (location.Y > pMax.Y) pMax.Y = location.Y;
		if (location.Z > pMax.Z) pMax.Z = location.Z;
	}

	float xLength = pMax.X - pMin.X;
	float yLength = pMax.Y - pMin.Y;

	FTransform trans;
	for (int divX = 0; divX <= NbrDivX; ++divX)
	{
		float x = (xLength / (float)NbrDivX) * divX;

		for (int divY = 0; divY <= NbrDivY; ++divY)
		{
			float y = (yLength / (float)NbrDivY) * divY;

			trans.SetLocation(FVector(x, y, 0.0f));
			ismc->AddInstance(trans);
		}
	}
}