Skip to content

Commit

Permalink
feat: Read the input Texture on GPU
Browse files Browse the repository at this point in the history
  • Loading branch information
homuler committed Aug 13, 2024
1 parent efb103a commit 2e6cf29
Showing 1 changed file with 12 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -108,41 +108,28 @@ public void Dispose()
/// If <paramref name="src" /> format is different from <see cref="format" />, it converts the format.
/// </summary>
/// <remarks>
/// After calling it, pixel data can't be read from CPU safely.
/// After calling it, pixel data can't be read on CPU safely.
/// To read pixel data on CPU, use <see cref="ReadTextureAsync" />.
/// </remarks>
public bool ReadTextureOnGPU(Texture src)
public void ReadTextureOnGPU(Texture src, bool flipHorizontally, bool flipVertically)
{
if (GetTextureFormat(src) != format)
{
return Graphics.ConvertTexture(src, _texture);
}
Graphics.CopyTexture(src, _texture);
return true;
}
ReadTextureInternal(src, flipHorizontally, flipVertically);

public AsyncGPUReadbackRequest ReadTextureAsync(Texture src)
{
if (!ReadTextureOnGPU(src))
{
throw new InvalidOperationException("Failed to read texture on GPU");
}

return AsyncGPUReadback.Request(_texture, 0, (req) =>
{
if (_texture == null)
{
return;
}
_texture.LoadRawTextureData(req.GetData<byte>());
_texture.Apply();
});
Graphics.CopyTexture(_tmpRenderTexture, _texture);
RenderTexture.ReleaseTemporary(_tmpRenderTexture);
}

/// <remarks>
/// This method is not thread-safe.
/// Avoid calling this method again before the returned <see cref="AsyncGPUReadbackRequest.done"/> is <see langword="true"/>.
/// </remarks>
public AsyncGPUReadbackRequest ReadTextureAsync(Texture src, bool flipHorizontally, bool flipVertically)
{
ReadTextureInternal(src, flipHorizontally, flipVertically);
return AsyncGPUReadback.Request(_tmpRenderTexture, 0, _onReadBackRenderTexture);
}

private void ReadTextureInternal(Texture src, bool flipHorizontally, bool flipVertically)
{
var graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(format, true);
_tmpRenderTexture = RenderTexture.GetTemporary(src.width, src.height, 32, graphicsFormat);
Expand All @@ -163,8 +150,6 @@ public AsyncGPUReadbackRequest ReadTextureAsync(Texture src, bool flipHorizontal
}
Graphics.Blit(src, _tmpRenderTexture, scale, offset);
RenderTexture.active = currentRenderTexture;

return AsyncGPUReadback.Request(_tmpRenderTexture, 0, _onReadBackRenderTexture);
}

private readonly Action<AsyncGPUReadbackRequest> _onReadBackRenderTexture;
Expand Down

0 comments on commit 2e6cf29

Please sign in to comment.