从osg::Texture中读取纹理图片,并动态转换为虚幻引擎的UTexture2D,不过这段代码只能转换图片格式为R8G8B8A8的纹理图片,其他格式请根据实际情况进行修改
UTexture2D* ConvertOsgTexture2UeTexture2D(osg::Texture* texture) {
if (texture)
{
const unsigned int numImages = texture->getNumImages();
if (numImages != 0) {
for (unsigned int j = 0; j < numImages; j++) {
osg::ref_ptr<osg::Image> img = texture->getImage(j);
//osgb的纹理坐标的y轴和虚幻引擎的纹理坐标的y轴是相反的
img->flipVertical();
const int imgWidth = img->s();
const int imgHeight = img->t();
UTexture2D* ueTexture2D = NewObject<UTexture2D>();
ueTexture2D->AddToRoot();
FTexturePlatformData* platformData = new FTexturePlatformData();
ueTexture2D->SetPlatformData(platformData);
ueTexture2D->PlatformData->SizeX = imgWidth;
ueTexture2D->PlatformData->SizeY = imgHeight;
ueTexture2D->PlatformData->SetNumSlices(1);
ueTexture2D->PlatformData->PixelFormat = EPixelFormat::PF_R8G8B8A8;
//填充texture,创建一个像素数组,然后为每个数组定义颜色。数组大小为width*height*每个像素的字节
const int32 numBlocksX = imgWidth / GPixelFormats[EPixelFormat::PF_R8G8B8A8].BlockSizeX;
const int32 numBlocksY = imgHeight / GPixelFormats[EPixelFormat::PF_R8G8B8A8].BlockSizeY;
const int32 size = numBlocksX * numBlocksY * GPixelFormats[EPixelFormat::PF_R8G8B8A8].BlockBytes;
//接下来,把颜色数组输入到纹理中去
FTexture2DMipMap* mip = new FTexture2DMipMap();
mip->SizeX = imgWidth;
mip->SizeY = imgHeight;
mip->BulkData.Lock(LOCK_READ_WRITE);
uint8* pTextureData = static_cast<uint8*>(mip->BulkData.Realloc(size));
memset(pTextureData, 255, size);
for (int k = 0; k < imgWidth * imgHeight; k++)
{
FMemory::Memcpy(&pTextureData[k * 4], &img->data()[k * 3], 3 * sizeof(uint8));
}
mip->BulkData.Unlock();
ueTexture2D->PlatformData->Mips.Add(mip);
//保存texture
ueTexture2D->UpdateResource();
return ueTexture2D;
}
}
}
return nullptr;
}