I have a C++ code that creates a Texture which is half red and half green. Afterwards, I want to remove the green pixels to create something similar to a ChromaKey. Creating the red and green texture works well but I don’t think changes to transparency (the alpha in RBGA) is working correctly. Here is the code:
int Width = 640;
int Height = 480;
int Channels = 4;
// Create a new transient texture object
UTexture2D* Texture = UTexture2D::CreateTransient(Width, Height, EPixelFormat::PF_R8G8B8A8);
Texture->SRGB = 0; // Disable sRGB color space conversion
// Set the texture settings
Texture->AddressX = TextureAddress::TA_Clamp;
Texture->AddressY = TextureAddress::TA_Clamp;
Texture->Filter = TextureFilter::TF_Default;
// Lock the texture data for writing
uint8* TextureData = static_cast<uint8*>(Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE));
// Set the pixel values for each color channel
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
const int32 index = (x + y * Width) * Channels;
if (x < Width / 2)
{
//Red side (left side)
TextureData[index] = 255; // R channel set to red
TextureData[index + 1] = 0; // G channel
}
else
{
//Green side (right side)
TextureData[index] = 0; // R channel
TextureData[index + 1] = 255; // G channel set to green
}
TextureData[index + 2] = 0; // B channel set to 0 for all pixels
TextureData[index + 3] = 255;
}
}
// Loop through the texture data again to set the alpha value based on the green channel value
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
const int32 index = (x + y * Width) * Channels;
//if G channel is greater than R and B channel (pixel is green)
if (TextureData[index + 1] > TextureData[index] && TextureData[index + 1] > TextureData[index + 2])
{
TextureData[index + 3] = 0; // Set the alpha value to 0 for any pixel with a green color
}
}
}
// Unlock the texture data
Texture->PlatformData->Mips[0].BulkData.Unlock();
// Update the texture resource
Texture->UpdateResource();