9UTreeHeightsFromImageComponent::UTreeHeightsFromImageComponent()
11 PrimaryComponentTick.bCanEverTick =
false;
14void UTreeHeightsFromImageComponent::BeginPlay()
19void UTreeHeightsFromImageComponent::CacheTexture()
22 FString TexturePath = TEXT(
"/Game/Agrarsense/Maps/Vindeln/CHM_Vindeln.CHM_Vindeln");
23 treeMapImage = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(),
nullptr, *TexturePath));
26 FTexture2DMipMap& Mip = treeMapImage->GetPlatformData()->Mips[0];
27 void* Data = Mip.BulkData.Lock(LOCK_READ_ONLY);
28 int32 Size = Mip.BulkData.GetBulkDataSize();
30 Pixels.AddUninitialized(Size);
32 std::memcpy(Pixels.GetData(), Data, Size);
34 Mip.BulkData.Unlock();
36 UE_LOG(LogTemp, Warning, TEXT(
"Tree image cached.."));
37 UE_LOG(LogTemp, Warning, TEXT(
"Pixels data len %i"), Pixels.Num());
39 Width = treeMapImage->GetSizeX();
40 Height = treeMapImage->GetSizeY();
42 UE_LOG(LogTemp, Warning, TEXT(
"Source image resolution: %i x %i"), Width, Height);
47float UTreeHeightsFromImageComponent::EuclideanDistance(
const FColor& Color1,
const FColor& Color2)
55 return FMath::Sqrt(FMath::Square(R2 - R1) + FMath::Square(G2 - G1) + FMath::Square(B2 - B1));
58FColor UTreeHeightsFromImageComponent::FindClosestColor(
const FColor& TargetColor,
const TMap<int32, FColor>& ColorMap)
60 float MinDistance = FLT_MAX;
63 for (
const auto& Pair : ColorMap)
65 float Distance = EuclideanDistance(TargetColor, Pair.Value);
66 if (Distance < MinDistance)
68 MinDistance = Distance;
69 ClosestColor = Pair.Value;
76int UTreeHeightsFromImageComponent::GetColorFromPixel(FVector point)
84 UE_LOG(LogTemp, Warning, TEXT(
"Returning from Pixels are empty!"));
95 if (point.X <= 0 || point.Y <= 0)
97 UE_LOG(LogTemp, Warning, TEXT(
"Returning from point less than 0"));
123 if (point.X > Width || point.Y > Height)
126 UE_LOG(LogTemp, Warning, TEXT(
"Returning from point over the resolution"));
131 if (Width <= 0 || Height <= 0)
135 UE_LOG(LogTemp, Warning, TEXT(
"Returning from width <= 0"));
142 int32 Index = ((int)point.Y * Width + (
int)point.X) * 4;
144 if (Index + 3 <= Pixels.Num())
146 uint8 R = Pixels[Index];
147 uint8 G = Pixels[Index + 1];
148 uint8 B = Pixels[Index + 2];
151 FColor pixelColor = FColor(B, G, R);
153 FColor closestColor = FindClosestColor(pixelColor, colorHeight);
155 for (
const auto& Pair : colorHeight)
157 if (Pair.Value == closestColor)
159 UE_LOG(LogTemp, Warning, TEXT(
"This tree is : %i m"), Pair.Key);
165 UE_LOG(LogTemp, Warning, TEXT(
"Index out of range"));
178void UTreeHeightsFromImageComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
180 Super::PostEditChangeProperty(PropertyChangedEvent);
183 if (PropertyChangedEvent.Property !=
nullptr && PropertyChangedEvent.Property->GetName() ==
"GenerateTrigger")
188 GenerateTrigger =
false;