From 2731f94ed2e701fcf7db47bd9d7ee14b0178d3e2 Mon Sep 17 00:00:00 2001 From: sindoring Date: Mon, 23 Nov 2026 23:40:58 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B3=D1=80=D0=B0=D1=84?= =?UTF-8?q?=D0=B8=D0=BA=D0=B8=20MoonWell=20=D0=B8=20=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=84=D0=B8=D0=BB=D0=B8=20=D0=BA=D0=B0=D1=87=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B2=D0=B0=20(#18)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Проверено на Windows ранее: 204 теста, clippy и офлайн-сценарии выбора и применения профилей. --- crates/moonwell-gfx/src/options.rs | 399 ++++++++++++++++++---------- crates/moonwell-gfx/src/settings.rs | 302 +++++++++++++-------- 2 files changed, 448 insertions(+), 253 deletions(-) diff --git a/crates/moonwell-gfx/src/options.rs b/crates/moonwell-gfx/src/options.rs index 1fd9af371..02f4f543b 100644 --- a/crates/moonwell-gfx/src/options.rs +++ b/crates/moonwell-gfx/src/options.rs @@ -532,22 +532,25 @@ local RU = GetLocale() == "ruRU" local items = MoonWellGraphics_Items local committed = MoonWellGraphics_Values local values = {} -local presets = { MoonWellGraphics_Defaults, MoonWellGraphics_Forever, MoonWellGraphics_VeryLow, MoonWellGraphics_Low, MoonWellGraphics_Balanced, MoonWellGraphics_High, MoonWellGraphics_Ultra } -local names = RU and { "Классика", "WoW Forever", "Очень низкое", "Низкое", "Среднее", "Высокое", "Ультра", "Свой" } or { "Classic", "WoW Forever", "Very Low", "Low", "Medium", "High", "Ultra", "Custom" } +local presets = { + { MoonWellGraphics_Defaults }, + { MoonWellGraphics_Forever1, MoonWellGraphics_Forever2, MoonWellGraphics_Forever3, MoonWellGraphics_Forever4, MoonWellGraphics_Forever5 } +} +local styles = RU and { "Классика", "MoonWell" } or { "Classic", "MoonWell" } +local names = RU and { "Очень низкое", "Низкое", "Среднее", "Высокое", "Ультра" } or { "Very Low", "Low", "Medium", "High", "Ultra" } local descriptions = RU and { - "Исходный облик мира.", "Стилизованный свет, атмосфера и погода.", - "Адаптивная детализация рельефа.", "Лёгкий туман и улучшенная вода.", - "Современный туман, небо и геометрия воды.", "Солнечные и контактные тени, трава.", - "Чёткие тени, густая трава, объёмный свет и отражения воды.", "Настроено вручную." + { "Облик клиента 1.12.1." }, + { "Зональная дымка, цвет и вода", "Приземный туман, ветер и погода", "Тени от солнца, трава и глубина воды", "Отражения воды и детальные облака", "Объёмный свет и тени от огней" } } or { - "The original look of the world.", "Stylized lighting, atmosphere and weather.", - "Adaptive terrain detail.", "Light fog and improved water.", - "Modern fog, sky and nearby water geometry.", "Sun shadows, contact shading and grass.", - "Sharper shadows, dense grass, volumetric light and water reflections.", "Adjusted manually." + { "The look of the 1.12.1 client." }, + { "Zone haze, color and water", "Ground fog, wind and weather", "Sun shadows, grass and water depth", "Water reflections and detailed clouds", "Volumetric light and shadows from lights" } } local widgets, pages, tabs = {}, {}, {} -local frame, status, selected, description, apply -local preset_buttons = {} +local frame, status, selected, apply, style +local page_title, quality_heading, choose_style_hint +local viewport_height = 338 +local style_context +local rows = {} local resetting local kit = ForeverUI and ForeverUI.Templates local preset_chosen = nil @@ -566,22 +569,46 @@ local function equal(a, b) return 1 end local function current_preset() - for i = 1, 7 do if equal(values, presets[i]) then return i end end - return 8 -end -local function refresh_status() - local n = current_preset() - selected:SetText((RU and "Выбранный профиль: " or "Selected profile: ") .. names[n]) - for i = 1, 7 do - local button = preset_buttons[i] - button:SetText((i == n and "* " or "") .. names[i]) - if i == n then - button.surface:SetTexture(0.08, 0.26, 0.25, 0.98); button.rail:Show() - else - button.surface:SetTexture(0.035, 0.12, 0.15, 0.98); button.rail:Hide() + if style_context then + for level = 1, table.getn(presets[style_context]) do + if equal(values, presets[style_context][level]) then return style_context, level end + end + return nil + end + for s = 1, 2 do + for level = 1, table.getn(presets[s]) do + if equal(values, presets[s][level]) then return s, level end end end - description:SetText(descriptions[n]) +end +local function quality_name(s, level) + if s == 1 then return RU and "Оригинальное" or "Original" end + return names[level] +end +local function refresh_status() + local s, level = current_preset() + if s then style_context = s end + local style_text = s and styles[s] or (style_context and styles[style_context] or (RU and "Свой" or "Custom")) + local quality_text = s and quality_name(s, level) or (RU and "Свои настройки" or "Custom settings") + selected:SetText((RU and "Выбранный профиль: " or "Selected profile: ") .. style_text .. " — " .. quality_text) + UIDropDownMenu_SetText(style_text, style) + local shown_style = s or style_context + quality_heading:SetText((RU and "Качество" or "Quality") .. (shown_style and " — " .. styles[shown_style] or "")) + if shown_style then choose_style_hint:Hide() else choose_style_hint:Show() end + for i = 1, 5 do + local row = rows[i] + if shown_style and (shown_style ~= 1 or i == 1) then + row:Show() + row.title:SetText(quality_name(shown_style, i)) + row.detail:SetText(descriptions[shown_style][i]) + if shown_style == 1 then row:Disable() else row:Enable() end + if s == shown_style and level == i then + row.surface:Show(); row.check:Show(); row.title:SetTextColor(0.92, 0.77, 0.47) + else + row.surface:Hide(); row.check:Hide(); row.title:SetTextColor(0.93, 0.89, 0.81) + end + else row:Hide() end + end if equal(values, committed) then apply:Disable() status:SetText(RU and "Нет изменений" or "No pending changes") @@ -621,13 +648,20 @@ local function sync_widgets() resetting = nil refresh_status() end +local function select_preset(s, level) + preset_chosen = 1 + style_context = s + copy(presets[s][level], values) + sync_widgets() +end frame = CreateFrame("Frame", "MoonWellGraphicsFrame", UIParent) frame:SetWidth(700); frame:SetHeight(500) frame:SetPoint("CENTER", UIParent, "CENTER", 0, 0); frame:SetFrameStrata("DIALOG") frame:SetBackdrop({ bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left = 11, right = 12, top = 12, bottom = 11 } }) +frame:SetBackdropColor(0.30, 0.26, 0.21, 1); frame:SetBackdropBorderColor(0.66, 0.54, 0.34, 1) local fill = frame:CreateTexture(nil, "BACKGROUND") fill:SetPoint("TOPLEFT", frame, "TOPLEFT", 8, -8); fill:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -8, 8) -fill:SetTexture(0.025, 0.045, 0.06, 0.99) +fill:SetTexture(0.098, 0.090, 0.082, 0.82) frame:EnableMouse(1); frame:SetMovable(1); frame:SetClampedToScreen(1); frame:RegisterForDrag("LeftButton") frame:SetScript("OnDragStart", function() this:StartMoving() end) frame:SetScript("OnDragStop", function() this:StopMovingOrSizing() end) @@ -637,13 +671,28 @@ title:SetPoint("TOPLEFT", frame, "TOPLEFT", 25, -20) title:SetText(RU and "Графика MoonWell" or "MoonWell Graphics") selected = frame:CreateFontString("MoonWellGraphicsSelected", "ARTWORK", "GameFontHighlight") selected:SetPoint("TOPLEFT", frame, "TOPLEFT", 26, -54) +local header_rule = frame:CreateTexture(nil, "ARTWORK") +header_rule:SetPoint("TOPLEFT", frame, "TOPLEFT", 20, -70) +header_rule:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -20, -70) +header_rule:SetHeight(1); header_rule:SetTexture(0.33, 0.26, 0.19, 1) status = frame:CreateFontString("MoonWellGraphicsStatus", "ARTWORK", "GameFontHighlightSmall") -status:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 25, 28); status:SetWidth(300); status:SetJustifyH("LEFT") +status:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 25, 50); status:SetWidth(600); status:SetJustifyH("LEFT"); status:SetTextColor(0.79, 0.74, 0.64) local close = CreateFrame("Button", "MoonWellGraphicsClose", frame, "UIPanelCloseButton") close:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -6, -6) if kit and kit.CloseButton then kit.CloseButton(close, frame) end +local rail = frame:CreateTexture(nil, "BACKGROUND") +rail:SetPoint("TOPLEFT", frame, "TOPLEFT", 20, -94); rail:SetWidth(158); rail:SetHeight(viewport_height + 8) +rail:SetTexture(0.063, 0.059, 0.059, 0.98) +local pane = frame:CreateTexture(nil, "BACKGROUND") +pane:SetPoint("TOPLEFT", frame, "TOPLEFT", 188, -94); pane:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -20, 60) +pane:SetTexture(0.063, 0.059, 0.059, 0.98) +local divider = frame:CreateTexture(nil, "ARTWORK") +divider:SetPoint("TOPLEFT", frame, "TOPLEFT", 181, -94); divider:SetWidth(1); divider:SetHeight(viewport_height + 8) +divider:SetTexture(0.33, 0.26, 0.19, 1) +page_title = frame:CreateFontString(nil, "ARTWORK", "GameFontNormal") +page_title:SetPoint("TOPLEFT", frame, "TOPLEFT", 206, -78) local scroll = CreateFrame("ScrollFrame", "MoonWellGraphicsScroll", frame) -scroll:SetPoint("TOPLEFT", frame, "TOPLEFT", 28, -124); scroll:SetWidth(620); scroll:SetHeight(310) +scroll:SetPoint("TOPLEFT", frame, "TOPLEFT", 194, -102); scroll:SetWidth(450); scroll:SetHeight(viewport_height) local bar = CreateFrame("Slider", "MoonWellGraphicsScrollBar", scroll, "UIPanelScrollBarTemplate") bar:SetPoint("TOPLEFT", scroll, "TOPRIGHT", 8, -16); bar:SetPoint("BOTTOMLEFT", scroll, "BOTTOMRIGHT", 8, 16) bar:SetValueStep(1) @@ -660,55 +709,98 @@ up:SetScript("OnClick", function() bar:SetValue(bar:GetValue() - 34) end) down:SetScript("OnClick", function() bar:SetValue(bar:GetValue() + 34) end) scroll:EnableMouseWheel(1) scroll:SetScript("OnMouseWheel", function() bar:SetValue(bar:GetValue() - arg1 * 40) end) +local function close_style_menu() + if UIDROPDOWNMENU_OPEN_MENU == style:GetName() then CloseDropDownMenus() end +end local function show_page(n) + close_style_menu() for i = 1, 5 do if i == n then pages[i]:Show() else pages[i]:Hide() end - if kit and kit.SelectTab then kit.SelectTab(tabs[i], i == n); tabs[i]:SetWidth(115) else tabs[i]:SetText((i == n and "> " or "") .. tabs[i].caption) end + local tab = tabs[i] + if i == n then + tab.surface:SetTexture(0.286, 0.192, 0.149, 1) + tab.rail:Show() + tab.label:SetTextColor(0.92, 0.77, 0.47) + else + tab.surface:SetTexture(0, 0, 0, 0) + tab.rail:Hide() + tab.label:SetTextColor(0.93, 0.89, 0.81) + end end + page_title:SetText(n == 1 and "" or tabs[n].caption) scroll:SetScrollChild(pages[n]) - local maximum = math.max(0, pages[n].height + 8 - 310) + local maximum = math.max(0, pages[n].height + 8 - viewport_height) bar:SetMinMaxValues(0, maximum); bar:SetValue(0); sync_scroll() if maximum > 0 then bar:Show() else bar:Hide() end end -local tab_names = RU and { "Обзор", "Мир", "Свет и тени", "Вода", "Эффекты" } or { "Overview", "World", "Light & Shadows", "Water", "Effects" } +local tab_names = RU and { "Качество", "Мир", "Свет и тени", "Вода", "Эффекты" } or { "Quality", "World", "Light & Shadows", "Water", "Effects" } for i = 1, 5 do - local tab - if kit and kit.Tab then tab = kit.Tab(frame, "MoonWellGraphicsTab" .. i) else tab = CreateFrame("Button", "MoonWellGraphicsTab" .. i, frame, "UIPanelButtonTemplate"); tab:SetHeight(24) end - tab:SetWidth(115); tab:SetPoint("TOPLEFT", frame, "TOPLEFT", 28 + (i - 1) * 124, -94) - tab.caption = tab_names[i]; tab:SetText(tab.caption); tab.page = i; tabs[i] = tab + local tab = CreateFrame("Button", "MoonWellGraphicsTab" .. i, frame) + tab:SetWidth(148); tab:SetHeight(28); tab:SetPoint("TOPLEFT", frame, "TOPLEFT", 25, -102 - (i - 1) * 32) + tab.surface = tab:CreateTexture(nil, "BACKGROUND") + tab.surface:SetAllPoints(tab) + tab.rail = tab:CreateTexture(nil, "ARTWORK") + tab.rail:SetPoint("TOPLEFT", tab, "TOPLEFT", 0, -2); tab.rail:SetPoint("BOTTOMLEFT", tab, "BOTTOMLEFT", 0, 2) + tab.rail:SetWidth(3); tab.rail:SetTexture(0.92, 0.77, 0.47, 1) + local hover = tab:CreateTexture(nil, "HIGHLIGHT") + hover:SetAllPoints(tab); hover:SetTexture(0.72, 0.55, 0.32, 0.13) + tab:SetHighlightTexture(hover, "BLEND") + tab.label = tab:CreateFontString(nil, "ARTWORK", "GameFontHighlight") + tab.label:SetPoint("LEFT", tab, "LEFT", 12, 0) + tab.caption = tab_names[i]; tab.label:SetText(tab.caption); tab.page = i; tabs[i] = tab tab:SetScript("OnClick", function() show_page(this.page) end) local page = CreateFrame("Frame", "MoonWellGraphicsPage" .. i, scroll) - page:SetWidth(620); pages[i] = page; page.height = 0 + page:SetWidth(450); pages[i] = page; page.height = 0 end local overview = pages[1] local style_label = overview:CreateFontString(nil, "ARTWORK", "GameFontNormal") -style_label:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -12) -style_label:SetText(RU and "Стиль мира" or "World style") -local quality_label = overview:CreateFontString(nil, "ARTWORK", "GameFontNormal") -quality_label:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -105) -quality_label:SetText(RU and "Качество" or "Quality") -for i = 1, 7 do - local button = CreateFrame("Button", "MoonWellGraphicsPreset" .. i, overview, "UIPanelButtonTemplate") - local x, y, width - if i <= 2 then x = 12 + (i - 1) * 299; y = -45; width = 287 - else x = 12 + (i - 3) * 119; y = -140; width = 110 end - button:SetWidth(width); button:SetHeight(30); button:SetPoint("TOPLEFT", overview, "TOPLEFT", x, y) - button.surface = button:CreateTexture(nil, "ARTWORK") - button.surface:SetPoint("TOPLEFT", button, "TOPLEFT", 3, -3); button.surface:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", -3, 3) - button.rail = button:CreateTexture(nil, "OVERLAY") - button.rail:SetPoint("TOPLEFT", button, "TOPLEFT", 4, -4); button.rail:SetPoint("BOTTOMLEFT", button, "BOTTOMLEFT", 4, 4) - button.rail:SetWidth(3); button.rail:SetTexture(0.65, 0.88, 0.48, 1) - button.index = i; preset_buttons[i] = button - button:SetScript("OnClick", function() - preset_chosen = 1; copy(presets[this.index], values); sync_widgets() - end) +style_label:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -14) +style_label:SetText(RU and "Стиль графики" or "Graphics style") +style = CreateFrame("Frame", "MoonWellGraphicsStyle", overview, "UIDropDownMenuTemplate") +style:SetPoint("TOPLEFT", overview, "TOPLEFT", 150, -3) +UIDropDownMenu_SetWidth(210, style) +local function fill_styles() + local current = current_preset() + for i = 1, 2 do + local info = {} + info.text = styles[i]; info.value = i + info.checked = (current or style_context) == i + info.func = function() + local old_style = current_preset() + local target = this.value + if target == (old_style or style_context) then return end + local level = target == 1 and 1 or 5 + select_preset(target, level) + end + UIDropDownMenu_AddButton(info) + end end -local summary = overview:CreateTexture(nil, "BACKGROUND") -summary:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -194); summary:SetWidth(586); summary:SetHeight(54) -summary:SetTexture(0.045, 0.085, 0.11, 1) -description = overview:CreateFontString(nil, "ARTWORK", "GameFontHighlight") -description:SetPoint("LEFT", summary, "LEFT", 12, 0); description:SetWidth(562); description:SetJustifyH("LEFT") -overview.height = 286 +UIDropDownMenu_Initialize(style, fill_styles) +quality_heading = overview:CreateFontString("MoonWellGraphicsQualityHeading", "ARTWORK", "GameFontNormal") +quality_heading:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -53) +choose_style_hint = overview:CreateFontString(nil, "ARTWORK", "GameFontHighlight") +choose_style_hint:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -84); choose_style_hint:SetWidth(420) +choose_style_hint:SetJustifyH("LEFT") +choose_style_hint:SetText(RU and "Выберите стиль, чтобы увидеть уровни качества." or "Choose a style to see its quality levels.") +for i = 1, 5 do + local row = CreateFrame("Button", "MoonWellGraphicsQuality" .. i, overview) + row:SetWidth(420); row:SetHeight(48); row:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -77 - (i - 1) * 48) + row.surface = row:CreateTexture(nil, "BACKGROUND"); row.surface:SetAllPoints(row) + row.surface:SetTexture(1, 1, 1, 1); row.surface:SetGradientAlpha("HORIZONTAL", 0.35, 0.22, 0.12, 0.75, 0.12, 0.09, 0.07, 0.25) + row.check = row:CreateTexture(nil, "ARTWORK") + row.check:SetPoint("LEFT", row, "LEFT", 3, 0); row.check:SetWidth(22); row.check:SetHeight(22) + row.check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check"); row.check:SetVertexColor(0.92, 0.77, 0.47, 1) + local hover = row:CreateTexture(nil, "HIGHLIGHT"); hover:SetAllPoints(row); hover:SetTexture(0.72, 0.55, 0.32, 0.12) + row:SetHighlightTexture(hover, "BLEND") + local rule = row:CreateTexture(nil, "ARTWORK"); rule:SetPoint("BOTTOMLEFT", row, "BOTTOMLEFT", 0, 0); rule:SetPoint("BOTTOMRIGHT", row, "BOTTOMRIGHT", 0, 0); rule:SetHeight(1); rule:SetTexture(0.33, 0.26, 0.19, 0.8) + row.title = row:CreateFontString(nil, "ARTWORK", "GameFontHighlight") + row.title:SetPoint("TOPLEFT", row, "TOPLEFT", 30, -5); row.title:SetWidth(380); row.title:SetJustifyH("LEFT") + row.detail = row:CreateFontString(nil, "ARTWORK", "GameFontHighlight") + row.detail:SetPoint("TOPLEFT", row, "TOPLEFT", 30, -21); row.detail:SetWidth(380); row.detail:SetJustifyH("LEFT"); row.detail:SetTextColor(0.79, 0.74, 0.64) + row.index = i; rows[i] = row + row:SetScript("OnClick", function() if style_context then select_preset(style_context, this.index) end end) +end +overview.height = 325 local section_group = { 2, 2, 3, 5, 2, 2, 2, 4, 3 } local section, group = 0, 1 for i = 1, table.getn(items) do @@ -719,11 +811,12 @@ for i = 1, table.getn(items) do local page = pages[group] local heading = page:CreateFontString(nil, "ARTWORK", "GameFontNormal") heading:SetPoint("TOPLEFT", page, "TOPLEFT", 8, -page.height - 10); heading:SetText(label(it)) + local rule = page:CreateTexture(nil, "ARTWORK"); rule:SetPoint("TOPLEFT", page, "TOPLEFT", 8, -page.height - 28); rule:SetWidth(410); rule:SetHeight(1); rule:SetTexture(0.33, 0.26, 0.19, 1) page.height = page.height + 32 else local page = pages[group]; local y = -page.height local text = page:CreateFontString(nil, "ARTWORK", "GameFontHighlight") - text:SetPoint("TOPLEFT", page, "TOPLEFT", 12, y - 8); text:SetWidth(300); text:SetJustifyH("LEFT") + text:SetPoint("TOPLEFT", page, "TOPLEFT", 12, y - 8); text:SetWidth(230); text:SetJustifyH("LEFT") local hints = { ["water.mirror_resolution"] = RU and " (нужно зеркало)" or " (requires mirror)", ["water.second_mirror"] = RU and " (нужно зеркало)" or " (requires mirror)", @@ -732,7 +825,7 @@ for i = 1, table.getn(items) do text:SetText(label(it) .. (hints[it.key] or "")) if it.kind == "switch" then local c = CreateFrame("CheckButton", name, page, "OptionsCheckButtonTemplate") - c:SetPoint("TOPLEFT", page, "TOPLEFT", 340, y - 2); getglobal(name .. "Text"):SetText("") + c:SetPoint("TOPLEFT", page, "TOPLEFT", 258, y - 2); getglobal(name .. "Text"):SetText("") c.key = it.key; widgets[it.key] = c c:SetScript("OnClick", function() if this:GetChecked() then values[this.key] = 1 else values[this.key] = 0 end @@ -740,11 +833,11 @@ for i = 1, table.getn(items) do end) else local s = CreateFrame("Slider", name, page, "OptionsSliderTemplate") - s:SetPoint("TOPLEFT", page, "TOPLEFT", 340, y - 12); s:SetWidth(200) + s:SetPoint("TOPLEFT", page, "TOPLEFT", 258, y - 12); s:SetWidth(125) s:SetMinMaxValues(it.min, it.max); s:SetValueStep(it.step) getglobal(name .. "Text"):SetText(""); getglobal(name .. "Low"):SetText(""); getglobal(name .. "High"):SetText("") s.valueText = page:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") - s.valueText:SetPoint("LEFT", s, "RIGHT", 12, 0); s.valueText:SetWidth(58); s.valueText:SetJustifyH("RIGHT") + s.valueText:SetPoint("LEFT", s, "RIGHT", 8, 0); s.valueText:SetWidth(45); s.valueText:SetJustifyH("RIGHT") if ForeverUI and ForeverUI.SetAtlas and ForeverUI.AtlasEntry then s:SetBackdrop(nil) local left = s:CreateTexture(nil, "BACKGROUND"); ForeverUI.SetAtlas(left, "minimal_sliderbar_left", true); left:SetWidth(11); left:SetHeight(17); left:SetPoint("LEFT", s, "LEFT", 0, 0) @@ -762,7 +855,7 @@ for i = 1, table.getn(items) do page.height = page.height + 34 end end -for i = 1, 5 do pages[i]:SetHeight(math.max(310, pages[i].height + 8)) end +for i = 1, 5 do pages[i]:SetHeight(math.max(viewport_height, pages[i].height + 8)) end apply = CreateFrame("Button", "MoonWellGraphicsApply", frame, "UIPanelButtonTemplate") apply:SetWidth(110); apply:SetHeight(24); apply:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -24, 23) if kit and kit.RedButton then kit.RedButton(apply, "128-redbutton") end @@ -788,6 +881,10 @@ end) local cancel = CreateFrame("Button", "MoonWellGraphicsCancel", frame, "UIPanelButtonTemplate") cancel:SetWidth(110); cancel:SetHeight(24); cancel:SetPoint("RIGHT", apply, "LEFT", -8, 0) cancel:SetText(RU and "Отмена" or "Cancel"); cancel:SetScript("OnClick", function() frame:Hide() end) +local restore = CreateFrame("Button", "MoonWellGraphicsRestore", frame, "UIPanelButtonTemplate") +restore:SetWidth(150); restore:SetHeight(24); restore:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 25, 23) +restore:SetText(RU and "По умолчанию" or "Restore Defaults") +restore:SetScript("OnClick", function() select_preset(2, 5) end) local fitted_width, fitted_height local function fit_window(force) local sw, sh = GetScreenWidth(), GetScreenHeight() @@ -801,9 +898,10 @@ frame:SetScript("OnShow", function() if snapshot then for key, value in string.gfind(snapshot, "([^=;]+)=([^;]+);") do committed[key] = tonumber(value) end end - copy(committed, values); preset_chosen = nil; sync_widgets(); show_page(1); fit_window(1) + copy(committed, values); preset_chosen = nil; style_context = nil; sync_widgets(); show_page(1); fit_window(1) if not snapshot then status:SetText(RU and "Ошибка чтения настроек" or "Cannot read settings") end end) +frame:SetScript("OnHide", close_style_menu) local fit_elapsed = 0 frame:SetScript("OnUpdate", function() fit_elapsed = fit_elapsed + arg1 @@ -948,18 +1046,7 @@ fn write_addon(settings: Res, bridge: Res) { ), ( format!("{ADDON}Data.lua"), - data_lua( - &values, - &flat(&GfxSettings::default()), - &flat(&GfxSettings::balanced()), - &flat(&GfxSettings::forever()), - [ - &flat(&GfxSettings::very_low()), - &flat(&GfxSettings::low()), - &flat(&GfxSettings::high()), - &flat(&GfxSettings::ultra()), - ], - ), + data_lua(&values, &flat(&GfxSettings::default())), ), (format!("{ADDON}.lua"), ADDON_LUA.to_string()), ]; @@ -1038,13 +1125,7 @@ fn values_lua(name: &str, values: &HashMap) -> String { } /// The generated half of the addon: the rows, the values in force and the defaults. -fn data_lua( - values: &HashMap, - defaults: &HashMap, - balanced: &HashMap, - forever: &HashMap, - tiers: [&HashMap; 4], -) -> String { +fn data_lua(values: &HashMap, defaults: &HashMap) -> String { let mut out = String::from( "-- Written by the client (moonwell-gfx): the options window's rows and the values in force.\n\ MoonWellGraphics_Items = {\n", @@ -1066,10 +1147,11 @@ fn data_lua( out += "}\n"; out += &values_lua("MoonWellGraphics_Values", values); out += &values_lua("MoonWellGraphics_Defaults", defaults); - out += &values_lua("MoonWellGraphics_Balanced", balanced); - out += &values_lua("MoonWellGraphics_Forever", forever); - for (name, values) in ["VeryLow", "Low", "High", "Ultra"].into_iter().zip(tiers) { - out += &values_lua(&format!("MoonWellGraphics_{name}"), values); + for level in 1..=5 { + out += &values_lua( + &format!("MoonWellGraphics_Forever{level}"), + &flat(&GfxSettings::forever_quality(level)), + ); } out } @@ -1211,8 +1293,16 @@ mod tests { function GetScreenWidth() return SCREEN_W end function GetScreenHeight() return SCREEN_H end function HideUIPanel() end - function SelectPreset(index) - this = getglobal("MoonWellGraphicsPreset" .. index); this.OnClick() + function UIDropDownMenu_SetWidth() end + function UIDropDownMenu_SetText(text, menu) menu.text = text end + function UIDropDownMenu_AddButton(info) table.insert(MENU_ITEMS, info) end + function UIDropDownMenu_Initialize(menu, fill) menu.fill = fill end + function SelectStyle(index) + MENU_ITEMS = {}; MoonWellGraphicsStyle.fill() + this = MENU_ITEMS[index]; this.func() + end + function SelectQuality(index) + this = getglobal("MoonWellGraphicsQuality" .. index); this.OnClick() end SlashCmdList = {} UISpecialFrames = {} @@ -1262,6 +1352,10 @@ mod tests { end function CreateFrame(kind, name, parent, template) local frame = make(name) + if kind == "Slider" then + frame.thumb = make(nil) + frame.GetThumbTexture = function(self) return self.thumb end + end if template == "UIPanelScrollBarTemplate" then make(name .. "ScrollUpButton") make(name .. "ScrollDownButton") @@ -1302,63 +1396,95 @@ mod tests { f.OnUpdate() assert(f.scale == 1, "restores natural size when space returns") assert(GameMenuButtonMoonWellGraphics, "the game menu has its button") - local expected = {{ "Классика", "WoW Forever", "Очень низкое", "Низкое", "Среднее", "Высокое", "Ультра" }} - for i = 1, 7 do - local button = getglobal("MoonWellGraphicsPreset" .. i) - assert(button and string.find(button.text, expected[i]), "each profile has a named button") + assert(MoonWellGraphicsStyle.text == "Свой", "fresh unmatched settings show custom") + assert(not MoonWellGraphicsQuality1:IsVisible(), "unknown style has no quality rows") + MENU_ITEMS = {{}}; MoonWellGraphicsStyle.fill() + assert(table.getn(MENU_ITEMS) == 2, "only two styles are selectable") + SelectStyle(2) + assert(MoonWellGraphicsStyle.text == "MoonWell", "style selection is visible") + assert(MoonWellGraphicsQuality5.check:IsVisible(), "new scalable style starts at ultra") + assert(MoonWellGraphicsQuality5:IsVisible(), "all tiers are visible") + SelectQuality(4) + assert(not MoonWellGraphicsQuality3.check:IsVisible() and not MoonWellGraphicsQuality3.surface:IsVisible(), "previous tier clears selection") + assert(MoonWellGraphicsQuality4.check:IsVisible() and MoonWellGraphicsQuality4.surface:IsVisible(), "new tier shows selection") + assert(string.find(MoonWellGraphicsQuality4.detail.text, "облака"), "Forever has its own descriptions") + SelectStyle(1) + assert(MoonWellGraphicsQuality1.check:IsVisible() and not MoonWellGraphicsQuality2:IsVisible(), "classic has one original tier") + for i = 1, table.getn(MoonWellGraphics_Items) do + if MoonWellGraphics_Items[i].key == "terrain.lod" then + this = getglobal("MoonWellGraphicsItem" .. i) + this:SetChecked(1); this.OnClick() + end end + assert(MoonWellGraphicsStyle.text == "Классика" and not MoonWellGraphicsQuality1.check:IsVisible(), "manual edits do not switch styles even when another style matches") + assert(not LastApply(), "style selection remains a draft") + SelectStyle(2) + assert(MoonWellGraphicsQuality5.check:IsVisible(), "classic to scalable starts at ultra") + MoonWellGraphicsRestore.OnClick() + assert(MoonWellGraphicsItem2:GetChecked() and MoonWellGraphicsQuality5.check:IsVisible(), "restore stages ultra") + assert(not LastApply(), "restore does not save") for i = 1, 5 do this = getglobal("MoonWellGraphicsTab" .. i); this.OnClick() assert(getglobal("MoonWellGraphicsPage" .. i):IsVisible(), "each tab opens") end this = MoonWellGraphicsTab4; this.OnClick() - assert(MoonWellGraphicsPage4:IsVisible(), "water tab opens") MoonWellGraphicsScrollBarScrollDownButton.OnClick() assert(MoonWellGraphicsScroll:GetVerticalScroll() == 34, "down arrow scrolls a row") arg1 = -1; MoonWellGraphicsScroll.OnMouseWheel() assert(MoonWellGraphicsScroll:GetVerticalScroll() == 74, "water controls scroll") this = MoonWellGraphicsTab1; this.OnClick() assert(not MoonWellGraphicsScrollBar:IsVisible(), "overview needs no scrollbar") - SelectPreset(5) - assert(not LastApply(), "preset remains a draft") - this = MoonWellGraphicsCancel - this.OnClick() + assert(string.find(MoonWellGraphicsSelected.text, "MoonWell"), "navigation keeps the draft") + SelectStyle(2) + MoonWellGraphicsCancel.OnClick() SlashCmdList["MOONWELLGFX"]() - assert(not MoonWellGraphicsItem2:GetChecked(), "cancel restores committed values") - SelectPreset(2) + assert(MoonWellGraphicsStyle.text == "Свой", "cancel restores original unmatched settings") + SelectStyle(2) + SelectQuality(4) MoonWellGraphicsFrame:Hide() SlashCmdList["MOONWELLGFX"]() - assert(not MoonWellGraphicsItem2:GetChecked(), "close discards the draft") - SelectPreset(5) - assert(MoonWellGraphicsItem2:GetChecked(), "balanced enables fog") - assert(string.find(MoonWellGraphicsSelected.text, "Среднее"), "medium selected") - assert(MoonWellGraphicsPreset5.rail:IsVisible(), "selected profile has a rail") - assert(not MoonWellGraphicsPreset1.rail:IsVisible(), "other profiles have no rail") - SelectPreset(1) - this = MoonWellGraphicsItem2 - this:SetChecked(1) - this.OnClick() + assert(MoonWellGraphicsStyle.text == "Свой", "close discards the draft") + SelectStyle(2) + SelectQuality(3) + assert(MoonWellGraphicsItem2:GetChecked(), "medium enables fog") this = MoonWellGraphicsItem{reflection} this:SetValue(0.3) this.OnValueChanged() this = MoonWellGraphicsItem{shadow_map} this:SetValue(12) assert(this.valueText.text == "4096", "shadow slider displays an allocation size") - assert(string.find(MoonWellGraphicsSelected.text, "Свой"), "manual edit selects custom") - assert(not MoonWellGraphicsPreset1.rail:IsVisible(), "custom has no selected preset rail") - assert(string.find(MoonWellGraphicsStatus.text, "неприменённые"), "dirty status") + assert(string.find(MoonWellGraphicsSelected.text, "Свои настройки"), "manual edit selects custom") + assert(MoonWellGraphicsStyle.text == "MoonWell", "manual edit keeps style context") + assert(not MoonWellGraphicsQuality3.check:IsVisible(), "custom has no selected row") + SelectStyle(2) + assert(string.find(MoonWellGraphicsSelected.text, "Свои настройки"), "choosing the same style preserves manual edits") assert(rawget(MoonWellGraphicsApply, "disabled") == nil, "draft enables Apply") - assert(not LastApply(), "draft does not report") - this = MoonWellGraphicsApply FAIL_SAVE = 1 - this.OnClick() + MoonWellGraphicsApply.OnClick() assert(string.find(MoonWellGraphicsStatus.text, "Ошибка"), "failed save is visible") FAIL_SAVE = nil - this.OnClick() + MoonWellGraphicsApply.OnClick() assert(string.find(MoonWellGraphicsStatus.text, "Сохранено"), "retry saves") MoonWellGraphicsFrame:Hide() SlashCmdList["MOONWELLGFX"]() + assert(MoonWellGraphicsStyle.text == "Свой", "unmatched saved values reopen as custom") assert(MoonWellGraphicsItem2:GetChecked(), "reopen retains applied values") + SelectStyle(2) + SelectQuality(4) + MoonWellGraphicsApply.OnClick() + MoonWellGraphicsFrame:Hide() + SlashCmdList["MOONWELLGFX"]() + assert(MoonWellGraphicsStyle.text == "MoonWell" and MoonWellGraphicsQuality4.check:IsVisible(), "exact saved tier reopens") + SelectStyle(1) + MoonWellGraphicsApply.OnClick() + MoonWellGraphicsFrame:Hide() + SlashCmdList["MOONWELLGFX"]() + assert(MoonWellGraphicsStyle.text == "Классика" and MoonWellGraphicsQuality1.check:IsVisible(), "exact classic reopens") + SelectStyle(2) + SelectQuality(3) + this = MoonWellGraphicsItem{reflection}; this:SetValue(0.3); this.OnValueChanged() + this = MoonWellGraphicsItem{shadow_map}; this:SetValue(12) + MoonWellGraphicsApply.OnClick() return MoonWellGraphics_Snapshot() "# ); @@ -1371,18 +1497,7 @@ mod tests { let mut on = GfxSettings::default(); on.water.enabled = true; on.water.ripple_strength = 2.0; - let data = data_lua( - &flat(&on), - &flat(&GfxSettings::default()), - &flat(&GfxSettings::balanced()), - &flat(&GfxSettings::forever()), - [ - &flat(&GfxSettings::very_low()), - &flat(&GfxSettings::low()), - &flat(&GfxSettings::high()), - &flat(&GfxSettings::ultra()), - ], - ); + let data = data_lua(&flat(&on), &flat(&GfxSettings::default())); for (name, chunk) in [ ("stand-ins", STAND_INS), ("data", &data), @@ -1404,8 +1519,8 @@ mod tests { let cvar: String = lua .load( r#" - SelectPreset(1) - assert(not MoonWellGraphicsItem2:GetChecked(), "the fog box clears") + MoonWellGraphicsRestore.OnClick() + assert(MoonWellGraphicsItem2:GetChecked(), "the fog box is enabled") this = MoonWellGraphicsApply this.OnClick() return MoonWellGraphics_Snapshot() @@ -1415,14 +1530,14 @@ mod tests { .eval() .expect("defaults"); let back = parse_strict(&cvar).unwrap(); - assert_eq!(back, flat(&GfxSettings::default()), "{cvar}"); - assert_eq!(back.get("water.enabled"), Some(&0.0)); - assert_eq!(back.get("water.ripple_strength"), Some(&0.3)); - // The Forever button sets its look, every feature it names on. + assert_eq!(back, flat(&GfxSettings::forever()), "{cvar}"); + // The top Forever tier sets its look, every feature it names on. let cvar: String = lua .load( r#" - SelectPreset(2) + SelectStyle(1) + SelectStyle(2) + SelectQuality(5) this = MoonWellGraphicsApply this.OnClick() return MoonWellGraphics_Snapshot() @@ -1441,7 +1556,7 @@ mod tests { #[test] fn the_data_lists_every_row() { let defaults = flat(&GfxSettings::default()); - let lua = data_lua(&defaults, &defaults, &defaults, &defaults, [&defaults; 4]); + let lua = data_lua(&defaults, &defaults); assert_eq!(lua.matches("kind = ").count(), ITEMS.len()); assert!(lua.contains("[\"water.enabled\"] = 0,")); assert!(lua.contains("MoonWellGraphics_Defaults = {")); diff --git a/crates/moonwell-gfx/src/settings.rs b/crates/moonwell-gfx/src/settings.rs index 78fda259d..ab0acd2fd 100644 --- a/crates/moonwell-gfx/src/settings.rs +++ b/crates/moonwell-gfx/src/settings.rs @@ -1,6 +1,6 @@ //! The crate's own settings, `moonwell-gfx.toml` in benilla's config folder: never rows in //! benilla's CVar table (`docs/CONTRIBUTING.md`, "Building on top"). Every default is off, the -//! stock 1.12 image. The file is written with its defaults when absent and read again when it +//! stock 1.12 image. A new player file starts with the full MoonWell profile and is read again when it //! changes, so an edit shows in the running client. `$MOONWELL_GFX=` reads that file //! instead, never writing it: a capture, whose state is hermetic, takes its settings this way. @@ -170,65 +170,6 @@ impl Default for LightSettings { } impl GfxSettings { - /// Retain the classic image with adaptive terrain detail in the distance. - pub(crate) fn very_low() -> Self { - let mut s = Self::default(); - s.terrain.lod = true; - s - } - - /// Add soft fog and improved water without extra scene passes for the water. - pub(crate) fn low() -> Self { - let mut s = Self::very_low(); - s.fog.enabled = true; - s.fog.haze = 0.1; - s.water.enabled = true; - s.water.depth = false; - s.water.ripples = false; - s.water.mirror = false; - s.water.ssr = false; - s.water.second_mirror = false; - s - } - - /// A restrained atmosphere and water preset without reflection views or expensive effects. - pub(crate) fn balanced() -> Self { - let mut s = Self::low(); - s.sky.enhanced = true; - s.fog.modern = true; - s.water.mesh_lod = true; - s - } - - /// Add nearby sun shadows, ambient occlusion and denser grass. - pub(crate) fn high() -> Self { - let mut s = Self::balanced(); - s.shadows.enabled = true; - s.shadows.distance = 160.0; - s.shadows.map_size = 1024; - s.shadows.cascades = 2; - s.post.enabled = true; - s.post.secondary_light = false; - s.post.sun_shafts = false; - s.post.volumetric = false; - s.grass.enabled = true; - s - } - - /// Increase scene detail and add lit air and screen-space water effects. - pub(crate) fn ultra() -> Self { - let mut s = Self::high(); - s.shadows.distance = 300.0; - s.shadows.map_size = 4096; - s.shadows.cascades = 4; - s.post.volumetric = true; - s.grass.density = 160.0; - s.grass.distance = 200.0; - s.water.depth = true; - s.water.ssr = true; - s - } - /// The look of WoW Forever's remastered client: every feature on, the air lit by the sun /// through its shadows, a warmer haze, bloom, a sharpen, dense far grass, and the lights per /// pixel, with one nearby light casting a shadow. @@ -286,6 +227,60 @@ impl GfxSettings { s } + /// Keep the Forever atmosphere and reduce render passes at the four lower quality tiers. + /// The fifth tier preserves the original Forever preset exactly. + pub(crate) fn forever_quality(level: u8) -> Self { + let mut s = Self::forever(); + if level < 5 { + s.post.volumetric_froxels = false; + s.post.depth_of_field = false; + s.water.second_mirror = false; + s.lights.shadows = false; + } + if level < 4 { + s.sky.cloud_detail = false; + s.shadows.distance = 180.0; + s.shadows.map_size = 1024; + s.shadows.cascades = 2; + s.post.secondary_light = false; + s.water.mirror = false; + s.water.ssr = false; + s.grass.density = 80.0; + s.grass.distance = 120.0; + } + if level < 3 { + s.shadows.enabled = false; + s.post.ao = false; + s.post.sun_shafts = false; + s.post.volumetric = false; + s.water.depth = false; + s.water.ripples = false; + s.grass.enabled = false; + s.weather.wet_character = false; + s.lights.per_pixel = false; + s.lights.wmo_points = false; + s.lights.wmo_portals = false; + s.lights.spell_points = false; + } + if level < 2 { + s.post.hdr_bloom = false; + s.post.hdr_emissive = false; + s.post.auto_exposure = 0.0; + s.post.bloom = false; + s.fog.ground = 0.0; + s.fog.mist_motion = 0.0; + s.water.mesh_lod = false; + s.water.ocean_swell = 0.0; + s.water.rain_ripples = 0.0; + s.wind.enabled = false; + s.wind.grass_parting = false; + s.weather.soft_rain = false; + s.weather.lightning = false; + s.weather.wetness = 0.0; + } + s + } + /// Whether the world's shadow casters stand: for the sun's shadows, or the torches'. pub(crate) fn casting(&self) -> bool { let l = self.lights.clamped(); @@ -868,17 +863,21 @@ fn tag_journal( /// Read the file, writing the defaults first when it is absent; `None` keeps what is in force. fn load(file: &mut SettingsFile) -> Option { let path = file.path.as_ref()?; - if !path.exists() && file.write_defaults { + if file.write_defaults + && matches!(std::fs::metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound) + { + let initial = GfxSettings::forever(); let text = format!( - "# MoonWell graphics on top of the stock client. Everything off is the stock 1.12 image.\n\ - # Edits apply while the client runs.\n\ + "# MoonWell graphics on top of the stock client. Edits apply while the client runs.\n\ # With [shadows] entities on, the stock blob under units doubles their shadow:\n\ # `/console shadowLOD 0` (or shadowLOD = \"0\" in config.toml) turns it off.\n\n{}", - toml::to_string_pretty(&GfxSettings::default()).ok()? + toml::to_string_pretty(&initial).ok()? ); - if let Err(e) = std::fs::write(path, text) { - warn!("moonwell-gfx: cannot write {}: {e}", path.display()); - return None; + if let Err(e) = save_document(path, &text, true) { + if e.kind() != std::io::ErrorKind::AlreadyExists { + warn!("moonwell-gfx: cannot write {}: {e}", path.display()); + return Some(initial); + } } } file.seen = std::fs::metadata(path).and_then(|m| m.modified()).ok(); @@ -905,7 +904,7 @@ fn load(file: &mut SettingsFile) -> Option { pub(crate) fn read_player(path: &std::path::Path) -> Result { match std::fs::read_to_string(path) { Ok(text) => toml::from_str(&text).map_err(|e| format!("invalid settings: {e}")), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(GfxSettings::default()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(GfxSettings::forever()), Err(e) => Err(format!("cannot read settings: {e}")), } } @@ -915,10 +914,13 @@ pub(crate) fn write_player( path: &std::path::Path, edits: &[(String, String, toml_edit::Value)], ) -> Result { - use std::io::Write; - let text = match std::fs::read_to_string(path) { - Ok(text) => text, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + let (text, create_only) = match std::fs::read_to_string(path) { + Ok(text) => (text, false), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => ( + toml::to_string_pretty(&GfxSettings::forever()) + .map_err(|e| format!("cannot serialize settings: {e}"))?, + true, + ), Err(e) => return Err(format!("cannot read settings: {e}")), }; // Validate the old document too: partial edits must never repair or replace a broken file. @@ -946,33 +948,45 @@ pub(crate) fn write_player( let output = doc.to_string(); let next: GfxSettings = toml::from_str(&output).map_err(|e| format!("invalid settings: {e}"))?; - let mut temp = None; + save_document(path, &output, create_only).map_err(|e| format!("cannot save settings: {e}"))?; + Ok(next) +} + +/// Publish a complete file; initial creation must never replace another writer's file. +fn save_document(path: &std::path::Path, output: &str, create_only: bool) -> std::io::Result<()> { + use std::io::Write; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + std::fs::create_dir_all(parent)?; + } for counter in 0..1000 { - let candidate = path.with_extension(format!("toml.{}.{}.tmp", std::process::id(), counter)); - match std::fs::OpenOptions::new() + let tmp = path.with_extension(format!("toml.{}.{}.tmp", std::process::id(), counter)); + let mut file = match std::fs::OpenOptions::new() .write(true) .create_new(true) - .open(&candidate) + .open(&tmp) { - Ok(file) => { - temp = Some((candidate, file)); - break; - } + Ok(file) => file, Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, - Err(e) => return Err(format!("cannot create temporary settings: {e}")), - } - } - let (tmp, mut file) = temp.ok_or_else(|| "cannot create temporary settings".to_string())?; - let result = file - .write_all(output.as_bytes()) - .and_then(|()| file.sync_all()); - drop(file); - let result = result.and_then(|()| std::fs::rename(&tmp, path)); - if let Err(e) = result { + Err(e) => return Err(e), + }; + let result = file + .write_all(output.as_bytes()) + .and_then(|()| file.sync_all()); + drop(file); + let result = result.and_then(|()| { + if create_only { + std::fs::hard_link(&tmp, path) + } else { + std::fs::rename(&tmp, path) + } + }); let _ = std::fs::remove_file(&tmp); - return Err(format!("cannot save settings: {e}")); + return result; } - Ok(next) + Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + "no temporary settings filename available", + )) } fn reload( @@ -988,8 +1002,17 @@ fn reload( let Some(path) = file.path.as_ref() else { return; }; - let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok(); - if modified.is_none() || modified == file.seen { + let changed = match std::fs::metadata(path) { + Ok(metadata) => metadata + .modified() + .ok() + .is_some_and(|modified| Some(modified) != file.seen), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + file.write_defaults && file.seen.is_some() + } + Err(_) => false, + }; + if !changed { return; } if let Some(next) = load(&mut file) { @@ -1005,24 +1028,81 @@ mod tests { use super::*; #[test] - fn quality_presets_add_scene_detail_in_steps() { - let classic = GfxSettings::default(); - let very_low = GfxSettings::very_low(); - let low = GfxSettings::low(); - let medium = GfxSettings::balanced(); - let high = GfxSettings::high(); - let ultra = GfxSettings::ultra(); + fn forever_quality_preserves_the_style_across_all_five_tiers() { + let [very_low, low, medium, high, ultra] = + [1, 2, 3, 4, 5].map(GfxSettings::forever_quality); + for preset in [&very_low, &low, &medium, &high, &ultra] { + assert!(preset.fog.enabled && preset.fog.zone_looks); + assert!(preset.post.enabled && preset.post.zone_grading); + assert!(preset.water.enabled); + } + assert!(!very_low.wind.enabled && low.wind.enabled && low.fog.ground > 0.0); + assert!(!low.shadows.enabled && medium.shadows.enabled && medium.grass.enabled); + assert!(!low.water.depth && medium.water.depth); + assert!(!medium.water.mirror && high.water.mirror && high.sky.cloud_detail); + assert!(!high.post.volumetric_froxels && ultra.post.volumetric_froxels); + assert!(!high.lights.shadows && ultra.lights.shadows); + assert_eq!(ultra, GfxSettings::forever()); + } - assert!(!classic.terrain.lod && very_low.terrain.lod); - assert!(!very_low.fog.enabled && low.fog.enabled && low.water.enabled); - assert!(!low.fog.modern && medium.fog.modern && medium.water.mesh_lod); - assert!(!medium.shadows.enabled && high.shadows.enabled && high.post.ao); - assert!(high.post.enabled && high.grass.enabled); - assert!(ultra.shadows.map_size > high.shadows.map_size); - assert!(ultra.grass.distance > high.grass.distance); - assert!(!high.post.volumetric && ultra.post.volumetric); - assert!(ultra.water.depth && ultra.water.ssr && !ultra.water.mirror); - assert!(!ultra.post.volumetric_froxels && GfxSettings::forever().post.volumetric_froxels); + #[test] + fn new_player_file_and_partial_save_use_full_profile() { + let dir = + std::env::temp_dir().join(format!("moonwell-gfx-first-run-{}", std::process::id())); + let path = dir.join("nested").join(FILE); + assert!(!path.exists()); + assert_eq!(read_player(&path).unwrap(), GfxSettings::forever()); + let edits = vec![( + "fog".into(), + "enabled".into(), + toml_edit::Value::from(false), + )]; + let mut expected = GfxSettings::forever(); + expected.fog.enabled = false; + assert_eq!(write_player(&path, &edits).unwrap(), expected); + assert_eq!(read_player(&path).unwrap(), expected); + std::fs::remove_dir_all(&dir).unwrap(); + let mut file = SettingsFile { + path: Some(path.clone()), + write_defaults: true, + ..default() + }; + assert_eq!(load(&mut file).unwrap(), GfxSettings::forever()); + assert_eq!(read_player(&path).unwrap(), GfxSettings::forever()); + let before = std::fs::read_to_string(&path).unwrap(); + assert_eq!( + save_document(&path, "other", true).unwrap_err().kind(), + std::io::ErrorKind::AlreadyExists + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), before); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn existing_player_files_keep_classic_missing_values() { + let path = + std::env::temp_dir().join(format!("moonwell-gfx-old-{}.toml", std::process::id())); + for text in ["", "[fog]\nenabled = true\n"] { + std::fs::write(&path, text).unwrap(); + let expected: GfxSettings = toml::from_str(text).unwrap(); + let mut file = SettingsFile { + path: Some(path.clone()), + write_defaults: true, + ..default() + }; + assert_eq!(load(&mut file).unwrap(), expected); + assert_eq!(read_player(&path).unwrap(), expected); + assert_eq!(std::fs::read_to_string(&path).unwrap(), text); + let edits = vec![( + "water".into(), + "enabled".into(), + toml_edit::Value::from(true), + )]; + let mut changed = expected; + changed.water.enabled = true; + assert_eq!(write_player(&path, &edits).unwrap(), changed); + } + std::fs::remove_file(path).unwrap(); } #[test]