using System.Diagnostics; using System.Globalization; using System.Text.RegularExpressions; using EvilEngine.Client.Audio; using EvilEngine.Formats; using EvilEngine.Formats.Records; using EvilEngine.Host; using EvilEngine.Host.Sessions; using EvilEngine.Host.Steps; using EvilEngine.Shared; using EvilEngine.Shared.Sessions; using EvilEngine.Shared.World; using Godot; namespace EvilEngine.Client.World; public partial class MapShot : Node { public override async void _Ready() { var args = OS.GetCmdlineUserArgs() .Select(arg => arg.Split('=', 2)) .Where(pair => pair.Length == 2) .ToDictionary(pair => pair[0], pair => pair[1]); var code = await Run(args); GetTree().Quit(code); } private async Task Run(Dictionary args) { var output = args.GetValueOrDefault("--screenshot"); var shots = args.GetValueOrDefault("--shots"); var bench = args.ContainsKey("--bench"); var frames = args.GetValueOrDefault("--frames"); if (!args.TryGetValue("--map", out var id) || new[] { output is not null, shots is not null, bench, frames is not null }.Count(given => given) != 1) { GD.PrintErr( "MapShot needs --map= and one of --bench=1 to time the map's start as Start runs it, entering it and drawing its first frame, --screenshot= with --at=x,y,z, --look=pitch,yaw and --fov, or --shots= of 'name x y z pitch yaw fov' lines with --out=, or --frames= of the same lines to measure each view uncapped, its draw calls, objects, primitives and rendering's CPU and GPU time, and takes --size=WxH, --exposure= to hold the tonemap scale, --bloom=0 to leave bloom out, --remastered=liquids to draw every liquid through evil:shaders/liquid, --sky= to show another sky, --lighting=baked|realtime to light it as a server would, each of gi, ao, ssil, ssr, fog and bloom after a + turning it on or a - off (like realtime+ssr-fog), and --walk=:,... to spawn the walking player and hold each set of keys (like W+Shift) for its seconds, facing the yaw after an @ if one is given, with kill as a step's keys running the kill command, --bots= to join that many bots, --playerclass= to live as that player class, --view=body|first|third to look through that view mode, and --spawn=[@x,y,z];... to spawn each model as a prop where the player aims or at the point, before the screenshot."); return 2; } var boot = await EngineBoot.Start(line => GD.Print(line.ToString())); AudioManager.Instance?.Attach(boot.Host.Conversion, id => boot.Registry.Sound(id)); if (boot.Registry.Map(ContentId.Parse(id)) is not { } map) { GD.PrintErr($"No map record {id}."); return 1; } var clock = Stopwatch.StartNew(); void Line(TranscriptTag tag, string text) { GD.Print(new TranscriptLine(clock.Elapsed, tag, text).ToString()); } var walk = args.GetValueOrDefault("--walk"); var size = (args.GetValueOrDefault("--size") ?? "1920x1080").Split('x').Select(int.Parse).ToArray(); GetWindow().Size = new Vector2I(size[0], size[1]); var (world, times) = await Task.Run(() => MapStart.Build(boot.Host.Conversion, map, Line, walk is not null || bench || shots is not null, args.GetValueOrDefault("--remastered") == "liquids")); if (world is null) return 1; if (bench) return await Bench(world, map.Id.ToString(), times, clock); if (args.GetValueOrDefault("--lighting") is { } lit) world.ShowLighting(Lighting(lit)); await world.Enter(this); if (args.GetValueOrDefault("--sky") is { } skyId) { var record = boot.Registry.Sky(ContentId.Parse(skyId)); var (look, problem) = await Task.Run(() => world.Look(boot.Host.Conversion, record?.Sky ?? ContentId.Parse(skyId))); if (look is null) { GD.PrintErr($"{skyId} didn't convert: {problem}"); return 1; } world.ShowSky(look); } if (walk is not null && world.Hulls is not null && output is not null) { var bots = int.Parse(args.GetValueOrDefault("--bots") ?? "0", CultureInfo.InvariantCulture); var life = args.GetValueOrDefault("--playerclass") is { } named ? boot.Registry.PlayerClass(ContentId.Parse(named)) ?? throw new ArgumentException($"No player class {named}.") : EnginePlayers.Default; var (server, client) = LocalServer.Play(world.SessionStart(map.Id, boot.Registry.Surface) with { Seed = 1, People = boot.Registry.Playermodels().ToArray(), Movements = boot.Registry.Movements, MaxPlayers = 1 + bots, PlayerClass = life, Flashlight = args.GetValueOrDefault("--flashlight") is { } beam ? FlashlightSettings(beam) : ServerFlashlight.Default, StepSounds = StepSounds.From(boot.Registry, boot.Host.Conversion) }, "MapShot"); for (var bot = 0; bot < bots; bot++) server.Session.AddBot(); var player = new PlayerCamera(client) { View = args.GetValueOrDefault("--view") switch { "first" => ViewMode.First, "third" => ViewMode.Third, _ => ViewMode.Body } }; world.AddChild(player); var bodies = new WorldBodies(client, boot.Host.Conversion, boot.Registry.Person) { DrawOwn = () => player.DrawsOwnBody }; player.Dressing = bodies.Dressing; world.AddChild(bodies); var props = new WorldProps(client, boot.Host.Conversion); world.AddChild(props); var sounds = new WorldSounds(client, bodies); world.AddChild(sounds); var ambience = new WorldAmbience(world, boot.Registry.Soundscape); world.AddChild(ambience); var flashlights = new WorldFlashlights(client) { OwnAim = () => player.Aim }; world.AddChild(flashlights); if (args.GetValueOrDefault("--exposure") is { } fixedExposure) world.ForceExposure(double.Parse(fixedExposure, CultureInfo.InvariantCulture)); if (args.GetValueOrDefault("--spawn") is { } spawning) { while (client.State != ClientState.Active || client.Controlled is null) await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); foreach (var spawn in spawning.Split(';', StringSplitOptions.RemoveEmptyEntries)) { var parts = spawn.Split('@'); client.Command(parts.Length > 1 ? $"{ServerSession.SpawnCommand} {parts[0]} {parts[1].Replace(',', ' ')}" : $"{ServerSession.SpawnCommand} {parts[0]}"); } } var steps = walk.Split(',', StringSplitOptions.RemoveEmptyEntries); var hold = args.ContainsKey("--hold"); foreach (var step in steps) { var timing = step.Split(':')[1].Split('@'); var (keys, seconds) = (step.Split(':')[0], double.Parse(timing[0], CultureInfo.InvariantCulture)); if (timing.Length > 1) player.Look(0, double.Parse(timing[1], CultureInfo.InvariantCulture)); if (keys == ServerSession.Kill) client.Command(ServerSession.Kill); var held = keys.Split('+', StringSplitOptions.RemoveEmptyEntries) .Where(key => key is not "-" and not ServerSession.Kill).Select(key => Enum.Parse(key, true)) .ToArray(); foreach (var key in held) Input.ParseInputEvent(new InputEventKey { PhysicalKeycode = key, Keycode = key, Pressed = true }); await ToSignal(GetTree().CreateTimer(seconds), SceneTreeTimer.SignalName.Timeout); if (!hold || !ReferenceEquals(step, steps[^1])) foreach (var key in held) Input.ParseInputEvent(new InputEventKey { PhysicalKeycode = key, Keycode = key, Pressed = false }); if (client.Controlled is { } body) GD.Print( $"walk {keys} {seconds} s: {body.Body} at {body.Feet}, moving {body.Velocity}, {(body.OnGround ? "on the ground" : "in the air")}{(body.Crouched ? ", crouched" : "")}, facing {body.Yaw}, {body.Health} health as {body.Look.Person?.ToString() ?? "nobody"}"); else if (client.OwnBody is { } dead) GD.Print($"walk {keys} {seconds} s: dead, {dead.Body} lying at {dead.Feet}"); GD.Print( $"walk {keys} {seconds} s: {sounds.Heard} sounds heard, {AudioManager.Instance?.Started ?? 0} started, {AudioManager.Instance?.Placed ?? 0} placed now, {flashlights.Lit} flashlights lit"); GD.Print( $"walk {keys} {seconds} s: soundscape {ambience.Playing?.ToString() ?? "none"}, {ambience.Loops} loops, {ambience.Randoms} random sets, {ambience.RandomsPlayed} random sounds played, {AudioManager.Instance?.Playing.Count(voice => voice.Record.Branch == SoundBranch.Ambience) ?? 0} playing on Ambience"); foreach (var prop in client.Props) GD.Print( $"walk {keys} {seconds} s: prop {prop.Prop} {prop.Model} at {prop.Position} turned {prop.Orientation} moving {prop.Velocity}{(prop.Asleep ? ", asleep" : "")}, {props.Drawn} drawn"); foreach (var other in client.Bodies.Where(other => other.Body != client.Own?.Body)) GD.Print( $"walk {keys} {seconds} s: {other.Body} of {other.Owner} at {other.Feet} facing {other.Yaw} as {other.Look.Person?.ToString() ?? "nobody"}, {(other.Alive ? "alive" : "dead")}, {bodies.Drawn} drawn"); } await Shoot(player, output); server.Stop("MapShot is done."); return 0; } var camera = new Camera3D { Transform = world.Spawn, Near = 0.05f, Far = 4000, Fov = float.Parse(args.GetValueOrDefault("--fov") ?? "75", CultureInfo.InvariantCulture) }; world.AddChild(camera); camera.MakeCurrent(); if (args.GetValueOrDefault("--exposure") is { } forced) world.ForceExposure(double.Parse(forced, CultureInfo.InvariantCulture)); if (args.GetValueOrDefault("--bloom") == "0") world.DropBloom(); if (frames is not null) { await Frames(camera, world, frames); return 0; } if (shots is null) { if (Numbers(args.GetValueOrDefault("--at")) is [var x, var y, var z]) camera.Position = new Vector3(x, y, z); if (Numbers(args.GetValueOrDefault("--look")) is [var pitch, var yaw]) camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(pitch), Mathf.DegToRad(yaw), 0)); await Shoot(camera, output!); return 0; } var folder = args.GetValueOrDefault("--out") ?? Path.GetDirectoryName(Path.GetFullPath(shots))!; var heard = new WorldAmbience(world, boot.Registry.Soundscape); world.AddChild(heard); foreach (var shot in File.ReadAllLines(shots) .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Where(parts => parts.Length == 7)) { var n = shot[1..].Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray(); camera.Position = new Vector3(n[0], n[1], n[2]); camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(n[3]), Mathf.DegToRad(n[4]), 0)); camera.Fov = n[5]; await Shoot(camera, Path.Combine(folder, shot[0] + ".png")); if (world.Ambience.Count > 0) GD.Print( $"shot {shot[0]}: soundscape {heard.Playing?.ToString() ?? "none"}, {heard.Loops} loops, {heard.Randoms} random sets, {heard.RandomsPlayed} random sounds played, {AudioManager.Instance?.Playing.Count(voice => voice.Record.Branch == SoundBranch.Ambience) ?? 0} playing on Ambience"); } return 0; } private async Task Bench(MapWorld world, string id, MapStartTimes times, Stopwatch clock) { var entering = clock.Elapsed; await world.Enter(this); if (world.Hulls is not null) world.AddChild(new PlayerCamera(LocalServer .Play(world.SessionStart(ContentId.Parse(id)) with { Seed = 1 }, "MapShot").Client)); else world.AddChild(new FreeCamera { Transform = world.Spawn }); var entered = clock.Elapsed; await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); var drawn = clock.Elapsed; var frames = new List(); for (var frame = 0; frame < 60; frame++) { var from = clock.Elapsed; await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); frames.Add((clock.Elapsed - from).TotalMilliseconds); } var waits = times.WaitCount == 0 ? "no waits" : $"{times.WaitCount:N0} waits for {times.Waited.TotalSeconds:0.00} s ({string.Join(", ", times.Waits.Take(3).Select(wait => $"{wait.Where} {wait.Count:N0}x {wait.Took.TotalMilliseconds:0} ms"))})"; GD.Print(string.Create(CultureInfo.InvariantCulture, $"bench {id}: load {times.Load.TotalSeconds:0.000} s, collision {times.Collision.TotalSeconds:0.000} s, world {times.World.TotalSeconds:0.000} s with {waits}, enter {(entered - entering).TotalSeconds:0.000} s, first frame {(drawn - entered).TotalSeconds:0.000} s, start to first frame {drawn.TotalSeconds:0.000} s, slowest of the next 60 frames {frames.Max():0.0} ms")); foreach (var wait in times.Waits) GD.Print(string.Create(CultureInfo.InvariantCulture, $"bench wait {wait.Where}: {wait.Count:N0}x, {wait.Took.TotalMilliseconds:0.0} ms, of which Godot's worker pool {wait.PoolCount:N0}x, {wait.PoolTook.TotalMilliseconds:0.0} ms")); return 0; } private async Task Frames(Camera3D camera, MapWorld world, string file) { DisplayServer.WindowSetVsyncMode(DisplayServer.VSyncMode.Disabled); Engine.MaxFps = 0; var viewports = new List { GetViewport().GetViewportRid() }; viewports.AddRange(world.FindChildren("*", nameof(SubViewport), true, false).Cast() .Select(view => view.GetViewportRid())); foreach (var viewport in viewports) RenderingServer.ViewportSetMeasureRenderTime(viewport, true); foreach (var shot in File.ReadAllLines(file) .Select(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) .Where(parts => parts.Length == 7)) { var n = shot[1..].Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray(); camera.Position = new Vector3(n[0], n[1], n[2]); camera.Basis = Basis.FromEuler(new Vector3(Mathf.DegToRad(n[3]), Mathf.DegToRad(n[4]), 0)); camera.Fov = n[5]; for (var frame = 0; frame < 60; frame++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); var samples = new List(); for (var frame = 0; frame < 240; frame++) { await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); double Info(Rid viewport, RenderingServer.ViewportRenderInfoType type, RenderingServer.ViewportRenderInfo info) { return RenderingServer.ViewportGetRenderInfo(viewport, type, info); } const RenderingServer.ViewportRenderInfo calls = RenderingServer.ViewportRenderInfo.DrawCallsInFrame; const RenderingServer.ViewportRenderInfoType visible = RenderingServer.ViewportRenderInfoType.Visible; const RenderingServer.ViewportRenderInfoType shadow = RenderingServer.ViewportRenderInfoType.Shadow; samples.Add([ Info(viewports[0], visible, calls), Info(viewports[0], shadow, calls), viewports.Skip(1).Sum(view => Info(view, visible, calls) + Info(view, shadow, calls)), Info(viewports[0], visible, RenderingServer.ViewportRenderInfo.ObjectsInFrame), viewports.Sum(view => Info(view, visible, RenderingServer.ViewportRenderInfo.PrimitivesInFrame) + Info(view, shadow, RenderingServer.ViewportRenderInfo.PrimitivesInFrame)), RenderingServer.GetFrameSetupTimeCpu() + viewports.Sum(RenderingServer.ViewportGetMeasuredRenderTimeCpu), viewports.Sum(RenderingServer.ViewportGetMeasuredRenderTimeGpu) ]); } double Median(int column) { var sorted = samples.Select(sample => sample[column]).Order().ToArray(); return sorted[sorted.Length / 2]; } GD.Print(string.Create(CultureInfo.InvariantCulture, $"frames {shot[0]}: {Median(0) + Median(1) + Median(2):0} draw calls ({Median(0):0} in view, {Median(1):0} for its shadows, {Median(2):0} in {viewports.Count - 1} other views), {Median(3):0} objects in view, {Median(4) / 1000:0} k primitives, rendering {Median(5):0.00} ms of CPU and {Median(6):0.00} ms of GPU")); } } private async Task Shoot(Camera3D camera, string output) { var world = camera.GetParent() as MapWorld; world?.SettleExposure(); for (var frame = 0; frame < 8 || (world is { ExposureSettled: false } && frame < 240); frame++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); for (var frame = 0; frame < 4; frame++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); var image = GetViewport().GetTexture().GetImage(); Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))!); image.SavePng(output); GD.Print( $"Saved {output} from {camera.Position}, looking {camera.Basis.GetEuler() * (180 / Mathf.Pi)}, exposure {world?.Exposure?.Scale ?? 1:0.000}"); } private static float[]? Numbers(string? text) { return text?.Split(',').Select(part => float.Parse(part, CultureInfo.InvariantCulture)).ToArray(); } private static ServerFlashlight FlashlightSettings(string text) { var flashlight = ServerFlashlight.Default; foreach (var pair in text.Split(',', StringSplitOptions.RemoveEmptyEntries)) { var (key, value) = (pair.Split('=')[0], pair.Split('=').ElementAtOrDefault(1) ?? ""); double Number() => double.Parse(value, CultureInfo.InvariantCulture); flashlight = key switch { "range" => flashlight with { Range = Number() }, "angle" => flashlight with { Angle = Number() }, "intensity" => flashlight with { Intensity = Number() }, "falloff" => flashlight with { Falloff = Number() }, "colour" when Color.HtmlIsValid(value) => flashlight with { Colour = ServerSettings.Vector(Color.FromHtml(value)) }, "cookie" => flashlight with { Cookie = value != "0" }, "click" => flashlight with { Click = value != "0" }, _ => throw new ArgumentException($"--flashlight has no {pair}.") }; } return flashlight; } private static ServerLighting Lighting(string text) { var parts = Regex.Split(text, "(?=[+-])"); var lighting = new ServerLighting { Mode = parts[0] switch { "baked" => LightingMode.Baked, "realtime" => LightingMode.Realtime, _ => throw new ArgumentException($"--lighting takes baked or realtime, not {parts[0]}.") } }; foreach (var part in parts.Skip(1)) { var on = part[0] == '+'; lighting = part[1..] switch { "gi" => lighting with { GlobalIllumination = on }, "ao" => lighting with { AmbientOcclusion = on }, "ssil" => lighting with { IndirectLight = on }, "ssr" => lighting with { Reflections = on }, "fog" => lighting with { Fog = on }, "bloom" => lighting with { Bloom = on }, _ => throw new ArgumentException($"--lighting has no {part[1..]}.") }; } return lighting; } }