neuroticfox

Draconic Control Redux v1.0 (xMAT)

May 26th, 2026 (edited)
135
0
Never
6
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 45.40 KB | None | 0 0
  1. --[[
  2.   Draconic Reactor GUI Controller
  3.   Clean rewrite: Unicode box UI, drag sliders, stable ETA display
  4.  
  5.   Usage:
  6.     dc1
  7.     dc1 -d
  8.     dc1 --in=<input flux gate address> --out=<output flux gate address>
  9.     dc1 --mult=10
  10.  
  11.   Normal mode:   Temp 2500-8000 C,  Field 1.0-50.0%
  12.   Danger mode:   Temp 2500-20000 C, Field 0.5-100.0%   (-d / --danger)
  13. ]]
  14.  
  15. local component = require("component")
  16. local event     = require("event")
  17. local term      = require("term")
  18.  
  19. --------------------------------------------------------------------------------
  20. -- CONFIG / ARGS
  21. --------------------------------------------------------------------------------
  22.  
  23. local OUTPUT_FLUX_ADDRESS     = nil
  24. local INPUT_FLUX_ADDRESS      = nil
  25. local reactorOutputMultiplier = 1
  26. local dangerMode              = false
  27.  
  28. local MAX_GATE_FLOW      = 2147000000
  29. local WARMUP_INPUT_RF_T  = 5000000
  30. local PROBE_INPUT_RF_T   = 1
  31. local PROBE_TICK_S       = 0.05
  32. local MC_TICKS_PER_S     = 20
  33. local FUEL_CUTOFF        = 0.875      -- stop at 87.5% conversion
  34.  
  35. -- ETA smoothing
  36. local ETA_ALPHA_STEADY   = 0.04   -- slow drift when stable
  37. local ETA_ALPHA_MOVING   = 0.18   -- faster when targets changing
  38. local ETA_STEADY_TEMP_ERR  = 200  -- C
  39. local ETA_STEADY_FIELD_ERR = 0.02
  40.  
  41. for _, arg in ipairs({...}) do
  42.   if     arg == "-d" or arg == "--danger" or arg == "--chaos" then
  43.     dangerMode = true
  44.   elseif arg:sub(1,6)  == "--out="  then OUTPUT_FLUX_ADDRESS     = arg:sub(7)
  45.   elseif arg:sub(1,5)  == "--in="   then INPUT_FLUX_ADDRESS      = arg:sub(6)
  46.   elseif arg:sub(1,7)  == "--mult=" then
  47.     reactorOutputMultiplier = tonumber(arg:sub(8)) or reactorOutputMultiplier
  48.   end
  49. end
  50.  
  51. --------------------------------------------------------------------------------
  52. -- COMPONENT SETUP
  53. --------------------------------------------------------------------------------
  54.  
  55. if not component.isAvailable("gpu")              then error("No GPU found.")             end
  56. if not component.isAvailable("screen")           then error("No screen found.")          end
  57. if not component.isAvailable("draconic_reactor") then error("No draconic_reactor found.") end
  58.  
  59. local gpu     = component.gpu
  60. local reactor = component.draconic_reactor
  61.  
  62. local savedFg = gpu.getForeground()
  63. local savedBg = gpu.getBackground()
  64.  
  65. --------------------------------------------------------------------------------
  66. -- PALETTE
  67. --------------------------------------------------------------------------------
  68.  
  69. local C = {
  70.   bg       = 0x0A0E1A,
  71.   panel    = 0x0F1629,
  72.   panel2   = 0x141E35,
  73.   border   = 0x2A3A5C,
  74.   text     = 0xD0D8F0,
  75.   muted    = 0x5A6A8A,
  76.   white    = 0xFFFFFF,
  77.   black    = 0x000000,
  78.   blue     = 0x4FC3F7,
  79.   purple   = 0xB39DDB,
  80.   green    = 0x66BB6A,
  81.   yellow   = 0xFFD54F,
  82.   orange   = 0xFF8A65,
  83.   red      = 0xEF5350,
  84.   slider_t = 0xFF6B35,   -- temp slider track/handle
  85.   slider_f = 0x42A5F5,   -- field slider track/handle
  86.   bar_bg   = 0x1A2540,
  87. }
  88.  
  89. --------------------------------------------------------------------------------
  90. -- UTILS
  91. --------------------------------------------------------------------------------
  92.  
  93. local function clamp(v, lo, hi)
  94.   v = tonumber(v) or lo
  95.   if v ~= v then return lo end
  96.   return math.max(lo, math.min(hi, v))
  97. end
  98.  
  99. local function safeDiv(a, b, fb)
  100.   a, b = tonumber(a) or 0, tonumber(b) or 0
  101.   if b == 0 then return fb or 0 end
  102.   return a / b
  103. end
  104.  
  105. local function formatRF(n)
  106.   n = tonumber(n) or 0
  107.   if math.abs(n) >= 1e9 then return string.format("%.2f GRF/t", n/1e9) end
  108.   if math.abs(n) >= 1e6 then return string.format("%.2f MRF/t", n/1e6) end
  109.   if math.abs(n) >= 1e3 then return string.format("%.2f kRF/t", n/1e3) end
  110.   return string.format("%d RF/t", math.floor(n+0.5))
  111. end
  112.  
  113. local function formatPct(p)
  114.   return string.format("%.1f%%", clamp(tonumber(p) or 0, 0, 1)*100)
  115. end
  116.  
  117. local function formatTargetPct(p)
  118.   return string.format("%.2f%%", clamp(tonumber(p) or 0, 0, 1)*100)
  119. end
  120.  
  121. local function shortAddr(a)
  122.   a = tostring(a or "none")
  123.   if #a <= 13 then return a end
  124.   return a:sub(1,8) .. "…" .. a:sub(-4)
  125. end
  126.  
  127. local function fit(s, w)
  128.   s = tostring(s or "")
  129.   if w <= 0 then return "" end
  130.   if #s > w then return s:sub(1,w-1) .. "…" end
  131.   return s .. string.rep(" ", w - #s)
  132. end
  133.  
  134. local function formatETA(sec)
  135.   sec = tonumber(sec)
  136.   if not sec or sec ~= sec or sec == math.huge or sec < 0 then return "--:--:--" end
  137.   if sec > 359999 then return ">99h" end
  138.   sec = math.floor(sec + 0.5)
  139.   local h = math.floor(sec / 3600)
  140.   local m = math.floor((sec % 3600) / 60)
  141.   local s = sec % 60
  142.   return string.format("%d:%02d:%02d", h, m, s)
  143. end
  144.  
  145. --------------------------------------------------------------------------------
  146. -- GPU HELPERS
  147. --------------------------------------------------------------------------------
  148.  
  149. local function setColor(fg, bg)
  150.   if fg then gpu.setForeground(fg) end
  151.   if bg then gpu.setBackground(bg) end
  152. end
  153.  
  154. local function writeAt(x, y, s, fg, bg)
  155.   setColor(fg or C.text, bg or C.bg)
  156.   gpu.set(x, y, tostring(s))
  157. end
  158.  
  159. local function fillAt(x, y, w, h, fg, bg, ch)
  160.   if w <= 0 or h <= 0 then return end
  161.   setColor(fg or C.text, bg or C.bg)
  162.   gpu.fill(x, y, w, h, ch or " ")
  163. end
  164.  
  165. --------------------------------------------------------------------------------
  166. -- BOX DRAWING  (real UTF-8 literals — no byte-escape gymnastics needed)
  167. --------------------------------------------------------------------------------
  168.  
  169. local BOX = {
  170.   tl="┌", tr="┐", bl="└", br="┘",
  171.   h="─", v="│",
  172.   lt="├", rt="┤", tt="┬", bt="┴", cross="┼",
  173. }
  174.  
  175. local function drawBox(x, y, w, h, title, fg, bg)
  176.   fg = fg or C.border
  177.   bg = bg or C.panel
  178.   if w < 3 or h < 2 then return end
  179.   fillAt(x, y, w, h, C.text, bg)
  180.   -- top
  181.   gpu.setForeground(fg); gpu.setBackground(bg)
  182.   gpu.set(x, y, BOX.tl .. string.rep(BOX.h, w-2) .. BOX.tr)
  183.   -- sides
  184.   for yy = y+1, y+h-2 do
  185.     gpu.set(x,     yy, BOX.v)
  186.     gpu.set(x+w-1, yy, BOX.v)
  187.   end
  188.   -- bottom
  189.   gpu.set(x, y+h-1, BOX.bl .. string.rep(BOX.h, w-2) .. BOX.br)
  190.   -- title
  191.   if title and title ~= "" then
  192.     writeAt(x+2, y, " " .. fit(title, w-6) .. " ", C.text, bg)
  193.   end
  194. end
  195.  
  196. local function hline(x, y, w, fg, bg)
  197.   setColor(fg or C.border, bg or C.panel)
  198.   gpu.set(x, y, BOX.lt .. string.rep(BOX.h, w-2) .. BOX.rt)
  199. end
  200.  
  201. --------------------------------------------------------------------------------
  202. -- BAR RENDERER
  203. -- Draws a horizontal bar from x,y of width w filled to fraction t (0-1)
  204. -- filled cells use fillChar (defaults to "█"), empty use "░"
  205. --------------------------------------------------------------------------------
  206.  
  207. local function drawBar(x, y, w, t, fillClr, emptyClr, bg)
  208.   t = clamp(t, 0, 1)
  209.   local filled = math.floor(t * w + 0.5)
  210.   bg = bg or C.panel
  211.   setColor(fillClr, bg)
  212.   if filled > 0 then gpu.fill(x, y, filled, 1, "█") end
  213.   setColor(emptyClr or C.bar_bg, bg)
  214.   if filled < w then gpu.fill(x+filled, y, w-filled, 1, "░") end
  215. end
  216.  
  217.  
  218.  
  219. --------------------------------------------------------------------------------
  220. -- FLUX GATE PROBE / BINDING
  221. --------------------------------------------------------------------------------
  222.  
  223. local gateMsg         = ""
  224. local input_flux      = nil
  225. local output_flux     = nil
  226. local input_flux_addr = nil
  227. local output_flux_addr= nil
  228.  
  229. local function rawSetGate(g, v)
  230.   if not g then return false end
  231.   v = math.floor(clamp(v or 0, 0, MAX_GATE_FLOW) + 0.5)
  232.   pcall(function() g.setOverrideEnabled(true) end)
  233.   return pcall(function() g.setFlowOverride(v) end)
  234. end
  235.  
  236. local function rawGetGate(g)
  237.   if not g then return 0 end
  238.   local ok, v = pcall(function() return g.getFlowOverride() end)
  239.   if ok then return tonumber(v) or 0 end
  240.   ok, v = pcall(function() return g.getFlow() end)
  241.   if ok then return tonumber(v) or 0 end
  242.   return 0
  243. end
  244.  
  245. local function collectGates()
  246.   local t = {}
  247.   for addr in pairs(component.list("flux_gate")) do
  248.     local ok, p = pcall(component.proxy, addr)
  249.     if ok and p then
  250.       pcall(function() p.setOverrideEnabled(true) end)
  251.       t[#t+1] = {address=addr, proxy=p}
  252.     end
  253.   end
  254.   return t
  255. end
  256.  
  257. local function zeroAll(gates)
  258.   for _, g in ipairs(gates or {}) do rawSetGate(g.proxy, 0) end
  259. end
  260.  
  261. local function reactorSnap()
  262.   local ok, s = pcall(function() return reactor.getReactorInfo() end)
  263.   if not ok or not s then return nil end
  264.   return {
  265.     status           = tostring(s.status or "unknown"),
  266.     temperature      = tonumber(s.temperature) or 0,
  267.     fieldStrength    = tonumber(s.fieldStrength) or 0,
  268.     maxFieldStrength = tonumber(s.maxFieldStrength) or 0,
  269.     energySaturation = tonumber(s.energySaturation) or 0,
  270.     maxEnergySaturation = tonumber(s.maxEnergySaturation) or 0,
  271.   }
  272. end
  273.  
  274. local function probeInputGate(gates)
  275.   term.clear(); term.setCursor(1,1)
  276.   print("Draconic Reactor: flux gate probe")
  277.   print("Found " .. #gates .. " gate(s). Sending 1 RF/t pulse per gate…")
  278.   zeroAll(gates)
  279.  
  280.   local snap0 = reactorSnap()
  281.   local status0 = snap0 and snap0.status or "unknown"
  282.   local temp0   = snap0 and snap0.temperature or 0
  283.   local canCharge = (status0=="cold" or status0=="cooling" or status0=="offline" or status0=="stopped") and temp0 < 1000
  284.  
  285.   if canCharge then
  286.     print("Cold state — requesting brief charge for probe.")
  287.     pcall(function() reactor.chargeReactor() end)
  288.     os.sleep(PROBE_TICK_S)
  289.   end
  290.  
  291.   local bestIdx, bestScore, bestFG, bestSG = nil, -1, 0, 0
  292.   for i, g in ipairs(gates) do
  293.     zeroAll(gates); os.sleep(PROBE_TICK_S)
  294.     local before = reactorSnap()
  295.     rawSetGate(g.proxy, PROBE_INPUT_RF_T)
  296.     os.sleep(PROBE_TICK_S)
  297.     local after = reactorSnap()
  298.     rawSetGate(g.proxy, 0)
  299.     local fg = (after and after.fieldStrength or 0) - (before and before.fieldStrength or 0)
  300.     local sg = (after and after.energySaturation or 0) - (before and before.energySaturation or 0)
  301.     local score = math.max(0,fg)*1000 + math.max(0,sg)
  302.     print(string.format("  Gate #%d %s  score=%d  field+=%d  sat+=%d", i, shortAddr(g.address), math.floor(score+0.5), math.floor(fg+0.5), math.floor(sg+0.5)))
  303.     if score > bestScore then bestIdx, bestScore, bestFG, bestSG = i, score, fg, sg end
  304.   end
  305.  
  306.   zeroAll(gates)
  307.   if canCharge then pcall(function() reactor.stopReactor() end) end
  308.  
  309.   if not bestIdx or bestScore < 1 then
  310.     gateMsg = "Probe inconclusive; defaulting gate #1=input, #2=output."
  311.     return 1, 2
  312.   end
  313.  
  314.   local outIdx
  315.   for i in ipairs(gates) do if i ~= bestIdx then outIdx = i; break end end
  316.   gateMsg = string.format("Probe: input=#%d  output=#%d  score=%d", bestIdx, outIdx or 0, math.floor(bestScore+0.5))
  317.   return bestIdx, outIdx
  318. end
  319.  
  320. local function findByAddr(gates, addr)
  321.   if not addr or addr == "" then return nil end
  322.   for i, g in ipairs(gates) do if g.address == addr then return i end end
  323.   return nil
  324. end
  325.  
  326. local function otherIdx(gates, idx)
  327.   for i in ipairs(gates) do if i ~= idx then return i end end
  328.   return nil
  329. end
  330.  
  331. local function bindGates()
  332.   local gates = collectGates()
  333.   if #gates < 2 then
  334.     error("Need at least 2 flux_gate components; found " .. #gates)
  335.   end
  336.  
  337.   local iIdx = findByAddr(gates, INPUT_FLUX_ADDRESS)
  338.   local oIdx = findByAddr(gates, OUTPUT_FLUX_ADDRESS)
  339.  
  340.   if not iIdx and not oIdx then
  341.     iIdx, oIdx = probeInputGate(gates)
  342.     os.sleep(0.5)
  343.   elseif iIdx and not oIdx then
  344.     oIdx = otherIdx(gates, iIdx)
  345.     gateMsg = "Manual input; output = first other gate."
  346.   elseif oIdx and not iIdx then
  347.     iIdx = otherIdx(gates, oIdx)
  348.     gateMsg = "Manual output; input = first other gate."
  349.   else
  350.     gateMsg = "Manual input/output bound."
  351.   end
  352.  
  353.   if not iIdx or not oIdx or iIdx == oIdx then
  354.     error("Could not allocate distinct input/output gates.")
  355.   end
  356.  
  357.   -- Hot-restart inversion: if the reactor is already hot, gate roles are flipped
  358.   local snap = reactorSnap()
  359.   local hotTemp = snap and snap.temperature or 0
  360.   if hotTemp > 2000 then
  361.     iIdx, oIdx = oIdx, iIdx
  362.     gateMsg = gateMsg .. string.format(" Hot-start %.0fC: roles inverted.", hotTemp)
  363.   end
  364.  
  365.   input_flux       = gates[iIdx].proxy
  366.   output_flux      = gates[oIdx].proxy
  367.   input_flux_addr  = gates[iIdx].address
  368.   output_flux_addr = gates[oIdx].address
  369.   rawSetGate(input_flux, 0)
  370.   rawSetGate(output_flux, 0)
  371. end
  372.  
  373. local function setGate(g, v)
  374.   if not g then return end
  375.   rawSetGate(g, math.floor(clamp(v or 0, 0, MAX_GATE_FLOW) + 0.5))
  376. end
  377.  
  378. --------------------------------------------------------------------------------
  379. -- CONTROL MATH  (verbatim from dc0.lua / pastebin v15.1)
  380. --------------------------------------------------------------------------------
  381.  
  382. local function computeControl(info, targetTemp, targetShield, multiplier)
  383.   if not info then return {} end
  384.  
  385.   local targetTemp50  = math.min((targetTemp / 10000) * 50, 99)
  386.   local coreSat       = safeDiv(info.energySaturation, info.maxEnergySaturation, 0)
  387.   local convLVL       = (safeDiv(info.fuelConversion, info.maxFuelConversion, 0) * 1.3) - 0.3
  388.  
  389.   local targetTempResist = (targetTemp50^4) / (100 - targetTemp50)
  390.   local targetTempExpo   = -(targetTempResist * convLVL) - 1000*convLVL + targetTempResist
  391.  
  392.   local term1      = 1334.1 - (3 * targetTempExpo)
  393.   local term2      = (1200690 - (2700 * targetTempExpo))^2
  394.   local inner      = (-4*term1^3 + term2)
  395.   local sqrtInner  = inner >= 0 and inner^0.5 or 0
  396.   local term3      = ((-1350*targetTempExpo) + sqrtInner/2 + 600345)^(1/3)
  397.   local targetNegCSat = -(term1/(3*term3)) - (term3/3)
  398.   local targetCoreSat = 1 - (targetNegCSat / 99)
  399.   local targetSat     = targetCoreSat * info.maxEnergySaturation
  400.   local satError      = info.energySaturation - targetSat
  401.  
  402.   local tempDrainFactor = 0
  403.   local t = info.temperature
  404.   if     t > 8000 then tempDrainFactor = 1 + (t-8000)^2 * 0.0000025
  405.   elseif t > 2000 then tempDrainFactor = 1
  406.   elseif t > 1000 then tempDrainFactor = (t-1000)/1000
  407.   end
  408.  
  409.   local baseMaxRFt  = (info.maxEnergySaturation / 1000) * multiplier * 1.5
  410.   local fieldDrain  = math.min(tempDrainFactor * math.max(0.01, 1-coreSat) * (baseMaxRFt/10.923556), MAX_GATE_FLOW)
  411.   -- Minimum field strength above 9000C: 10% + temp/500 percent
  412.   -- Prevents cascade collapse where drain acceleration outpaces a single tick's input
  413.   local minField = 0.0
  414.   if info.temperature > 9000 then
  415.     minField = (0.10 + (info.temperature / 500)) / 100
  416.   end
  417.   local effectiveShield = math.max(targetShield, minField)
  418.   local fsError     = (info.maxFieldStrength * effectiveShield) - info.fieldStrength
  419.   local reqInput    = math.min(
  420.     safeDiv(info.maxFieldStrength * info.fieldDrainRate, info.maxFieldStrength - info.fieldStrength, 0),
  421.     info.maxFieldStrength - info.fieldStrength
  422.   )
  423.  
  424.   local outputNeeded = math.min(satError, info.maxEnergySaturation / 40) + (info.generationRate or 0)
  425.  
  426.   local inputCmd     = math.min(fsError + reqInput, info.maxFieldStrength)
  427.  
  428.   return {
  429.     satError        = satError,
  430.     fieldStrengthError = fsError,
  431.     requiredInput   = reqInput,
  432.     outputNeeded    = outputNeeded,
  433.     inputCommand    = inputCmd,
  434.     targetCoreSat   = targetCoreSat,
  435.     tempDrainFactor = tempDrainFactor,
  436.     convLVL         = convLVL,
  437.     targetTempResist= targetTempResist,
  438.   }
  439. end
  440.  
  441. --------------------------------------------------------------------------------
  442. -- ETA MODEL  (fuel remaining / burn rate at current temperature)
  443. --------------------------------------------------------------------------------
  444.  
  445. -- Fuel burn rate model (nb/tick) as a function of temperature.
  446. -- Derived from the pastebin v15 reference table at known operating points.
  447. -- convLVL is (fuelConversion/maxFuelConversion * 1.3) - 0.3
  448. local function modeledFuelNbPerTick(temp, convLVL)
  449.   -- At temp T the saturation target drives a specific burn rate.
  450.   -- We approximate via the observed relationship: rate ∝ temp^1.8 / 1e9
  451.   -- This is a rough model; the actual figure from getReactorInfo is used
  452.   -- for smoothing, not raw ETA.
  453.   temp    = clamp(tonumber(temp) or 4000, 1000, 25000)
  454.   convLVL = clamp(tonumber(convLVL) or 0, 0, 1)
  455.   return math.max(0.001, (temp^1.8) / 3e10 * (0.5 + convLVL))
  456. end
  457.  
  458. local function etaSecondsToConversion(info, targetConv, temp)
  459.   if not info then return nil end
  460.   local fuelRemaining = (info.maxFuelConversion or 0) - (info.fuelConversion or 0)
  461.   local toConsume     = math.max(0, targetConv * (info.maxFuelConversion or 0) - (info.fuelConversion or 0))
  462.   -- Prefer live rate, fall back to model
  463.   local liveRate = tonumber(info.fuelConversionRate) or 0  -- nb/tick
  464.   if liveRate < 0.001 then
  465.     local cLVL = safeDiv(info.fuelConversion, info.maxFuelConversion, 0) * 1.3 - 0.3
  466.     liveRate = modeledFuelNbPerTick(temp or 4000, cLVL) / 1e6  -- convert nb to internal units
  467.   end
  468.   -- fuelConversionRate is in nb/tick; maxFuelConversion is in "units" where 1 unit = 1e6 nb
  469.   -- ETA in seconds = toConsume_units / (liveRate_nb_per_tick / 1e6) / MC_TICKS_PER_S
  470.   local rateUnitsPerTick = liveRate / 1e6
  471.   if rateUnitsPerTick < 1e-12 then return nil end
  472.   return toConsume / (rateUnitsPerTick * MC_TICKS_PER_S)
  473. end
  474.  
  475. -- Smoothed ETA state
  476. local etaStopSec, etaEmptySec = nil, nil
  477.  
  478. local function smoothEta(which, raw, isStable)
  479.   if not raw then return nil end
  480.   local alpha = isStable and ETA_ALPHA_STEADY or ETA_ALPHA_MOVING
  481.   if which == "stop" then
  482.     if not etaStopSec then etaStopSec = raw end
  483.     etaStopSec = etaStopSec + (raw - etaStopSec) * alpha
  484.     return etaStopSec
  485.   else
  486.     if not etaEmptySec then etaEmptySec = raw end
  487.     etaEmptySec = etaEmptySec + (raw - etaEmptySec) * alpha
  488.     return etaEmptySec
  489.   end
  490. end
  491.  
  492. --------------------------------------------------------------------------------
  493. -- LAYOUT
  494. -- Screen assumed 80×25 minimum; adapts to actual resolution
  495. --------------------------------------------------------------------------------
  496.  
  497. local W, H         -- screen dimensions, set in buildLayout
  498. local layout       = {}
  499.  
  500. local function buildLayout()
  501.   W, H = gpu.getResolution()
  502.   W, H = tonumber(W) or 80, tonumber(H) or 25
  503.  
  504.   -- Three columns:
  505.   --  Left  (stats)  : x=1,  width = floor(W*0.45)
  506.   --  Right (calc)   : x=lw+1, width = W - lw - 1
  507.   -- Rows:
  508.   --  Title bar      : y=1
  509.   --  Status box     : y=2,   height=10  (stats + bars)
  510.   --  Slider section : y=13,  height=6
  511.   --  Button row     : y=20
  512.   --  Gate / ETA row : y=22
  513.   --  Status line    : y=H
  514.  
  515.   local lw = math.floor(W * 0.55)
  516.   local rw = W - lw
  517.  
  518.   layout.W, layout.H = W, H
  519.   layout.lw, layout.rw = lw, rw
  520.  
  521.   -- Main stats box
  522.   layout.statsBox = { x=1, y=2, w=lw, h=11 }
  523.   -- Calc/debug box
  524.   layout.calcBox  = { x=lw+1, y=2, w=rw, h=11 }
  525.   -- Slider section (inside a box) — expanded to fit offset slider
  526.   layout.sliderBox = { x=1, y=13, w=W, h=11 }
  527.  
  528.   -- Sliders (inside sliderBox, 2 rows)
  529.   local sw = math.floor((W - 6) / 2)
  530.   layout.sliders = {
  531.     temp  = { x=3,      y=17, w=sw,       min=dangerMode and 2500 or 2500, max=dangerMode and 20000 or 8000, step=25,     isTemp=true  },
  532.     field = { x=3+sw+2, y=17, w=W-5-sw,   min=dangerMode and 0.005 or 0.01, max=dangerMode and 1.0 or 0.50, step=0.0025, isTemp=false },
  533.     -- Bipolar output offset slider: ±1,000,000 RF/t, zero at center
  534.     offset = { x=3, y=21, w=W-4, min=-1000000, max=1000000, step=1000, isOffset=true },
  535.   }
  536.  
  537.   -- Button row
  538.   layout.btnY = 24
  539.   layout.btnStart  = { x=2,    y=layout.btnY, w=12, h=1 }
  540.   layout.btnStop   = { x=15,   y=layout.btnY, w=12, h=1 }
  541.   layout.btnQuit   = { x=W-7,  y=layout.btnY, w=7,  h=1 }
  542.  
  543.   -- Status line
  544.   layout.statusY = H
  545. end
  546.  
  547. --------------------------------------------------------------------------------
  548. -- STATE
  549. --------------------------------------------------------------------------------
  550.  
  551. local lastInfo        = nil
  552. local lastCalc        = {}
  553. local lastSentOutput  = nil
  554. local emaOutput       = nil
  555. local EMA_ALPHA       = 0.15
  556. local outputOffset    = 0       -- bipolar RF/t offset applied to output gate
  557. local targetTemp      = 8000
  558. local targetShield    = 0.15    -- 15%
  559. local controlEnabled  = true
  560. local armed           = false
  561. local running         = true
  562. local statusMsg       = ""
  563. local lastError       = nil
  564. local timers          = {}
  565.  
  566. -- Dirty flags
  567. local staticDirty     = true
  568. local dynDirty        = true
  569. local sliderDirty     = true
  570. local btnDirty        = true
  571.  
  572. -- Drag state
  573. local dragging        = nil    -- "temp" | "field"
  574.  
  575. --------------------------------------------------------------------------------
  576. -- STATIC UI
  577. --------------------------------------------------------------------------------
  578.  
  579. local function drawStaticUI()
  580.   gpu.setResolution(W, H)
  581.   fillAt(1, 1, W, H, C.text, C.bg)
  582.  
  583.   -- Title bar
  584.   setColor(C.bg, C.blue)
  585.   gpu.fill(1, 1, W, 1, " ")
  586.   local title = " ◈ DRACONIC REACTOR CONTROLLER"
  587.   if dangerMode then title = title .. "  ⚠ DANGER MODE" end
  588.   writeAt(2, 1, title, C.bg, C.blue)
  589.   writeAt(W-12, 1, fit("mult×"..reactorOutputMultiplier, 12), C.bg, C.blue)
  590.  
  591.   -- Stats box
  592.   drawBox(layout.statsBox.x, layout.statsBox.y, layout.statsBox.w, layout.statsBox.h, "Reactor Status", C.border, C.panel)
  593.   -- Calc box
  594.   drawBox(layout.calcBox.x, layout.calcBox.y, layout.calcBox.w, layout.calcBox.h, "Control Math", C.border, C.panel)
  595.   -- Slider box
  596.   drawBox(layout.sliderBox.x, layout.sliderBox.y, layout.sliderBox.w, layout.sliderBox.h, "Setpoints", C.border, C.panel)
  597.  
  598.   -- Slider labels (static portion — values drawn in dynamic)
  599.   local sl = layout.sliders
  600.   writeAt(sl.temp.x,  layout.sliderBox.y+1, "Temperature Target", C.muted, C.panel)
  601.   writeAt(sl.field.x, layout.sliderBox.y+1, "Shield Field Target", C.muted, C.panel)
  602.   writeAt(sl.offset.x, layout.sliderBox.y+6, "RF Input Offset", C.muted, C.panel)
  603.   -- slider rail labels
  604.   writeAt(sl.temp.x,  sl.temp.y+1,  tostring(sl.temp.min)  .. "C", C.muted, C.panel)
  605.   writeAt(sl.temp.x + sl.temp.w - #tostring(sl.temp.max) - 1,  sl.temp.y+1, tostring(sl.temp.max) .. "C", C.muted, C.panel)
  606.   writeAt(sl.field.x, sl.field.y+1, string.format("%.0f%%", sl.field.min*100), C.muted, C.panel)
  607.   local fmaxStr = string.format("%.0f%%", sl.field.max*100)
  608.   writeAt(sl.field.x + sl.field.w - #fmaxStr - 1, sl.field.y+1, fmaxStr, C.muted, C.panel)
  609.   -- offset rail labels
  610.   writeAt(sl.offset.x, sl.offset.y+1, "-1,000,000 RF/t", C.muted, C.panel)
  611.   local omaxStr = "+1,000,000 RF/t"
  612.   writeAt(sl.offset.x + sl.offset.w - #omaxStr, sl.offset.y+1, omaxStr, C.muted, C.panel)
  613.  
  614.   staticDirty = false
  615. end
  616.  
  617. --------------------------------------------------------------------------------
  618. -- SLIDER DRAWING
  619. --------------------------------------------------------------------------------
  620.  
  621. local function sliderPos(sl, val)
  622.   -- returns pixel x of the handle for value val
  623.   local t = safeDiv(val - sl.min, sl.max - sl.min, 0)
  624.   return sl.x + math.floor(t * (sl.w - 1) + 0.5)
  625. end
  626.  
  627. local function sliderVal(sl, px)
  628.   -- Map pixel x linearly into the value range, then snap to nearest step.
  629.   -- We do NOT add 0.5 bias before flooring — that shifts the snap boundary
  630.   -- and causes some pixel positions to jump 2 steps while others jump 0.
  631.   -- Plain round() (floor + 0.5 applied to the step-divided value) is correct.
  632.   local t   = clamp(safeDiv(px - sl.x, sl.w - 1, 0), 0, 1)
  633.   local raw = sl.min + t * (sl.max - sl.min)
  634.   -- Round to nearest step symmetrically
  635.   local snapped = math.floor(raw / sl.step + 0.5) * sl.step
  636.   return clamp(snapped, sl.min, sl.max)
  637. end
  638.  
  639. local function drawSlider(sl, val, color, label)
  640.   -- Rail
  641.   local ry = sl.y
  642.   local t  = safeDiv(val - sl.min, sl.max - sl.min, 0)
  643.   -- filled portion
  644.   local filled = math.floor(t * sl.w + 0.5)
  645.   setColor(color, C.panel)
  646.   if filled > 0 then gpu.fill(sl.x, ry, filled, 1, "▬") end
  647.   setColor(C.muted, C.panel)
  648.   if filled < sl.w then gpu.fill(sl.x+filled, ry, sl.w-filled, 1, "─") end
  649.   -- Handle
  650.   local hx = sliderPos(sl, val)
  651.   setColor(C.bg, color)
  652.   gpu.set(hx, ry, "◆")
  653.   -- Value label above handle
  654.   local lbl = label or (sl.isTemp and (tostring(math.floor(val+0.5)) .. "C") or string.format("%.2f%%", val*100))
  655.   local lx  = clamp(hx - math.floor(#lbl/2), sl.x, sl.x + sl.w - #lbl)
  656.   writeAt(lx, ry-1, lbl, color, C.panel)
  657.   -- Clear rest of label row
  658.   if lx > sl.x then
  659.     writeAt(sl.x, ry-1, string.rep(" ", lx - sl.x), C.panel, C.panel)
  660.   end
  661.   local rEnd = lx + #lbl
  662.   if rEnd < sl.x + sl.w then
  663.     writeAt(rEnd, ry-1, string.rep(" ", sl.x + sl.w - rEnd), C.panel, C.panel)
  664.   end
  665. end
  666.  
  667. local function drawOffsetSlider()
  668.   local sl = layout.sliders.offset
  669.   local ry = sl.y
  670.   local mid = sl.x + math.floor(sl.w / 2)
  671.   local t = (outputOffset - sl.min) / (sl.max - sl.min)  -- 0..1
  672.   local hx = sl.x + math.floor(t * (sl.w - 1) + 0.5)
  673.  
  674.   -- Draw full rail as empty first
  675.   setColor(C.muted, C.panel)
  676.   gpu.fill(sl.x, ry, sl.w, 1, "─")
  677.  
  678.   -- Fill from center to handle
  679.   local fillColor = outputOffset >= 0 and C.green or C.red
  680.   if hx >= mid then
  681.     setColor(fillColor, C.panel)
  682.     gpu.fill(mid, ry, hx - mid + 1, 1, "▬")
  683.   elseif hx < mid then
  684.     setColor(fillColor, C.panel)
  685.     gpu.fill(hx, ry, mid - hx + 1, 1, "▬")
  686.   end
  687.  
  688.   -- Center mark
  689.   setColor(C.muted, C.panel)
  690.   gpu.set(mid, ry, "┼")
  691.  
  692.   -- Handle
  693.   setColor(C.bg, fillColor)
  694.   gpu.set(hx, ry, "◆")
  695.  
  696.   -- Value label
  697.   local lbl
  698.   if outputOffset == 0 then lbl = "0 RF/t"
  699.   elseif outputOffset > 0 then lbl = "+" .. formatRF(outputOffset)
  700.   else lbl = "-" .. formatRF(math.abs(outputOffset))
  701.   end
  702.   local lx = clamp(hx - math.floor(#lbl/2), sl.x, sl.x + sl.w - #lbl)
  703.   writeAt(lx, ry-1, lbl, fillColor, C.panel)
  704.   if lx > sl.x then fillAt(sl.x, ry-1, lx - sl.x, 1, C.panel, C.panel) end
  705.   local rEnd = lx + #lbl
  706.   if rEnd < sl.x + sl.w then fillAt(rEnd, ry-1, sl.x + sl.w - rEnd, 1, C.panel, C.panel) end
  707. end
  708.  
  709. local function drawSliders()
  710.   local sl = layout.sliders
  711.   drawSlider(sl.temp,  targetTemp,    C.slider_t)
  712.   drawSlider(sl.field, targetShield,  C.slider_f)
  713.   drawOffsetSlider()
  714.   sliderDirty = false
  715. end
  716.  
  717. --------------------------------------------------------------------------------
  718. -- DYNAMIC INFO
  719. --------------------------------------------------------------------------------
  720.  
  721. -- Cache to avoid redundant gpu.set calls
  722. local dynCache = {}
  723. local function putDyn(id, x, y, w, text, fg, bg)
  724.   local s = fit(tostring(text or ""), w)
  725.   local k = id .. "\0" .. tostring(fg)
  726.   if dynCache[k] == s then return end
  727.   dynCache[k] = s
  728.   writeAt(x, y, s, fg, bg)
  729. end
  730.  
  731. local function drawBarCached(id, x, y, w, t, fillClr, emptyClr, bg)
  732.   t = clamp(t, 0, 1)
  733.   local filled = math.floor(t * w + 0.5)
  734.   local key = id .. "_bar"
  735.   if dynCache[key] == filled then return end
  736.   dynCache[key] = filled
  737.   drawBar(x, y, w, t, fillClr, emptyClr, bg)
  738. end
  739.  
  740. local function drawStat(id, x, y, label, value, vcolor, w)
  741.   local lb = fit(label .. ":", 14)
  742.   putDyn(id .. "_l", x, y, 14, lb, C.muted, C.panel)
  743.   putDyn(id .. "_v", x+14, y, (w or 20)-14, value, vcolor or C.text, C.panel)
  744. end
  745.  
  746. local function statusColor(s)
  747.   s = tostring(s or "")
  748.   if s == "running"                                   then return C.green  end
  749.   if s == "warming_up" or s == "charged"              then return C.yellow end
  750.   if s == "stopping"                                  then return C.orange end
  751.   if s == "cold" or s == "offline" or s == "stopped" or s == "cooling" then return C.muted end
  752.   return C.red
  753. end
  754.  
  755. local function tempColor(t)
  756.   t = clamp(tonumber(t) or 2500, 2000, 20000)
  757.   if t < 6000  then return C.blue   end
  758.   if t < 8500  then return C.yellow end
  759.   if t < 12000 then return C.orange end
  760.   return C.red
  761. end
  762.  
  763. local function drawDynamicInfo()
  764.   local sb = layout.statsBox
  765.   local info = lastInfo
  766.  
  767.   -- Layout constants for the stats box
  768.   -- Each row: [label 11] [value 12] [bar BW] with 2 char left margin
  769.   -- Right block starts at midpoint: [label 11] [value 14]
  770.   local LX    = sb.x + 2          -- left block start
  771.   local LBLW  = 11                 -- label column width
  772.   local VALW  = 12                 -- value column width (right-aligned in here)
  773.   local MID   = sb.x + math.floor(sb.w * 0.52)  -- right block start
  774.   local RVALW = 16                 -- right value column width
  775.   local BW    = MID - LX - LBLW - VALW - 3  -- bar width, gap of 1 each side
  776.  
  777.   -- Helper: write a right-aligned value in a fixed-width field
  778.   local function rval(id, x, y, w, s, fg)
  779.     local padded = string.rep(" ", math.max(0, w - #s)) .. s
  780.     putDyn(id, x, y, w, padded, fg, C.panel)
  781.   end
  782.  
  783.   -- Helper: label + right-aligned value + optional bar, all on one row
  784.   local function statRow(id, row, label, value, vcolor, barFrac, barColor)
  785.     local lbl = fit(label, LBLW)
  786.     putDyn(id.."_l", LX,            row, LBLW, lbl,   C.muted,  C.panel)
  787.     rval(id.."_v",   LX+LBLW,       row, VALW, value, vcolor)
  788.     if barFrac and BW > 3 then
  789.       drawBarCached(id, LX+LBLW+VALW+1, row, BW, barFrac, barColor, C.bar_bg, C.panel)
  790.     elseif BW > 3 then
  791.       -- clear bar area for rows without a bar (ETA rows) — cached
  792.       putDyn(id.."_bar_clr", LX+LBLW+VALW+1, row, BW, string.rep(" ", BW), C.panel, C.panel)
  793.     end
  794.   end
  795.  
  796.   -- Helper: right-side label + value (no bar)
  797.   local function statRowR(id, row, label, value, vcolor)
  798.     local lbl = fit(label, LBLW)
  799.     putDyn(id.."_l", MID,       row, LBLW, lbl,   C.muted,  C.panel)
  800.     rval(id.."_v",   MID+LBLW,  row, RVALW, value, vcolor)
  801.   end
  802.  
  803.   if info then
  804.     local status      = tostring(info.status or "unknown")
  805.     local fieldPct    = safeDiv(info.fieldStrength + (info.fieldDrainRate or 0), info.maxFieldStrength, 0)
  806.     local satPct      = safeDiv(info.energySaturation, info.maxEnergySaturation, 0)
  807.     local fuelConvPct = safeDiv(info.fuelConversion, info.maxFuelConversion, 0)
  808.     local fuelLeftPct = clamp(1 - fuelConvPct, 0, 1)
  809.     local temp        = tonumber(info.temperature) or 0
  810.  
  811.     local isSteady = status == "running"
  812.       and math.abs(temp - targetTemp) <= ETA_STEADY_TEMP_ERR
  813.       and math.abs(fieldPct - targetShield) <= ETA_STEADY_FIELD_ERR
  814.  
  815.     local rawStop  = etaSecondsToConversion(info, FUEL_CUTOFF, temp)
  816.     local rawEmpty = etaSecondsToConversion(info, 1.0, temp)
  817.     local etaStop  = formatETA(smoothEta("stop",  rawStop,  isSteady))
  818.     local etaEmpty = formatETA(smoothEta("empty", rawEmpty, isSteady))
  819.  
  820.     local row = sb.y + 1
  821.  
  822.     -- Status (no bar — text value, variable width)
  823.     local statusVal = fit(status, VALW)
  824.     putDyn("status_l", LX,       row, LBLW, fit("Status", LBLW), C.muted, C.panel)
  825.     putDyn("status_v", LX+LBLW,  row, VALW + BW + 1, fit(status, VALW + BW + 1), statusColor(status), C.panel)
  826.  
  827.     -- Temperature: "8000.0 C" right-aligned in value column
  828.     local tempStr  = string.format("%.1fC", temp)
  829.     local tempFrac = clamp((temp - 2000) / (dangerMode and 18000 or 6000), 0, 1)
  830.     statRow("temp",  row+1, "Temp",      tempStr,  tempColor(temp),  tempFrac, tempColor(temp))
  831.  
  832.     -- Field: "15.000%" right-aligned
  833.     local fieldStr = string.format("%.3f%%", fieldPct * 100)
  834.     local fieldOk  = fieldPct >= targetShield * 0.97
  835.     statRow("field", row+2, "Field",     fieldStr, fieldOk and C.green or C.red, fieldPct, C.slider_f)
  836.  
  837.     -- Saturation: "11.4%"
  838.     local satStr   = string.format("%.1f%%", satPct * 100)
  839.     statRow("sat",   row+3, "Saturation",satStr,   C.blue,           satPct,    C.blue)
  840.  
  841.     -- Fuel left: "99.7%"
  842.     local fuelStr  = string.format("%.1f%%", fuelLeftPct * 100)
  843.     local fuelClr  = fuelLeftPct < 0.15 and C.red or C.text
  844.     statRow("fuel",  row+4, "Fuel Left", fuelStr,  fuelClr,          fuelLeftPct, fuelLeftPct < 0.15 and C.red or C.green)
  845.  
  846.     -- ETA rows (no bar)
  847.     statRow("etastop", row+5, "ETA cutoff", etaStop,  C.yellow, nil, nil)
  848.     statRow("etaemp",  row+6, "ETA empty",  etaEmpty, C.orange, nil, nil)
  849.  
  850.     -- Right column
  851.     statRowR("gen",    row,   "Generation",  formatRF(info.generationRate or 0),  C.green)
  852.     statRowR("fdrain", row+1, "Field Drain", formatRF(info.fieldDrainRate or 0),  C.orange)
  853.     statRowR("frate",  row+2, "Fuel Rate",   formatRF((tonumber(info.fuelConversionRate) or 0) * MC_TICKS_PER_S), C.purple)
  854.     statRowR("igate",  row+3, "In Gate",     formatRF(rawGetGate(input_flux)),    C.purple)
  855.     statRowR("ogate",  row+4, "Out Gate",    formatRF(rawGetGate(output_flux)),   C.purple)
  856.  
  857.     -- Calc box
  858.     local c   = lastCalc
  859.     local cb  = layout.calcBox
  860.     local cx  = cb.x + 2
  861.     local cw  = cb.w - 4
  862.     local crow = cb.y + 1
  863.     local function cc(id, lbl, val, vc)
  864.       putDyn(id, cx, crow, cw, fit(lbl .. ": " .. tostring(val), cw), vc or C.text, C.panel)
  865.       crow = crow + 1
  866.     end
  867.     cc("cm1",  "Target Sat",   string.format("%.1f%%", (c.targetCoreSat or 0)*100), C.yellow)
  868.     cc("cm2",  "Sat Error",    formatRF(c.satError or 0),                            C.text)
  869.     cc("cm3",  "Req Input",    formatRF(c.requiredInput or 0),                       C.purple)
  870.     cc("cm4",  "Out Needed",   formatRF(c.outputNeeded or 0),                        C.green)
  871.     cc("cm5",  "In Cmd",       formatRF(c.inputCommand or 0),                        C.blue)
  872.     cc("cm6",  "Drain Factor", string.format("%.3f", c.tempDrainFactor or 0),        C.text)
  873.     cc("cm7",  "ConvLVL",      string.format("%.3f", c.convLVL or 0),               C.muted)
  874.     cc("cm8",  "In Gate",      shortAddr(input_flux_addr),                           C.muted)
  875.     cc("cm9",  "Out Gate",     shortAddr(output_flux_addr),                          C.muted)
  876.   else
  877.     local cb = layout.calcBox
  878.     putDyn("noinfo", cb.x+2, cb.y+1, cb.w-4, "Waiting for reactor data…", C.yellow, C.panel)
  879.   end
  880. end
  881.  
  882. --------------------------------------------------------------------------------
  883. -- BUTTONS
  884. --------------------------------------------------------------------------------
  885.  
  886. local function drawBtn(btn, label, fg, bg)
  887.   setColor(fg, bg)
  888.   gpu.fill(btn.x, btn.y, btn.w, btn.h, " ")
  889.   local tx = btn.x + math.floor((btn.w - #label)/2)
  890.   gpu.set(tx, btn.y, label)
  891. end
  892.  
  893. local function drawButtons()
  894.   local info = lastInfo
  895.   local status = info and tostring(info.status or "unknown") or "unknown"
  896.   local canStart = status == "cold" or status == "cooling" or status == "offline" or status == "stopped" or status == "stopping"
  897.   local canStop  = status == "running" or status == "warming_up"
  898.  
  899.   if canStart then
  900.     drawBtn(layout.btnStart, " ▶ START ", C.bg, C.green)
  901.   else
  902.     drawBtn(layout.btnStart, " ▶ START ", C.muted, C.panel2)
  903.   end
  904.   if canStop then
  905.     drawBtn(layout.btnStop, " ■ STOP  ", C.bg, C.red)
  906.   else
  907.     drawBtn(layout.btnStop, " ■ STOP  ", C.muted, C.panel2)
  908.   end
  909.   drawBtn(layout.btnQuit, " QUIT ", C.bg, 0x444444)
  910.  
  911.   btnDirty = false
  912. end
  913.  
  914. --------------------------------------------------------------------------------
  915. -- STATUS LINE
  916. --------------------------------------------------------------------------------
  917.  
  918. local function drawStatusLine()
  919.   local msg = lastError or statusMsg or ""
  920.   local color = lastError and C.red or C.muted
  921.   putDyn("statusline", 2, layout.statusY, W-2, msg, color, C.bg)
  922. end
  923.  
  924. --------------------------------------------------------------------------------
  925. -- CONTROL TICK
  926. --------------------------------------------------------------------------------
  927.  
  928. local function readInfo()
  929.   local ok, s = pcall(function() return reactor.getReactorInfo() end)
  930.   if not ok or not s then lastError = "reactor.getReactorInfo() failed"; return end
  931.   lastError = nil
  932.   lastInfo = {
  933.     status              = tostring(s.status or "unknown"),
  934.     temperature         = tonumber(s.temperature)         or 0,
  935.     fieldStrength       = tonumber(s.fieldStrength)       or 0,
  936.     maxFieldStrength    = tonumber(s.maxFieldStrength)    or 0,
  937.     energySaturation    = tonumber(s.energySaturation)    or 0,
  938.     maxEnergySaturation = tonumber(s.maxEnergySaturation) or 0,
  939.     fuelConversion      = tonumber(s.fuelConversion)      or 0,
  940.     maxFuelConversion   = tonumber(s.maxFuelConversion)   or 0,
  941.     fuelConversionRate  = tonumber(s.fuelConversionRate)  or 0,
  942.     generationRate      = tonumber(s.generationRate)      or 0,
  943.     fieldDrainRate      = tonumber(s.fieldDrainRate)      or 0,
  944.   }
  945. end
  946.  
  947. local function controlTick()
  948.   readInfo()
  949.   if not lastInfo then return end
  950.  
  951.   local info   = lastInfo
  952.   local status = info.status
  953.  
  954.   lastCalc = computeControl(info, targetTemp, targetShield, reactorOutputMultiplier)
  955.  
  956.   -- Safety: emergency stop if fuel nearly gone
  957.   if info.maxFuelConversion > 0 then
  958.     local conv = safeDiv(info.fuelConversion, info.maxFuelConversion, 0)
  959.     if conv >= FUEL_CUTOFF and (status == "running" or status == "warming_up") then
  960.       pcall(function() reactor.stopReactor() end)
  961.       setGate(output_flux, 0)
  962.       setGate(input_flux, 0)
  963.       statusMsg = "Fuel cutoff reached — reactor stopped."
  964.       return
  965.     end
  966.   end
  967.  
  968.   -- Activate whenever the reactor is ready: charged state, or warm enough,
  969.   -- or still warming up (activateReactor during warming_up is what kicks it
  970.   -- over to running once the field fills — same as the original script).
  971.   if status == "charged" or status == "warming_up" then
  972.     pcall(function() reactor.activateReactor() end)
  973.   elseif info.temperature >= 2000 and status ~= "stopping" then
  974.     pcall(function() reactor.activateReactor() end)
  975.   end
  976.  
  977.   if not controlEnabled then return end
  978.  
  979.   if status == "running" then
  980.     local smoothOut = math.max(0, lastCalc.outputNeeded or 0)
  981.     lastSentOutput = smoothOut
  982.     setGate(output_flux, smoothOut)
  983.     setGate(input_flux, math.max(0, (lastCalc.inputCommand or 0) + outputOffset))
  984.   elseif status == "warming_up" then
  985.     lastSentOutput = 0
  986.     setGate(output_flux, 0)
  987.     setGate(input_flux, WARMUP_INPUT_RF_T)
  988.   elseif status == "stopping" or status == "cooling" then
  989.     lastSentOutput  = 0
  990.     emaOutput       = nil
  991.     setGate(output_flux, 0)
  992.     setGate(input_flux, math.max(0, lastCalc.requiredInput or 0))
  993.   else
  994.     lastSentOutput  = 0
  995.     emaOutput       = nil
  996.     setGate(output_flux, 0)
  997.     setGate(input_flux, 0)
  998.   end
  999.  
  1000.   dynDirty = true
  1001.   btnDirty = true
  1002. end
  1003.  
  1004. --------------------------------------------------------------------------------
  1005. -- ARM / STOP
  1006. --------------------------------------------------------------------------------
  1007.  
  1008. local function armStart()
  1009.   if not lastInfo then return end
  1010.   local s = lastInfo.status
  1011.   if s == "cold" or s == "cooling" or s == "offline" or s == "stopped" then
  1012.     pcall(function() reactor.chargeReactor() end)
  1013.     statusMsg = "Reactor charging…"
  1014.   elseif s == "stopping" then
  1015.     pcall(function() reactor.activateReactor() end)
  1016.     statusMsg = "Reactor reactivating…"
  1017.   elseif s == "charged" then
  1018.     -- Charging complete — kick it over to running
  1019.     pcall(function() reactor.activateReactor() end)
  1020.     statusMsg = "Reactor activating…"
  1021.   end
  1022.   btnDirty, dynDirty = true, true
  1023. end
  1024.  
  1025. local function stopReactor()
  1026.   pcall(function() reactor.stopReactor() end)
  1027.   setGate(output_flux, 0)
  1028.   statusMsg = "Reactor stop commanded."
  1029.   btnDirty, dynDirty = true, true
  1030. end
  1031.  
  1032. --------------------------------------------------------------------------------
  1033. -- INPUT HANDLING
  1034. --------------------------------------------------------------------------------
  1035.  
  1036. local function ptInBtn(x, y, btn)
  1037.   return x >= btn.x and x < btn.x+btn.w and y >= btn.y and y < btn.y+btn.h
  1038. end
  1039.  
  1040. local function ptInSlider(x, y, sl)
  1041.   return y >= sl.y-2 and y <= sl.y+1 and x >= sl.x and x < sl.x+sl.w
  1042. end
  1043.  
  1044. -- Relative drag state: anchor pixel and value at touch-down.
  1045. -- Each pixel of movement adds exactly one step to the anchor value.
  1046. -- The handle visually decouples from the finger position, which is the
  1047. -- only way to get fine-grained steps on a rail that's too narrow to
  1048. -- represent them spatially (e.g. 77px covering 5500C = 71C/px >> 25C/step).
  1049. local dragAnchorX   = 0
  1050. local dragAnchorVal = 0
  1051.  
  1052. local function commitSlider(which, val)
  1053.   local sl = layout.sliders
  1054.   if which == "temp" then
  1055.     local snapped = math.floor(val / sl.temp.step + 0.5) * sl.temp.step
  1056.     targetTemp    = clamp(snapped, sl.temp.min, sl.temp.max)
  1057.   elseif which == "field" then
  1058.     local snapped = math.floor(val / sl.field.step + 0.5) * sl.field.step
  1059.     targetShield  = clamp(snapped, sl.field.min, sl.field.max)
  1060.   elseif which == "offset" then
  1061.     local snapped = math.floor(val / sl.offset.step + 0.5) * sl.offset.step
  1062.     outputOffset  = clamp(snapped, sl.offset.min, sl.offset.max)
  1063.   end
  1064.   sliderDirty = true
  1065. end
  1066.  
  1067. local function handleTouch(ex, ey)
  1068.   -- Buttons
  1069.   if ptInBtn(ex, ey, layout.btnStart) then armStart(); return end
  1070.   if ptInBtn(ex, ey, layout.btnStop)  then stopReactor(); return end
  1071.   if ptInBtn(ex, ey, layout.btnQuit)  then running = false; return end
  1072.  
  1073.   -- Sliders: snap to click position, then anchor for relative drag from there
  1074.   local sl = layout.sliders
  1075.   if ptInSlider(ex, ey, sl.temp) then
  1076.     dragging      = "temp"
  1077.     -- Snap to absolute position at click, then anchor for relative drag
  1078.     local clickVal = sl.temp.min + (ex - sl.temp.x) / (sl.temp.w - 1) * (sl.temp.max - sl.temp.min)
  1079.     local snapped  = math.floor(clickVal / sl.temp.step + 0.5) * sl.temp.step
  1080.     targetTemp     = clamp(snapped, sl.temp.min, sl.temp.max)
  1081.     dragAnchorX    = ex
  1082.     dragAnchorVal  = targetTemp
  1083.     sliderDirty    = true
  1084.     return
  1085.   end
  1086.   if ptInSlider(ex, ey, sl.field) then
  1087.     dragging      = "field"
  1088.     local clickVal = sl.field.min + (ex - sl.field.x) / (sl.field.w - 1) * (sl.field.max - sl.field.min)
  1089.     local snapped  = math.floor(clickVal / sl.field.step + 0.5) * sl.field.step
  1090.     targetShield   = clamp(snapped, sl.field.min, sl.field.max)
  1091.     dragAnchorX    = ex
  1092.     dragAnchorVal  = targetShield
  1093.     sliderDirty    = true
  1094.     return
  1095.   end
  1096.   if ptInSlider(ex, ey, sl.offset) then
  1097.     dragging      = "offset"
  1098.     local clickVal = sl.offset.min + (ex - sl.offset.x) / (sl.offset.w - 1) * (sl.offset.max - sl.offset.min)
  1099.     local snapped  = math.floor(clickVal / sl.offset.step + 0.5) * sl.offset.step
  1100.     outputOffset   = clamp(snapped, sl.offset.min, sl.offset.max)
  1101.     dragAnchorX    = ex
  1102.     dragAnchorVal  = outputOffset
  1103.     sliderDirty    = true
  1104.     return
  1105.   end
  1106. end
  1107.  
  1108. local function handleDrag(ex, ey)
  1109.   if not dragging then return end
  1110.   local sl = layout.sliders
  1111.   local delta = ex - dragAnchorX
  1112.   if dragging == "temp" then
  1113.     commitSlider("temp",   dragAnchorVal + delta * sl.temp.step)
  1114.   elseif dragging == "field" then
  1115.     commitSlider("field",  dragAnchorVal + delta * sl.field.step)
  1116.   elseif dragging == "offset" then
  1117.     commitSlider("offset", dragAnchorVal + delta * sl.offset.step)
  1118.   end
  1119. end
  1120.  
  1121. local function handleKey(char)
  1122.   if not char or char <= 0 then return end
  1123.   local c = string.lower(string.char(char))
  1124.   local sl = layout.sliders
  1125.   if     c == "q" then running = false
  1126.   elseif c == "s" then armStart()
  1127.   elseif c == "x" then stopReactor()
  1128.   elseif c == "c" then
  1129.     statusMsg = "Use START/STOP buttons to control the reactor."
  1130.     btnDirty, dynDirty = true, true
  1131.   -- Keyboard temp nudges
  1132.   elseif c == "," then targetTemp    = clamp(targetTemp - sl.temp.step,    sl.temp.min,   sl.temp.max);   sliderDirty=true
  1133.   elseif c == "." then targetTemp    = clamp(targetTemp + sl.temp.step,    sl.temp.min,   sl.temp.max);   sliderDirty=true
  1134.   elseif c == "[" then targetShield  = clamp(targetShield - sl.field.step, sl.field.min,  sl.field.max);  sliderDirty=true
  1135.   elseif c == "]" then targetShield  = clamp(targetShield + sl.field.step, sl.field.min,  sl.field.max);  sliderDirty=true
  1136.   elseif c == "-" then outputOffset  = clamp(outputOffset - sl.offset.step, sl.offset.min, sl.offset.max); sliderDirty=true
  1137.   elseif c == "=" then outputOffset  = clamp(outputOffset + sl.offset.step, sl.offset.min, sl.offset.max); sliderDirty=true
  1138.   elseif c == "0" then outputOffset  = 0; sliderDirty=true
  1139.   end
  1140. end
  1141.  
  1142. local function handleEvent(ev)
  1143.   local name = ev[1]
  1144.   if     name == "touch"          then handleTouch(ev[3], ev[4])
  1145.   elseif name == "drag"           then handleDrag(ev[3], ev[4])
  1146.   elseif name == "drop"           then dragging = nil
  1147.   elseif name == "key_down"       then handleKey(ev[3])
  1148.   elseif name == "screen_resized" then
  1149.     buildLayout(); dynCache={}
  1150.     drawStaticUI(); sliderDirty=true; btnDirty=true; dynDirty=true
  1151.   elseif name == "interrupted"    then running = false
  1152.   end
  1153. end
  1154.  
  1155. --------------------------------------------------------------------------------
  1156. -- DRAW LOOP
  1157. --------------------------------------------------------------------------------
  1158.  
  1159. local function drawDynamic()
  1160.   if sliderDirty then drawSliders() end
  1161.   if btnDirty    then drawButtons() end
  1162.   if dynDirty    then drawDynamicInfo() end
  1163.   drawStatusLine()
  1164.   dynDirty    = false
  1165.   sliderDirty = false
  1166. end
  1167.  
  1168. --------------------------------------------------------------------------------
  1169. -- MAIN
  1170. --------------------------------------------------------------------------------
  1171.  
  1172. local function restoreScreen()
  1173.   for _, tid in ipairs(timers) do pcall(event.cancel, tid) end
  1174.   pcall(function() setGate(output_flux, 0) end)
  1175.   gpu.setForeground(savedFg or C.white)
  1176.   gpu.setBackground(savedBg or C.black)
  1177.   term.clear()
  1178. end
  1179.  
  1180. local function main()
  1181.   running = true
  1182.   timers  = {}
  1183.  
  1184.   bindGates()
  1185.  
  1186.   buildLayout()
  1187.   drawStaticUI()
  1188.   readInfo()
  1189.   drawDynamic()
  1190.  
  1191.   statusMsg = gateMsg
  1192.  
  1193.   timers[#timers+1] = event.timer(0.05, function() controlTick() end, math.huge)
  1194.   timers[#timers+1] = event.timer(0.25, function() dynDirty = true end, math.huge)
  1195.  
  1196.   while running do
  1197.     local ev = {event.pull(0.05)}
  1198.     if ev and ev[1] then handleEvent(ev) end
  1199.     drawDynamic()
  1200.   end
  1201. end
  1202.  
  1203. local ok, err = xpcall(main, debug.traceback)
  1204. restoreScreen()
  1205.  
  1206. if not ok then
  1207.   print("Draconic Reactor GUI crashed:")
  1208.   print(tostring(err))
  1209. else
  1210.   print("Draconic Reactor GUI closed.")
  1211. end
  1212. print("Keys: S=start  X=stop  C=toggle control  Q=quit  ,./[]=nudge targets")
Advertisement
Comments
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
  • User was banned
Add Comment
Please, Sign In to add comment