Initial Unity project import

This commit is contained in:
Netherwarlord
2026-11-20 10:52:58 -05:00
commit 136065772b
254 changed files with 54630 additions and 0 deletions
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Listen-only Unity monitor for live Art-Net tests (e.g. ChamSys MagicQ) of the Legend 230SR Beam test scene.
# It never sends Art-Net. Requires the Unity Editor to be CLOSED for this project (it runs Unity in batch mode).
#
# l230sr_live_monitor.sh preflight # port 6454 owner, interfaces, Unity lock
# l230sr_live_monitor.sh start [minutes] # start the monitor in the background (default 30 min)
# l230sr_live_monitor.sh status # current receiver + fixture state (refreshed every second)
# l230sr_live_monitor.sh snap <label> # snapshot: JSON line + PNG in Logs/
# l230sr_live_monitor.sh stop # end the session and print the summary
set -euo pipefail
PROJECT="${PROJECT:-$HOME/The_Pressure_Chamber}"
UNITY="${UNITY:-$HOME/Unity/Hub/Editor/6000.3.28f1/Editor/Unity}"
LOGS="$PROJECT/Logs"
mkdir -p "$LOGS"
case "${1:-help}" in
preflight)
echo "== UDP 6454 listeners (Unity monitor and MagicQ must not both hold it exclusively)"
ss -lunp 2>/dev/null | awk 'NR==1 || /:6454 /' || true
echo "== IPv4 interfaces"; ip -4 -br addr
echo "== Unity project lock"; [ -e "$PROJECT/Temp/UnityLockfile" ] && echo "LOCKED: Unity Editor has the project open" || echo "free"
;;
start)
[ -e "$PROJECT/Temp/UnityLockfile" ] && { echo "Unity Editor has the project open; close it first." >&2; exit 1; }
rm -f "$LOGS"/L230SR_live_* "$LOGS"/L230SR_snap_*
L230SR_LIVE_MONITOR=1 L230SR_MONITOR_MINUTES="${2:-30}" nohup "$UNITY" -batchmode -projectPath "$PROJECT" \
-runTests -testPlatform PlayMode \
-testFilter 'PressureChamber.Fixtures.Legend230SR.LiveMonitor.Legend230SRLiveMonitor.LiveMonitor_ListenOnly' \
-testResults "$LOGS/L230SR_live_results.xml" -logFile "$LOGS/L230SR_live_unity.log" >/dev/null 2>&1 &
echo $! > "$LOGS/L230SR_live.pid"
echo "monitor starting (pid $(cat "$LOGS/L230SR_live.pid")); waiting for the first status file..."
for _ in $(seq 1 180); do [ -s "$LOGS/L230SR_live_status.json" ] && break; sleep 1; done
[ -s "$LOGS/L230SR_live_status.json" ] && grep -E '"(receiver_bound|receiver_port|last_sender)"' "$LOGS/L230SR_live_status.json" \
|| { echo "no status after 180 s; see $LOGS/L230SR_live_unity.log" >&2; exit 1; }
;;
status)
cat "$LOGS/L230SR_live_status.json"
;;
snap)
label="${2:?usage: snap <label>}"
touch "$LOGS/L230SR_snap_$label"
for _ in $(seq 1 20); do [ -e "$LOGS/L230SR_snap_$label" ] || break; sleep 0.5; done
[ -e "$LOGS/L230SR_snap_$label" ] && { echo "snapshot not taken (is the monitor running?)" >&2; exit 1; }
tail -n 1 "$LOGS/L230SR_live_snapshots.jsonl"
;;
stop)
touch "$LOGS/L230SR_live_stop"
pid="$(cat "$LOGS/L230SR_live.pid" 2>/dev/null || true)"
for _ in $(seq 1 120); do [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null || break; sleep 1; done
cat "$LOGS/L230SR_live_summary.json" 2>/dev/null || echo "no summary; see $LOGS/L230SR_live_unity.log"
grep -oE '<test-run[^>]*>' "$LOGS/L230SR_live_results.xml" 2>/dev/null | grep -oE 'result="[^"]+"' || true
;;
*) sed -n '2,10p' "$0" ;;
esac
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ec7005e04c14e4167829584eee0c9a3e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,228 @@
// End-to-end Play Mode test: real Art-Net (ArtDMX over UDP to 127.0.0.1:6454) -> package ArtNetReceiver ->
// DmxRigController -> DmxFixtureComponent on the Legend 230SR Beam prefab, inside the isolated fixture test scene.
// Run: Unity -batchmode -projectPath <proj> -runTests -testPlatform PlayMode
// -testFilter PressureChamber.Fixtures.Legend230SR.Tests -testResults <file.xml>
// Writes Logs/L230SR_playmode_artnet_report.json and Logs/L230SR_playmode_*.png (project Logs folder).
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using ArtNet.Runtime;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif
namespace PressureChamber.Fixtures.Legend230SR.Tests
{
public class Legend230SRArtNetPlayModeTests
{
const string ScenePath = "Assets/Fixtures/Chauvet_Legend_230SR_Beam/Scenes/L230SR_FixtureTest.unity";
const float TiltY = 0.3735f;
readonly List<string> _log = new();
readonly StringBuilder _json = new();
static float PanDeg(int v16) => (v16 / 65535f - 0.5f) * 540f; // DmxFixtureComponent mapping (no invert/offset)
static float TiltDeg(int v16) => (v16 / 65535f - 0.5f) * 270f;
static byte[] ArtDmx(int universe, byte[] dmx, byte seq)
{
var p = new byte[18 + 512];
Encoding.ASCII.GetBytes("Art-Net\0").CopyTo(p, 0);
p[8] = 0x00; p[9] = 0x50; // OpDmx (0x5000, little endian)
p[10] = 0; p[11] = 14; // protocol version 14
p[12] = seq; p[13] = 0;
p[14] = (byte)(universe & 0xFF); // SubUni
p[15] = (byte)((universe >> 8) & 0x7F); // Net
p[16] = 0x02; p[17] = 0x00; // length 512, big endian
Buffer.BlockCopy(dmx, 0, p, 18, 512);
return p;
}
static void Put16(byte[] u, int addr, int ch, int v) { u[addr + ch - 2] = (byte)(v >> 8); u[addr + ch - 1] = (byte)(v & 0xFF); }
static void Put8(byte[] u, int addr, int ch, int v) { u[addr + ch - 2] = (byte)v; }
// Mode 2 (18ch) @ address 1: 1-2 pan, 3-4 tilt, 5 P/T speed, 6-7 dimmer, 8 shutter, 9 colour, 10 gobo, 11 prism, 12 prism rot ...
// Mode 1 (15ch) @ address 21: 1-2 pan, 3-4 tilt, 5 speed, 6 dimmer, 7 shutter, 8 colour, 9 gobo, 10 prism, 11 prism rot ...
struct State
{
public string name;
public int aPan, aTilt, aDim16, aShutter, aColor, aGobo, aPrism;
public int bPan, bTilt, bDim, bShutter, bColor, bGobo;
}
static byte[] Build(State s)
{
var u = new byte[512];
const int A = 1, B = 21;
Put16(u, A, 1, s.aPan); Put16(u, A, 3, s.aTilt); Put16(u, A, 6, s.aDim16);
Put8(u, A, 8, s.aShutter); Put8(u, A, 9, s.aColor); Put8(u, A, 10, s.aGobo); Put8(u, A, 11, s.aPrism);
Put16(u, B, 1, s.bPan); Put16(u, B, 3, s.bTilt); Put8(u, B, 6, s.bDim);
Put8(u, B, 7, s.bShutter); Put8(u, B, 8, s.bColor); Put8(u, B, 9, s.bGobo);
return u;
}
[UnityTest, Timeout(120000)]
public IEnumerator ArtNet_Udp_Drives_Legend230SR_Fixtures()
{
#if UNITY_EDITOR
var op = EditorSceneManager.LoadSceneAsyncInPlayMode(ScenePath, new LoadSceneParameters(LoadSceneMode.Single));
while (!op.isDone) yield return null;
#else
Assert.Ignore("Editor-only test (loads the fixture test scene from the AssetDatabase).");
#endif
yield return new WaitForSecondsRealtime(0.5f);
var fixtures = UnityEngine.Object.FindObjectsByType<DmxFixtureComponent>(FindObjectsSortMode.None);
var a = fixtures.Single(f => f.name.StartsWith("L230SR_A"));
var b = fixtures.Single(f => f.name.StartsWith("L230SR_B"));
Transform Find(Component c, string n) => c.GetComponentsInChildren<Transform>(true).First(t => t.name == n);
Transform aYoke = Find(a, "Yoke"), aHead = Find(a, "Head"), bYoke = Find(b, "Yoke"), bHead = Find(b, "Head");
var receiver = UnityEngine.Object.FindAnyObjectByType<ArtNetReceiver>();
Assert.NotNull(receiver, "ArtNetReceiver missing in test scene");
_json.Append("{\n \"receiver_port\": ").Append(receiver.port).Append(",\n \"steps\": [\n");
var states = new[]
{
new State { name = "1_A_pan+135_tilt-67.5_full_colour1_gobo4__B_tilt+135_dimmer0",
aPan = 0xC000, aTilt = 0x4000, aDim16 = 0xFFFF, aShutter = 255, aColor = 6, aGobo = 14, aPrism = 0,
bPan = 0x8000, bTilt = 0xFFFF, bDim = 0, bShutter = 8, bColor = 0, bGobo = 0 },
new State { name = "2_A_pan-270_tilt+45_colour10_prism__B_pan+90_tilt-81_full_open",
aPan = 0x0000, aTilt = 0xAAAA, aDim16 = 0xFFFF, aShutter = 255, aColor = 42, aGobo = 0, aPrism = 128,
bPan = 0xAAAA, bTilt = 0x3333, bDim = 255, bShutter = 255, bColor = 0, bGobo = 0 },
new State { name = "3_both_dmx_centre_shutter_open_dimmer_half",
aPan = 0x8000, aTilt = 0x8000, aDim16 = 0x8000, aShutter = 8, aColor = 0, aGobo = 0, aPrism = 0,
bPan = 0x8000, bTilt = 0x8000, bDim = 128, bShutter = 8, bColor = 0, bGobo = 0 },
new State { name = "4_beam_look_both_tilt+67.5_towards_front_wall__A_open_white__B_colour9_gobo4",
aPan = 0x8000, aTilt = 0xC000, aDim16 = 0xFFFF, aShutter = 255, aColor = 0, aGobo = 0, aPrism = 0,
bPan = 0x8000, bTilt = 0xC000, bDim = 255, bShutter = 255, bColor = 38, bGobo = 14 },
};
bool allOk = true;
using var udp = new UdpClient();
byte seq = 1;
for (int si = 0; si < states.Length; si++)
{
var s = states[si];
var dmx = Build(s);
var packet = ArtDmx(0, dmx, seq);
float t0 = Time.realtimeSinceStartup;
Quaternion expAYoke = Quaternion.AngleAxis(PanDeg(s.aPan), Vector3.up), expAHead = Quaternion.AngleAxis(TiltDeg(s.aTilt), -Vector3.right);
Quaternion expBYoke = Quaternion.AngleAxis(PanDeg(s.bPan), Vector3.up), expBHead = Quaternion.AngleAxis(TiltDeg(s.bTilt), -Vector3.right);
float errAY = 999, errAH = 999, errBY = 999, errBH = 999, prevSum = 999; int still = 0;
while (Time.realtimeSinceStartup - t0 < 10f)
{
seq = (byte)(seq == 255 ? 1 : seq + 1); packet[12] = seq;
udp.Send(packet, packet.Length, "127.0.0.1", receiver.port);
yield return new WaitForSecondsRealtime(1f / 30f);
errAY = Quaternion.Angle(aYoke.localRotation, expAYoke); errAH = Quaternion.Angle(aHead.localRotation, expAHead);
errBY = Quaternion.Angle(bYoke.localRotation, expBYoke); errBH = Quaternion.Angle(bHead.localRotation, expBHead);
float sum = errAY + errAH + errBY + errBH;
still = Mathf.Abs(prevSum - sum) < 0.002f ? still + 1 : 0; // wait until the smoothing has fully settled
prevSum = sum;
if (still >= 5 && Time.realtimeSinceStartup - t0 > 1.5f) break;
}
// keep sending briefly so shutter / colour / gobo states settle, then sample
for (int k = 0; k < 15; k++) { udp.Send(packet, packet.Length, "127.0.0.1", receiver.port); yield return new WaitForSecondsRealtime(1f / 30f); }
float settle = Time.realtimeSinceStartup - t0;
var la = a.targetLight; var lb = b.targetLight;
bool ok = errAY < 0.05f && errAH < 0.05f && errBY < 0.05f && errBH < 0.05f;
string colorCheck = "n/a";
string lensGobo = LensGoboName(a);
int aLit = a.GetComponentsInChildren<Light>(true).Count(x => x.isActiveAndEnabled && x.intensity > 0.01f);
if (si == 0)
{
bool aOn = la.enabled && la.intensity > 0.01f, bOff = !lb.enabled || lb.intensity < 1e-3f;
bool red = la.color.r > 2f * la.color.g && la.color.r > 2f * la.color.b;
// the package projects the gobo through a generated focus cookie, so the raw texture is checked on the lens
bool gobo = la.cookie != null && (lensGobo == null || lensGobo.Contains("04_Aperture_L"));
colorCheck = $"A_on={aOn} B_off={bOff} A_red={red} A_cookie_present={la.cookie != null} lens_gobo={lensGobo ?? "n/a"}";
ok &= aOn && bOff && red && gobo;
}
else if (si == 1)
{
bool blue = la.color.b > 2f * la.color.r && la.color.b > la.color.g;
bool bWhite = lb.intensity > 0.01f && Mathf.Abs(lb.color.r - lb.color.b) < 0.1f;
bool noGobo = la.cookie == null || !la.cookie.name.Contains("L230SR_Gobo_");
var beamTpl = a.GetComponentsInChildren<Renderer>(true).FirstOrDefault(r => r.name == "PseudoBeam");
int facets = beamTpl == null ? 0 : a.GetComponentsInChildren<Renderer>(false)
.Count(r => r.enabled && r != beamTpl && r.sharedMaterial != null && r.sharedMaterial == beamTpl.sharedMaterial);
colorCheck = $"A_blue={blue} A_gobo_cleared={noGobo} B_on_white={bWhite} A_lit_lights_with_prism={aLit} A_prism_beam_facets={facets} lens_gobo={lensGobo ?? "n/a"}";
ok &= blue && bWhite && noGobo && aLit >= 8 && facets >= 8;
}
else if (si == 2)
{
// 16-bit 0x8000 (Mode 2) and 8-bit 128 (Mode 1) should both land near half of the driver maximum
bool half = la.intensity > 0.01f && lb.intensity > 0.01f && Mathf.Abs(la.intensity - lb.intensity) < 0.1f * Mathf.Max(la.intensity, lb.intensity);
colorCheck = $"both_on_at_half={half} A_I={la.intensity:0.###} B_I={lb.intensity:0.###}";
ok &= half;
}
else
{
bool aWhite = la.intensity > 0.01f && Mathf.Abs(la.color.r - la.color.b) < 0.1f;
bool bMagenta = lb.intensity > 0.01f && lb.color.r > 2f * lb.color.g && lb.color.b > 2f * lb.color.g;
var beamA = a.GetComponentsInChildren<Renderer>(true).FirstOrDefault(r => r.name == "PseudoBeam");
bool beamOn = beamA != null && beamA.enabled && beamA.gameObject.activeInHierarchy;
colorCheck = $"A_white={aWhite} B_magenta={bMagenta} A_pseudobeam_active={beamOn} lensB_gobo={LensGoboName(b) ?? "n/a"}";
ok &= aWhite && bMagenta && beamOn;
}
allOk &= ok;
string line = string.Format(CultureInfo.InvariantCulture,
"{0}: ok={1} settle={2:0.00}s errA(yoke,head)=({3:0.000},{4:0.000})deg errB=({5:0.000},{6:0.000})deg " +
"A.light(I={7:0.###}, col={8}, cookie={9}) B.light(I={10:0.###}, col={11}) {12}",
s.name, ok, settle, errAY, errAH, errBY, errBH, la.intensity, la.color, la.cookie ? la.cookie.name : "none", lb.intensity, lb.color, colorCheck);
_log.Add(line);
Debug.Log("[L230SR-PLAYMODE] " + line);
_json.Append(" {\"state\": \"").Append(s.name).Append("\", \"ok\": ").Append(ok ? "true" : "false")
.Append(", \"detail\": \"").Append(line.Replace("\"", "'")).Append("\"}").Append(si < states.Length - 1 ? ",\n" : "\n");
Capture($"L230SR_playmode_step{si + 1}.png");
}
_json.Append(" ],\n \"all_ok\": ").Append(allOk ? "true" : "false").Append("\n}\n");
Directory.CreateDirectory("Logs");
File.WriteAllText(Path.Combine("Logs", "L230SR_playmode_artnet_report.json"), _json.ToString());
Assert.IsTrue(allOk, string.Join("\n", _log));
}
static string LensGoboName(DmxFixtureComponent f)
{
var lens = f.GetComponentsInChildren<Renderer>(true).FirstOrDefault(r => r.name == "Lens");
if (lens == null) return null;
var mpb = new MaterialPropertyBlock();
for (int i = -1; i < lens.sharedMaterials.Length; i++)
{
if (i < 0) lens.GetPropertyBlock(mpb); else lens.GetPropertyBlock(mpb, i);
if (mpb.isEmpty) continue;
var t = mpb.GetTexture("_GoboTexture");
if (t != null) return t.name;
}
foreach (var m in lens.sharedMaterials)
if (m != null && m.HasProperty("_GoboTexture") && m.GetTexture("_GoboTexture") != null) return m.GetTexture("_GoboTexture").name + " (material)";
return null;
}
static void Capture(string file)
{
try
{
var cam = Camera.main;
if (cam == null) return;
var rt = new RenderTexture(1280, 720, 24);
cam.targetTexture = rt; cam.Render();
RenderTexture.active = rt;
var tex = new Texture2D(1280, 720, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, 1280, 720), 0, 0); tex.Apply();
cam.targetTexture = null; RenderTexture.active = null;
Directory.CreateDirectory("Logs");
File.WriteAllBytes(Path.Combine("Logs", file), tex.EncodeToPNG());
UnityEngine.Object.Destroy(tex); rt.Release();
}
catch (Exception e) { Debug.LogWarning("[L230SR-PLAYMODE] capture failed: " + e.Message); }
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 225c94d6e29ea1e708b55c6b68356cb1
@@ -0,0 +1,296 @@
// LISTEN-ONLY live monitor for testing the Legend 230SR Beam against an external Art-Net source (e.g. ChamSys MagicQ).
// It never sends Art-Net. It loads the isolated fixture test scene, records what the package receiver actually gets
// (sender address, universe, opcode, rate), decodes each fixture's channels from its own patch (universe / start address /
// mode), and compares them with the fixture's real state (pan/tilt angles, dimmer, shutter, colour, gobo).
//
// Gate: runs only with environment variable L230SR_LIVE_MONITOR=1 (otherwise Ignored). Driven by
// Assets/Fixtures/Chauvet_Legend_230SR_Beam/Tests/MagicQ~/l230sr_live_monitor.sh (start | status | snap <label> | stop)
// Files (project Logs/): L230SR_live_status.json (rewritten every second), L230SR_live_snapshots.jsonl (one line per
// snapshot), L230SR_live_<label>.png, L230SR_live_summary.json. Trigger files: L230SR_snap_<label>, L230SR_live_stop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using ArtNet.Runtime;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.TestTools;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif
namespace PressureChamber.Fixtures.Legend230SR.LiveMonitor
{
public class Legend230SRLiveMonitor
{
const string ScenePath = "Assets/Fixtures/Chauvet_Legend_230SR_Beam/Scenes/L230SR_FixtureTest.unity";
const string LogDir = "Logs";
static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
sealed class FixtureProbe
{
public DmxFixtureComponent F;
public Transform Yoke, Head;
public Renderer Lens;
public readonly Queue<(float t, float i)> Window = new();
public Dictionary<string, int> Ch = new(); // logical name -> absolute 1-based channel
public bool Dimmer16;
}
readonly Dictionary<string, long> _packetCounts = new();
readonly Dictionary<int, int[]> _latestDmx = new();
readonly Dictionary<int, float> _firstSeen = new(), _lastSeen = new();
readonly List<string> _errors = new();
long _dmxPackets, _nonDmxPackets;
[UnityTest, Category("LiveArtNet"), Timeout(7200000)]
public IEnumerator LiveMonitor_ListenOnly()
{
if (Environment.GetEnvironmentVariable("L230SR_LIVE_MONITOR") != "1")
Assert.Ignore("Live monitor: set L230SR_LIVE_MONITOR=1 (use Tests/MagicQ~/l230sr_live_monitor.sh).");
float minutes = float.TryParse(Environment.GetEnvironmentVariable("L230SR_MONITOR_MINUTES"), NumberStyles.Float, Inv, out var m) ? m : 30f;
LogAssert.ignoreFailingMessages = true; // a monitoring session must not abort on a logged error
Application.logMessageReceived += OnLog;
Directory.CreateDirectory(LogDir);
foreach (var f in Directory.GetFiles(LogDir, "L230SR_snap_*")) File.Delete(f);
if (File.Exists(Path.Combine(LogDir, "L230SR_live_stop"))) File.Delete(Path.Combine(LogDir, "L230SR_live_stop"));
#if UNITY_EDITOR
var op = EditorSceneManager.LoadSceneAsyncInPlayMode(ScenePath, new LoadSceneParameters(LoadSceneMode.Single));
while (!op.isDone) yield return null;
#endif
yield return new WaitForSecondsRealtime(0.5f);
var receiver = UnityEngine.Object.FindAnyObjectByType<ArtNetReceiver>();
Assert.NotNull(receiver, "No ArtNetReceiver in the test scene.");
var probes = UnityEngine.Object.FindObjectsByType<DmxFixtureComponent>(FindObjectsSortMode.None)
.OrderBy(f => f.name).Select(MakeProbe).ToList();
receiver.OnDataReceived += OnPacket;
float start = Time.realtimeSinceStartup, nextStatus = 0f;
bool stop = false;
string stopReason = "timeout";
while (!stop && Time.realtimeSinceStartup - start < minutes * 60f)
{
yield return null;
float now = Time.realtimeSinceStartup;
foreach (var p in probes) SampleLight(p, now);
if (now >= nextStatus)
{
nextStatus = now + 1f;
WriteAtomic(Path.Combine(LogDir, "L230SR_live_status.json"), BuildReport("status", receiver, probes, now - start));
}
foreach (var trig in Directory.GetFiles(LogDir, "L230SR_snap_*"))
{
string label = Sanitize(Path.GetFileName(trig).Substring("L230SR_snap_".Length));
// (no WaitForEndOfFrame: it is not evoked in batch mode and stalls the test's frame loop)
string png = Path.Combine(LogDir, $"L230SR_live_{label}.png");
Capture(png);
File.AppendAllText(Path.Combine(LogDir, "L230SR_live_snapshots.jsonl"),
BuildReport(label, receiver, probes, Time.realtimeSinceStartup - start).Replace("\n", " ") + "\n");
File.Delete(trig);
Debug.Log($"[L230SR-LIVE] snapshot '{label}' written");
}
if (File.Exists(Path.Combine(LogDir, "L230SR_live_stop"))) { stop = true; stopReason = "stop file"; }
}
receiver.OnDataReceived -= OnPacket;
Application.logMessageReceived -= OnLog;
var summary = BuildReport("summary:" + stopReason, receiver, probes, Time.realtimeSinceStartup - start);
WriteAtomic(Path.Combine(LogDir, "L230SR_live_summary.json"), summary);
Debug.Log("[L230SR-LIVE] " + summary.Replace("\n", " "));
Assert.IsTrue(receiver.Statistics.IsActive, "Receiver never bound UDP " + receiver.port + " (port in use by another program?)");
}
void OnLog(string msg, string stack, LogType type)
{
if ((type == LogType.Error || type == LogType.Exception || type == LogType.Assert) && _errors.Count < 50)
_errors.Add(type + ": " + msg.Split('\n')[0]);
}
void OnPacket(ArtNetData d)
{
string key = $"{d.OpCode} (0x{(int)d.OpCode & 0xFFFF:X4}) -> universe {d.Universe}";
_packetCounts[key] = _packetCounts.TryGetValue(key, out var c) ? c + 1 : 1;
float now = Time.realtimeSinceStartup;
if (!_firstSeen.ContainsKey(d.Universe)) _firstSeen[d.Universe] = now;
_lastSeen[d.Universe] = now;
if (d.OpCode == ArtNetOpCode.OpDmx) { _dmxPackets++; _latestDmx[d.Universe] = (int[])d.Channels.Clone(); }
else _nonDmxPackets++;
}
static FixtureProbe MakeProbe(DmxFixtureComponent f)
{
var p = new FixtureProbe
{
F = f,
Yoke = f.GetComponentsInChildren<Transform>(true).First(t => t.name == "Yoke"),
Head = f.GetComponentsInChildren<Transform>(true).First(t => t.name == "Head"),
Lens = f.GetComponentsInChildren<Renderer>(true).FirstOrDefault(r => r.name == "Lens"),
};
var mode = f.fixture.modes[f.mode];
for (int i = 0; i < mode.elements.Count; i++)
{
var e = mode.elements[i];
string n = e.attribute switch
{
FixtureAttribute.Pan => e.byteRole == FixtureByteRole.Fine ? "pan_fine" : "pan",
FixtureAttribute.Tilt => e.byteRole == FixtureByteRole.Fine ? "tilt_fine" : "tilt",
FixtureAttribute.Dimmer => e.byteRole == FixtureByteRole.Fine ? "dimmer_fine" : "dimmer",
FixtureAttribute.Strobe => "shutter",
FixtureAttribute.ColorWheel => "color",
FixtureAttribute.GoboWheel => "gobo",
FixtureAttribute.Prism when e.role == FixtureChannelRole.SelectMode => "prism",
FixtureAttribute.Control => "control",
_ => null
};
if (n != null && !p.Ch.ContainsKey(n)) p.Ch[n] = f.startAddress + i;
}
p.Dimmer16 = p.Ch.ContainsKey("dimmer_fine");
return p;
}
static void SampleLight(FixtureProbe p, float now)
{
var l = p.F.targetLight;
p.Window.Enqueue((now, l != null && l.isActiveAndEnabled ? l.intensity : 0f));
while (p.Window.Count > 0 && now - p.Window.Peek().t > 1f) p.Window.Dequeue();
}
string BuildReport(string label, ArtNetReceiver r, List<FixtureProbe> probes, float elapsed)
{
var st = r.Statistics;
var sb = new StringBuilder();
sb.Append("{\n");
KV(sb, "label", label); KV(sb, "time_local", DateTime.Now.ToString("s", Inv)); KV(sb, "elapsed_s", elapsed);
KV(sb, "receiver_bound", st.IsActive); KV(sb, "receiver_host", r.host); KV(sb, "receiver_port", st.LocalPort);
KV(sb, "last_sender", st.LastSenderAddress == null ? "none" : $"{st.LastSenderAddress}:{st.LastSenderPort}");
KV(sb, "packets_received", st.ReceivedPacketCount); KV(sb, "packets_valid_artnet", st.ValidArtNetPacketCount);
KV(sb, "packets_invalid", st.InvalidPacketCount); KV(sb, "receive_errors", st.ReceiveErrorCount);
KV(sb, "dmx_packets", _dmxPackets); KV(sb, "non_dmx_packets_reaching_rig", _nonDmxPackets);
sb.Append(" \"packets_by_opcode_universe\": {");
sb.Append(string.Join(", ", _packetCounts.OrderBy(k => k.Key).Select(k => $"\"{Esc(k.Key)}\": {k.Value}")));
sb.Append("},\n \"universe_rate_hz\": {");
sb.Append(string.Join(", ", _firstSeen.Keys.OrderBy(u => u).Select(u =>
{
string key = _packetCounts.Keys.FirstOrDefault(k => k.EndsWith($"universe {u}") && k.StartsWith("OpDmx"));
long n = key != null ? _packetCounts[key] : 0;
float span = Mathf.Max(0.001f, _lastSeen[u] - _firstSeen[u]);
return $"\"{u}\": {(n > 1 ? (n - 1) / span : 0f).ToString("0.0", Inv)}";
})));
sb.Append("},\n \"fixtures\": [\n");
for (int i = 0; i < probes.Count; i++)
{
sb.Append(DescribeFixture(probes[i]));
sb.Append(i < probes.Count - 1 ? ",\n" : "\n");
}
sb.Append(" ],\n \"errors\": [");
sb.Append(string.Join(", ", _errors.Select(e => "\"" + Esc(e) + "\"")));
sb.Append("]\n}\n");
return sb.ToString();
}
string DescribeFixture(FixtureProbe p)
{
var f = p.F;
_latestDmx.TryGetValue(f.universe, out var u);
int V(string n) => u != null && p.Ch.TryGetValue(n, out int ch) && ch >= 1 && ch <= 512 ? u[ch - 1] : -1;
int pan16 = V("pan") < 0 ? -1 : (V("pan") << 8) | Math.Max(0, V("pan_fine"));
int tilt16 = V("tilt") < 0 ? -1 : (V("tilt") << 8) | Math.Max(0, V("tilt_fine"));
float dim01 = V("dimmer") < 0 ? -1 : p.Dimmer16 ? ((V("dimmer") << 8) | Math.Max(0, V("dimmer_fine"))) / 65535f : V("dimmer") / 255f;
float ExpPan() { float d = (pan16 / 65535f - 0.5f) * f.panRangeDeg; if (f.panInvert) d = -d; return d + f.panOffsetDeg; }
float ExpTilt() { float d = (tilt16 / 65535f - 0.5f) * f.tiltRangeDeg; if (f.tiltInvert) d = -d; return d + f.tiltOffsetDeg; }
var fwd = p.Yoke.localRotation * Vector3.forward;
var up = p.Head.localRotation * Vector3.up;
float measPan = Mathf.Atan2(fwd.x, fwd.z) * Mathf.Rad2Deg; // pan about +Y (prefab: panAxis Y)
float measTilt = Mathf.Atan2(-up.z, up.y) * Mathf.Rad2Deg; // tilt about -X (prefab: tiltAxis MinusX)
var mode = f.fixture.modes[f.mode];
string ShutterRange()
{
int v = V("shutter"); if (v < 0) return "n/a";
var el = mode.elements[p.Ch["shutter"] - f.startAddress];
var rg = el.ranges.FirstOrDefault(x => x.Contains(v));
return rg == null ? "no range" : $"{rg.name} [{rg.type}]";
}
var cw = mode.wheelBindings.FirstOrDefault(b => b.attribute == FixtureAttribute.ColorWheel)?.colorWheel;
var cr = cw != null && V("color") >= 0 ? cw.ResolveRange(V("color")) : null;
var l = f.targetLight;
float mn = p.Window.Count > 0 ? p.Window.Min(x => x.i) : 0f, mx = p.Window.Count > 0 ? p.Window.Max(x => x.i) : 0f;
var sb = new StringBuilder(" {");
sb.Append($"\"name\": \"{Esc(f.name)}\", \"mode\": \"{Esc(mode.modeName)}\", \"universe\": {f.universe}, \"start_address\": {f.startAddress}, ");
sb.Append($"\"channels\": {{{string.Join(", ", p.Ch.OrderBy(k => k.Value).Select(k => $"\"{k.Key}\": {k.Value}"))}}}, ");
sb.Append($"\"dmx_received\": {(u != null ? "true" : "false")}, ");
sb.Append($"\"raw\": {{{string.Join(", ", p.Ch.OrderBy(k => k.Value).Select(k => $"\"{k.Key}\": {V(k.Key)}"))}}}, ");
if (pan16 >= 0)
sb.Append(string.Format(Inv, "\"pan\": {{\"dmx16\": {0}, \"expected_deg\": {1:0.00}, \"measured_deg_wrapped\": {2:0.00}, \"error_deg\": {3:0.000}}}, ",
pan16, ExpPan(), measPan, Mathf.Abs(Mathf.DeltaAngle(measPan, ExpPan()))));
if (tilt16 >= 0)
sb.Append(string.Format(Inv, "\"tilt\": {{\"dmx16\": {0}, \"expected_deg\": {1:0.00}, \"measured_deg\": {2:0.00}, \"error_deg\": {3:0.000}}}, ",
tilt16, ExpTilt(), measTilt, Mathf.Abs(Mathf.DeltaAngle(measTilt, ExpTilt()))));
sb.Append(string.Format(Inv, "\"dimmer\": {{\"value01\": {0:0.0000}, \"bits\": {1}}}, ", dim01, p.Dimmer16 ? 16 : 8));
sb.Append($"\"shutter\": {{\"dmx\": {V("shutter")}, \"range\": \"{Esc(ShutterRange())}\"}}, ");
sb.Append($"\"color\": {{\"dmx\": {V("color")}, \"range\": \"{Esc(cr != null ? $"{cr.name} [{cr.type}]" : "n/a")}\", " +
$"\"slot_rgb\": \"{(cr != null ? Rgb(cr.colorA) : "n/a")}\"}}, ");
sb.Append($"\"gobo\": {{\"dmx\": {V("gobo")}, \"lens_texture\": \"{Esc(LensGobo(p.Lens) ?? "none")}\"}}, ");
sb.Append(string.Format(Inv, "\"light\": {{\"enabled\": {0}, \"intensity\": {1:0.###}, \"intensity_min_1s\": {2:0.###}, \"intensity_max_1s\": {3:0.###}, \"rgb\": \"{4}\", \"cookie\": \"{5}\"}}",
(l != null && l.isActiveAndEnabled) ? "true" : "false", l ? l.intensity : 0f, mn, mx, l ? Rgb(l.color) : "n/a", l && l.cookie ? Esc(l.cookie.name) : "none"));
sb.Append("}");
return sb.ToString();
}
static string LensGobo(Renderer lens)
{
if (lens == null) return null;
var mpb = new MaterialPropertyBlock();
for (int i = 0; i < lens.sharedMaterials.Length; i++)
{
lens.GetPropertyBlock(mpb, i);
if (!mpb.isEmpty && mpb.GetTexture("_GoboTexture") is Texture t && t != null) return t.name;
}
return null;
}
static string Rgb(Color c) => string.Format(Inv, "{0:0.000},{1:0.000},{2:0.000}", c.r, c.g, c.b);
static string Esc(string s) => (s ?? "").Replace("\\", "\\\\").Replace("\"", "\\\"");
static string Sanitize(string s) => new string(s.Select(ch => char.IsLetterOrDigit(ch) || ch == '-' || ch == '_' ? ch : '_').ToArray());
static void KV(StringBuilder sb, string k, object v)
{
string val = v switch
{
string s => "\"" + Esc(s) + "\"",
bool b => b ? "true" : "false",
float f => f.ToString("0.###", Inv),
_ => Convert.ToString(v, Inv)
};
sb.Append($" \"{k}\": {val},\n");
}
static void WriteAtomic(string path, string text)
{
string tmp = path + ".tmp";
File.WriteAllText(tmp, text);
if (File.Exists(path)) File.Delete(path);
File.Move(tmp, path);
}
static void Capture(string file)
{
var cam = Camera.main;
if (cam == null) return;
var rt = new RenderTexture(1280, 720, 24);
cam.targetTexture = rt; cam.Render();
RenderTexture.active = rt;
var tex = new Texture2D(1280, 720, TextureFormat.RGB24, false);
tex.ReadPixels(new Rect(0, 0, 1280, 720), 0, 0); tex.Apply();
cam.targetTexture = null; RenderTexture.active = null;
File.WriteAllBytes(file, tex.EncodeToPNG());
UnityEngine.Object.Destroy(tex); rt.Release();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b53ce8ff85d486d9dbcaa17de91afcf7
@@ -0,0 +1,19 @@
{
"name": "PressureChamber.Fixtures.Legend230SR.PlayModeTests",
"rootNamespace": "PressureChamber.Fixtures.Legend230SR.Tests",
"references": [
"ArtNet.Runtime"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": false,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false,
"optionalUnityReferences": [
"TestAssemblies"
]
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 905e5883ea82f719a9c7efd00844d842
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant: