Client: the Synaptic Induction Chamber scene, ticked once per 120 Hz physics frame, drawn from Ymir's lanes, with readout, controls and an orbit camera

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 02:30:48 +01:00
commit 14b140953e
7 changed files with 403 additions and 0 deletions

93
client/BodyRenderer.cs Normal file
View file

@ -0,0 +1,93 @@
using System.Collections.Generic;
using Godot;
using Ymir.Box3D;
namespace BadDay.Client;
/// <summary>
/// Draws Ymir's world: one MeshInstance3D per StableId, its mesh from the Kind and Size lanes, its transform from the
/// pose lanes every tick. The renderer owns no dimensions and writes nothing back; the lanes are the only source.
/// Meshes are stylised low poly with flat normals.
/// </summary>
public partial class BodyRenderer : Node3D
{
private readonly Dictionary<ulong, MeshInstance3D> _nodes = new();
private readonly HashSet<ulong> _seen = new();
private readonly StandardMaterial3D _dynamic = Flat(new Color(0.88f, 0.10f, 0.08f));
private readonly StandardMaterial3D _fixed = Flat(new Color(0.74f, 0.74f, 0.72f));
public int NodeCount => _nodes.Count;
public MeshInstance3D? NodeFor(ulong stableId) => _nodes.GetValueOrDefault(stableId);
/// <summary>Makes the nodes match the lanes: creates the missing, frees the gone, then poses every node. <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
public void Sync(in Box3DSoaView view, bool teleport = false)
{
var ids = view.StableId;
var kind = view.Kind;
if (ids.Length != _nodes.Count || !AllPresent(ids))
{
_seen.Clear();
for (int i = 0; i < ids.Length; i++) _seen.Add(ids[i]);
foreach (var id in new List<ulong>(_nodes.Keys))
{
if (_seen.Contains(id)) continue;
_nodes[id].QueueFree();
_nodes.Remove(id);
}
for (int i = 0; i < ids.Length; i++)
{
if (_nodes.ContainsKey(ids[i])) continue;
var node = new MeshInstance3D { Name = $"Body{ids[i]}", Mesh = MeshFor((Box3DSoaKind)kind[i], view.Size0[i], view.Size1[i], view.Size2[i]) };
node.MaterialOverride = (Box3DSoaKind)kind[i] == Box3DSoaKind.StaticBox ? _fixed : _dynamic;
AddChild(node);
_nodes[ids[i]] = node;
teleport = true;
}
}
var px = view.PositionX; var py = view.PositionY; var pz = view.PositionZ;
var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW;
for (int i = 0; i < ids.Length; i++)
{
var node = _nodes[ids[i]];
node.Transform = new Transform3D(new Basis(new Quaternion(rx[i], ry[i], rz[i], rw[i])), new Vector3(px[i], py[i], pz[i]));
if (teleport) node.ResetPhysicsInterpolation();
}
}
private bool AllPresent(System.ReadOnlySpan<ulong> ids)
{
foreach (var id in ids) if (!_nodes.ContainsKey(id)) return false;
return true;
}
/// <summary>The mesh for a body: sphere radius Size0; capsule radius Size0 and half-length Size1 along Y (Godot's height counts the caps); box half-extents Size0..2.</summary>
public static Mesh MeshFor(Box3DSoaKind kind, float size0, float size1, float size2) => kind switch
{
Box3DSoaKind.Sphere => FlatShaded(new SphereMesh { Radius = size0, Height = 2f * size0, RadialSegments = 8, Rings = 5 }),
Box3DSoaKind.Capsule => FlatShaded(new CapsuleMesh { Radius = size0, Height = 2f * (size1 + size0), RadialSegments = 8, Rings = 2 }),
_ => FlatShaded(new BoxMesh { Size = new Vector3(2f * size0, 2f * size1, 2f * size2) }),
};
/// <summary>The same triangles with one normal per face.</summary>
private static ArrayMesh FlatShaded(PrimitiveMesh source)
{
var arrays = source.GetMeshArrays();
var vertices = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
var indices = arrays[(int)Mesh.ArrayType.Index].AsInt32Array();
var st = new SurfaceTool();
st.Begin(Mesh.PrimitiveType.Triangles);
st.SetSmoothGroup(uint.MaxValue);
foreach (int i in indices) st.AddVertex(vertices[i]);
st.GenerateNormals();
return st.Commit();
}
private static StandardMaterial3D Flat(Color color) => new()
{
AlbedoColor = color,
Roughness = 1f,
MetallicSpecular = 0f,
};
}

39
client/Chamber.cs Normal file
View file

@ -0,0 +1,39 @@
using System;
using BadDay.Ymir;
using Godot;
namespace BadDay.Client;
/// <summary>The Synaptic Induction Chamber: the stimulus volume drawn as a translucent box, its glow following the box's intensity.</summary>
public partial class Chamber : Node3D
{
private readonly MeshInstance3D _volume = new() { Mesh = new BoxMesh { Size = Vector3.One } };
private readonly OmniLight3D _glow = new() { OmniRange = 1.6f, LightColor = new Color(1f, 0.85f, 0.15f), LightEnergy = 0f };
private readonly StandardMaterial3D _material = new()
{
Transparency = BaseMaterial3D.TransparencyEnum.Alpha,
AlbedoColor = new Color(1f, 0.85f, 0.15f, 0.2f),
EmissionEnabled = true,
Emission = new Color(1f, 0.85f, 0.15f),
CullMode = BaseMaterial3D.CullModeEnum.Disabled,
};
public override void _Ready()
{
_volume.MaterialOverride = _material;
_volume.CastShadow = GeometryInstance3D.ShadowCastingSetting.Off;
AddChild(_volume);
AddChild(_glow);
}
public void Sync(BodyPainBoxSession session)
{
var box = session.Chamber;
Position = new Vector3(box.CenterX, box.CenterY, box.CenterZ);
_volume.Scale = new Vector3(2f * box.HalfX, 2f * box.HalfY, 2f * box.HalfZ);
float glow = (float)Math.Min(1.0, box.Intensity / 1.5);
_material.AlbedoColor = new Color(1f, 0.85f, 0.15f, 0.06f + 0.3f * glow);
_material.EmissionEnergyMultiplier = 0.1f + 2.5f * glow;
_glow.LightEnergy = 3f * glow;
}
}

80
client/Hud.cs Normal file
View file

@ -0,0 +1,80 @@
using System.Text;
using BadDay.Core;
using BadDay.Ymir;
using Godot;
namespace BadDay.Client;
/// <summary>Readout and controls. Every number comes from the session; every control calls a Main method that calls it.</summary>
public partial class Hud : CanvasLayer
{
private readonly Main _main;
private readonly Label _readout = new();
private readonly SpinBox _seed = new() { MinValue = 0, MaxValue = 999999999, Step = 1, Value = 1 };
private readonly HSlider _intensity = new() { MinValue = 0, MaxValue = PainBox.MaxLevel, Step = 0.05, CustomMinimumSize = new Vector2(220, 24) };
private readonly StringBuilder _text = new();
public Hud(Main main) => _main = main;
public override void _Ready()
{
var margin = new MarginContainer();
margin.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.FullRect);
foreach (var side in new[] { "left", "top", "right", "bottom" }) margin.AddThemeConstantOverride($"margin_{side}", 16);
margin.MouseFilter = Control.MouseFilterEnum.Ignore;
AddChild(margin);
var row = new HBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore };
margin.AddChild(row);
_readout.AddThemeColorOverride("font_color", new Color(0.08f, 0.08f, 0.08f));
_readout.AddThemeFontSizeOverride("font_size", 16);
_readout.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
_readout.MouseFilter = Control.MouseFilterEnum.Ignore;
row.AddChild(_readout);
var controls = new VBoxContainer { SizeFlagsVertical = Control.SizeFlags.ShrinkBegin };
row.AddChild(controls);
var seedRow = new HBoxContainer();
seedRow.AddChild(new Label { Text = "Seed", Modulate = new Color(0.08f, 0.08f, 0.08f) });
seedRow.AddChild(_seed);
controls.AddChild(seedRow);
controls.AddChild(Button("Reset", () => _main.Reset((ulong)_seed.Value)));
controls.AddChild(new Label { Text = "Intensity", Modulate = new Color(0.08f, 0.08f, 0.08f) });
_intensity.Value = _main.Intensity;
_intensity.ValueChanged += v => _main.SetIntensity(v);
controls.AddChild(_intensity);
controls.AddChild(Button("Box off", () => _main.SwitchOff()));
var slow = new CheckButton { Text = "Slow motion", Modulate = new Color(0.08f, 0.08f, 0.08f) };
slow.Toggled += on => _main.SetSlowMotion(on);
controls.AddChild(slow);
}
public override void _Process(double delta)
{
var s = _main.Session;
var r = s.Result();
_text.Clear();
_text.Append($"seed {_main.Seed} t {s.TickIndex * BodyPainBox.TickSeconds:F2} s (tick {s.TickIndex})\n");
_text.Append($"box intensity {s.BoxIntensity:F2} (set {_main.Intensity:F2})\n");
_text.Append($"pain {s.Pain:F2} strain {s.Strain:F2} resolve {s.Resolve:F2}\n");
_text.Append($"goal {s.Goal} flinches {r.Flinches}\n");
_text.Append($"will broke at {Ms(r.TimeToBreakMs)} withdrew {(s.Goal == Lodur.Goal.Withdraw ? "yes" : "no")}\n");
_text.Append($"hand {(s.Hand.InBox ? "in box" : "out of box")} hand out at {Ms(s.HandOutMs)}\n");
_text.Append(s.Finished ? $"outcome {r.Outcome}\n" : "running\n");
foreach (var line in _main.Log) _text.Append(line).Append('\n');
_readout.Text = _text.ToString();
}
private static string Ms(long? ms) => ms is { } v ? $"{v / 1000.0:F2} s" : "-";
private static Button Button(string text, System.Action pressed)
{
var b = new Button { Text = text };
b.Pressed += pressed;
return b;
}
}

23
client/Look.cs Normal file
View file

@ -0,0 +1,23 @@
using Godot;
namespace BadDay.Client;
/// <summary>The scene's stylised look: a bright flat world, one hard light, saturated red figures.</summary>
public static class Look
{
public static Godot.Environment Environment() => new()
{
BackgroundMode = Godot.Environment.BGMode.Color,
BackgroundColor = new Color(0.94f, 0.94f, 0.92f),
AmbientLightSource = Godot.Environment.AmbientSource.Color,
AmbientLightColor = new Color(1f, 1f, 1f),
AmbientLightEnergy = 0.3f,
};
public static DirectionalLight3D Sun() => new()
{
RotationDegrees = new Vector3(-50f, 35f, 0f),
LightEnergy = 1.5f,
ShadowEnabled = true,
};
}

113
client/Main.cs Normal file
View file

@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using BadDay.Core;
using BadDay.Ymir;
using Godot;
namespace BadDay.Client;
/// <summary>
/// The client's root. Godot's physics frame decides when a tick happens (120 Hz, physics interpolation on, Godot's own
/// physics engine Dummy); <see cref="BodyPainBoxSession"/> decides everything a tick does. This node only steps it,
/// draws it and forwards the player's commands to it.
/// </summary>
public partial class Main : Node3D
{
private const int LogLines = 6;
private readonly List<string> _log = new();
private BodyRenderer _bodies = null!;
private Chamber _chamber = null!;
private OrbitCamera _camera = null!;
private Hud _hud = null!;
private BodyPainBoxSession? _session;
private double _intensity = new PainBoxParameters().BoxIntensity;
private bool _deltaReported;
public BodyPainBoxSession Session => _session ?? throw new InvalidOperationException("Main has no session before _Ready.");
public BodyRenderer Bodies => _bodies;
public ulong Seed { get; private set; } = 1;
/// <summary>The intensity the box is set to; the next Reset starts with it.</summary>
public double Intensity => _intensity;
public bool SlowMotion => Engine.TimeScale < 1.0;
public IReadOnlyList<string> Log => _log;
/// <summary>The parameters of a run at the given box intensity: every default except the 1/120 s tick the body needs.</summary>
public static PainBoxParameters ParametersFor(double intensity) =>
new() { TickSeconds = BodyPainBox.TickSeconds, BoxIntensity = intensity };
public override void _Ready()
{
AddChild(new WorldEnvironment { Environment = Look.Environment() });
AddChild(Look.Sun());
_bodies = new BodyRenderer { Name = "Bodies" };
AddChild(_bodies);
_chamber = new Chamber { Name = "Chamber" };
AddChild(_chamber);
_camera = new OrbitCamera { Name = "Camera" };
AddChild(_camera);
_hud = new Hud(this) { Name = "Hud" };
AddChild(_hud);
Reset(Seed);
}
public override void _ExitTree()
{
Engine.TimeScale = 1.0;
_session?.Dispose();
_session = null;
}
public override void _PhysicsProcess(double delta)
{
if (_session is null) return;
if (Math.Abs(delta - BodyPainBox.TickSeconds) > 1e-9 && !_deltaReported)
{
_deltaReported = true;
GD.PushError($"BadDay: physics delta {delta} is not 1/120; the session steps 1/120 s regardless.");
}
_session.Step(); // never Godot's delta: the ragdoll's gains are tuned at 1/120
Present(teleport: false);
}
/// <summary>Starts a new run from <paramref name="seed"/> at the current intensity, replacing the session.</summary>
public void Reset(ulong seed)
{
_session?.Dispose();
_session = null;
_session = new BodyPainBoxSession(ParametersFor(_intensity), seed);
Seed = seed;
_log.Clear();
Present(teleport: true);
}
/// <summary>Sets the box intensity now and for the next Reset.</summary>
public void SetIntensity(double level)
{
_session?.SetIntensity(level);
_intensity = level;
}
public void SwitchOff() => _session?.SwitchOff();
public void SetSlowMotion(bool on) => Engine.TimeScale = on ? 0.25 : 1.0;
private void Present(bool teleport)
{
var s = Session;
_bodies.Sync(s.View, teleport);
_chamber.Sync(s);
Span<BodyEvent> events = stackalloc BodyEvent[8];
int n;
while ((n = s.DrainEvents(events)) > 0)
{
for (int i = 0; i < n; i++)
{
_log.Add($"{events[i].Tick * BodyPainBox.TickSeconds,6:F2} s {events[i].Events}");
if (_log.Count > LogLines) _log.RemoveAt(0);
}
}
}
}

6
client/Main.tscn Normal file
View file

@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://Main.cs" id="1"]
[node name="Main" type="Node3D"]
script = ExtResource("1")

49
client/OrbitCamera.cs Normal file
View file

@ -0,0 +1,49 @@
using System;
using BadDay.Ymir;
using Godot;
namespace BadDay.Client;
/// <summary>A camera orbiting the chamber: right-drag orbits, the wheel zooms.</summary>
public partial class OrbitCamera : Camera3D
{
private Vector3 _target = new(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z);
private float _yaw = 0.35f;
private float _pitch = 0.2f;
private float _distance = 2.4f;
public override void _Ready()
{
Fov = 55f;
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off; // moved in _Process, not on the physics tick
Current = true;
Place();
}
public override void _UnhandledInput(InputEvent e)
{
switch (e)
{
case InputEventMouseMotion m when (m.ButtonMask & MouseButtonMask.Right) != 0:
_yaw -= m.Relative.X * 0.006f;
_pitch = Math.Clamp(_pitch + m.Relative.Y * 0.006f, -0.2f, 1.4f);
Place();
break;
case InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.WheelUp }:
_distance = Math.Max(0.6f, _distance * 0.9f);
Place();
break;
case InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.WheelDown }:
_distance = Math.Min(12f, _distance * 1.1f);
Place();
break;
}
}
private void Place()
{
var offset = new Vector3(MathF.Sin(_yaw) * MathF.Cos(_pitch), MathF.Sin(_pitch), MathF.Cos(_yaw) * MathF.Cos(_pitch)) * _distance;
Position = _target + offset;
LookAt(_target, Vector3.Up);
}
}