GruppeC/frontend/SmartLectureRoom/Assets/SmartRoom/Scripts/UI/SmartRoomHUD.cs

694 lines
35 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.Globalization;
using UnityEngine;
namespace SmartRoom
{
/// <summary>
/// Schlichtes, dunkles Dashboard (IMGUI, keine Zusatzpakete nötig):
/// links Raumklima + Außenwerte + Szenarien, rechts Steuerung / Nutzerwünsche / Verbindung,
/// unten der zuletzt durchlaufene Pfad der Entscheidungslogik.
/// </summary>
public class SmartRoomHUD : MonoBehaviour
{
public RoomEnvironment env;
public RoomDevices devices;
public ClimateController controller;
public ArduinoBridge bridge;
public WeatherService weather;
public OrbitCamera orbit;
public bool visible = true;
static readonly Color Accent = new Color(0.20f, 0.74f, 0.78f);
static readonly Color Good = new Color(0.35f, 0.82f, 0.55f);
static readonly Color Warn = new Color(0.98f, 0.74f, 0.30f);
static readonly Color Bad = new Color(0.95f, 0.40f, 0.38f);
static readonly Color TextMain = new Color(0.93f, 0.95f, 0.97f);
static readonly Color TextDim = new Color(0.60f, 0.65f, 0.70f);
float scale = -1f;
GUIStyle panel, card, title, header, label, dim, valueRight, bigValue, button, seg, slider, thumb, field, tagStyle, bar, pill, logLine, logLineStrong;
Texture2D texPanel, texCard, texBtn, texBtnHover, texBtnOn, texTrack, texThumb, texWhite, texField, texPill;
Rect leftRect, rightRect, bottomRect;
bool showBottom, logCollapsed;
Vector2 leftScroll, rightScroll, logScroll;
int tab;
string latField, lonField, udpField, backendField;
string[] foundPorts;
static readonly string[] Tabs = { "Steuerung", "Wünsche", "Verbindung" };
static readonly string[] SpeedLabels = { "Pause", "1×", "5×", "20×" };
static readonly float[] Speeds = { 0f, 1f, 5f, 20f };
float S(float v) => v * scale;
int I(float v) => Mathf.RoundToInt(v * scale);
// ================================================================ OnGUI
void OnGUI()
{
if (env == null || devices == null || controller == null) return;
EnsureStyles();
var e = Event.current;
if (e.type == EventType.KeyDown && GUIUtility.keyboardControl == 0) HandleKeys(e);
if (!visible)
{
GUI.Label(new Rect(S(16), Screen.height - S(36), S(400), S(24)), "H – Dashboard einblenden", dim);
ForwardToCamera(e, false);
return;
}
float m = S(16);
leftRect = new Rect(m, m, S(330), Screen.height - 2 * m);
rightRect = new Rect(Screen.width - S(350) - m, m, S(350), Screen.height - 2 * m);
float bw = Mathf.Min(S(760), rightRect.x - leftRect.xMax - 2 * m);
float bh = logCollapsed ? S(46) : S(230);
bottomRect = new Rect((leftRect.xMax + rightRect.x) / 2f - bw / 2f, Screen.height - bh - m, bw, bh);
showBottom = bw > S(280);
DrawPanel(leftRect, ref leftScroll, DrawLeft);
DrawPanel(rightRect, ref rightScroll, DrawRight);
if (showBottom) DrawBottom();
bool over = leftRect.Contains(e.mousePosition) || rightRect.Contains(e.mousePosition) ||
(showBottom && bottomRect.Contains(e.mousePosition));
ForwardToCamera(e, over);
}
void ForwardToCamera(Event e, bool overUi)
{
if (orbit == null || e.type == EventType.Used) return;
bool relevant = e.isMouse || e.type == EventType.ScrollWheel;
if (relevant && (!overUi || orbit.IsDragging)) orbit.HandleEvent(e);
}
void HandleKeys(Event e)
{
switch (e.keyCode)
{
case KeyCode.H: visible = !visible; break;
case KeyCode.Alpha1: orbit?.Preset(0); break;
case KeyCode.Alpha2: orbit?.Preset(1); break;
case KeyCode.Alpha3: orbit?.Preset(2); break;
case KeyCode.Alpha4: orbit?.Preset(3); break;
case KeyCode.T: devices.door?.Toggle(); break;
case KeyCode.B: if (devices.projector != null) devices.projector.beamerOn = !devices.projector.beamerOn; break;
case KeyCode.Space: controller.RunCycle(); break;
default: return;
}
e.Use();
}
void DrawPanel(Rect r, ref Vector2 scroll, Action content)
{
GUI.Box(r, GUIContent.none, panel);
GUILayout.BeginArea(new Rect(r.x + S(16), r.y + S(14), r.width - S(32), r.height - S(28)));
scroll = GUILayout.BeginScrollView(scroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
content();
GUILayout.EndScrollView();
GUILayout.EndArea();
}
// ================================================================ Links: Raumklima
void DrawLeft()
{
GUILayout.Label("Smart Lecture Room", title);
string src = env.AnyMeasured ? "Arduino live" : bridge != null && bridge.Connected ? "warte auf Arduino" : "Simulation";
GUILayout.Label($"Digitaler Zwilling · {env.ClockText} · {src}", dim);
GUILayout.Space(S(8));
GUILayout.BeginHorizontal();
GUILayout.Label("Vorlesung läuft", label);
GUILayout.FlexibleSpace();
env.lectureRunning = Switch(env.lectureRunning);
GUILayout.EndHorizontal();
GUILayout.Space(S(4));
GUILayout.Label("Zeitraffer (simulierte Minuten pro Sekunde)", dim);
int speedIdx = Array.IndexOf(Speeds, env.timeScale);
int newIdx = GUILayout.Toolbar(speedIdx, SpeedLabels, seg);
if (newIdx != speedIdx && newIdx >= 0) env.timeScale = Speeds[newIdx];
Section("INNENRAUM");
float t = env.indoorTemp, co2 = env.co2;
Metric("Temperatur", $"{t:0.0} °C", Mathf.InverseLerp(10f, 35f, t),
t >= controller.limits.tempLow && t <= controller.limits.tempHigh ? Good : (t >= 18f && t <= 27f ? Warn : Bad),
env.IsMeasured("t"));
Metric("CO2", $"{co2:0} ppm", Mathf.InverseLerp(400f, 2000f, co2),
co2 < 800f ? Good : co2 <= controller.limits.co2Limit ? Warn : Bad, env.IsMeasured("co2"));
Metric("Helligkeit", env.IsMeasured("lightpct") ? $"{env.lightPercent:0} % (≈ {env.indoorLux:0} lx)" : $"{env.indoorLux:0} lx",
Mathf.InverseLerp(0f, 1200f, env.indoorLux), Accent, env.IsMeasured("lux"));
Metric("Lärm im Raum", $"{env.indoorNoise:0} dB", Mathf.InverseLerp(30f, 90f, env.indoorNoise),
env.indoorNoise < 55f ? Good : env.indoorNoise < 70f ? Warn : Bad, env.IsMeasured("noise"));
// Luftfeuchte und TVOC werden nicht simuliert – nur anzeigen, wenn der Arduino sie liefert
if (env.IsMeasured("rh"))
Metric("Luftfeuchte", $"{env.indoorHumidity:0} %", env.indoorHumidity / 100f,
env.indoorHumidity >= 30f && env.indoorHumidity <= 60f ? Good : Warn, true);
if (env.IsMeasured("tvoc"))
Metric("TVOC", $"{env.tvoc:0} ppb", Mathf.InverseLerp(0f, 1000f, env.tvoc),
env.tvoc < 220f ? Good : env.tvoc < 660f ? Warn : Bad, true);
env.occupants = Mathf.RoundToInt(SliderRow("Personen im Raum", env.occupants, 0f, 120f, "{0:0}", !env.IsMeasured("persons")));
if (!env.IsMeasured("t"))
env.indoorTemp = SliderRow("Temperatur innen setzen", env.indoorTemp, 10f, 35f, "{0:0.0} °C");
if (!env.IsMeasured("co2"))
env.co2 = SliderRow("CO2 innen setzen", env.co2, 400f, 2500f, "{0:0} ppm");
Section(weather != null && weather.useLiveWeather ? "AUSSEN · OPEN-METEO" : "AUSSEN");
env.outdoorTemp = SliderRow("Temperatur", env.outdoorTemp, -15f, 40f, "{0:0.0} °C");
env.outdoorAqi = SliderRow("Luftqualität (AQI, hoch = schlecht)", env.outdoorAqi, 0f, 120f, "{0:0}");
env.outdoorNoise = SliderRow(env.IsMeasured("nout") ? "Lärm (Mikrofon draußen)" : "Lärm", env.outdoorNoise, 30f, 100f, "{0:0} dB", !env.IsMeasured("nout"));
env.windSpeed = SliderRow("Wind", env.windSpeed, 0f, 25f, "{0:0.0} m/s");
env.solar = SliderRow("Sonneneinstrahlung", env.solar, 0f, 1000f, "{0:0} W/m²");
Section("SZENARIEN");
GUILayout.BeginHorizontal();
GUILayout.Label("Erkannt", label);
GUILayout.FlexibleSpace();
Tag(controller.Scenario, controller.Scenario == ClimateController.NormalScenario ? Good : Warn);
Tag(env.AnyMeasured ? "AUS SENSORDATEN" : "AUS SIMULATION", env.AnyMeasured ? Good : TextDim);
GUILayout.EndHorizontal();
ScenarioRow("Hitze 30 °C", () => { env.indoorTemp = 30f; env.outdoorTemp = 24f; env.solar = 750f; env.windSpeed = 2f; env.outdoorNoise = 55f; env.outdoorAqi = 25f; },
"Stickig + kalt", () => { env.co2 = 1600f; env.outdoorTemp = -2f; env.solar = 150f; });
ScenarioRow("Schlechte Außenluft", () => { env.co2 = 1450f; env.outdoorAqi = 85f; env.outdoorTemp = 15f; },
"Baustellenlärm", () => { env.co2 = 1350f; env.outdoorNoise = 82f; env.outdoorTemp = 15f; env.outdoorAqi = 25f; });
ScenarioRow("Sturm", () => { env.co2 = 1300f; env.windSpeed = 16f; env.outdoorTemp = 12f; env.outdoorNoise = 55f; env.outdoorAqi = 25f; },
"Wintermorgen", () => { env.indoorTemp = 17.5f; env.co2 = 600f; env.outdoorTemp = -3f; env.solar = 80f; env.windSpeed = 3f; });
ScenarioRow("Pralle Sonne", () => { env.solar = 850f; env.outdoorTemp = 22f; },
"Normalbetrieb", () =>
{
env.indoorTemp = 22f; env.co2 = 650f; env.outdoorTemp = 14f; env.outdoorAqi = 25f;
env.outdoorNoise = 55f; env.windSpeed = 3f; env.solar = 350f;
});
GUILayout.Label("Das passende Szenario wird aus den Werten erkannt (hervorgehoben) und löst sofort einen Prüfzyklus aus. Mit Arduino kommen Temperatur und CO2 vom Sensor – Knöpfe setzen dann nur noch die Außenwerte.", dim);
GUILayout.Space(S(4));
GUILayout.Label("Maus: ziehen = drehen · Shift/rechts = schieben · Rad = Zoom · Tür anklicken\nTasten: 1–4 Ansichten · T Tür · B Beamer · Leertaste prüfen · H Dashboard", dim);
}
void ScenarioRow(string a, Action fa, string b, Action fb)
{
GUILayout.BeginHorizontal();
ScenarioButton(a, fa);
ScenarioButton(b, fb);
GUILayout.EndHorizontal();
}
void ScenarioButton(string text, Action set)
{
// erkanntes Szenario wird wie ein aktiver Knopf dargestellt ("Hitze 30 °C" passt zu "Hitze")
bool active = text.StartsWith(controller.Scenario, StringComparison.Ordinal);
if (GUILayout.Toggle(active, text, button) != active) { set(); controller.RunCycle(); }
}
// ================================================================ Rechts: Tabs
void DrawRight()
{
tab = GUILayout.Toolbar(tab, Tabs, seg);
GUILayout.Space(S(6));
switch (tab)
{
case 0: DrawControl(); break;
case 1: DrawWishes(); break;
default: DrawConnection(); break;
}
}
void DrawControl()
{
Section("BETRIEBSART");
int mode = GUILayout.Toolbar(controller.autoMode ? 0 : 1, new[] { "Automatik", "Manuell" }, seg);
bool auto = mode == 0;
if (auto != controller.autoMode)
{
controller.autoMode = auto;
if (auto) controller.RunCycle();
}
GUILayout.BeginHorizontal();
GUILayout.Label(env.lectureRunning
? $"Nächste Prüfung in {controller.MinutesUntilNextCheck:0} min (alle {controller.checkIntervalMinutes:0} min)"
: "Keine Vorlesung – Steuerung pausiert", dim);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Jetzt prüfen", button, GUILayout.Width(S(110)))) controller.RunCycle();
GUILayout.EndHorizontal();
Section("AKTOREN");
bool manual = !controller.autoMode;
// Fenster
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label("Fenster (4×)", label);
GUILayout.FlexibleSpace();
GUILayout.Label(devices.WindowLabel, valueRight);
GUILayout.EndHorizontal();
Bar(devices.WindowAirflow, Accent);
if (manual)
{
int w = GUILayout.Toolbar((int)devices.WindowTarget, new[] { "Zu", "Kipp", "Auf" }, seg);
if (w != (int)devices.WindowTarget) devices.SetWindows((WindowState)w);
}
GUILayout.EndVertical();
float v;
v = DeviceRow("Jalousien", devices.BlindPosition > 0.5f ? "unten" : "oben", devices.BlindPosition, devices.BlindTarget, manual);
if (manual && !Mathf.Approximately(v, devices.BlindTarget)) devices.SetBlinds(v);
v = DeviceRow("Heizung", null, devices.HeatingLevel, devices.HeatingTarget, manual, new Color(1f, 0.55f, 0.35f));
if (manual && !Mathf.Approximately(v, devices.HeatingTarget)) devices.SetHeating(v);
v = DeviceRow("Lüftungsanlage", null, devices.VentLevel, devices.VentTarget, manual);
if (manual && !Mathf.Approximately(v, devices.VentTarget)) devices.SetVentilation(v);
v = DeviceRow("Licht", null, devices.LightLevel, devices.LightTarget, manual, new Color(1f, 0.9f, 0.6f));
if (manual && !Mathf.Approximately(v, devices.LightTarget)) devices.SetLights(v);
Section("MEDIEN & ZUGANG");
if (devices.projector != null)
{
GUILayout.BeginHorizontal(card);
GUILayout.Label("Beamer + Leinwand", label);
GUILayout.FlexibleSpace();
devices.projector.beamerOn = Switch(devices.projector.beamerOn);
GUILayout.EndHorizontal();
}
if (devices.door != null)
{
GUILayout.BeginHorizontal(card);
GUILayout.Label("Tür offen", label);
GUILayout.FlexibleSpace();
devices.door.open = Switch(devices.door.open);
GUILayout.EndHorizontal();
}
if (!manual) GUILayout.Label("Im Automatikmodus steuert die Logik Fenster, Jalousien, Heizung, Lüftung und Licht. Für Handsteuerung auf \"Manuell\" wechseln.", dim);
}
float DeviceRow(string name, string state, float current, float target, bool editable, Color? color = null)
{
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label(name, label);
GUILayout.FlexibleSpace();
string pct = $"{current * 100f:0} %";
GUILayout.Label(state != null ? $"{state} · {pct}" : pct, valueRight);
GUILayout.EndHorizontal();
Bar(current, color ?? Accent);
if (editable) target = GUILayout.HorizontalSlider(target, 0f, 1f, slider, thumb);
GUILayout.EndVertical();
return target;
}
void DrawWishes()
{
Section("DEIN WUNSCH");
if (controller.wishes.Count == 0) controller.wishes.Add(new UserWish("Du", 22f, false));
var own = controller.wishes[0];
own.temperature = SliderRow("Wunschtemperatur", own.temperature, 18f, 26f, "{0:0.0} °C");
GUILayout.BeginHorizontal();
GUILayout.Label("Fenster öffnen gewünscht", label);
GUILayout.FlexibleSpace();
own.windowOpen = Switch(own.windowOpen);
GUILayout.EndHorizontal();
Section("ALLE EINGABEN");
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label($"Ø {controller.AverageWish:0.0} °C", bigValue);
GUILayout.FlexibleSpace();
GUILayout.Label($"Fenster: {controller.WindowVotes} von {controller.wishes.Count} dafür", valueRight);
GUILayout.EndHorizontal();
GUILayout.EndVertical();
for (int i = 1; i < controller.wishes.Count; i++)
{
var w = controller.wishes[i];
GUILayout.BeginHorizontal();
GUILayout.Label(w.name, label);
GUILayout.FlexibleSpace();
GUILayout.Label($"{w.temperature:0.0} °C · Fenster {(w.windowOpen ? "ja" : "nein")}", valueRight);
GUILayout.EndHorizontal();
}
GUILayout.Space(S(4));
GUILayout.BeginHorizontal();
if (GUILayout.Button("+ Teilnehmer", button))
controller.wishes.Add(new UserWish($"Teilnehmer {controller.wishes.Count}",
Mathf.Round(UnityEngine.Random.Range(19.5f, 24f) * 2f) / 2f, UnityEngine.Random.value < 0.35f));
if (GUILayout.Button("– Teilnehmer", button) && controller.wishes.Count > 1)
controller.wishes.RemoveAt(controller.wishes.Count - 1);
GUILayout.EndHorizontal();
if (GUILayout.Button("Wünsche jetzt anwenden", button)) controller.RunCycle();
GUILayout.Label("Die Wünsche werden gemittelt (Aggregation) und fließen beim nächsten Prüfzyklus in Heizung und Fenstersteuerung ein.", dim);
}
void DrawConnection()
{
Section("SENSORQUELLE");
int m = GUILayout.Toolbar((int)bridge.mode, new[] { "Simulation", "Seriell", "UDP", "Backend" }, seg);
if (m != (int)bridge.mode)
{
bridge.Disconnect();
bridge.mode = (LinkMode)m;
bridge.Disconnect(); // Status aktualisieren
}
if (bridge.mode == LinkMode.Serial)
{
GUILayout.Label("Serieller Port", dim);
bridge.serialPort = GUILayout.TextField(bridge.serialPort, field);
GUILayout.BeginHorizontal();
GUILayout.Label($"Baudrate {bridge.baudRate}", dim);
GUILayout.FlexibleSpace();
if (ArduinoBridge.SerialSupported && GUILayout.Button("Ports suchen", button, GUILayout.Width(S(110))))
foundPorts = ArduinoBridge.ListSerialPorts();
GUILayout.EndHorizontal();
if (foundPorts != null)
foreach (var p in foundPorts)
if (GUILayout.Button(p, button)) bridge.serialPort = p;
if (!ArduinoBridge.SerialSupported)
GUILayout.Label("Hinweis: Für USB-Seriell in Unity unter Project Settings → Player → Api Compatibility Level \".NET Framework\" wählen. Alternativ UDP/WLAN nutzen.", dim);
}
else if (bridge.mode == LinkMode.Udp)
{
GUILayout.Label("Empfangsport (Antworten gehen an Port " + bridge.udpReplyPort + " des Absenders)", dim);
if (udpField == null) udpField = bridge.udpListenPort.ToString();
udpField = GUILayout.TextField(udpField, field);
if (int.TryParse(udpField, out var port)) bridge.udpListenPort = port;
}
else if (bridge.mode == LinkMode.Backend)
{
GUILayout.Label("Adresse von backend/server.py (Arduino → ESP-01 → Server → Unity)", dim);
if (backendField == null) backendField = bridge.backendUrl;
backendField = GUILayout.TextField(backendField, field);
bridge.backendUrl = backendField.Trim();
GUILayout.Label($"Fragt alle {bridge.backendPollSeconds:0.#} s GET /api/messwerte ab (Temperatur, Luftfeuchte, eCO2, TVOC, Lautstärke, Helligkeit) und meldet die Steuerbefehle per POST /api/steuerung zurück.", dim);
GUILayout.BeginHorizontal();
GUILayout.Label("Mikrofon steht draußen", label);
GUILayout.FlexibleSpace();
bridge.MicrophoneOutdoor = Switch(bridge.MicrophoneOutdoor);
GUILayout.EndHorizontal();
GUILayout.Label(bridge.MicrophoneOutdoor ? "Lautstärke zählt als Außenlärm: über 70 dB wird die Fensteröffnung gesperrt."
: "Lautstärke zählt als Lärm im Raum (nur Anzeige).", dim);
}
if (bridge.mode != LinkMode.Simulation)
{
GUILayout.Space(S(4));
if (GUILayout.Button(bridge.Connected ? "Trennen" : "Verbinden", button))
{
if (bridge.Connected) bridge.Disconnect(); else bridge.Connect();
}
GUILayout.BeginHorizontal();
GUILayout.Label("Steuerbefehle senden", label);
GUILayout.FlexibleSpace();
bridge.sendCommands = Switch(bridge.sendCommands);
GUILayout.EndHorizontal();
}
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
Tag(bridge.Connected ? "VERBUNDEN" : bridge.mode == LinkMode.Simulation ? "SIMULATION" : "GETRENNT",
bridge.Connected ? Good : TextDim);
GUILayout.FlexibleSpace();
if (bridge.LastPacketTime >= 0f)
GUILayout.Label($"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s", valueRight);
GUILayout.EndHorizontal();
GUILayout.Label(bridge.Status, dim);
if (!string.IsNullOrEmpty(bridge.LastLine)) GUILayout.Label("← " + bridge.LastLine, dim);
if (bridge.Connected && !string.IsNullOrEmpty(bridge.LastSent)) GUILayout.Label("→ " + bridge.LastSent, dim);
GUILayout.EndVertical();
if (weather != null)
{
Section("WETTERDATEN (EXTERN)");
GUILayout.BeginHorizontal();
GUILayout.Label("Live-Wetter (Open-Meteo)", label);
GUILayout.FlexibleSpace();
bool live = Switch(weather.useLiveWeather);
if (live != weather.useLiveWeather) weather.SetLive(live);
GUILayout.EndHorizontal();
var ci = CultureInfo.InvariantCulture;
if (latField == null) latField = weather.latitude.ToString(ci);
if (lonField == null) lonField = weather.longitude.ToString(ci);
GUILayout.BeginHorizontal();
GUILayout.Label("Breite", dim, GUILayout.Width(S(50)));
latField = GUILayout.TextField(latField, field);
GUILayout.Label("Länge", dim, GUILayout.Width(S(50)));
lonField = GUILayout.TextField(lonField, field);
GUILayout.EndHorizontal();
if (float.TryParse(latField, NumberStyles.Float, ci, out var lat)) weather.latitude = lat;
if (float.TryParse(lonField, NumberStyles.Float, ci, out var lon)) weather.longitude = lon;
GUILayout.BeginHorizontal();
GUILayout.Label(weather.Status, dim);
GUILayout.FlexibleSpace();
if (weather.useLiveWeather && GUILayout.Button("Aktualisieren", button, GUILayout.Width(S(110)))) weather.RefreshNow();
GUILayout.EndHorizontal();
}
Section("PROTOKOLL");
GUILayout.Label("Arduino → Unity (eine JSON-Zeile, alle Felder optional):\n{\"t\":30.2,\"co2\":1250,\"rh\":45,\"tvoc\":30,\"lux\":320,\"noise\":48,\"tout\":12,\"aq\":30,\"nout\":55,\"wind\":3.5,\"sun\":420,\"persons\":40}\n\nBackend (server.py): {\"temperatur\":22.5,\"luftfeuchte\":45,\"eco2\":612,\"tvoc\":30,\"lautstaerke\":48.5,\"helligkeit\":60}\n\nUnity → Arduino:\n{\"window\":\"open|tilted|closed\",\"blind\":1.00,\"heat\":0.50,\"vent\":0.80,\"light\":0.40,\"beamer\":0}", dim);
}
// ================================================================ Unten: Entscheidungslogik
void DrawBottom()
{
GUI.Box(bottomRect, GUIContent.none, panel);
GUILayout.BeginArea(new Rect(bottomRect.x + S(16), bottomRect.y + S(10), bottomRect.width - S(32), bottomRect.height - S(18)));
var d = controller.Last;
GUILayout.BeginHorizontal();
GUILayout.Label("ENTSCHEIDUNGSLOGIK" + (d != null ? " · " + d.time : ""), header);
GUILayout.FlexibleSpace();
if (d != null)
{
Tag($"Fenster {d.window.Label()}", Accent);
Tag($"Lüftung {d.ventilation * 100:0} %", Accent);
Tag($"Heizung {d.heating * 100:0} %", new Color(1f, 0.55f, 0.35f));
Tag(d.blinds > 0.5f ? "Jalousie ↓" : "Jalousie ↑", TextDim);
}
if (GUILayout.Button(logCollapsed ? "+" : "–", button, GUILayout.Width(S(30)))) logCollapsed = !logCollapsed;
GUILayout.EndHorizontal();
if (!logCollapsed && d != null)
{
logScroll = GUILayout.BeginScrollView(logScroll, false, false, GUIStyle.none, GUIStyle.none, GUIStyle.none);
for (int i = 0; i < d.path.Count; i++)
{
string line = d.path[i];
GUILayout.Label($"{i + 1,2}. {line}", line.Contains("→") ? logLineStrong : logLine);
}
GUILayout.EndScrollView();
}
GUILayout.EndArea();
}
// ================================================================ Bausteine
void Section(string text)
{
GUILayout.Space(S(12));
GUILayout.Label(text, header);
}
void Metric(string name, string value, float norm, Color status, bool measured)
{
GUILayout.BeginVertical(card);
GUILayout.BeginHorizontal();
GUILayout.Label(name, dim);
GUILayout.FlexibleSpace();
Tag(measured ? "SENSOR" : "SIM", measured ? Good : TextDim);
GUILayout.EndHorizontal();
GUILayout.Label(value, bigValue);
Bar(norm, status);
GUILayout.EndVertical();
}
float SliderRow(string name, float v, float min, float max, string fmt, bool enabled = true)
{
GUILayout.BeginHorizontal();
GUILayout.Label(name, label);
GUILayout.FlexibleSpace();
GUILayout.Label(string.Format(fmt, v), valueRight);
GUILayout.EndHorizontal();
bool was = GUI.enabled;
GUI.enabled = was && enabled;
v = GUILayout.HorizontalSlider(v, min, max, slider, thumb);
GUI.enabled = was;
GUILayout.Space(S(2));
return v;
}
bool Switch(bool on)
{
Rect r = GUILayoutUtility.GetRect(S(40), S(22), GUILayout.Width(S(40)), GUILayout.Height(S(22)));
if (GUI.Button(r, GUIContent.none, GUIStyle.none)) on = !on;
if (Event.current.type == EventType.Repaint)
{
var old = GUI.color;
GUI.color = on ? Accent : new Color(1f, 1f, 1f, 0.18f);
pill.Draw(r, false, false, false, false);
GUI.color = Color.white;
float k = S(18);
var knob = new Rect(on ? r.xMax - k - S(2) : r.x + S(2), r.y + (r.height - k) / 2f, k, k);
GUI.DrawTexture(knob, texThumb);
GUI.color = old;
}
return on;
}
void Bar(float v, Color c)
{
Rect r = GUILayoutUtility.GetRect(S(10), S(6), GUILayout.ExpandWidth(true), GUILayout.Height(S(6)));
if (Event.current.type != EventType.Repaint) return;
var old = GUI.color;
GUI.color = new Color(1f, 1f, 1f, 0.08f);
bar.Draw(r, false, false, false, false);
v = Mathf.Clamp01(v);
if (v > 0.002f)
{
GUI.color = c;
bar.Draw(new Rect(r.x, r.y, Mathf.Max(r.height, r.width * v), r.height), false, false, false, false);
}
GUI.color = old;
}
void Tag(string text, Color c)
{
var bg = GUI.backgroundColor;
var cc = GUI.contentColor;
GUI.backgroundColor = new Color(c.r, c.g, c.b, 0.22f);
GUI.contentColor = c;
GUILayout.Label(text, tagStyle);
GUI.backgroundColor = bg;
GUI.contentColor = cc;
}
// ================================================================ Styles
void EnsureStyles()
{
float s = Mathf.Clamp(Screen.height / 1000f, 0.8f, 2.2f);
if (panel != null && Mathf.Approximately(s, scale)) return;
scale = s;
DestroyTextures();
texPanel = Rounded(I(14), new Color(0.07f, 0.08f, 0.10f, 0.88f));
texCard = Rounded(I(10), new Color(1f, 1f, 1f, 0.045f));
texBtn = Rounded(I(7), new Color(1f, 1f, 1f, 0.07f));
texBtnHover = Rounded(I(7), new Color(1f, 1f, 1f, 0.13f));
texBtnOn = Rounded(I(7), new Color(Accent.r, Accent.g, Accent.b, 0.85f));
texField = Rounded(I(6), new Color(0f, 0f, 0f, 0.35f));
texWhite = Rounded(I(3), Color.white);
texPill = Rounded(I(11), Color.white);
texThumb = Circle(I(16), Color.white);
texTrack = Track(I(4), new Color(1f, 1f, 1f, 0.18f));
int fs = I(13);
panel = Styled(texPanel, I(14), 0);
card = Styled(texCard, I(10), 0);
card.padding = new RectOffset(I(12), I(12), I(9), I(10));
card.margin = new RectOffset(0, 0, I(3), I(5));
title = Text(I(19), TextMain, FontStyle.Bold);
header = Text(I(11), TextDim, FontStyle.Bold);
header.margin = new RectOffset(0, 0, I(2), I(4));
label = Text(fs, TextMain);
dim = Text(I(12), TextDim);
dim.wordWrap = true;
valueRight = Text(fs, TextMain, FontStyle.Bold);
valueRight.alignment = TextAnchor.MiddleRight;
bigValue = Text(I(22), TextMain, FontStyle.Bold);
logLine = Text(I(12), TextDim);
logLine.wordWrap = true;
logLineStrong = Text(I(12), TextMain);
logLineStrong.wordWrap = true;
button = Styled(texBtn, I(7), fs);
button.hover.background = texBtnHover;
button.active.background = texBtnOn;
button.onNormal.background = texBtnOn;
button.onHover.background = texBtnOn;
button.onActive.background = texBtnOn;
foreach (var st in new[] { button.normal, button.hover, button.active, button.onNormal, button.onHover, button.onActive })
st.textColor = TextMain;
button.alignment = TextAnchor.MiddleCenter;
button.padding = new RectOffset(I(10), I(10), I(6), I(6));
button.margin = new RectOffset(I(2), I(2), I(2), I(2));
seg = new GUIStyle(button) { fontStyle = FontStyle.Bold };
slider = new GUIStyle { normal = { background = texTrack }, border = new RectOffset(I(4), I(4), 0, 0), fixedHeight = S(18), margin = new RectOffset(I(2), I(2), I(2), I(4)) };
thumb = new GUIStyle { normal = { background = texThumb }, hover = { background = texThumb }, active = { background = texThumb }, fixedWidth = S(16), fixedHeight = S(16), margin = new RectOffset(0, 0, I(1), 0) };
field = Styled(texField, I(6), fs);
field.normal.textColor = field.focused.textColor = field.hover.textColor = TextMain;
field.focused.background = texField;
field.hover.background = texField;
field.padding = new RectOffset(I(8), I(8), I(5), I(5));
field.margin = new RectOffset(I(2), I(2), I(2), I(4));
field.alignment = TextAnchor.MiddleLeft;
field.clipping = TextClipping.Clip;
tagStyle = Styled(texWhite, I(3), I(10));
tagStyle.normal.textColor = Color.white;
tagStyle.fontStyle = FontStyle.Bold;
tagStyle.padding = new RectOffset(I(6), I(6), I(2), I(2));
tagStyle.margin = new RectOffset(I(3), I(3), I(3), I(3));
tagStyle.alignment = TextAnchor.MiddleCenter;
bar = Styled(texWhite, I(3), 0);
pill = Styled(texPill, I(11), 0);
}
static GUIStyle Styled(Texture2D bg, int border, int fontSize)
=> new GUIStyle { normal = { background = bg }, border = new RectOffset(border, border, border, border), fontSize = fontSize };
static GUIStyle Text(int size, Color c, FontStyle style = FontStyle.Normal)
=> new GUIStyle { fontSize = size, fontStyle = style, normal = { textColor = c }, margin = new RectOffset(0, 0, 2, 2), padding = new RectOffset(0, 0, 1, 1), alignment = TextAnchor.MiddleLeft };
static Texture2D NewTex(int w, int h)
=> new Texture2D(w, h, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, hideFlags = HideFlags.HideAndDontSave };
/// <summary>Abgerundetes Rechteck mit weichen Kanten (für 9-Slice, border = r).</summary>
static Texture2D Rounded(int r, Color c)
{
r = Mathf.Max(r, 1);
int n = 2 * r + 4;
var t = NewTex(n, n);
var px = new Color[n * n];
for (int y = 0; y < n; y++)
for (int x = 0; x < n; x++)
{
var p = new Vector2(x + 0.5f, y + 0.5f);
var q = new Vector2(Mathf.Clamp(p.x, r, n - r), Mathf.Clamp(p.y, r, n - r));
float a = Mathf.Clamp01(r - Vector2.Distance(p, q) + 0.5f);
px[y * n + x] = new Color(c.r, c.g, c.b, c.a * a);
}
t.SetPixels(px);
t.Apply();
return t;
}
static Texture2D Circle(int r, Color c) => Rounded(r, c);
/// <summary>Horizontale Schiene, vertikal zentriert in einer höheren Textur (Slider-Hintergrund).</summary>
static Texture2D Track(int thickness, Color c)
{
int w = 16, h = Mathf.Max(16, thickness * 4);
var t = NewTex(w, h);
var px = new Color[w * h];
float mid = h / 2f;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
{
float a = Mathf.Clamp01(thickness / 2f - Mathf.Abs(y + 0.5f - mid) + 0.5f);
px[y * w + x] = new Color(c.r, c.g, c.b, c.a * a);
}
t.SetPixels(px);
t.Apply();
return t;
}
void DestroyTextures()
{
foreach (var t in new[] { texPanel, texCard, texBtn, texBtnHover, texBtnOn, texTrack, texThumb, texWhite, texField, texPill })
if (t != null) Destroy(t);
}
void OnDestroy() => DestroyTextures();
}
}