ruen-ui/RuenUI/Optimizer.lua

237 lines
12 KiB
Lua

local _, P = ...
-- Bounded, opt-in frame-time calibration. Hardware telemetry comes from the
-- companion, never from a guess based on FPS. No resolution/API/fan/voltage edits.
local f, run, pending, context, warmup, elapsed, frames, histogram, windows, good, pendingLoad
local function say(en,ru) print('|cff60d5ffRuen UI:|r '..P.Localized(en,ru or en)) end
local function db()
RuenUIDB.optimizer=RuenUIDB.optimizer or {original={},profiles={}}
return RuenUIDB.optimizer
end
local function targetFPS(value)
local n=tonumber(value)
if n and n>=20 and n<=240 and n==math.floor(n) then return n end
return 60
end
local tiers={
{0,0,1,1,1,1,1}, {1,0,2,2,2,2,1}, {2,1,3,3,3,2,2},
{2,1,5,5,4,3,2}, {3,2,7,6,5,3,3},
}
local fields={'ShadowQuality','SSAO','ViewDistance','EnvironmentDetail','GroundClutter','LiquidDetail','ComputeEffects'}
local function mode()
local inside,kind=IsInInstance()
if inside and (kind=='raid' or kind=='pvp') then return 'raid' end
if not inside then return 'world' end
return nil -- a dungeon is not evidence for open-world or raid calibration
end
local function fingerprint()
local w,h=GetPhysicalScreenSize()
return w..'x'..h..':'..(C_CVar.GetCVar('gxAdapter') or '')..':'..(C_CVar.GetCVar('gxApi') or '')
end
local function hardware()
local h=P.hardwareProfile or {}
if not h.checkedAt or time()-h.checkedAt>604800 or time()<h.checkedAt then return {} end
return h
end
local function write(key,value,raid)
local d=db();local before=C_CVar.GetCVar(key)
if before==nil then return false end
if key:find('Graphics') or key:find('^graphics') then
local reason=IsGraphicsSettingValueSupported and IsGraphicsSettingValueSupported(key,value,raid or false)
if reason and reason~=0 then return false end
end
if d.original[key]==nil then d.original[key]=before end
if before==tostring(value) then return true end
local ok=pcall(C_CVar.SetCVar,key,tostring(value))
return ok
end
local function profile(which,tier)
local prefix=which=='raid' and 'raidGraphics' or 'graphics'
for i,suffix in ipairs(fields) do write(prefix..suffix,tiers[tier][i],which=='raid') end
-- Preserve readable surfaces, full-size UI and ground telegraphs.
write(prefix..'ProjectedTextures',1,which=='raid')
write(prefix..'ParticleDensity',2,which=='raid')
write(prefix..'SpellDensity',which=='raid' and 0 or 1,which=='raid')
write(prefix..'DepthEffects',0,which=='raid')
end
local function cap(value)
write('useMaxFPS',1);write('maxFPS',value)
write('useMaxFPSBk',1);write('maxFPSBk',15)
end
local function reset(seconds)
warmup,elapsed,frames,histogram=seconds or 15,0,0,{}
end
local function percent(p)
local count=0
for tenthMS=1,20000 do
count=count+(histogram[tenthMS] or 0)
if count>=frames*p then return 10000/tenthMS end
end
return 0
end
local function finish()
local d=db(); local r=d.profiles[context]
profile(context,r.best or 1);r.tier=r.best or 1;r.calibrated=true;r.fingerprint=fingerprint();r.time=time()
r.metTarget=r.best~=nil
pending=nil;cap(d.target)
say(('Graphics %s: tier %d/5 saved; %d FPS cap. %s'):format(context,r.tier,d.target,
r.metTarget and 'Measured headroom passed.' or 'Target not sustained at the lowest tier; this profile is a compromise.'),
('Графика %s: уровень %d/5, лимит %d FPS. %s'):format(context,r.tier,d.target,
r.metTarget and 'Запас производительности подтверждён.' or 'Минимальные настройки не обеспечили целевую частоту кадров.'))
context=nil;reset(30)
f:SetScript("OnUpdate",nil) -- sleep until an environment/resolution event
end
local function commit()
if not run or InCombatLockdown() or not pending then return end
if mode()~=context then pending=nil;context=nil;cap(db().target);reset(30);return end
local r=db().profiles[context]
if pending=='finish' then finish();return end
r.tier=pending;pending=nil;profile(context,r.tier);reset(15)
end
local function result()
local d=db();local r=d.profiles[context]
windows=windows+1
local p10,low=percent(.90),percent(.99)
r.last={p10=p10,low1=low,frames=frames,seconds=elapsed,tier=r.tier}
-- Require two complete windows at the same tier and about 10% headroom.
local passed=p10>=d.target*1.08 and low>=d.target*.80
if passed then good=good+1 else good=0 end
if good>=2 then
r.best=r.tier;good=0
pending=(r.tier<d.ceiling and windows<8) and r.tier+1 or 'finish'
elseif not passed then
if r.best then pending='finish'
elseif r.tier>1 then pending=r.tier-1
elseif windows>=4 then pending='finish' end
end
if windows>=8 then pending='finish' end
reset(0);commit()
end
local function startContext(which)
local d=db();local r=d.profiles[which]
if r.calibrated and r.fingerprint==fingerprint() then return false end
if InCombatLockdown() then return false end
context=which;windows,good=0,0;r.tier=math.min(r.tier or 2,d.ceiling);r.best=nil
profile(which,r.tier);cap(math.ceil(d.target*1.2));reset(60)
say('Calibrating '..which..': play normally, keep WoW focused. Quality changes wait for combat to end; /ruen optimize pause before switching apps.',
'Калибровка '..which..': играйте в активном окне. Изменения применяются вне боя. Перед переключением окон: /ruen optimize pause.')
return true
end
local function update(_,dt)
if not run or RuenUIDB.disabled then f:SetScript("OnUpdate",nil);return end
local d=db()
local which=mode()
if not context and (not which or (d.profiles[which].calibrated and d.profiles[which].fingerprint==fingerprint())) then
f:SetScript("OnUpdate",nil);return
end
if which~=context then
if InCombatLockdown() then reset(30); return end
if context then context=nil;pending=nil;cap(d.target);reset(30) end
if which then startContext(which) end
return
end
if not context then return end
if pending then commit();return end
if dt>2 then reset(15);return end -- loading/suspended frame is not a valid sample
if warmup>0 then warmup=warmup-dt;return end
if dt<=0 then return end
-- 0.1 ms bins avoid rounding a healthy high-FPS sample below its target.
local bin=math.min(20000,math.max(1,math.ceil(dt*10000)))
histogram[bin]=(histogram[bin] or 0)+1;frames=frames+1;elapsed=elapsed+dt
if elapsed>=45 then result() end
end
function P.StopOptimizer()
if not RuenUIDB or not RuenUIDB.optimizer then return end
local d=db();run=false;d.enabled=false
if context then
local r=d.profiles[context];profile(context,r.best or 1)
end
context,pending=nil,nil
if f then f:SetScript('OnUpdate',nil) end
cap(d.target or 60)
end
function P.OptimizerCommand(arg)
local d=db()
if arg=='status' then
local h=hardware()
say(('Optimizer: %s. Requested: %d FPS; effective: %d FPS. Thermal evidence: %s. World: %s; raid: %s.'):format(run and 'ON' or 'OFF',targetFPS(d.requestedFPS),d.target or targetFPS(d.requestedFPS),
h.evidence or 'not measured',d.profiles.world and d.profiles.world.calibrated and 'measured' or 'provisional',
d.profiles.raid and d.profiles.raid.calibrated and 'measured' or 'provisional'),
('Калибровка: %s. Запрошено: %d FPS; текущая цель: %d FPS. Температуры: %s. Мир: %s; рейд: %s.'):format(run and 'ВКЛ' or 'ВЫКЛ',targetFPS(d.requestedFPS),d.target or targetFPS(d.requestedFPS),
h.evidence or 'не измерены',d.profiles.world and d.profiles.world.calibrated and 'проверен' or 'не проверен',
d.profiles.raid and d.profiles.raid.calibrated and 'проверен' or 'не проверен'))
return
end
if InCombatLockdown() then say('Change optimization outside combat.','Меняйте оптимизацию вне боя.');return end
if arg=='off' or arg=='pause' then P.StopOptimizer();say('Calibration paused; current settled quality retained.','Калибровка приостановлена.');return end
if arg=='restore' then
P.StopOptimizer()
for k,v in pairs(d.original) do pcall(C_CVar.SetCVar,k,v) end
RuenUIDB.optimizer=nil;say('Pre-optimization graphics restored.','Исходные настройки графики восстановлены.');return
end
if arg~='' and arg~='start' and arg~='resume' and arg~='world' and arg~='raid' then
say('/ruen optimize [world|raid|pause|resume|status|restore]');return
end
if (arg=='world' or arg=='raid') and mode()~=arg then
say('Run this in the requested environment. A solo test cannot validate raid performance.','Запустите в соответствующей зоне. Соло-тест не проверяет производительность в рейде.');return
end
if arg~='resume' then
if context then P.StopOptimizer() end
if arg=='world' or arg=='raid' then d.profiles[arg]={tier=2}
else d.profiles={world={tier=2},raid={tier=1}} end
end
d.profiles.world=d.profiles.world or {tier=2};d.profiles.raid=d.profiles.raid or {tier=1}
local h=hardware()
d.requestedFPS=targetFPS(d.requestedFPS)
local nextTarget=h.thermalPressure and math.min(d.requestedFPS,45) or d.requestedFPS
local nextCeiling=(h.thermalPressure or h.performancePressure) and 2 or (h.loaded and h.thermalCoverage=="full") and 5 or 3
if d.target~=nextTarget or d.ceiling~=nextCeiling then
for _,r in pairs(d.profiles) do
r.calibrated=false;r.best=nil;r.tier=math.min(r.tier or 1,nextCeiling)
end
end
d.target=nextTarget;d.ceiling=nextCeiling
write('RAIDsettingsEnabled',1);write('RenderScale',1);write('MSAAQuality','0,0');write('msaaAlphaTest',0)
write('ffxAntiAliasingMode',1);write('vsync',0);write('useTargetFPS',0)
profile('world',d.profiles.world.tier);profile('raid',d.profiles.raid.tier);cap(d.target)
run=true;d.enabled=true;context=nil;reset(30)
f:SetScript('OnUpdate',update)
say('Adaptive calibration enabled. World and raid learn separately. Thermal monitoring must be run from the bundled Optimize tool; /reload imports its report.',
'Калибровка включена. Мир и рейд проверяются отдельно. Температуры проверяет утилита Optimize из комплекта; /reload загружает отчёт.')
say(('Requested target: %d FPS; effective target: %d FPS.'):format(d.requestedFPS,d.target),
('Запрошенная цель: %d FPS; текущая цель: %d FPS.'):format(d.requestedFPS,d.target))
end
function P.InitializeOptimizer()
if f then return end
f=CreateFrame('Frame')
f:RegisterEvent('PLAYER_ENTERING_WORLD');f:RegisterEvent('PLAYER_REGEN_ENABLED');f:RegisterEvent('DISPLAY_SIZE_CHANGED');f:RegisterEvent('ZONE_CHANGED_NEW_AREA')
f:SetScript('OnEvent',function(_,event)
if event=='PLAYER_REGEN_ENABLED' then
if pendingLoad then local load=pendingLoad;pendingLoad=nil;load() end
commit()
elseif run then
if InCombatLockdown() then reset(60);return end
-- Never compare frames from different resolutions or loading screens.
context,pending=nil,nil;cap(db().target);reset(60)
if event=='DISPLAY_SIZE_CHANGED' then
for _,p in pairs(db().profiles) do p.calibrated=false;p.best=nil end
say('Resolution changed: calibration will measure this resolution.','Разрешение изменено: калибровка будет повторена.') end
end
if run then f:SetScript('OnUpdate',update) end
end)
local function initializeSaved()
local h=hardware()
local importKey=h.checkedAt and (tostring(h.checkedAt)..':'..targetFPS(h.targetFPS))
if h.autoStart and RuenUIDB.hardwareImport~=importKey then
db().requestedFPS=targetFPS(h.targetFPS)
P.OptimizerCommand('start');RuenUIDB.hardwareImport=importKey
return
end
local d=RuenUIDB.optimizer
if d then
cap(d.target or 60) -- recover a benchmark cap after logout/crash
if d.enabled then P.OptimizerCommand('resume') end
end
end
if InCombatLockdown() then pendingLoad=initializeSaved else initializeSaved() end
end