using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.UIElements;
namespace GrassCutter
{
///
/// Off-screen screenshots for the dev bots. The main camera and the UI panel render into textures that we
/// composite and save, so the game can run with -batchmode (no window, no focus or mouse stealing).
///
public static class BotCapture
{
static RenderTexture _scene, _ui;
static Camera _cam;
static Texture2D _read;
public static bool Enabled => _scene != null;
/// The next shots look from here instead of through the player's eyes.
public static (Vector3 at, Vector3 target)? From;
public static void Setup(int w, int h)
{
if (_scene) return;
_scene = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotScene", antiAliasing = 1 };
_ui = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB) { name = "BotUI" };
_scene.Create(); _ui.Create();
var cam = CameraFx.Cam ? CameraFx.Cam : Camera.main;
if (cam) cam.targetTexture = _scene;
_cam = cam;
var doc = Object.FindAnyObjectByType();
if (doc && doc.panelSettings)
{
doc.panelSettings.targetTexture = _ui;
doc.panelSettings.clearColor = true;
doc.panelSettings.colorClearValue = new Color(0, 0, 0, 0);
}
Application.targetFrameRate = 60;
Debug.Log($"[BotCapture] off-screen capture {w}x{h} (batchmode={Application.isBatchMode})");
}
///
/// What a frame really costs: render by hand and wait for the GPU to finish it (a -batchmode player draws nothing
/// on its own, so frames per second there say nothing). Hands back the mean milliseconds.
///
public static IEnumerator FrameCost(int frames, System.Action done)
{
if (!Enabled || !_cam) { done(0f); yield break; }
var one = new Texture2D(1, 1, TextureFormat.RGBA32, false, false);
var clock = new System.Diagnostics.Stopwatch();
for (int i = 0; i < frames; i++)
{
yield return new WaitForEndOfFrame();
clock.Start();
_cam.targetTexture = _scene;
_cam.Render();
var prev = RenderTexture.active;
RenderTexture.active = _scene;
one.ReadPixels(new Rect(0, 0, 1, 1), 0, 0, false);
RenderTexture.active = prev;
clock.Stop();
}
Object.Destroy(one);
done((float)clock.Elapsed.TotalMilliseconds / frames);
}
/// Saves the current frame (scene + UI) as PNG. Falls back to a normal screenshot if not set up.
public static IEnumerator Shot(string path)
{
yield return new WaitForEndOfFrame();
Directory.CreateDirectory(Path.GetDirectoryName(path));
if (!Enabled) { ScreenCapture.CaptureScreenshot(path); yield break; }
// a -batchmode player never renders cameras on its own (UI Toolkit panels still update), so render by hand
if (Application.isBatchMode && _cam)
{
Vector3 eye = _cam.transform.position;
Quaternion turn = _cam.transform.rotation;
if (From is (Vector3, Vector3) f) _cam.transform.SetPositionAndRotation(f.at, Quaternion.LookRotation(f.target - f.at, Planet.Up(f.at)));
_cam.targetTexture = _scene;
_cam.Render();
_cam.transform.SetPositionAndRotation(eye, turn);
}
int w = _scene.width, h = _scene.height;
if (!_read) _read = new Texture2D(w, h, TextureFormat.RGBA32, false, false);
var scene = Read(_scene, w, h);
// `-clean`: the world alone as well, for the store page
if (CommandLine.Has("-clean")) Save(Path.ChangeExtension(path, null) + "_clean.png", scene);
var ui = Read(_ui, w, h);
// UI is rendered over transparent black, i.e. premultiplied: out = ui + scene * (1 - ui.a)
for (int i = 0; i < scene.Length; i++)
{
var u = ui[i];
if (u.a == 0) continue;
var s = scene[i];
float k = 1f - u.a / 255f;
scene[i] = new Color32((byte)Mathf.Min(255, u.r + s.r * k), (byte)Mathf.Min(255, u.g + s.g * k), (byte)Mathf.Min(255, u.b + s.b * k), 255);
}
Save(path, scene);
Debug.Log("[BotCapture] " + path);
}
static void Save(string path, Color32[] pixels)
{
_read.SetPixels32(pixels);
_read.Apply();
File.WriteAllBytes(path, _read.EncodeToPNG());
}
static Color32[] Read(RenderTexture rt, int w, int h)
{
var prev = RenderTexture.active;
RenderTexture.active = rt;
_read.ReadPixels(new Rect(0, 0, w, h), 0, 0, false);
_read.Apply();
RenderTexture.active = prev;
return _read.GetPixels32();
}
}
}