[UE4] 將RenderTarget轉成Color陣列以儲存至SaveData
有時我們會需要儲存RenderTarget的Pixel資訊在遊戲存檔,如地圖探索範圍、拍照照片等等。然而UE4的SaveData不支援直接儲存RenderTarget,因此需要轉化成可以儲存的格式。這邊我們使用FColor的陣列儲存。
儲存:RenderTarget至TArray<FColor>
使用ReadPixels
TArray<FColor> OutputBuffer;
UTextureRenderTarget2D* RenderTarget = GetSourceFogRenderTarget();
FTextureRenderTarget2DResource* TextureResource = (FTextureRenderTarget2DResource*)RenderTarget->GameThread_GetRenderTargetResource();
TextureResource->ReadPixels(OutputBuffer);
之後將OutputBuffer以一般陣列儲存即可。
讀取:TArray<FColor>至RenderTarget
透過Canvas將Pixel資訊畫回RenderTarget
TArray<FColor> InputBuffer;
UTextureRenderTarget2D* RenderTarget = GetSourceFogRenderTarget();
UCanvas* Canvas;
FVector2D Size;
FDrawToRenderTargetContext RenderContext;
UKismetRenderingLibrary::BeginDrawCanvasToRenderTarget(this, RenderTarget, Canvas, Size, RenderContext);
if (Canvas)
{
// 讀取的PixelData寫入Texture (MipMaps [0])
UTexture2D* ReconstructedTexture = UTexture2D::CreateTransient(RenderTarget->SizeX, RenderTarget->SizeY, PF_B8G8R8A8);
uint8* MipData = (uint8*)ReconstructedTexture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE);
const int32 DataSize = RenderTarget->SizeY * RenderTarget->SizeX * 4;
FMemory::Memcpy(MipData, InputBuffer.GetData(), DataSize);
ReconstructedTexture->PlatformData->Mips[0].BulkData.Unlock();
ReconstructedTexture->UpdateResource();
// 將Texture填滿Canvas
Canvas->K2_DrawTexture(ReconstructedTexture, FVector2D::ZeroVector, Size, FVector2D(0, 0), FVector2D(1, 1), FLinearColor::White, EBlendMode::BLEND_Opaque);
}
UKismetRenderingLibrary::EndDrawCanvasToRenderTarget(this, RenderContext);