Mirro1871
(Mirro1871)
1
void CreateTexture() {
// Texture Information
FString FileName = FString("MyTexture");
int width = 1024;
int height = 1024;
uint8 * pixels = (uint8 *)malloc(height * width * 4); // x4 because it's RGBA. 4 integers, one for Red, one for Green, one for Blue, one for Alpha
// filling the pixels with dummy data (4 boxes: red, green, blue and white)
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (x < width / 2) {
if (y < height / 2) {
pixels[y * 4 * width + x * 4 + 0] = 255; // R
pixels[y * 4 * width + x * 4 + 1] = 0; // G
pixels[y * 4 * width + x * 4 + 2] = 0; // B
pixels[y * 4 * width + x * 4 + 3] = 255; // A
}
else {
pixels[y * 4 * width + x * 4 + 0] = 0; // R
pixels[y * 4 * width + x * 4 + 1] = 255; // G
pixels[y * 4 * width + x * 4 + 2] = 0; // B
pixels[y * 4 * width + x * 4 + 3] = 255; // A
}
}
else {
if (y < height / 2) {
pixels[y * 4 * width + x * 4 + 0] = 0; // R
pixels[y * 4 * width + x * 4 + 1] = 0; // G
pixels[y * 4 * width + x * 4 + 2] = 255; // B
pixels[y * 4 * width + x * 4 + 3] = 255; // A
}
else {
pixels[y * 4 * width + x * 4 + 0] = 255; // R
pixels[y * 4 * width + x * 4 + 1] = 255; // G
pixels[y * 4 * width + x * 4 + 2] = 255; // B
pixels[y * 4 * width + x * 4 + 3] = 255; // A
}
}
}
}
// Create Package
FString pathPackage = FString("/Game/MyTextures/");
FString absolutePathPackage = FPaths::GameContentDir() + "/MyTextures/";
FPackageName::RegisterMountPoint(*pathPackage, *absolutePathPackage);
UPackage * Package = CreatePackage(nullptr, *pathPackage);
// Create the Texture
FName TextureName = MakeUniqueObjectName(Package, UTexture2D::StaticClass(), FName(*FileName));
UTexture2D* Texture = NewObject<UTexture2D>(Package, TextureName, RF_Public | RF_Standalone);
// Texture Settings
Texture->PlatformData = new FTexturePlatformData();
Texture->PlatformData->SizeX = width;
Texture->PlatformData->SizeY = height;
Texture->PlatformData->PixelFormat = PF_R8G8B8A8;
// Passing the pixels information to the texture
FTexture2DMipMap* Mip = new(Texture->PlatformData->Mips) FTexture2DMipMap();
Mip->SizeX = width;
Mip->SizeY = height;
Mip->BulkData.Lock(LOCK_READ_WRITE);
uint8* TextureData = (uint8 *) Mip->BulkData.Realloc(height * width * sizeof(uint8)*4);
FMemory::Memcpy(TextureData, pixels, sizeof(uint8) * height * width * 4);
Mip->BulkData.Unlock();
// Updating Texture & mark it as unsaved
Texture->AddToRoot();
Texture->UpdateResource();
Package->MarkPackageDirty();
UE_LOG(LogTemp, Log, TEXT( "Texture created: %s" ), &FileName);
free(pixels);
pixels = NULL;
}