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

1115 lines
56 KiB
C#
Raw Permalink 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.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace SmartRoom
{
/// <summary>
/// Dashboard im Look des Web-Frontends „Ambient²“ (hell, Salbei/Grün, Karten): Raumstatus mit 3D-Ansicht,
/// Messwert-Kacheln, Dozentensteuerung, Raumstimmung, Verlauf und Demo-Szenarien.
/// Gleiche Logik wie <see cref="SmartRoomHUD"/>, nur andere Optik. Ausgelegt auf 1440 × 900, wird auf den Bildschirm skaliert.
/// Die Raumkamera rendert in eine Textur, die in der Karte „Raumstatus“ angezeigt wird.
/// </summary>
public class AmbientHUD : MonoBehaviour
{
public RoomEnvironment env;
public RoomDevices devices;
public ClimateController controller;
public ArduinoBridge bridge;
public WeatherService weather;
public OrbitCamera orbit;
public Camera roomCamera;
[Header("Texte")]
public string campus = "KlimaCampus";
public string roomName = "Raum 2.14";
public string building = "Gebäude West";
public string roomLong = "Seminarraum 2.14";
public string lecturer = "Frau Weber";
[Header("Bedienung")]
public bool lecturerView = true;
[Tooltip("Dauer des Beamer-Modus in simulierten Minuten")] public float[] beamerDurations = { 30f, 60f, 90f };
public int beamerDurationIndex = 1;
[Tooltip("Jalousien manuell: Automatik pausiert für (simulierte) Minuten")] public float manualBlindMinutes = 30f;
// Farben des Frontends (CSS-Variablen in Ambient2)
static readonly Color Ink = Hex(0x16221d), Muted = Hex(0x68746f), Line = Hex(0xdfe6e1), Surface = Color.white,
Soft = Hex(0xf7f9f7), Green = Hex(0x175c45), Green2 = Hex(0x2b8063), GreenSoft = Hex(0xe8f3ed), Mint = Hex(0xcbe6d8),
Amber = Hex(0xa86518), AmberSoft = Hex(0xfff3dc), Red = Hex(0xa83f35), RedSoft = Hex(0xfceae7),
Blue = Hex(0x3e6578), BlueSoft = Hex(0xe9f2f5), CoolVote = Hex(0x9fb8c6), WarmVote = Hex(0xc99a64),
SkyColor = new Color(0.88f, 0.93f, 0.91f);
static Color Hex(int rgb) => new Color(((rgb >> 16) & 255) / 255f, ((rgb >> 8) & 255) / 255f, (rgb & 255) / 255f);
static readonly CultureInfo De = new CultureInfo("de-DE");
struct Tone
{
public Color fg, bg;
public Tone(Color fg, Color bg) { this.fg = fg; this.bg = bg; }
}
static readonly Tone ToneGreen = new Tone(Green, GreenSoft), ToneAmber = new Tone(Amber, AmberSoft),
ToneRed = new Tone(Red, RedSoft), ToneBlue = new Tone(Blue, BlueSoft);
struct BannerState { public string title, text, icon; public Tone tone; public int priority; }
class Demo { public string name, sub; public Action apply; }
class Entry { public string time, title, text; public Color dot; }
const float RefW = 1440f, RefH = 900f;
float k = 1f; // Skalierung virtuelle Einheit → Pixel
Vector2 origin; // linke obere Ecke der virtuellen Fläche
Font sans, serif;
readonly Dictionary<string, GUIStyle> textStyles = new Dictionary<string, GUIStyle>();
readonly Dictionary<int, GUIStyle> roundStyles = new Dictionary<int, GUIStyle>();
readonly Dictionary<int, GUIStyle> holeStyles = new Dictionary<int, GUIStyle>();
readonly List<Texture2D> textures = new List<Texture2D>();
GUIStyle fieldStyle;
float stylesFor = -1f;
readonly List<Demo> demos = new List<Demo>();
readonly List<Entry> history = new List<Entry>();
Decision prevDecision;
int prevClamped;
RenderTexture rt;
Camera bgCam;
Rect vpRect, popRect;
bool settingsOpen, drawingPopover, wasBeamer;
double beamerUntil = double.NegativeInfinity;
string fieldText;
LinkMode fieldMode = (LinkMode)(-1);
float BeamerMinutes => beamerDurations[Mathf.Clamp(beamerDurationIndex, 0, beamerDurations.Length - 1)];
// ================================================================ Start / Update
void Start()
{
SeedWishes();
BuildDemos();
controller.Decided += OnDecided;
if (controller.Last != null) OnDecided(controller.Last);
SetupCameras();
}
void OnDestroy()
{
if (controller != null) controller.Decided -= OnDecided;
if (roomCamera != null) roomCamera.targetTexture = null;
if (rt != null) { rt.Release(); Destroy(rt); }
foreach (var t in textures) if (t != null) Destroy(t);
}
/// <summary>Wie im Frontend: 9 Stimmen (1 kühler, 7 angenehm, 1 wärmer), falls noch die Standardliste aktiv ist.</summary>
void SeedWishes()
{
if (controller.wishes.Count != 5) return;
float[] extra = { 22f, 22f, 21.8f, 22.2f };
for (int i = 0; i < extra.Length; i++)
controller.wishes.Add(new UserWish($"Teilnehmer {5 + i}", extra[i], false));
}
void SetupCameras()
{
if (roomCamera == null) roomCamera = orbit != null ? orbit.GetComponent<Camera>() : Camera.main;
if (roomCamera == null) return;
roomCamera.clearFlags = CameraClearFlags.SolidColor;
roomCamera.backgroundColor = SkyColor;
roomCamera.fieldOfView = 44f;
// Hintergrundkamera füllt den Bildschirm, die Raumkamera rendert nur in die Textur der Karte "Raumstatus"
bgCam = new GameObject("Hintergrund (Ambient-Dashboard)").AddComponent<Camera>();
bgCam.clearFlags = CameraClearFlags.SolidColor;
bgCam.backgroundColor = Soft;
bgCam.cullingMask = 0;
bgCam.depth = roomCamera.depth - 10f;
if (orbit != null)
{
orbit.rayProvider = p => roomCamera.ViewportPointToRay(new Vector3(
(p.x - vpRect.x) / Mathf.Max(1f, vpRect.width), 1f - (p.y - vpRect.y) / Mathf.Max(1f, vpRect.height), 0f));
FrontView(true);
}
}
/// <summary>Frontansicht wie die Raumillustration im Frontend: Blick auf Leinwand, Fenster links.</summary>
void FrontView(bool snap) => orbit?.SetView(new Vector3(0f, 1.5f, 2.6f), 0f, 6f, 9.4f, snap);
void Update()
{
if (env == null || devices == null || controller == null) return;
// Beamer-Modus endet nach der gewählten Dauer
bool on = devices.BeamerOn;
if (on && !wasBeamer && beamerUntil <= env.simMinutes) beamerUntil = env.simMinutes + BeamerMinutes;
if (on && env.simMinutes >= beamerUntil)
{
devices.projector.beamerOn = false;
on = false;
controller.RunCycle();
}
wasBeamer = on;
}
void SetBeamer(bool on)
{
if (devices.projector == null) return;
devices.projector.beamerOn = on;
beamerUntil = on ? env.simMinutes + BeamerMinutes : double.NegativeInfinity;
wasBeamer = on;
controller.RunCycle();
}
// ================================================================ Demo-Szenarien
void BuildDemos()
{
demos.Add(new Demo { name = "Normal", sub = "Alle Werte im Zielbereich", apply = () =>
{
Outdoor(14f, 25f, 45f, 2.5f, 350f);
env.indoorTemp = 22f; env.co2 = 650f;
RemoveOutlier();
if (devices.BeamerOn) SetBeamer(false);
} });
demos.Add(new Demo { name = "CO₂ zu hoch", sub = "Gesundheit priorisiert Lüften", apply = () =>
{
Outdoor(14f, 25f, 45f, 2.5f, 350f);
env.co2 = 1350f;
} });
demos.Add(new Demo { name = "CO₂ + Außenlärm", sub = "Frischluft mit Lärmschutz", apply = () =>
{
Outdoor(14f, 25f, 82f, 2.5f, 350f);
env.co2 = 1350f;
} });
demos.Add(new Demo { name = "Sturm", sub = "Fenster werden gesperrt", apply = () =>
{
Outdoor(12f, 25f, 50f, 16f, 250f);
env.co2 = 1300f;
} });
demos.Add(new Demo { name = "Vortragsmodus", sub = "Licht und Jalousien angepasst", apply = () => SetBeamer(true) });
demos.Add(new Demo { name = "Ausreißer-Stimme", sub = "Mehrheit bleibt ausschlaggebend", apply = () =>
{
RemoveOutlier();
controller.wishes.Add(new UserWish("Ausreißer", 30f, false));
} });
demos.Add(new Demo { name = "Hitze", sub = "Zu warm, Fenster öffnen", apply = () =>
{
Outdoor(24f, 25f, 45f, 2f, 750f);
env.indoorTemp = 29f; env.co2 = 700f;
} });
demos.Add(new Demo { name = "Kalter Morgen", sub = "Heizen auf Ø-Wunsch", apply = () =>
{
Outdoor(-3f, 25f, 40f, 3f, 80f);
env.indoorTemp = 17.5f; env.co2 = 600f;
} });
}
void Outdoor(float temp, float aqi, float noise, float wind, float sun)
{
env.outdoorTemp = temp; env.outdoorAqi = aqi; env.outdoorNoise = noise; env.windSpeed = wind; env.solar = sun;
}
void RemoveOutlier() => controller.wishes.RemoveAll(w => w.name == "Ausreißer");
/// <summary>Welche Demo-Kachel zum erkannten Zustand passt (Sensorwerte lösen sie automatisch aus).</summary>
string ActiveDemo()
{
if (devices.BeamerOn) return "Vortragsmodus";
switch (controller.Scenario)
{
case "Stickige Luft":
case "Stickig + kalt":
case "Schlechte Außenluft": return "CO₂ zu hoch";
case "Baustellenlärm": return "CO₂ + Außenlärm";
case "Sturm": return "Sturm";
case "Hitze": return "Hitze";
case "Wintermorgen": return "Kalter Morgen";
case ClimateController.NormalScenario: return controller.ClampedWishes > 0 ? "Ausreißer-Stimme" : "Normal";
default: return null;
}
}
// ================================================================ Verlauf
void OnDecided(Decision d)
{
var e = Describe(d);
if (controller.ClampedWishes > prevClamped)
Push(new Entry { time = d.time, title = "Temperaturwunsch begrenzt", text = "Wunsch liegt außerhalb des zulässigen Bereichs.", dot = Amber });
prevClamped = controller.ClampedWishes;
Push(e);
prevDecision = d;
}
void Push(Entry e)
{
e.time = e.time?.Replace(" Uhr", "");
if (history.Count > 0 && history[0].title == e.title && history[0].text == e.text)
{
history[0].time = e.time; // gleiche Meldung nicht stapeln
return;
}
history.Insert(0, e);
if (history.Count > 8) history.RemoveAt(history.Count - 1);
}
Entry Describe(Decision d)
{
var e = new Entry { time = d.time, dot = Green };
var p = prevDecision;
if (!env.lectureRunning)
{
e.title = "Energiesparmodus"; e.text = "Keine Vorlesung – Fenster zu, Geräte aus."; e.dot = Blue;
}
else if (p != null && p.window == d.window && Same(p.ventilation, d.ventilation) && Same(p.heating, d.heating) && Same(p.blinds, d.blinds))
{
e.title = "Zielwerte gehalten"; e.text = "Raumklima stabil. Keine Anpassung erforderlich.";
}
else if (d.window != WindowState.Closed && (p == null || p.window != d.window))
{
e.title = d.window == WindowState.Open ? "Gelüftet" : "Fenster gekippt";
e.text = env.co2 > controller.limits.co2Limit ? $"CO₂ {N(env.co2, 0)} ppm über dem Grenzwert."
: env.indoorTemp > controller.limits.tempHigh ? $"Zu warm ({N(env.indoorTemp, 1)} °C)."
: "Fensteröffnung gewünscht.";
if (d.window == WindowState.Tilted) e.text += " Wind begrenzt die Öffnung.";
e.dot = Amber;
}
else if (d.ventilation > 0.01f && (p == null || p.ventilation <= 0.01f))
{
e.title = "Lüftungsanlage an";
e.text = env.outdoorAqi > controller.limits.outdoorAqiLimit ? "Außenluft belastet – Fenster bleiben zu."
: env.outdoorTemp < controller.limits.outdoorColdLimit ? "Draußen zu kalt – Fenster bleiben zu."
: env.outdoorNoise > controller.limits.noiseLimit ? "Außenlärm – Fenster bleiben zu."
: "Frischluft über die Anlage.";
e.dot = Amber;
}
else if (d.heating > 0.01f && (p == null || p.heating <= 0.01f))
{
e.title = "Heizung an"; e.text = $"Zielwert {N(Target, 1)} °C wird angesteuert."; e.dot = Blue;
}
else if (p != null && p.window != WindowState.Closed && d.window == WindowState.Closed)
{
e.title = "Fenster geschlossen"; e.text = $"Zielwert {N(Target, 1)} °C wird wieder angesteuert.";
}
else if (p != null && !Same(p.blinds, d.blinds))
{
e.title = d.blinds > p.blinds ? "Jalousien geschlossen" : "Jalousien geöffnet";
e.text = devices.BeamerOn ? "Vortragsmodus: Raum abgedunkelt." : env.solar > controller.limits.sunLimit ? "Sonnenschutz." : "Tageslicht nutzen.";
e.dot = Blue;
}
else
{
e.title = "Steuerung angepasst"; e.text = $"Fenster {d.window.Label()}, Heizung {d.heating * 100:0} %, Lüftung {d.ventilation * 100:0} %.";
}
return e;
}
static bool Same(float a, float b) => Mathf.Abs(a - b) < 0.02f;
// ================================================================ Zustand → Texte
float Target => Mathf.Clamp(controller.AverageWish, 18f, 26f);
BannerState Banner()
{
var L = controller.limits;
if (!env.lectureRunning)
return new BannerState { title = "Keine Vorlesung", text = "Raum im Energiesparmodus – Fenster zu, Geräte aus.", icon = "i", tone = ToneBlue, priority = 4 };
switch (controller.Scenario)
{
case "Stickige Luft":
return new BannerState { title = "CO₂ zu hoch – es wird gelüftet", text = $"{N(env.co2, 0)} ppm über dem Grenzwert von {N(L.co2Limit, 0)} ppm. Gesundheit hat Vorrang.", icon = "!", tone = ToneAmber, priority = 1 };
case "Stickig + kalt":
return new BannerState { title = "CO₂ zu hoch, draußen zu kalt", text = "Lüftungsanlage statt Fenster, damit der Raum nicht auskühlt.", icon = "!", tone = ToneAmber, priority = 1 };
case "Schlechte Außenluft":
return new BannerState { title = "Lüften ohne Fenster", text = $"Außenluft belastet (AQI {env.outdoorAqi:0}). Die Lüftungsanlage übernimmt.", icon = "!", tone = ToneAmber, priority = 1 };
case "Baustellenlärm":
return new BannerState
{
title = "Frischluft, trotz hoher Außenlautstärke",
text = devices.WindowTarget == WindowState.Open
? "CO₂ erfordert Lüften. Die Mehrheit wünscht das Fenster offen."
: "CO₂ erfordert Lüften. Der Lärmschutz hält die Fenster zu – Lüftungsanlage läuft.",
icon = "!", tone = ToneAmber, priority = 1
};
case "Sturm":
return new BannerState { title = "Sturm – Fenster nur gekippt", text = $"Wind {N(env.windSpeed * 3.6f, 0)} km/h. Die Kontext-Sperre begrenzt die Öffnung.", icon = "!", tone = ToneRed, priority = 2 };
case "Hitze":
return new BannerState { title = "Zu warm – es wird gelüftet", text = $"{N(env.indoorTemp, 1)} °C im Raum, Ziel {N(Target, 1)} °C.", icon = "!", tone = ToneAmber, priority = 1 };
case "Wintermorgen":
return new BannerState { title = "Raum wird aufgeheizt", text = $"{N(env.indoorTemp, 1)} °C im Raum. Zielwert {N(Target, 1)} °C aus {controller.wishes.Count} Stimmen.", icon = "i", tone = ToneBlue, priority = 3 };
case "Pralle Sonne":
return new BannerState { title = "Sonnenschutz aktiv", text = "Starke Sonneneinstrahlung – die Jalousien fahren herunter.", icon = "i", tone = ToneBlue, priority = 4 };
}
if (devices.BeamerOn)
return new BannerState { title = $"Vortragsmodus aktiv bis {Clock(beamerUntil)}", text = "Jalousien geschlossen, Raumautomatik bleibt im Hintergrund aktiv.", icon = "i", tone = ToneBlue, priority = 4 };
return new BannerState { title = "Raumklima im Zielbereich", text = "Temperatur und Luftqualität sind stabil.", icon = "✓", tone = ToneGreen, priority = 4 };
}
static readonly string[] PriorityNames = { "", "Gesundheit", "Kontext", "Mehrheit", "Energie" };
static string N(float v, int dec) => v.ToString("N" + dec, De);
static string Clock(double simMinutes)
{
if (double.IsInfinity(simMinutes)) return "–";
var t = TimeSpan.FromMinutes(simMinutes % 1440.0);
return $"{t.Hours:00}:{t.Minutes:00}";
}
string Greeting()
{
int h = (int)(env.simMinutes % 1440.0 / 60.0);
return h < 11 ? "Guten Morgen" : h < 18 ? "Guten Tag" : "Guten Abend";
}
// ================================================================ 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);
popRect = settingsOpen ? V(RefW - 24f - 340f, 62f, 340f, SettingsHeight()) : Rect.zero;
if (settingsOpen && e.type == EventType.MouseDown && !popRect.Contains(e.mousePosition) && !V(RefW - 300f, 10f, 276f, 40f).Contains(e.mousePosition))
settingsOpen = false;
// Bildschirmränder außerhalb der 1440×900-Fläche
Fill(new Rect(0, 0, Screen.width, Screen.height), Soft);
var banner = Banner();
DrawTopBar();
DrawHeader();
DrawBanner(banner);
DrawRoomCard();
DrawMetrics();
DrawDemos();
if (lecturerView)
{
DrawLecturerCard(V(1016, 236, 400, 254));
DrawMood(V(1016, 502, 400, 198), false);
}
else
{
DrawMood(V(1016, 236, 400, 234), true);
DrawPriorities(V(1016, 482, 400, 218), banner.priority);
}
DrawHistory(V(1016, 712, 400, 138));
DrawFooter();
if (settingsOpen) DrawSettings();
ForwardToCamera(e);
}
void HandleKeys(Event e)
{
switch (e.keyCode)
{
case KeyCode.Alpha0: case KeyCode.R: FrontView(false); 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: SetBeamer(!devices.BeamerOn); break;
case KeyCode.Space: controller.RunCycle(); break;
default: return;
}
e.Use();
}
void ForwardToCamera(Event e)
{
if (orbit == null || e.type == EventType.Used) return;
bool relevant = e.isMouse || e.type == EventType.ScrollWheel;
bool over = vpRect.Contains(e.mousePosition) && !(settingsOpen && popRect.Contains(e.mousePosition));
if (relevant && (over || orbit.IsDragging)) orbit.HandleEvent(e);
}
// ---------------------------------------------------------------- Kopfzeile
void DrawTopBar()
{
var bar = new Rect(0, 0, Screen.width, V(0, 0, 1, 60).yMax);
Fill(bar, Surface);
Fill(new Rect(0, bar.yMax - 1, Screen.width, 1), Line);
Box(V(24, 12, 36, 36), Green, 9);
Text(V(24, 12, 36, 36), "≋", 20, Color.white, true, TextAnchor.MiddleCenter);
Text(V(70, 13, 300, 18), campus, 15, Ink, true);
Text(V(70, 32, 300, 16), $"{roomName} · {building}", 11, Muted);
// Studierende / Dozent
var seg = V(RefW / 2 - 110, 12, 220, 36);
Box(seg, Soft, 10, Line);
var a = V(RefW / 2 - 106, 16, 106, 28);
var b = V(RefW / 2, 16, 106, 28);
var active = lecturerView ? b : a;
Shadow(active, 7);
Box(active, Surface, 7, Line);
Text(a, "Studierende", 12, lecturerView ? Muted : Ink, true, TextAnchor.MiddleCenter);
Text(b, "Dozent", 12, lecturerView ? Ink : Muted, true, TextAnchor.MiddleCenter);
if (Click(a)) lecturerView = false;
if (Click(b)) lecturerView = true;
// Status rechts → Einstellungen
bool live = env.AnyMeasured;
string status = !env.lectureRunning ? "Energiesparmodus" : live ? "Arduino live" : bridge != null && bridge.Connected ? "Warte auf Arduino" : "System aktiv";
float w = TextWidth(status, 12, false) + 52f;
var pill = V(RefW - 24 - w, 16, w, 28);
if (settingsOpen || Hover(pill)) Box(pill, Soft, 8, Line);
Box(V(VX(pill) + 10, 26.5f, 8, 8), env.lectureRunning ? Green2 : Muted, 4);
Text(V(VX(pill) + 24, 16, w - 24, 28), status + " ≡", 12, Ink);
if (Click(pill)) settingsOpen = !settingsOpen;
}
// ---------------------------------------------------------------- Begrüßung
void DrawHeader()
{
Text(V(24, 74, 600, 16), roomLong.ToUpperInvariant(), 11, Green, true);
string title = lecturerView ? $"{Greeting()}, {lecturer}." : $"{Greeting()}.";
Text(V(22, 90, 900, 44), title, 34, Ink, false, TextAnchor.MiddleLeft, true);
Text(V(24, 134, 900, 18), lecturerView ? "Das Raumklima wird automatisch und fair gesteuert."
: "Wie fühlt sich der Raum für dich an? Deine Stimme zählt – anonym.", 13, Muted);
// Außenwerte
string tOut = $"<b>{N(env.outdoorTemp, 0)} °C</b> außen";
string wind = $"<b>{N(env.windSpeed * 3.6f, 0)} km/h</b> Wind";
float w1 = TextWidth(tOut, 12, false) + 28f, w2 = TextWidth(wind, 12, false) + 28f;
float x = RefW - 24 - w1 - w2;
var r = V(x, 102, w1 + w2, 38);
Box(r, Surface, 10, Line);
Text(V(x, 102, w1, 38), tOut, 12, Ink, false, TextAnchor.MiddleCenter);
Fill(V(x + w1, 111, 1, 20), Line);
Text(V(x + w1, 102, w2, 38), wind, 12, Ink, false, TextAnchor.MiddleCenter);
}
// ---------------------------------------------------------------- Hinweisband
void DrawBanner(BannerState s)
{
var r = V(24, 164, RefW - 48, 58);
Box(r, s.tone.bg, 12, Color.Lerp(s.tone.bg, s.tone.fg, 0.18f));
Box(V(40, 175, 36, 36), Color.Lerp(s.tone.bg, Color.white, 0.55f), 9, Color.Lerp(s.tone.bg, s.tone.fg, 0.25f));
Text(V(40, 175, 36, 36), s.icon, 16, s.tone.fg, true, TextAnchor.MiddleCenter);
Text(V(90, 174, 900, 20), s.title, 14, Ink, true);
Text(V(90, 194, 900, 18), s.text, 11.5f, Muted);
string prio = $"Priorität {s.priority}: {PriorityNames[s.priority]}";
float w = TextWidth(prio, 11.5f, true) + 26f;
var chip = V(RefW - 40 - w, 178, w, 30);
Box(chip, Surface, 8, Color.Lerp(s.tone.bg, s.tone.fg, 0.2f));
Text(chip, prio, 11.5f, s.tone.fg, true, TextAnchor.MiddleCenter);
}
// ---------------------------------------------------------------- Raumstatus mit 3D-Ansicht
void DrawRoomCard()
{
var card = V(24, 236, 976, 312);
Card(card);
Text(V(42, 252, 400, 20), "Raumstatus", 15, Ink, true);
Text(V(42, 272, 400, 16), "Live-Ansicht der automatischen Steuerung", 11, Muted);
string right;
if (env.AnyMeasured)
{
right = $"Arduino live · vor {Mathf.Max(0f, Time.unscaledTime - bridge.LastPacketTime):0} s";
if (env.IsMeasured("rh")) right += $" · Feuchte {N(env.indoorHumidity, 0)} %";
if (env.IsMeasured("tvoc")) right += $" · TVOC {N(env.tvoc, 0)} ppb";
if (env.IsMeasured("lightpct")) right += $" · Licht {N(env.lightPercent, 0)} %";
}
else right = env.lectureRunning ? $"Simulation · nächste Prüfung in {controller.MinutesUntilNextCheck:0} min" : "Simulation";
float rw = TextWidth(right, 11, false);
Box(V(984 - rw - 14, 262.5f, 7, 7), env.AnyMeasured ? Green2 : Mint, 3.5f);
Text(V(984 - rw, 254, rw, 24), right, 11, Muted);
// 3D-Ansicht
vpRect = V(38, 296, 948, 238);
UpdateRenderTexture();
if (rt != null && Event.current.type == EventType.Repaint) GUI.DrawTexture(vpRect, rt, ScaleMode.StretchToFill, false);
Hole(vpRect, Surface, 10);
// Overlays unten: Aktorzustände
float x = 50f, y = 498f;
x += Chip(x, y, $"Fenster: {devices.WindowLabel}", Ink, Surface) + 8;
if (devices.HeatingLevel > 0.02f) x += Chip(x, y, $"Heizung {devices.HeatingLevel * 100f:0} %", Amber, Surface) + 8;
if (devices.VentLevel > 0.02f) x += Chip(x, y, $"Lüftung {devices.VentLevel * 100f:0} %", Blue, Surface) + 8;
if (devices.LightLevel > 0.02f) x += Chip(x, y, $"Licht {devices.LightLevel * 100f:0} %", Ink, Surface) + 8;
string blinds = $"Jalousien: {devices.BlindPosition * 100f:0} %" + (controller.BlindOverrideActive ? " · manuell" : "");
float bw = TextWidth(blinds, 11, true) + 22f;
Chip(974 - bw, y, blinds, Ink, Surface);
// Ansicht zurücksetzen
var reset = V(974 - 104, 308, 104, 24);
if (Hover(reset)) Box(reset, Surface, 7, Line); else Box(reset, new Color(1, 1, 1, 0.82f), 7, Line);
Text(reset, "Frontansicht", 10.5f, Ink, true, TextAnchor.MiddleCenter);
if (Click(reset)) FrontView(false);
}
void UpdateRenderTexture()
{
if (roomCamera == null || Event.current.type != EventType.Repaint) return;
int w = Mathf.Max(16, Mathf.RoundToInt(vpRect.width)), h = Mathf.Max(16, Mathf.RoundToInt(vpRect.height));
if (rt != null && rt.width == w && rt.height == h) return;
if (rt != null) { roomCamera.targetTexture = null; rt.Release(); Destroy(rt); }
rt = new RenderTexture(w, h, 24) { antiAliasing = 4, name = "Raumansicht" };
roomCamera.targetTexture = rt;
}
// ---------------------------------------------------------------- Messwert-Kacheln
void DrawMetrics()
{
var L = controller.limits;
float w = (976f - 36f) / 4f, y = 560f;
float co2 = env.co2, t = env.indoorTemp, noise = env.outdoorNoise, kmh = env.windSpeed * 3.6f;
Metric(24, y, w, "CO₂", "Luftqualität", env.IsMeasured("co2"), N(co2, 0), "ppm", co2 / (L.co2Limit * 1.6f),
co2 < 800f ? ("Gut", ToneGreen) : co2 <= L.co2Limit ? ("Mäßig", ToneAmber) : ("Zu hoch", ToneRed),
$"Grenzwert {N(L.co2Limit, 0)} ppm · fest");
Metric(24 + (w + 12), y, w, "°C", "Temperatur", env.IsMeasured("t"), N(t, 1), "°C", Mathf.InverseLerp(14f, 32f, t),
t > L.tempHigh ? ("Zu warm", ToneAmber) : t < L.tempLow ? ("Zu kalt", ToneBlue) : ("Im Ziel", ToneGreen),
$"Zielbereich {N(L.tempLow, 0)}–{N(L.tempHigh, 0)} °C · Ziel {N(Target, 1)} °C");
if (!bridge.MicrophoneOutdoor && env.IsMeasured("noise"))
{
// Mikrofon steht im Raum: Lärm im Raum zeigen, Außenlärm bleibt simuliert
float inside = env.indoorNoise;
Metric(24 + 2 * (w + 12), y, w, "dB", "Lärm im Raum", true, N(inside, 0), "dB", Mathf.InverseLerp(30f, 95f, inside),
inside <= 50f ? ("Ruhig", ToneGreen) : inside <= 65f ? ("Mäßig", ToneAmber) : ("Laut", ToneRed),
$"Außen {N(noise, 0)} dB (Simulation)");
}
else
Metric(24 + 2 * (w + 12), y, w, "dB", "Außenlärm", env.IsMeasured("nout"), N(noise, 0), "dB", Mathf.InverseLerp(30f, 95f, noise),
noise <= 55f ? ("Ruhig", ToneGreen) : noise <= L.noiseLimit ? ("Mäßig", ToneAmber) : ("Außen laut", ToneAmber),
noise > L.noiseLimit ? "Fensteröffnung gesperrt" : "Öffnung wird ggf. begrenzt");
Metric(24 + 3 * (w + 12), y, w, "≋", "Wind", false, N(kmh, 0), "km/h", Mathf.InverseLerp(0f, 70f, kmh),
kmh <= 20f ? ("Leicht", ToneGreen) : env.windSpeed <= L.windLimit ? ("Mäßig", ToneAmber) : ("Stark", ToneRed),
$"Außenluft AQI {env.outdoorAqi:0} · {N(env.outdoorTemp, 0)} °C");
}
void Metric(float x, float y, float w, string icon, string label, bool measured, string value, string unit, float norm,
(string text, Tone tone) status, string foot)
{
var r = V(x, y, w, 128);
Card(r);
Box(V(x + 14, y + 14, 32, 32), GreenSoft, 8);
Text(V(x + 14, y + 14, 32, 32), icon, icon.Length > 2 ? 10 : 12, Green, true, TextAnchor.MiddleCenter);
float pw = TextWidth(status.text, 10, true) + 16f;
Box(V(x + w - 14 - pw, y + 18, pw, 22), status.tone.bg, 6);
Text(V(x + w - 14 - pw, y + 18, pw, 22), status.text, 10, status.tone.fg, true, TextAnchor.MiddleCenter);
Text(V(x + 14, y + 54, w - 28, 16), measured ? $"{label} <color=#{ColorUtility.ToHtmlStringRGB(Green2)}>● Sensor</color>" : label, 11.5f, Muted);
Text(V(x + 14, y + 70, w - 28, 30), $"<b>{value}</b> <size={F(12)}><color=#{ColorUtility.ToHtmlStringRGB(Muted)}>{unit}</color></size>", 24, Ink);
var track = V(x + 14, y + 104, w - 28, 4);
Box(track, Line, 2);
Box(V(x + 14, y + 104, Mathf.Max(4f, (w - 28) * Mathf.Clamp01(norm)), 4), status.tone.fg, 2);
Text(V(x + 14, y + 110, w - 28, 14), foot, 9.5f, Muted);
}
// ---------------------------------------------------------------- Demo-Szenarien
void DrawDemos()
{
var card = V(24, 700, 976, 150);
Card(card);
Box(V(40, 712, 30, 30), GreenSoft, 8);
Text(V(40, 712, 30, 30), "✦", 13, Green, true, TextAnchor.MiddleCenter);
Text(V(80, 710, 400, 18), "Demo-Szenarien", 13.5f, Ink, true);
Text(V(80, 728, 500, 16), "Systemreaktionen direkt simulieren – Sensorwerte lösen sie automatisch aus", 10.5f, Muted);
string active = ActiveDemo();
string pill = "Aktiv: " + (active ?? controller.Scenario) + (env.AnyMeasured ? " · Sensor" : "");
float pw = TextWidth(pill, 10.5f, true) + 18f;
Box(V(984 - pw, 715, pw, 24), GreenSoft, 7);
Text(V(984 - pw, 715, pw, 24), pill, 10.5f, Green, true, TextAnchor.MiddleCenter);
float tw = (976f - 32f - 3 * 8f) / 4f;
for (int i = 0; i < demos.Count; i++)
{
var d = demos[i];
float x = 40 + (i % 4) * (tw + 8), y = 752 + (i / 4) * 46;
var r = V(x, y, tw, 40);
bool on = d.name == active;
bool hover = Hover(r);
Box(r, on ? GreenSoft : hover ? Soft : Surface, 9, on ? Color.Lerp(Green2, Mint, 0.4f) : Line);
Box(V(x + 10, y + 13, 14, 14), on ? Green2 : Surface, 7, on ? Green2 : Hex(0xb9c4bd));
if (on) Text(V(x + 10, y + 13, 14, 14), "✓", 9, Color.white, true, TextAnchor.MiddleCenter);
Text(V(x + 32, y + 4, tw - 38, 17), d.name, 11.5f, Ink, true);
Text(V(x + 32, y + 20, tw - 38, 15), d.sub, 9.5f, Muted);
if (Click(r))
{
d.apply();
controller.RunCycle();
}
}
}
// ---------------------------------------------------------------- Dozentensteuerung
void DrawLecturerCard(Rect card)
{
Card(card);
float x = VX(card), y = VY(card), w = card.width / k;
Text(V(x + 18, y + 14, 300, 16), "DOZENTENSTEUERUNG", 10, Green, true);
bool beamer = devices.BeamerOn;
Text(V(x + 18, y + 38, 260, 20), "Beamer-Modus", 14, Ink, true);
Text(V(x + 18, y + 58, 300, 16), beamer
? $"Aktiv bis {Clock(beamerUntil)} · noch {Mathf.Max(0f, (float)(beamerUntil - env.simMinutes)):0} min"
: "Jalousien schließen, Raum abdunkeln", 11, beamer ? Green2 : Muted);
bool sw = Switch(V(x + w - 18 - 46, y + 42, 46, 26), beamer);
if (sw != beamer) SetBeamer(sw);
Text(V(x + 18, y + 84, 200, 16), "Dauer", 11, Ink, true);
float bw = (w - 36 - 2 * 8) / 3f;
for (int i = 0; i < beamerDurations.Length && i < 3; i++)
{
var r = V(x + 18 + i * (bw + 8), y + 102, bw, 30);
bool on = i == beamerDurationIndex;
Box(r, on ? GreenSoft : Surface, 8, on ? Color.Lerp(Green2, Mint, 0.4f) : Line);
Text(r, $"{beamerDurations[i]:0} Min.", 11, on ? Green : Ink, on, TextAnchor.MiddleCenter);
if (Click(r))
{
beamerDurationIndex = i;
if (devices.BeamerOn) beamerUntil = env.simMinutes + BeamerMinutes;
}
}
Fill(V(x + 18, y + 144, w - 36, 1), Line);
Text(V(x + 18, y + 154, 260, 16), "Jalousien manuell fahren", 11, Ink, true);
Text(V(x + 18, y + 172, 280, 16), controller.BlindOverrideActive
? $"Automatik pausiert · noch {controller.BlindOverrideMinutesLeft:0} Min."
: $"Pausiert die Automatik für {manualBlindMinutes:0} Min.", 10.5f, controller.BlindOverrideActive ? Amber : Muted);
var up = V(x + w - 18 - 66, y + 154, 30, 30);
var down = V(x + w - 18 - 30, y + 154, 30, 30);
Box(up, Hover(up) ? Soft : Surface, 8, Line);
Box(down, Hover(down) ? Soft : Surface, 8, Line);
Text(up, "↑", 13, Ink, true, TextAnchor.MiddleCenter);
Text(down, "↓", 13, Ink, true, TextAnchor.MiddleCenter);
if (Click(up)) controller.OverrideBlinds(Mathf.Round((devices.BlindTarget - 0.25f) * 4f) / 4f, manualBlindMinutes);
if (Click(down)) controller.OverrideBlinds(Mathf.Round((devices.BlindTarget + 0.25f) * 4f) / 4f, manualBlindMinutes);
var note = V(x + 18, y + 202, w - 36, 40);
Box(note, Soft, 8, Line);
Text(V(x + 28, y + 202, 20, 40), "ⓘ", 12, Muted, false, TextAnchor.MiddleCenter);
Text(V(x + 50, y + 204, w - 80, 36), "<b>Schutzregeln bleiben aktiv.</b> CO₂-Grenzwert und Kontext-Sperren können nicht überschrieben werden.", 9.5f, Muted, false, TextAnchor.MiddleLeft, false, true);
}
// ---------------------------------------------------------------- Raumstimmung (Abstimmung)
void DrawMood(Rect card, bool student)
{
Card(card);
float x = VX(card), y = VY(card), w = card.width / k;
var wishes = controller.wishes;
if (wishes.Count == 0) wishes.Add(new UserWish("Du", 22f, false));
var own = wishes[0];
int cool = 0, ok = 0, warm = 0;
foreach (var wsh in wishes)
{
if (wsh.temperature < 21.5f) cool++;
else if (wsh.temperature > 22.5f) warm++;
else ok++;
}
int ownVote = own.temperature < 21.5f ? 0 : own.temperature > 22.5f ? 2 : 1;
Text(V(x + 18, y + 14, 260, 20), student ? "Deine Stimme" : "Raumstimmung", 15, Ink, true);
Text(V(x + 18, y + 34, 300, 16), $"{wishes.Count} Stimmen · Ø Wunsch {N(controller.AverageWish, 1)} °C", 11, Muted);
Text(V(x + w - 18 - 30, y + 14, 30, 30), "☺", 16, Muted, false, TextAnchor.MiddleCenter);
Text(V(x + 18, y + 58, w - 36, 18), "Wie fühlt sich der Raum für dich an?", 12, Ink, true);
float bh = student ? 62f : 52f, bw = (w - 36 - 2 * 8) / 3f;
string[] icons = { "↓", "—", "↑" };
string[] labels = { "Kühler", "Angenehm", "Wärmer" };
int[] counts = { cool, ok, warm };
float[] temps = { 21f, 22f, 23f };
for (int i = 0; i < 3; i++)
{
var r = V(x + 18 + i * (bw + 8), y + 80, bw, bh);
bool mine = i == ownVote;
Box(r, mine ? GreenSoft : Hover(r) ? Soft : Surface, 9, mine ? Color.Lerp(Green2, Mint, 0.4f) : Line);
Text(V(x + 18 + i * (bw + 8), y + 84, bw, 16), icons[i], 12, mine ? Green : Ink, true, TextAnchor.MiddleCenter);
Text(V(x + 18 + i * (bw + 8), y + 100, bw, 14), labels[i], 10.5f, mine ? Green : Ink, mine, TextAnchor.MiddleCenter);
Text(V(x + 18 + i * (bw + 8), y + 114, bw, 14), counts[i].ToString(), 10.5f, Muted, false, TextAnchor.MiddleCenter);
if (Click(r))
{
own.temperature = temps[i];
controller.RunCycle();
}
}
// Verteilung
float by = y + 80 + bh + 10, total = Mathf.Max(1, wishes.Count), tw = w - 36, bx = x + 18;
float[] parts = { cool / total, ok / total, warm / total };
Color[] cols = { CoolVote, Green, WarmVote };
for (int i = 0; i < 3; i++)
{
float pw = tw * parts[i];
if (pw > 0.5f) Box(V(bx, by, Mathf.Max(6f, pw - 3f), 6), cols[i], 3);
bx += pw;
}
Text(V(x + 18, by + 10, tw, 14), $"kühler · {cool}", 9.5f, Muted);
Text(V(x + 18, by + 10, tw, 14), $"angenehm · {ok}", 9.5f, Muted, false, TextAnchor.MiddleCenter);
Text(V(x + 18, by + 10, tw, 14), $"wärmer · {warm}", 9.5f, Muted, false, TextAnchor.MiddleRight);
float ny = by + 30;
if (student)
{
Text(V(x + 18, ny, 260, 22), "Frische Luft (Fenster öffnen)", 11.5f, Ink, true);
bool wantWindow = Switch(V(x + w - 18 - 46, ny - 2, 46, 26), own.windowOpen);
if (wantWindow != own.windowOpen)
{
own.windowOpen = wantWindow;
controller.RunCycle();
}
ny += 28;
Text(V(x + 18, ny, w - 36, 16), $"Fenster: {controller.WindowVotes} von {wishes.Count} dafür · Anonym, zählt wie jede andere Stimme.", 9.5f, Muted);
}
else Text(V(x + 18, ny, w - 36, 16), "ⓘ Die Stimme des Dozenten zählt wie jede andere.", 10, Muted);
}
// ---------------------------------------------------------------- Prioritäten (Studierendenansicht)
void DrawPriorities(Rect card, int current)
{
Card(card);
float x = VX(card), y = VY(card), w = card.width / k;
Text(V(x + 18, y + 14, 300, 16), "SO ENTSCHEIDET DAS SYSTEM", 10, Green, true);
string[] subs =
{
$"CO₂-Grenzwert {N(controller.limits.co2Limit, 0)} ppm – kann nicht überstimmt werden",
"Lärm, Wind und Außenluft sperren ggf. das Fenster",
"Ø aller Temperaturwünsche wird zum Zielwert",
"Fenster offen → Heizung aus, Licht nach Tageslicht",
};
for (int i = 0; i < 4; i++)
{
float ry = y + 38 + i * 44;
bool on = i + 1 == current;
var r = V(x + 12, ry, w - 24, 40);
if (on) Box(r, GreenSoft, 9, Color.Lerp(Green2, Mint, 0.4f));
Box(V(x + 22, ry + 9, 22, 22), on ? Green : Soft, 11, on ? Green : Line);
Text(V(x + 22, ry + 9, 22, 22), (i + 1).ToString(), 10.5f, on ? Color.white : Muted, true, TextAnchor.MiddleCenter);
Text(V(x + 54, ry + 4, w - 80, 17), PriorityNames[i + 1] + (on ? " · gerade maßgeblich" : ""), 11.5f, Ink, true);
Text(V(x + 54, ry + 20, w - 80, 15), subs[i], 9.5f, Muted);
}
}
// ---------------------------------------------------------------- Verlauf
void DrawHistory(Rect card)
{
Card(card);
float x = VX(card), y = VY(card), w = card.width / k;
Text(V(x + 18, y + 12, 260, 20), "Verlauf", 15, Ink, true);
Text(V(x + 18, y + 32, 300, 14), "Entscheidungen des Systems", 10.5f, Muted);
int n = Mathf.Min(3, history.Count);
for (int i = 0; i < n; i++)
{
var h = history[i];
float ry = y + 52 + i * 28;
if (i < n - 1) Fill(V(x + 21.5f, ry + 10, 1, 26), Line);
Box(V(x + 18, ry + 3, 8, 8), h.dot, 4);
Text(V(x + 34, ry - 2, w - 110, 16), h.title, 11, Ink, true);
Text(V(x + w - 18 - 60, ry - 2, 60, 16), h.time, 9.5f, Muted, false, TextAnchor.MiddleRight);
Text(V(x + 34, ry + 12, w - 52, 14), h.text, 9.5f, Muted);
}
if (n == 0) Text(V(x + 18, y + 56, w - 36, 16), "Noch keine Entscheidungen.", 10.5f, Muted);
}
// ---------------------------------------------------------------- Fußzeile
void DrawFooter()
{
Text(V(24, 860, 700, 20), "ⓘ Automatische Steuerung nach Gesundheit, Kontext, Mehrheit und Energie", 10.5f, Muted);
string src = bridge == null ? "Simulation"
: bridge.mode == LinkMode.Backend ? (env.AnyMeasured ? $"Sensorquelle: Arduino über {bridge.backendUrl}" : $"Sensorquelle: {bridge.backendUrl} (keine Werte)")
: bridge.mode == LinkMode.Simulation ? "Sensorquelle: Simulation" : $"Sensorquelle: {bridge.mode}";
Text(V(RefW - 24 - 700, 860, 700, 20), $"{src} · Simulationszeit {env.ClockText}", 10.5f, Muted, false, TextAnchor.MiddleRight);
}
// ---------------------------------------------------------------- Einstellungen (Klick auf Status oben rechts)
float SettingsHeight()
{
bool link = bridge != null && bridge.mode != LinkMode.Simulation;
bool backend = bridge != null && bridge.mode == LinkMode.Backend;
return 46 + 54 + (link ? 52 + 74 : 0) + (backend ? 34 : 0) + 14 + 34 + 34 + 20 + 34 + 16;
}
void DrawSettings()
{
drawingPopover = true;
float x = VX(popRect), y = VY(popRect), w = popRect.width / k;
Shadow(popRect, 14);
Box(popRect, Surface, 14, Line);
Text(V(x + 18, y + 14, 300, 20), "Einstellungen", 14, Ink, true);
y += 46;
// Sensorquelle
Text(V(x + 18, y, 300, 16), "Sensorquelle", 10.5f, Muted);
LinkMode[] modes = { LinkMode.Simulation, LinkMode.Backend, LinkMode.Udp, LinkMode.Serial };
string[] names = { "Simulation", "Backend", "UDP", "Seriell" };
float sw = (w - 36) / 4f;
Box(V(x + 18, y + 18, w - 36, 30), Soft, 8, Line);
for (int i = 0; i < 4; i++)
{
var r = V(x + 18 + i * sw + 2, y + 20, sw - 4, 26);
bool on = bridge.mode == modes[i];
if (on) Box(r, Surface, 6, Line);
Text(r, names[i], 10.5f, on ? Ink : Muted, on, TextAnchor.MiddleCenter);
if (Click(r) && !on)
{
bridge.Disconnect();
bridge.mode = modes[i];
bridge.Disconnect(); // Statustext aktualisieren
fieldMode = (LinkMode)(-1);
}
}
y += 54;
if (bridge.mode != LinkMode.Simulation)
{
string label = bridge.mode == LinkMode.Backend ? "Adresse von backend/server.py"
: bridge.mode == LinkMode.Udp ? "UDP-Empfangsport" : "Serieller Port";
Text(V(x + 18, y, w - 36, 16), label, 10.5f, Muted);
if (fieldMode != bridge.mode)
{
fieldMode = bridge.mode;
fieldText = bridge.mode == LinkMode.Backend ? bridge.backendUrl
: bridge.mode == LinkMode.Udp ? bridge.udpListenPort.ToString() : bridge.serialPort;
}
var fr = V(x + 18, y + 18, w - 36, 30);
Box(fr, Surface, 8, Line);
fieldText = GUI.TextField(fr, fieldText ?? "", fieldStyle);
if (bridge.mode == LinkMode.Backend) bridge.backendUrl = fieldText.Trim();
else if (bridge.mode == LinkMode.Udp && int.TryParse(fieldText, out var port)) bridge.udpListenPort = port;
else if (bridge.mode == LinkMode.Serial) bridge.serialPort = fieldText.Trim();
y += 52;
var btn = V(x + 18, y, 110, 30);
Box(btn, bridge.Connected ? Surface : Green, 8, bridge.Connected ? Line : Green);
Text(btn, bridge.Connected ? "Trennen" : "Verbinden", 11, bridge.Connected ? Ink : Color.white, true, TextAnchor.MiddleCenter);
if (Click(btn)) { if (bridge.Connected) bridge.Disconnect(); else bridge.Connect(); }
string packets = bridge.LastPacketTime >= 0f ? $"{bridge.PacketCount} Pakete · vor {Time.unscaledTime - bridge.LastPacketTime:0} s" : "";
Text(V(x + 138, y, w - 156, 30), packets, 10, Muted);
Text(V(x + 18, y + 34, w - 36, 36), bridge.Status, 9.5f, Muted, false, TextAnchor.UpperLeft, false, true);
y += 74;
}
if (bridge.mode == LinkMode.Backend)
{
Text(V(x + 18, y, 260, 26), "Mikrofon steht draußen", 11.5f, Ink);
bridge.MicrophoneOutdoor = Switch(V(x + w - 18 - 46, y, 46, 26), bridge.MicrophoneOutdoor);
y += 34;
}
Fill(V(x + 18, y + 4, w - 36, 1), Line);
y += 14;
if (weather != null)
{
Text(V(x + 18, y, 260, 26), "Live-Wetter (Open-Meteo)", 11.5f, Ink);
bool live = Switch(V(x + w - 18 - 46, y, 46, 26), weather.useLiveWeather);
if (live != weather.useLiveWeather) weather.SetLive(live);
}
y += 34;
Text(V(x + 18, y, 260, 26), "Vorlesung läuft", 11.5f, Ink);
env.lectureRunning = Switch(V(x + w - 18 - 46, y, 46, 26), env.lectureRunning);
y += 34;
Text(V(x + 18, y, 300, 16), "Zeitraffer (simulierte Minuten pro Sekunde)", 10.5f, Muted);
float[] speeds = { 0f, 1f, 5f, 20f };
string[] speedNames = { "Pause", "1×", "5×", "20×" };
Box(V(x + 18, y + 18, w - 36, 30), Soft, 8, Line);
for (int i = 0; i < 4; i++)
{
var r = V(x + 18 + i * sw + 2, y + 20, sw - 4, 26);
bool on = Mathf.Approximately(env.timeScale, speeds[i]);
if (on) Box(r, Surface, 6, Line);
Text(r, speedNames[i], 10.5f, on ? Ink : Muted, on, TextAnchor.MiddleCenter);
if (Click(r)) env.timeScale = speeds[i];
}
drawingPopover = false;
}
// ================================================================ Bausteine
Rect V(float x, float y, float w, float h) => new Rect(origin.x + x * k, origin.y + y * k, w * k, h * k);
float VX(Rect r) => (r.x - origin.x) / k;
float VY(Rect r) => (r.y - origin.y) / k;
int F(float size) => Mathf.Max(7, Mathf.RoundToInt(size * k));
bool Hover(Rect r) => r.Contains(Event.current.mousePosition) && !(settingsOpen && !drawingPopover && popRect.Contains(Event.current.mousePosition));
/// <summary>Unsichtbarer Knopf; unter dem offenen Einstellungsfenster gibt es keine Klicks.</summary>
bool Click(Rect r)
{
if (settingsOpen && !drawingPopover && popRect.Contains(Event.current.mousePosition)) return false;
return GUI.Button(r, GUIContent.none, GUIStyle.none);
}
void Card(Rect r)
{
Shadow(r, 14);
Box(r, Surface, 14, Line);
}
void Shadow(Rect r, float radius)
{
if (Event.current.type != EventType.Repaint) return;
for (int i = 1; i <= 3; i++)
{
float g = i * 2f * k;
var s = new Rect(r.x - g, r.y - g + 4f * k, r.width + 2 * g, r.height + 2 * g);
Box(s, new Color(0.118f, 0.2f, 0.16f, 0.022f), radius + i * 2f);
}
}
void Fill(Rect r, Color c)
{
if (Event.current.type != EventType.Repaint) return;
var old = GUI.color;
GUI.color = c;
GUI.DrawTexture(r, Texture2D.whiteTexture);
GUI.color = old;
}
/// <summary>Abgerundetes Rechteck (Radius in virtuellen Einheiten), optional mit 1-px-Rahmen.</summary>
void Box(Rect r, Color fill, float radius, Color? border = null)
{
if (Event.current.type != EventType.Repaint) return;
var old = GUI.color;
if (border.HasValue)
{
GUI.color = border.Value;
RoundStyle(radius).Draw(r, false, false, false, false);
float px = Mathf.Max(1f, Mathf.Round(k));
r = new Rect(r.x + px, r.y + px, r.width - 2 * px, r.height - 2 * px);
radius = Mathf.Max(0f, radius - px / k);
}
GUI.color = fill;
RoundStyle(radius).Draw(r, false, false, false, false);
GUI.color = old;
}
/// <summary>Rundet die Ecken der 3D-Ansicht ab (Ecken in Kartenfarbe übermalen).</summary>
void Hole(Rect r, Color c, float radius)
{
if (Event.current.type != EventType.Repaint) return;
int rp = Mathf.Max(2, Mathf.RoundToInt(radius * k));
if (!holeStyles.TryGetValue(rp, out var st))
{
var tex = RoundedTex(rp, true);
st = new GUIStyle { normal = { background = tex }, border = new RectOffset(rp + 1, rp + 1, rp + 1, rp + 1) };
holeStyles[rp] = st;
}
var old = GUI.color;
GUI.color = c;
st.Draw(r, false, false, false, false);
GUI.color = old;
}
GUIStyle RoundStyle(float radius)
{
int rp = Mathf.Max(1, Mathf.RoundToInt(radius * k));
if (!roundStyles.TryGetValue(rp, out var st))
{
var tex = RoundedTex(rp, false);
st = new GUIStyle { normal = { background = tex }, border = new RectOffset(rp + 1, rp + 1, rp + 1, rp + 1) };
roundStyles[rp] = st;
}
return st;
}
Texture2D RoundedTex(int r, bool hole)
{
int n = 2 * r + 4;
var t = new Texture2D(n, n, TextureFormat.RGBA32, false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, hideFlags = HideFlags.HideAndDontSave };
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(1f, 1f, 1f, hole ? 1f - a : a);
}
t.SetPixels(px);
t.Apply();
textures.Add(t);
return t;
}
bool Switch(Rect r, bool on)
{
if (Click(r)) on = !on;
Box(r, on ? Green2 : Line, r.height / 2f / k);
float kn = r.height - 6f * k;
var knob = new Rect(on ? r.xMax - kn - 3f * k : r.x + 3f * k, r.y + 3f * k, kn, kn);
Box(knob, Surface, kn / 2f / k);
return on;
}
float Chip(float x, float y, string text, Color fg, Color bg)
{
float w = TextWidth(text, 11, true) + 22f;
var r = V(x, y, w, 26);
Box(r, new Color(bg.r, bg.g, bg.b, 0.94f), 8, Line);
Text(r, text, 11, fg, true, TextAnchor.MiddleCenter);
return w;
}
void Text(Rect r, string s, float size, Color c, bool bold = false, TextAnchor anchor = TextAnchor.MiddleLeft, bool useSerif = false, bool wrap = false)
=> GUI.Label(r, s, TextStyle(size, c, bold, anchor, useSerif, wrap));
float TextWidth(string s, float size, bool bold) => TextStyle(size, Ink, bold, TextAnchor.MiddleLeft, false, false).CalcSize(new GUIContent(s)).x / k;
GUIStyle TextStyle(float size, Color c, bool bold, TextAnchor anchor, bool useSerif, bool wrap)
{
string key = $"{size}|{ColorUtility.ToHtmlStringRGBA(c)}|{bold}|{anchor}|{useSerif}|{wrap}";
if (textStyles.TryGetValue(key, out var st)) return st;
st = new GUIStyle
{
font = useSerif ? serif : sans,
fontSize = F(size),
fontStyle = bold ? FontStyle.Bold : FontStyle.Normal,
alignment = anchor,
wordWrap = wrap,
richText = true,
clipping = TextClipping.Overflow,
normal = { textColor = c },
};
textStyles[key] = st;
return st;
}
/// <summary>Erste installierte Schrift aus der Liste (null = Unity-Standardschrift).
/// Nur einen vorhandenen Namen übergeben – mit fehlenden Namen rendert IMGUI in Unity 6 falsche Texte.</summary>
static Font OsFont(int size, params string[] names)
{
var installed = new HashSet<string>(Font.GetOSInstalledFontNames());
foreach (var n in names)
if (installed.Contains(n)) return Font.CreateDynamicFontFromOSFont(n, size);
return null;
}
void EnsureStyles()
{
k = Mathf.Min(Screen.width / RefW, Screen.height / RefH);
origin = new Vector2(Mathf.Round((Screen.width - RefW * k) / 2f), Mathf.Round((Screen.height - RefH * k) / 2f));
if (Mathf.Approximately(stylesFor, k) && sans != null) return;
stylesFor = k;
textStyles.Clear();
roundStyles.Clear();
holeStyles.Clear();
foreach (var t in textures) if (t != null) Destroy(t);
textures.Clear();
// Systemschriften wie im Frontend (Sans + Serifen-Überschrift)
if (sans == null) sans = OsFont(14, "Inter", "Helvetica Neue", "Helvetica", "Segoe UI", "Arial");
if (serif == null) serif = OsFont(32, "Georgia", "Charter", "Times New Roman", "Times");
fieldStyle = new GUIStyle
{
font = sans,
fontSize = F(11.5f),
alignment = TextAnchor.MiddleLeft,
padding = new RectOffset(F(10), F(10), 0, 0),
clipping = TextClipping.Clip,
normal = { textColor = Ink },
focused = { textColor = Ink },
hover = { textColor = Ink },
};
}
}
}