diff --git a/README.md b/README.md index 6226ca8..0532907 100644 --- a/README.md +++ b/README.md @@ -64,43 +64,51 @@ session, `BodyPainBoxSession` (create, `Step`, read `Hand` and the world's lanes `client/` is a Godot 4.7.2 (mono) project that renders the body run and takes the player's commands: the Synaptic Induction Chamber, the dummy strapped to a stool with its right hand in the box. It owns presentation and input only. Godot's physics engine is set to Dummy; each 120 Hz physics frame the client calls -`BodyPainBoxSession.Step()` once and draws Ymir's lanes: one pose-carrying node per stable id, and the body drawn as one -skinned SDF mesh (a surface-nets isosurface of the shape lanes, limbs smooth-blended into the body they hang from and -joined by a ball at each joint, built once at startup and rebuilt only when the bodies or joints change; skinned on the CPU every frame by `PuppetSkin`, which derives the facets, creases, vertex normals and altitudes from the skinned surface; flat-shaded, each edge softened by a bevel 2 px wide (`Look.BevelScreen`, at least `Look.BevelMin`, question lodur:question:bds-puppet-bevel-look-width): the fragment shader tilts the facet normal to each edge's bisector and blends corners to the vertex normal). The puppet is glazed porcelain: a bisque lit by a studio (a shadowing key and two rims, `Look.Studio`) that the camera carries (lodur:ruling:porcelain-studio-follows-camera), plus an analytic glaze that reflects the same studio (`client/studio.gdshaderinc`, Fresnel times the studio in the reflected direction, added as emission so it draws the same under gl_compatibility), pooled darker in concave creases. The highlights are prefiltered where the shader decides them (geometric specular antialiasing, Tokuyoshi and Kaplanyan 2021): the spread of the shading normal over a pixel widens the studio the glaze reads, so a highlight does not crawl as the camera moves; the 3D draws with MSAA 4x (`rendering/anti_aliasing/quality/msaa_3d`) for silhouettes and triangle edges. +`BodyPainBoxSession.Step()` once and draws Ymir's lanes: one pose-carrying node per stable id (`BodyRenderer`), each holding its body's own +primitive (a capsule, box or sphere of the lane's size; the figure is a placeholder of primitives until the anatomy meshes come). The look is +PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy): every surface is `ps1.gdshader` (vertices snapped to the line grid, affine texture +coordinates, unfiltered texels, light, glow and fog per vertex, in raw sRGB arithmetic), and `ps1_post.gdshader` on a full-screen rect under the +HUD quantises the frame to one colour per block of a 240-line grid (`Look.Lines`, blocks of round(H / 240) pixels anchored at the screen centre) +in 15-bit colour with the 4x4 ordered dither. No `Light3D` exists: the shader lights the scene from the globals `ps1_*` (`project.godot` +`[shader_globals]`), which `Look` (constants), `Main` (`ps1_res`) and `Chamber` (the glow light, 0.9 m range) write. Needs the .NET 8+ SDK, cmake and a C compiler (MinGW gcc on Windows), the sibling Lodur, Ymir (with joint origin lanes, ABI 8) and CultLib -checkouts (`..\Lodur`, `..\Ymir`, `..\CultLib`, or `LODUR_ROOT`, `YMIR_ROOT` and `CULTLIB_ROOT`; CultLib must be a clean checkout of +checkouts Ymir builds against (`..\Lodur`, `..\Ymir`, `..\CultLib`, or `LODUR_ROOT`, `YMIR_ROOT` and `CULTLIB_ROOT`; CultLib must be a clean checkout of 42dce361, the revision Ymir admits, or the build refuses), and Godot 4.7.2 mono. ``` -dotnet build client/BadDay.Client.csproj # CultLib Geometry, Lodur, Ymir (cmake) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug +dotnet build client/BadDay.Client.csproj # Lodur, Ymir (cmake, CultLib) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug --path client # play: Blender's navigation: middle-drag orbits the puppet, Shift+middle-drag pans, Ctrl+middle-drag and the wheel zoom; Alt+left-drag stands for the middle button (OrbitCamera.Emulate3ButtonMouse) --headless --path client res://tests/Smoke.tscn # the smoke; exit code 0 passes - --path client res://tests/RenderCheck.tscn # the render check, in a window (not headless); exit code 0 passes + --path client res://tests/RenderCheck.tscn # the render check, in a window (not headless); exit code 0 passes; -- --frames= keeps its frames +bash client/tests/render-mutants.sh # breaks the look once per claim; each break must fail its line ``` Or open `client/project.godot` in the Godot editor, Build, Play. The HUD has Reset with a seed, a live intensity slider, Box off and Slow motion. Do not run `godot --import` on a fresh checkout; a plain run creates `.godot`. Exports need export templates (not installed here yet), so the client runs from the editor and headless for now. -The smoke has no renderer. `RenderCheck.tscn` is the check that does: it poses the puppet in a bent pose under a moved parent, renders one frame -(gl_compatibility, the client's renderer), and compares the drawn silhouette with the mesh skinned on the CPU (intersection over union, at -least 0.999: a correct render measures 1.0000, and a forearm bone 10 degrees off, a bone 2 cm off and hard weights fail), and checks the bisque (the glaze off) is not clipped to white and that the chamber's light still lights it (a glow of 0 fails); with the glaze on at the close view, from the front and from behind, the glaze must change at least 3% of the puppet's pixels and, from the front, clip at most 12% (add `-- --glaze-png=` or `--glaze-behind-png=`). It also draws the shading normal (the soft bevel) on the torso and compares it with a CPU reference of the whole formula, skinned, welded and derived by the check itself, in five views: close up and from 3.7 m at 1280x720, close up in a bend of 90 degrees, and at 1920x1080 from 2.2 m and from 3.7 m (so a width fixed at 720 lines fails). In each: 90th percentile error at most 2 degrees, 0.6 across the bevel band, 1.5 on triangles whose width the smallest altitude caps, at most 0.7 on the pixels the corner blend reaches (the smooth vertex normal, in view space, within 1.5 widths of a corner) and at most 1.5 on the band of edges turning by 115 to 137 degrees (a bevel that is off, a stale crease, a linear falloff, a missing edge strip or width cap, the wrong width, a vertex normal left in model space, a shorter corner reach and a lower crease clamp fail). The drawn normals across triangle boundaries stay continuous: at most 0.5% of adjacent pixel pairs over 30 degrees at a bend of 60 degrees and 3% at 90, where some edges fold past 120 degrees and 2 px cannot soften them. The oracle frames above are drawn with MSAA off (they check the shader's own pixels). Last, the flicker check draws the glaze with the project's MSAA from 16 sub-pixel camera shifts in seven framings in the pose the player sees (five at 2.4 m, FOV 55, the first being where the orbit camera starts, and two at 0.7 m) and in three of them with the puppet bent 30 and 60 degrees, against the same shifts drawn 8 times the window's size, MSAA off, and box-filtered down in linear light. On the pixels the puppet covers fully, the 99th percentile of the per-pixel luma standard deviation over the shifts must stay within 1.45 (1.33 close) times the reference's and the mean luma of the reference's highlights (245 or more) within 1.5 levels of the reference's (a glaze that crawls, or one blurred away, fails); on the silhouette's ring the mean distance from the reference must stay under 22 levels (the 3D without MSAA fails); and under a slow orbit (30 frames of 0.15 degrees at the shipped framing) the error against the reference, differenced twice in time over the halo of the highlights, must average at most 8 levels (the shipped glaze 5.6, an unfiltered one 10.5). The whole check takes about 2 minutes on a GTX 1070. Add `-- --png=`, `-- --normals-png=` or `-- --normals-far-png=` (also `--normals-bend90-png=`, `--normals-mid-png=`, `--normals-far1080-png=`) to keep a frame. It needs a display. -Known gap: the culling box. `Puppet` sets the mesh's `CustomAabb` to the skinned bounds every frame; a 1 cm box at the origin or at the centre culls the puppet in the close view and fails, but a box of half the bounds around the centre passes, since it only drops limbs where the box leaves the screen, which no view samples. +The smoke has no renderer. `RenderCheck.tscn` is the check that does: it renders real frames (gl_compatibility, the client's renderer at 1280x720) +of seed 1 stopped at a pinned tick and reads them back, so every reading is the same run to run. It checks that every channel is a multiple of 8 (15-bit +colour), that every block of the grid is one colour, that a probe box's drawn blocks are those of its hull with the corners snapped to a coarse grid (the +unsnapped hull differs in 8 blocks), that the texel runs of a checker triangle seen at 60 degrees keep equal widths along a scanline (affine), that the +chamber at full glow lights the figure by at least 1.2 levels over dark, and that each dynamic body's lane origin projects onto a figure pixel. Bounds sit +at the midpoint of the shipped worst and the least claimed mutant (`lodur:ruling:deterministic-bound-margin`), each stated in its comment; +`client/tests/render-mutants.sh` applies one edit per claim (post off, per-pixel blocks, snap off, perspective-correct UVs, glow unwritten, carriers +unposed) and wants that claim's line to fail. It needs a display. ### Who owns what (the map) -The client's puppet pipeline, one owner per decision (the paragraphs above say how it looks; this says who may write what): +The client's drawing pipeline, one owner per decision (the paragraphs above say how it looks; this says who may write what): | Owner | Inputs | Outputs | Derived state | Forbidden writers | |---|---|---|---|---| | Ymir (the session's world, ABI 8) | the session's commands and Lodur's torque lanes | pose, shape, stable-id and joint lanes, including each joint's origin in the world (the joint origin lanes) | none the client keeps | the client writes no lane; Ymir never reads the client | -| `PuppetField` (`Build`: the mesher, untangle included) | shape bodies (id, kind, size, bind pose), qualifying joints (kind, body A, body B, origin in A's frame), the `Look` blend constants, the cell | `PuppetShape`: the welded vertices (each once, with its two bones and weight), triangles as `Corners`, edge pairing as `Across`, the untangle's `Pulled` and `OffSurface` | nothing: a pure, engine-free function of its inputs | anything that reads lanes, Godot types, a call per frame | -| `PuppetModel` | `Box3DSoaView` (kind, size, stable id, pose, joint kind, bodies and origins), read by `Lanes` | the current `PuppetShape`, and whether this update rebuilt it | the bind (each body's pose the first time it is seen), each joint's origin kept in body A's frame from the origin lane at first sight, the topology signature (ordered id, kind and size of the shape bodies; ordered kind, A and B of the qualifying joints) | `Puppet` or the scene deciding when to rebuild; a pose or an origin alone causing a rebuild | -| `PuppetSkin` (one per shape) | the shape and one `Rigid` per bone, every frame | `Skinned`, `Facet`, `Crease`, `VertexNormal`, `Altitude`, `SmallestAltitude`, `Lo` and `Hi` | all of it, every frame, from the deformed surface; nothing kept from the bind; buffers allocated once | the shader, `Puppet` or RenderCheck deriving a facet, crease, vertex normal or distance of their own | -| `Puppet` | the lanes (a carrier per stable id, posed each physics frame), the model's shape, the skin's arrays | the Godot mesh (two streams uploaded in place each frame), `CustomAabb`, `MeshBuilds` | the build counter, the client's only one: it counts Godot mesh builds | geometry derived here; a second build counter; writing a lane | -| `puppet.gdshader` | `CUSTOM0..3` (altitudes, creases, facet normal, vertex normal), `Look.BevelScreen` and `BevelMin` | the shading normal (the bevel) and the colour | none | skinning, evaluating the SDF, owning a width or a crease | -| `tests/RenderCheck.cs` (the windowed oracle), `PuppetChecks.cs`, `Smoke.cs` | the same lanes through the real renderer, and an independent CPU reference of the whole bevel | an exit code, optional PNGs | none | writing the puppet's state; sharing `PuppetSkin`'s derivation (the reference derives its own) | +| `BodyRenderer` | the lanes (kind, size, stable id, pose), each physics frame | one carrier per stable id with one primitive `MeshInstance3D`; `PoseOf`, `InterpolatedPoseOf`, `PuppetCentre` (the union of the dynamic bodies' carrier-placed primitive boxes), `MeshBuilds` | `MeshBuilds`, the smoke's counter: a Reset with the same ids makes no mesh | geometry derived from anything but the lane's size; writing a lane | +| `ps1.gdshader` | `Look`'s numbers and the `ps1_*` globals, the mesh's vertices, normals and UVs | every surface's colour: snapped vertices, affine texels, per-vertex light, glow and fog | none | skinning; a second light model; a `Light3D` | +| `ps1_post.gdshader` | the frame and `ps1_res` | the framebuffer at the line grid in 15-bit colour with the dither | none | a second resolution owner (viewport scaling, stretch mode, a SubViewport) | +| `Look`, `Main`, `Chamber` | `Look`: constants and textures; `Main`: the window size; `Chamber`: the box's intensity | `Look`: the constant globals and `Look.Ps1` materials; `Main`: `ps1_res` and the post layer; `Chamber`: `ps1_glow_*` | `ps1_res` is the window over `Look.BlockSize`, never set elsewhere | any other writer of a `ps1_*` global | +| `tests/RenderCheck.cs` (the windowed check), `render-mutants.sh`, `Smoke.cs` | the same lanes through the real renderer | an exit code, optional PNGs | none | writing the scene's state beyond pinning a tick and a probe | The scenarios, one owner per decision: diff --git a/client/tests/RenderCheck.cs b/client/tests/RenderCheck.cs new file mode 100644 index 0000000..faaafbd --- /dev/null +++ b/client/tests/RenderCheck.cs @@ -0,0 +1,342 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using BadDay.Core; +using BadDay.Ymir; +using Godot; +using Ymir.Box3D; + +namespace BadDay.Client.Tests; + +/// +/// The windowed check of the PS1 look: it renders real frames (gl_compatibility, the client's renderer) and reads them back. Every reading is +/// deterministic (seed 1, ticks pinned, physics frozen before a capture, probes drawn with the client's own materials), so a bound +/// sits at the geometric midpoint of the shipped worst and the least claimed mutant and needs at least 1.2 between them +/// (lodur:ruling:deterministic-bound-margin); tests/render-mutants.sh breaks the shipped code once per claim and wants that claim's line to fail. +/// godot --path client res://tests/RenderCheck.tscn [-- --frames=dir]; exit code 0 passes, 1 fails. It needs a window. +/// +public partial class RenderCheck : Node +{ + private const int Width = 1280, Height = 720; + private const double WatchdogSeconds = 120; + + private readonly List _failures = new(); + private Main _main = null!; + private OrbitCamera _camera = null!; + private string? _frames; + private bool _done; + + private BodyPainBoxSession Session => _main.Session; + private int Block => Look.BlockSize(Height); + + public override void _Ready() + { + foreach (var arg in OS.GetCmdlineUserArgs()) + if (arg.StartsWith("--frames=")) _frames = arg["--frames=".Length..]; + _ = RunAsync(); + } + + public override void _Process(double delta) + { + if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000) + { + Fail("watchdog", $"no result after {WatchdogSeconds} s"); + Finish(); + } + } + + private async Task RunAsync() + { + try + { + DisplayServer.WindowSetSize(new Vector2I(Width, Height)); + _main = GD.Load("res://Main.tscn").Instantiate
(); + AddChild(_main); + _camera = _main.GetNode("Camera"); + _main.Hud.Visible = false; // the HUD draws above the post pass: it is not the 3D's + Engine.PhysicsTicksPerSecond = 1200; + if (_main.Failure is { } failure) Fail("start", failure); + else await Scenario(); + } + catch (Exception e) + { + Fail("exception", e.ToString()); + } + Finish(); + } + + private async Task Scenario() + { + await Frames(3); + var window = GetWindow().Size; + if (window != new Vector2I(Width, Height)) { Fail("window", $"the window is {window}, not {Width}x{Height}"); return; } + + // The play view at tick 240 of seed 1. + await UntilTick(240); + _main.SetPhysicsProcess(false); // the run stops here; the carriers settle on its pose + await Frames(3); + var play = await Capture("play"); + + CheckFifteenBit(play); + CheckBlocks(play, Block); + CheckFigureWhereLanesAre(play); + + var home = _camera.Transform; + _camera.Distance = 0.9f; + await Frames(2); + await Capture("close"); + _camera.Transform = home; + + await CheckSnapAndAffine(); + await CheckGlow(); + } + + /// Every channel of every pixel is a multiple of 8: 15-bit colour, within one level of the 8-bit rounding. Bound 0; shipped 0, post off 1729077 channels. + private void CheckFifteenBit(Frame f) + { + int bad = 0; + for (int i = 0; i < f.Data.Length; i += 4) + for (int c = 0; c < 3; c++) + if (f.Data[i + c] % 8 is not (0 or 1 or 7)) bad++; + Report("15-bit", bad, 0); + Check(bad == 0, "15-bit", $"{bad} channels are not a multiple of 8"); + } + + /// Every block of the line grid, anchored at the screen centre, is one colour. Bound 0 pixels; shipped 0, sampling per pixel 218066. + private void CheckBlocks(Frame f, int s) + { + var seen = new Dictionary<(int, int), uint>(); + int bad = 0; + for (int y = 0; y < f.Height; y++) + for (int x = 0; x < f.Width; x++) + { + var key = (BlockOf(x, f.Width, s), BlockOf(y, f.Height, s)); + var colour = f.Rgb(x, y); + if (!seen.TryGetValue(key, out var first)) seen[key] = colour; + else if (first != colour) bad++; + } + Report("blocks", bad, 0); + Check(bad == 0, "blocks", $"{bad} pixels differ from the first pixel of their block"); + } + + /// Each dynamic body's lane origin, projected through the camera, lands on a figure pixel (skin is red over blue; floor, background and chamber are blue over red). Bound 0 misses; shipped 0, carriers left unposed 19. + private void CheckFigureWhereLanesAre(Frame play) + { + var view = Session.View; + var camera = GetViewport().GetCamera3D(); + int missed = 0, checkedBodies = 0; + for (int i = 0; i < view.Count; i++) + { + var kind = (Box3DSoaKind)view.Kind[i]; + if (kind is Box3DSoaKind.StaticBox or Box3DSoaKind.Anchor) continue; + var p = camera.UnprojectPosition(new Vector3(view.PositionX[i], view.PositionY[i], view.PositionZ[i])); + int x = (int)p.X, y = (int)p.Y; + checkedBodies++; + if (x < 0 || y < 0 || x >= Width || y >= Height || (play.Rgb(x, y) >> 16 & 0xff) < (play.Rgb(x, y) & 0xff) + 16) missed++; + } + Report("figure at lanes", missed, 0); + Check(checkedBodies > 5 && missed == 0, "figure at lanes", $"{missed} of {checkedBodies} dynamic bodies' origins are not on a figure pixel"); + } + + /// + /// The snap and the affine probes: the figure and floor are hidden and a probe is drawn with the client's own material under the client's camera. + /// Snap: a box on a 30-line grid (blocks of 24 px), its drawn blocks against the blocks the CPU-projected hull covers with its corners snapped to + /// that grid and with them not snapped. Affine: one triangle with a checker texture seen from 60 degrees, one scanline, the widths of its texel runs. + /// + private async Task CheckSnapAndAffine() + { + _main.Bodies.Visible = false; + _main.Chamber.Visible = false; + var home = _camera.Transform; + var res = _main.Ps1Res; + var probes = new Node3D(); + _main.AddChild(probes); + + // Snap. Blocks of 24 px; the pose is chosen so that snapping moves enough of the silhouette to count. + const int coarse = 24; + Look.Set("ps1_res", new Vector2(Width / (float)coarse, Height / (float)coarse)); + _camera.GlobalTransform = new Transform3D(Basis.Identity, new Vector3(0, 0, 3f)); + var box = new MeshInstance3D { Mesh = new BoxMesh { Size = new Vector3(1.2f, 0.8f, 0.6f) }, MaterialOverride = Look.Ps1(null, Colors.White, emissive: true) }; + box.Transform = new Transform3D(new Basis(Vector3.Up, 0.5f) * new Basis(Vector3.Right, 0.35f), new Vector3(0.13f, -0.07f, 0f)); + probes.AddChild(box); + await Frames(3); + var snapFrame = await Capture("snap"); + var corners = new List(); + foreach (var sx in new[] { -0.6f, 0.6f }) foreach (var sy in new[] { -0.4f, 0.4f }) foreach (var sz in new[] { -0.3f, 0.3f }) + corners.Add(_camera.UnprojectPosition(box.GlobalTransform * new Vector3(sx, sy, sz))); + var exact = Hull(corners); + var snapped = Hull(corners.Select(p => new Vector2(Width / 2f + coarse * MathF.Floor((p.X - Width / 2f) / coarse + 0.5f), Height / 2f - coarse * MathF.Floor(-(p.Y - Height / 2f) / coarse + 0.5f))).ToList()); + int offSnapped = 0, offExact = 0; + for (int by = BlockOf(0, Height, coarse); by <= BlockOf(Height - 1, Height, coarse); by++) + for (int bx = BlockOf(0, Width, coarse); bx <= BlockOf(Width - 1, Width, coarse); bx++) + { + var centre = new Vector2(Width / 2f + (bx + 0.5f) * coarse, Height / 2f + (by + 0.5f) * coarse); + bool drawn = snapFrame.Luma((int)centre.X, (int)centre.Y) > 128, wantSnapped = Inside(snapped, centre), wantExact = Inside(exact, centre); + if (drawn != wantSnapped) offSnapped++; + if (drawn != wantExact) offExact++; + } + // Bound 2 blocks: shipped worst 0, snap off 9 (a shipped worst of 0 counts as half a block: sqrt(0.5 x 9) = 2.1, separation 18). + Report("snap: blocks off the snapped hull", offSnapped, 2); + Report("snap: blocks off the unsnapped hull", offExact, 0); + Check(offSnapped <= 2, "snap", $"{offSnapped} blocks differ from the hull of the snapped corners (the unsnapped hull differs in {offExact})"); + Check(offExact >= 4, "snap", $"the pose does not tell snapping from not: the drawn blocks differ from the unsnapped hull in {offExact}"); + box.QueueFree(); + + // Affine. Full resolution, the camera at the triangle's base height so its base edge is the horizon row: a row 40 px above is a constant-height scanline. + Look.Set("ps1_res", new Vector2(Width, Height)); + _camera.GlobalTransform = new Transform3D(Basis.Identity, new Vector3(0, -0.6f, 3f)); + var checker = Image.CreateEmpty(2, 2, false, Image.Format.Rgb8); + checker.SetPixel(0, 0, Colors.White); checker.SetPixel(1, 1, Colors.White); checker.SetPixel(1, 0, Colors.Black); checker.SetPixel(0, 1, Colors.Black); + var arrays = new Godot.Collections.Array(); + arrays.Resize((int)Mesh.ArrayType.Max); + arrays[(int)Mesh.ArrayType.Vertex] = new[] { new Vector3(-1.6f, -0.6f, 0), new Vector3(-1.6f, 1.8f, 0), new Vector3(1.6f, -0.6f, 0) }; + arrays[(int)Mesh.ArrayType.Normal] = new[] { Vector3.Back, Vector3.Back, Vector3.Back }; + arrays[(int)Mesh.ArrayType.TexUV] = new[] { new Vector2(0, 0), new Vector2(0, 8), new Vector2(8, 0) }; + var mesh = new ArrayMesh(); + mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays); + var triangle = new MeshInstance3D { Mesh = mesh, MaterialOverride = Look.Ps1(ImageTexture.CreateFromImage(checker), Colors.White, emissive: true) }; + triangle.Transform = new Transform3D(new Basis(Vector3.Up, Mathf.DegToRad(60)), Vector3.Zero); + probes.AddChild(triangle); + await Frames(3); + var affineFrame = await Capture("affine"); + var runs = Runs(affineFrame, Height / 2 - 40); + float spread = runs.Count > 3 ? runs.Skip(1).Take(runs.Count - 2).Max() - runs.Skip(1).Take(runs.Count - 2).Min() : float.PositiveInfinity; + // Bound 8 px: shipped worst 1, perspective-correct UVs 67 (sqrt(1 x 67) = 8.2, separation 67). + Report("affine: spread of texel run widths in px (" + string.Join(" ", runs) + ")", spread, 8); + Check(runs.Count >= 6 && spread <= 8, "affine", $"texel runs along a scanline are {string.Join(" ", runs)} px wide (spread {spread}); an affine texture keeps them equal within 8"); + + probes.QueueFree(); + _camera.Transform = home; + Look.Set("ps1_res", res); + _main.Bodies.Visible = true; + _main.Chamber.Visible = true; + } + + /// + /// The chamber's light lights the figure: at tick 1 of seed 1 the chamber at full glow (box intensity 6) and dark (0), the bodies in the same + /// pose, the chamber's own volume hidden so only the light differs; the mean luma of the 300 px square about the held hand is higher + /// lit. Bound: half the shipped difference; a chamber whose light is not written reads 0. + /// + private async Task CheckGlow() + { + var means = new double[2]; + var poses = new List(); + for (int run = 0; run < 2; run++) + { + _main.SetPhysicsProcess(true); + _main.SetIntensity(run == 0 ? 6 : 0); + _main.Reset(1); + await UntilTick(1); + _main.SetPhysicsProcess(false); + await Frames(3); + _main.Chamber.Volume.Visible = false; + var frame = await Capture(run == 0 ? "glow-full" : "glow-off"); + _main.Chamber.Volume.Visible = true; + var hold = _camera.UnprojectPosition(new Vector3(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z)); + double sum = 0; int n = 0; + for (int y = (int)hold.Y - 150; y < (int)hold.Y + 150; y++) + for (int x = (int)hold.X - 150; x < (int)hold.X + 150; x++) + { + if (x < 0 || y < 0 || x >= Width || y >= Height) continue; + sum += frame.Luma(x, y); n++; + } + means[run] = sum / n; + poses.Add(Session.View.StableId.ToArray().Select(id => _main.Bodies.PoseOf(id)).ToArray()); + } + bool samePose = poses[0].Zip(poses[1]).All(p => p.First is { } a && p.Second is { } b && a.Origin.DistanceTo(b.Origin) < 1e-4f); + double lift = means[0] - means[1]; + // Bound 1.2 levels: shipped 2.4, light not written 0 (half the shipped lift: the mutant's reading has no spread to take a midpoint of). + Report("glow: luma lift near the hand", lift, 1.2); + Check(samePose, "glow", "the bodies are not in the same pose at tick 1 with the box lit and dark; the probe proves nothing"); + Check(lift >= 1.2, "glow", $"the figure is {lift:F2} levels brighter with the chamber at full glow than dark, under 1.2"); + } + + private readonly record struct Frame(int Width, int Height, byte[] Data) + { + public uint Rgb(int x, int y) { int i = 4 * (y * Width + x); return (uint)(Data[i] << 16 | Data[i + 1] << 8 | Data[i + 2]); } + public double Luma(int x, int y) { int i = 4 * (y * Width + x); return 0.299 * Data[i] + 0.587 * Data[i + 1] + 0.114 * Data[i + 2]; } + } + + private async Task Capture(string name) + { + await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); + var image = GetViewport().GetTexture().GetImage(); + image.Convert(Image.Format.Rgba8); + if (_frames is not null) image.SavePng($"{_frames}/{name}.png"); + return new Frame(image.GetWidth(), image.GetHeight(), image.GetData()); + } + + /// The widths in pixels of the white and black runs along row inside the lit triangle, edges included. + private static List Runs(Frame f, int y) + { + var runs = new List(); + int start = 0; bool? last = null; + for (int x = 0; x < f.Width; x++) + { + if (f.Luma(x, y) is var l && l is > 60 and < 190) { last = null; continue; } // a dithered or blended pixel: not a clean texel + bool white = f.Luma(x, y) > 128; + if (last is null) { start = x; last = white; } + else if (last != white) { runs.Add(x - start); start = x; last = white; } + } + return runs; + } + + /// The block a pixel belongs to on a grid of -pixel blocks anchored at the centre of an axis of pixels. + private static int BlockOf(int pixel, int length, int s) => (int)Math.Floor((pixel - length / 2.0) / s); + + private static List Hull(List points) + { + var p = points.OrderBy(a => a.X).ThenBy(a => a.Y).ToList(); + var h = new List(); + foreach (var pass in new[] { p, Enumerable.Reverse(p).ToList() }) + { + int floor = h.Count; + foreach (var q in pass) + { + while (h.Count >= floor + 2 && Cross(h[^2], h[^1], q) <= 0) h.RemoveAt(h.Count - 1); + h.Add(q); + } + h.RemoveAt(h.Count - 1); + } + return h; + } + + private static float Cross(Vector2 o, Vector2 a, Vector2 b) => (a.X - o.X) * (b.Y - o.Y) - (a.Y - o.Y) * (b.X - o.X); + + private static bool Inside(List hull, Vector2 q) + { + for (int i = 0; i < hull.Count; i++) if (Cross(hull[i], hull[(i + 1) % hull.Count], q) < 0) return false; + return true; + } + + private async Task Frames(int n) + { + for (int i = 0; i < n; i++) await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + + private async Task UntilTick(long tick) + { + while (Session.TickIndex < tick && !Session.Finished) await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + if (Session.TickIndex != tick) Fail("tick", $"the run stopped at tick {Session.TickIndex}, not {tick}"); + await Frames(1); + } + + private void Report(string name, double reading, double bound) => GD.Print($"RENDER {name}: {reading:0.##} (bound {bound:0.##})"); + + private void Check(bool ok, string name, string failure) + { + if (!ok) Fail(name, failure); + } + + private void Fail(string name, string failure) => _failures.Add($"{name}: {failure}"); + + private void Finish() + { + if (_done) return; + _done = true; + foreach (var f in _failures) GD.PrintErr("RENDER FAIL " + f); + GD.Print(_failures.Count == 0 ? "RENDER PASS" : $"RENDER FAILED ({_failures.Count})"); + GetTree().Quit(_failures.Count == 0 ? 0 : 1); + } +} diff --git a/client/tests/RenderCheck.tscn b/client/tests/RenderCheck.tscn new file mode 100644 index 0000000..ead52d2 --- /dev/null +++ b/client/tests/RenderCheck.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/RenderCheck.cs" id="1"] + +[node name="RenderCheck" type="Node"] +script = ExtResource("1") diff --git a/client/tests/render-mutants.sh b/client/tests/render-mutants.sh new file mode 100644 index 0000000..a4b206b --- /dev/null +++ b/client/tests/render-mutants.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Breaks the shipped look once per claim of RenderCheck and wants that claim's line to fail. Each mutant is one edit that must apply +# exactly once; the file is restored whatever happens. Needs a window (RenderCheck draws). Run from anywhere: +# GODOT= bash client/tests/render-mutants.sh +set -u +cd "$(dirname "$0")/.." +GODOT="${GODOT:-F:/Applications/Godot_v4.7.2-stable_mono_win64/Godot_v4.7.2-stable_mono_win64_console.exe}" + +# name | file | old | new | the RenderCheck line it must fail +MUTANTS=( +'post-off|ps1_post.gdshader|COLOR = vec4(floor(c / 8.0) * 8.0 / 255.0, 1.0);|COLOR = vec4(c / 255.0, 1.0);|15-bit' +'block-off|ps1_post.gdshader|textureLod(screen_tex, (size * 0.5 + (b + 0.5) * s) / size, 0.0)|textureLod(screen_tex, SCREEN_UV, 0.0)|blocks' +'snap-off|ps1.gdshader|if (clip.w > 0.05) {|if (false) {|snap' +'perspective-uv|ps1.gdshader|auv = vec3(uv * clip.w, clip.w);|auv = vec3(uv, 1.0);|affine' +'glow-unset|Chamber.cs|Look.GlowLightEnergy * glow|0f|glow' +'carrier-unposed|BodyRenderer.cs|node.Transform = new Transform3D(new Basis(new Quaternion(rx[i]|_ = new Transform3D(new Basis(new Quaternion(rx[i]|figure at lanes' +) + +status=0 +for m in "${MUTANTS[@]}"; do + IFS='|' read -r name file old new want <<<"$m" + cp "$file" "$file.orig" + restore() { mv -f "$file.orig" "$file"; } + if ! python - "$file" "$old" "$new" <<'PY' +import sys +path, old, new = sys.argv[1:4] +raw = open(path, newline='').read() +text = raw.replace('\r\n', '\n') +if text.count(old) != 1: + sys.exit(f"{path}: the edit applies {text.count(old)} times, not once") +text = text.replace(old, new) +open(path, 'w', newline='').write(text.replace('\n', '\r\n') if '\r\n' in raw else text) +PY + then restore; echo "MUTANT $name: edit did not apply once; aborting"; exit 2; fi + if ! dotnet build BadDay.Client.csproj 2>&1 | grep -q "Build succeeded"; then restore; echo "MUTANT $name: does not build; aborting"; exit 2; fi + out="$("$GODOT" --path . res://tests/RenderCheck.tscn 2>&1)" + restore + readings="$(grep '^RENDER ' <<<"$out" | grep -v 'FAIL\|PASS\|FAILED' | sed 's/^RENDER //' | tr '\n' ';')" + if grep -q "^RENDER FAIL $want:" <<<"$out"; then echo "MUTANT $name: fails '$want' as wanted [$readings]" + else echo "MUTANT $name: DOES NOT FAIL '$want' [$readings]"; status=1; fi +done +dotnet build BadDay.Client.csproj 2>&1 | grep -q "Build succeeded" || { echo "the shipped code does not build after the run"; status=1; } +exit $status