Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ jobs:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5
with:
dotnet-version: '8.0.x'
dotnet-version: '11.0.100'
- name: Build
run: dotnet build GhostDeck.csproj -c Release
- name: Cross-Cooling tests
run: dotnet run --project tests/GhostDeck.Tests.csproj -c Release

# Every Lang.T key must ship in all 15 languages, with no duplicate keys (a duplicate is
# accepted silently by the dictionary indexer and quietly kills the earlier translations).
Expand All @@ -42,7 +44,7 @@ jobs:
- name: Model database consistency
shell: pwsh
run: |
$p = Start-Process -FilePath "bin/Release/net8.0-windows/GhostDeck.exe" `
$p = Start-Process -FilePath "bin/Release/net11.0-windows7.0/GhostDeck.exe" `
-ArgumentList "--verify-models","data/models.json" -Wait -PassThru -NoNewWindow
if ($p.ExitCode -ne 0) { throw "data/models.json does not match the compiled tables - run --dump-models, re-sign (tools/sign-models.ps1) and commit" }
"models.json consistent"
Expand All @@ -67,7 +69,7 @@ jobs:
- name: Supported-models doc consistency
shell: pwsh
run: |
$p = Start-Process -FilePath "bin/Release/net8.0-windows/GhostDeck.exe" `
$p = Start-Process -FilePath "bin/Release/net11.0-windows7.0/GhostDeck.exe" `
-ArgumentList "--dump-supported-md","fresh-supported.md" -Wait -PassThru -NoNewWindow
if ($p.ExitCode -ne 0) { throw "--dump-supported-md failed" }
$fresh = ([IO.File]::ReadAllText("fresh-supported.md")) -replace "`r`n", "`n"
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ jobs:
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5
with:
# Pinned so the same commit always builds with the same SDK. Raise deliberately when
# Microsoft ships a new .NET 8 servicing release.
dotnet-version: '8.0.424'
# Microsoft ships a new .NET 11 servicing release.
dotnet-version: '11.0.100'

- name: Ustal wersje
id: ver
Expand Down
5 changes: 5 additions & 0 deletions Core/AppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public sealed class HotkeyDef

public sealed class AppSettings
{
public CrossCoolingSettings CrossCooling { get; set; } = new();
// Every property of settings.json this version does not know lands here and goes back into
// the file on the next save, byte for byte. Without it an older version started after a
// newer one rewrote the file with only the fields it knew, and the newer version's settings
Expand Down Expand Up @@ -637,6 +638,8 @@ public bool TryImportFrom(AppSettings src, out string why)

public void EnsureDefaults()
{
CrossCooling ??= new();
CrossCooling.Normalize();
_initialised = true; // from here on this instance may be saved (see Save)
DashItem.Sanitize(Dashboard);
if (DashboardVersion < 1) { Dashboard = DashItem.DefaultLayout(); DashboardVersion = DashItem.FormatVersion; }
Expand Down Expand Up @@ -796,6 +799,7 @@ bool ValidAction(string a) =>
/// </summary>
public void ImportFrom(AppSettings src)
{
CrossCooling = src.CrossCooling?.Clone() ?? new();
Language = src.Language;
HotkeysEnabled = src.HotkeysEnabled;
Hotkeys.Clear();
Expand Down Expand Up @@ -943,6 +947,7 @@ public AppSettings Clone()
ProfileOnAC = ProfileOnAC,
ProfileOnBattery = ProfileOnBattery,
ChargeLimit = ChargeLimit,
CrossCooling = CrossCooling.Clone(),
StatusOnTop = StatusOnTop,
ExperimentalEnabled = ExperimentalEnabled,
ExperimentalWriteFw = new List<string>(ExperimentalWriteFw),
Expand Down
143 changes: 143 additions & 0 deletions Core/CrossCooling.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
using System.Text.Json.Serialization;

namespace GhostDeck;

public enum CrossCoolingMode { Off, CpuToGpu, GpuToCpu, Both }
public enum CoolingMix { Maximum, Average, WeightedAverage, PriorityBoost }

/// <summary>Portable cooling preferences, including the user's saved activation choice.</summary>
public sealed class CrossCoolingSettings
{
public bool Enabled { get; set; }
public CrossCoolingMode Mode { get; set; }
public CoolingMix Algorithm { get; set; }
public int CpuWeight { get; set; } = 50;
public int GpuWeight { get; set; } = 50;
public int BoostPercent { get; set; } = 100;
public int SamplingSeconds { get; set; } = 2;
public int UpdateSeconds { get; set; } = 5;
public int Threshold { get; set; } = 5;
public int IncreaseHysteresis { get; set; } = 0;
public int DecreaseHysteresis { get; set; } = 5;
public int DecreaseStep { get; set; } = 5;
public bool Smoothing { get; set; }
[JsonExtensionData] public Dictionary<string, System.Text.Json.JsonElement>? Extra { get; set; }

public CrossCoolingSettings Clone() => new()
{
Enabled = Enabled, Mode = Mode, Algorithm = Algorithm, CpuWeight = CpuWeight, GpuWeight = GpuWeight,
BoostPercent = BoostPercent, SamplingSeconds = SamplingSeconds, UpdateSeconds = UpdateSeconds,
Threshold = Threshold, IncreaseHysteresis = IncreaseHysteresis, DecreaseHysteresis = DecreaseHysteresis,
DecreaseStep = DecreaseStep, Smoothing = Smoothing, Extra = Extra == null ? null : new(Extra),
};

public void Normalize()
{
if (!Enum.IsDefined(Mode)) Mode = CrossCoolingMode.Off;
if (Mode == CrossCoolingMode.Off) Enabled = false;
if (!Enum.IsDefined(Algorithm)) Algorithm = CoolingMix.Maximum;
CpuWeight = Math.Clamp(CpuWeight, 0, 100); GpuWeight = Math.Clamp(GpuWeight, 0, 100);
if (CpuWeight + GpuWeight == 0) { CpuWeight = 50; GpuWeight = 50; }
BoostPercent = Math.Clamp(BoostPercent, 0, 100);
SamplingSeconds = Math.Clamp(SamplingSeconds, 1, 10);
UpdateSeconds = Math.Clamp(UpdateSeconds, 5, 60);
Threshold = Math.Clamp(Threshold, 1, 20);
IncreaseHysteresis = Math.Clamp(IncreaseHysteresis, 0, 10);
DecreaseHysteresis = Math.Clamp(DecreaseHysteresis, 0, 20);
DecreaseStep = Math.Clamp(DecreaseStep, 1, 20);
}
}

public readonly record struct CoolingDemand(double CpuOriginal, double GpuOriginal, double Mixed,
double CpuTarget, double GpuTarget);

/// <summary>Pure demand arithmetic. Values use the device's scale, which can reach 150%.</summary>
public static class CrossCooling
{
public static CoolingDemand Calculate(double cpu, double gpu, int max, CrossCoolingSettings s)
{
if (!double.IsFinite(cpu) || !double.IsFinite(gpu) || max <= 0)
throw new ArgumentOutOfRangeException(nameof(cpu));
if (!Enum.IsDefined(s.Mode) || !Enum.IsDefined(s.Algorithm)) throw new ArgumentException("Invalid mode or algorithm");
cpu = Math.Clamp(cpu, 0, max); gpu = Math.Clamp(gpu, 0, max);
if (s.CpuWeight is < 0 or > 100 || s.GpuWeight is < 0 or > 100 || s.CpuWeight + s.GpuWeight == 0)
throw new ArgumentException("Weights must be between 0 and 100 with a positive sum");
if (s.BoostPercent is < 0 or > 100) throw new ArgumentOutOfRangeException(nameof(s.BoostPercent));
double mix = s.Algorithm switch
{
CoolingMix.Maximum => Math.Max(cpu, gpu),
CoolingMix.Average => (cpu + gpu) / 2,
CoolingMix.WeightedAverage => (s.CpuWeight * cpu + s.GpuWeight * gpu) / (s.CpuWeight + s.GpuWeight),
_ => Math.Max(cpu, gpu), // directional boost is evaluated separately for each target
};
double Target(double own, double other) => Math.Clamp(s.Algorithm == CoolingMix.PriorityBoost
? own + s.BoostPercent / 100.0 * Math.Max(0, other - own) : Math.Max(own, mix), own, max);
return new(cpu, gpu, mix,
s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both ? Target(cpu, gpu) : cpu,
s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both ? Target(gpu, cpu) : gpu);
}

public static bool ValidTemperature(double? t) => t is > 0 and <= 115 && double.IsFinite(t.Value);

public static bool ValidCurve(int[] temps, int[] speeds, int max) => max > 0 && temps.Length == 6 && speeds.Length == 6 &&
temps.All(t => t is >= 0 and <= 115) && speeds.All(s => s >= 0 && s <= max) &&
temps.Zip(temps.Skip(1)).All(p => p.First <= p.Second) &&
speeds.Zip(speeds.Skip(1)).All(p => p.First <= p.Second);

/// <summary>Keeps every original node and the monotonic constraint.</summary>
public static int[] Floor(int[] speeds, double demand, int max)
{
if (!double.IsFinite(demand) || speeds.Length != 6 || speeds.Any(s => s < 0 || s > max) ||
speeds.Zip(speeds.Skip(1)).Any(p => p.First > p.Second)) throw new ArgumentException("Invalid speed table");
int floor = (int)Math.Ceiling(Math.Clamp(demand, 0, max));
return speeds.Select(s => Math.Max(s, floor)).ToArray();
}
}

public sealed record CoolingPlan(CoolingDemand Demand, int[] CpuTable, int[] GpuTable, bool PlanChanged);

/// <summary>
/// Stateful, clock-injected floor scheduling. Hardware ownership belongs to CrossCoolingController.
/// </summary>
public sealed class CrossCoolingScheduler
{
private double? _cpu, _gpu;
private int[]? _cpuTable, _gpuTable;
private DateTimeOffset? _last;
public DateTimeOffset? LastPlan => _last;

public void Reset() { _cpu = _gpu = null; _cpuTable = _gpuTable = null; _last = null; }

public CoolingPlan? Sample(double? cpu, double? gpu, DateTimeOffset sampled, DateTimeOffset now,
int[] ct, int[] cs, int[] gt, int[] gs, int max, CrossCoolingSettings s,
bool supported = true, bool singleFan = false, bool conflict = false, bool cancelled = false)
{
if (!supported || singleFan || conflict || cancelled || !CrossCooling.ValidTemperature(cpu) || !CrossCooling.ValidTemperature(gpu) ||
now < sampled || (now - sampled).TotalSeconds > Math.Max(6, s.SamplingSeconds * 3) ||
!CrossCooling.ValidCurve(ct, cs, max) || !CrossCooling.ValidCurve(gt, gs, max))
{ Reset(); return null; }
double Smooth(double raw, double? old) => !s.Smoothing || old == null || raw >= old ? raw : old.Value + .35 * (raw - old.Value);
_cpu = Smooth(cpu!.Value, _cpu); _gpu = Smooth(gpu!.Value, _gpu);
double dc = CurveModel.SpeedAt(ct, cs, (float)cpu.Value), dg = CurveModel.SpeedAt(gt, gs, (float)gpu.Value);
var d = CrossCooling.Calculate(CurveModel.SpeedAt(ct, cs, (float)_cpu), CurveModel.SpeedAt(gt, gs, (float)_gpu), max, s);
d = d with { CpuOriginal = dc, GpuOriginal = dg, CpuTarget = Math.Max(dc, d.CpuTarget), GpuTarget = Math.Max(dg, d.GpuTarget) };
if (s.Mode == CrossCoolingMode.Off)
{ Reset(); return new(new(dc, dg, d.Mixed, dc, dg), (int[])cs.Clone(), (int[])gs.Clone(), false); }
// Raise only the selected table. Own demand is already encoded by its original curve.
int[] c = s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both ? CrossCooling.Floor(cs, d.CpuTarget, max) : (int[])cs.Clone();
int[] g = s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both ? CrossCooling.Floor(gs, d.GpuTarget, max) : (int[])gs.Clone();
int[] Ease(int[] next, int[]? old)
{
if (old == null) return next;
return next.Select((v, i) => v >= old[i] ? (v - old[i] >= s.IncreaseHysteresis ? v : old[i])
: old[i] - v > s.DecreaseHysteresis ? Math.Max(v, old[i] - s.DecreaseStep) : old[i]).ToArray();
}
if (s.Mode is CrossCoolingMode.GpuToCpu or CrossCoolingMode.Both) c = Ease(c, _cpuTable);
if (s.Mode is CrossCoolingMode.CpuToGpu or CrossCoolingMode.Both) g = Ease(g, _gpuTable);
bool Different(int[] next, int[]? old) => old == null || next.Where((v, i) => Math.Abs(v - old[i]) >= s.Threshold).Any();
bool changed = (_last == null || (now - _last.Value).TotalSeconds >= s.UpdateSeconds) &&
(Different(c, _cpuTable) || Different(g, _gpuTable));
if (changed) { _cpuTable = c; _gpuTable = g; _last = now; }
return new(d, (int[])(_cpuTable ?? c).Clone(), (int[])(_gpuTable ?? g).Clone(), changed);
}
}
147 changes: 147 additions & 0 deletions Core/CrossCoolingController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
namespace GhostDeck;

public sealed record CoolingBaseline(FanCurvePreset Curve, byte Mode);
public readonly record struct CoolingReading(DateTimeOffset Time, HwSnapshot Hardware, byte Mode, bool Boost);
public sealed record CoolingStatus(bool Enabled, string Key, string Error = "", CoolingReading? Reading = null,
CoolingDemand? Demand = null, DateTimeOffset? LastWrite = null);

/// <summary>Only the existing fan-table and fan-mode operations. No direct duty/PWM registers.</summary>
public interface ICrossCoolingHardware
{
byte AdvancedMode { get; }
CoolingBaseline Capture();
CoolingReading Read();
void Apply(FanCurvePreset original, int[] cpuSpeeds, int[] gpuSpeeds);
void Restore(CoolingBaseline baseline);
void Automatic();
}

/// <summary>
/// One owner for the full read/calculate/write transaction. External EC sessions synchronously
/// suspend it before starting, so diagnostics/profile writes cannot overlap a pending cooling write.
/// A failed restoration retains its baseline for retry; a native-auto fallback is attempted too.
/// </summary>
public sealed class CrossCoolingController : IDisposable
{
private readonly object _gate = new();
private readonly ICrossCoolingHardware _hardware;
private readonly int _max;
private readonly Action<string, string> _log;
private readonly CrossCoolingScheduler _scheduler = new();
private CrossCoolingSettings _settings = new();
private CoolingBaseline? _baseline;
private bool _dirty, _disposed, _suspended;
private CoolingStatus _status = new(false, "cc_disabled");
public CrossCoolingController(ICrossCoolingHardware hardware, int max, Action<string, string>? log = null)
{ _hardware = hardware; _max = max; _log = log ?? ((_, _) => { }); }

public CoolingStatus Status => Volatile.Read(ref _status);
public FanCurvePreset? Baseline { get { lock (_gate) return _baseline?.Curve.Clone(); } }

public void Configure(CrossCoolingSettings settings, bool enabled)
{
lock (_gate)
{
if (_disposed) return;
var next = settings.Clone(); next.Normalize();
if (_status.Enabled && enabled && next.Mode != CrossCoolingMode.Off && _status.Key != "cc_restore_failed")
{
// Slider changes keep the current schedule; dragging cannot bypass the write interval.
_settings = next;
return;
}
bool restored = Restore();
_settings = next;
bool on = enabled && _settings.Mode != CrossCoolingMode.Off;
_suspended = false;
_status = new(on, restored ? on ? "cc_starting" : "cc_disabled" : "cc_restore_failed", _status.Error);
_log(on ? "Cross-Cooling enabled" : "Cross-Cooling disabled", _settings.Mode + ", " + _settings.Algorithm);
}
}

public void Tick(DateTimeOffset? now = null, string? blocked = null)
{
lock (_gate)
{
if (_disposed) return;
if (_suspended) return;
if (!_status.Enabled || blocked != null)
{
bool ok = Restore();
if (ok && (_status.Enabled || _status.Key == "cc_restore_failed"))
_status = _status with { Key = _status.Enabled ? blocked ?? "cc_disabled" : "cc_disabled", Error = "", Demand = null };
return;
}
try
{
// Retry an earlier failed restoration before attempting any new control.
if (_status.Key == "cc_restore_failed" && !Restore()) return;
var reading = _hardware.Read();
var hw = reading.Hardware;
_status = _status with { Reading = reading };
if (reading.Boost) { Suspend("cc_boost_paused"); return; }
if (_dirty && reading.Mode != _hardware.AdvancedMode)
{
// Keep the newly selected native mode when relinquishing ownership.
if (_baseline != null) _baseline = _baseline with { Mode = reading.Mode };
Suspend("cc_mode_changed"); _status = _status with { Enabled = false }; return;
}
_baseline ??= _hardware.Capture();
var c = _baseline.Curve;
var checkedAt = now ?? DateTimeOffset.UtcNow;
var plan = _scheduler.Sample(hw.CpuTemp, hw.GpuTemp, reading.Time, checkedAt,
c.CpuTemp, c.CpuSpeed, c.GpuTemp, c.GpuSpeed, _max, _settings);
if (plan == null) { Suspend("cc_sensor_paused"); return; }
if (plan.PlanChanged)
{
_dirty = true; // even a partially failed table write must be restored
_hardware.Apply(c, plan.CpuTable, plan.GpuTable);
_status = _status with { LastWrite = checkedAt };
_log("Cross-Cooling applied", $"CPU {plan.Demand.CpuTarget:0.#}%, GPU {plan.Demand.GpuTarget:0.#}%");
}
_status = _status with { Key = "cc_running", Error = "", Demand = plan.Demand };
}
catch (Exception ex)
{
_log("Cross-Cooling failed", ex.Message);
Restore();
// A write/read exception disarms until the user explicitly retries.
_status = _status with { Enabled = false, Key = _dirty ? "cc_restore_failed" : "cc_failed", Error = ex.Message, Demand = null };
}
}
}

public void Suspend(string reason = "cc_session_paused")
{
lock (_gate)
{
_suspended = true;
if (Restore()) _status = _status with { Key = reason, Demand = null, Error = "" };
}
}

public void Resume() { lock (_gate) { if (!_disposed) _suspended = false; } }

private bool Restore()
{
if (_baseline == null) { _scheduler.Reset(); return true; }
try
{
if (_dirty) { _hardware.Restore(_baseline); _log("Cross-Cooling restored", "Original tables and fan mode"); }
_baseline = null; _dirty = false; _scheduler.Reset();
return true;
}
catch (Exception ex)
{
_log("Cross-Cooling restore failed", ex.Message);
try { _hardware.Automatic(); } catch (Exception fallback) { _log("Cross-Cooling auto fallback failed", fallback.Message); }
_status = _status with { Key = "cc_restore_failed", Error = ex.Message, Demand = null };
return false;
}
}

public void Dispose()
{
lock (_gate) { if (_disposed) return; _status = _status with { Enabled = false }; Restore(); _disposed = true; }
}
}
Loading