#!/usr/bin/env python3
# coding=utf-8
#
# Copyright (c) 2019 Collabora Ltd
# Copyright © 2020,2025 Valve Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# SPDX-License-Identifier: MIT

# Dumps snapshot images from a renderdoc capture for stability testing.
# Renders the last frame N times, saving a PNG for each iteration, so that
# the caller can verify that the output is stable across loops.

import argparse
import atexit
import os
import shutil
import sys
import tempfile
from pathlib import Path

TMP_DIR = tempfile.mkdtemp()
atexit.register(lambda: shutil.rmtree(TMP_DIR))
RENDERDOC_DEBUG_FILE = TMP_DIR + "/renderdoc.log"

# Needs to be in the environment before importing the module
os.environ['RENDERDOC_DEBUG_LOG_FILE'] = RENDERDOC_DEBUG_FILE

import renderdoc as rd  # noqa: E402

try:
    from renderdoc import ResultCode
except ImportError:
    from renderdoc import ReplayStatus as ResultCode


def load_capture(filename):
    cap = rd.OpenCaptureFile()

    status = cap.OpenFile(filename, '', None)

    if status != ResultCode.Succeeded:
        if os.path.exists(RENDERDOC_DEBUG_FILE):
            print(open(RENDERDOC_DEBUG_FILE, "r").read(), file=sys.stderr)
        raise RuntimeError("Couldn't open file: " + str(status))

    if not cap.LocalReplaySupport():
        raise RuntimeError("Capture cannot be replayed")

    status, controller = cap.OpenCapture(rd.ReplayOptions(), None)

    if status != ResultCode.Succeeded:
        if os.path.exists(RENDERDOC_DEBUG_FILE):
            print(open(RENDERDOC_DEBUG_FILE, "r").read(), file=sys.stderr)
        raise RuntimeError("Couldn't initialise replay: " + str(status))

    return cap, controller


def get_snapshot_action(controller):
    """Find the last root action that has a non-null color output."""
    try:
        actions = list(controller.GetRootActions())
    except AttributeError:
        actions = list(controller.GetDrawcalls())

    for action in reversed(actions):
        if action.outputs[0] != rd.ResourceId.Null():
            return action

    raise RuntimeError("No action with color output found in capture")


def dump_snapshot(controller, action, output_path):
    controller.SetFrameEvent(action.eventId, True)

    texsave = rd.TextureSave()
    texsave.resourceId = action.outputs[0]

    # Most formats can only display a single image per file, so we select the
    # first mip and first slice
    texsave.mip = 0
    texsave.slice.sliceIndex = 0

    # For formats with an alpha channel, preserve it
    texsave.alpha = rd.AlphaMapping.Preserve
    texsave.destType = rd.FileType.PNG
    controller.SaveTexture(texsave, str(output_path))

    print("Wrote " + str(output_path))


def main():
    parser = argparse.ArgumentParser(
        description='Dump snapshot images from a renderdoc capture')
    parser.add_argument('file_path', help='path to the trace file')
    parser.add_argument(
        'output_dir', help='directory in which to place the results')
    parser.add_argument('--loops', type=int, default=1,
                        help='number of snapshot captures (default 1)')
    args = parser.parse_args()

    rd.InitialiseReplay(rd.GlobalEnvironment(), [])

    cap, controller = load_capture(args.file_path)
    action = get_snapshot_action(controller)

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    for i in range(args.loops):
        output_path = output_dir / f"snapshot{i + 1:04d}.png"
        dump_snapshot(controller, action, output_path)

    cap.Shutdown()
    rd.ShutdownReplay()


if __name__ == '__main__':
    main()
