Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d07be13cf9 | |||
| da619863c0 | |||
| 0913e16df5 | |||
| 5d22985205 | |||
| cc4da3cb61 | |||
| d1961e79fc | |||
| 241e37d760 | |||
| d201c8e469 | |||
| 2ef92a2032 | |||
| ac0a4fbc47 | |||
| 53b0907393 | |||
| 97a92194cc | |||
| da72c705f1 |
@@ -1,5 +1,10 @@
|
||||
# Rust build artifacts
|
||||
/target/
|
||||
/dist/
|
||||
/.env
|
||||
/.env.*
|
||||
# Locally supplied patch source content.
|
||||
/src/Data/
|
||||
**/*.rs.bk
|
||||
# Cargo.lock IS committed (this workspace produces binaries).
|
||||
|
||||
|
||||
Generated
+812
-51
File diff suppressed because it is too large
Load Diff
@@ -75,6 +75,17 @@ benilla builds and runs on macOS, Linux and Windows. You need:
|
||||
Xcode command line tools, on Linux the ALSA and udev development packages and pkg-config, on
|
||||
Windows the MSVC build tools that the Rust installer sets up.
|
||||
|
||||
This fork also reads community **ruRU language packs for 1.12.1** from `Data/ruRU`.
|
||||
Keep the base MPQs in `Data` and the Russian `patch-*.MPQ` files in that subfolder;
|
||||
`WOW_DATA` points to `Data`, not to `ruRU`. An installed pack selects Russian automatically.
|
||||
`WOW_LOCALE=ruRU` requires the pack, `WOW_LOCALE=enUS` selects the English base chain, and
|
||||
`WOW_LOCALE=auto` restores automatic selection. Restart the client after changing the language.
|
||||
The selected chain supplies DBC names, interface strings, fonts, textures and audio; missing
|
||||
localized files fall back to the base chain. Benilla's own settings and menu captions also have
|
||||
Russian translations. The login sends the selected locale to the server; server-supplied quest,
|
||||
NPC and item text requires translations on that server. Packs for later expansions are unsupported.
|
||||
`moonwell-deploy stage` preserves an installed `ruRU` archive folder in the distribution.
|
||||
|
||||
```sh
|
||||
WOW_DATA=/path/to/WoW/Data cargo run --release -p benilla
|
||||
```
|
||||
|
||||
@@ -5,6 +5,27 @@
|
||||
BENILLA_REALMLIST and BENILLA_REALMLIST_PINNED (set while $WOW_HOST fixes the address),
|
||||
and reopens the dialog with the typed text when it is not an address. -->
|
||||
<Script>
|
||||
-- CharacterSelect.xml:679 compares the confirmation through strupper. Native 1.12 upper
|
||||
-- (0x7fc180) leaves Cyrillic unchanged; the community ruRU pack needs its own case fold.
|
||||
if GetLocale() == "ruRU" then
|
||||
local function upper(text)
|
||||
local result = strupper(text)
|
||||
local lower = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
|
||||
local capitals = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
|
||||
for i = 1, string.len(lower), 2 do
|
||||
result = string.gsub(result, string.sub(lower, i, i + 1), string.sub(capitals, i, i + 1))
|
||||
end
|
||||
return result
|
||||
end
|
||||
CharacterDeleteEditBox:SetScript("OnTextChanged", function()
|
||||
if upper(this:GetText()) == upper(DELETE_CONFIRM_STRING) then
|
||||
CharacterDeleteButton1:Enable()
|
||||
else
|
||||
CharacterDeleteButton1:Disable()
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
GlueDialogTypes["BENILLA_REALMLIST"] = {
|
||||
-- The realmList CVar's registered help text.
|
||||
text = "Address of realm list server",
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
-- space: a width or height of 0 is no size in 1.12's layout, not a flat rect.
|
||||
|
||||
-- Literal: 1.12 has no GAMEMENU_OPTIONS; its OPTIONS_MENU is "Options Menu".
|
||||
GameMenuButtonOptions:SetText("Options")
|
||||
GameMenuButtonOptions:SetText(BenillaUiText("Options"))
|
||||
GameMenuButtonOptions:ClearAllPoints()
|
||||
GameMenuButtonOptions:SetPoint("TOP", GameMenuFrame, "TOP", 0, -32)
|
||||
GameMenuButtonOptions:SetScript("OnClick", function()
|
||||
@@ -68,12 +68,12 @@
|
||||
local editMode = CreateFrame("Button", "BenillaGameMenuButtonEditMode", GameMenuFrame,
|
||||
"GameMenuButtonTemplate")
|
||||
editMode:SetPoint("TOP", GameMenuButtonKeybindings, "TOP", 0, -19)
|
||||
editMode:SetText("Edit Mode")
|
||||
editMode:SetText(BenillaUiText("Edit Mode"))
|
||||
editMode:Disable()
|
||||
local support = CreateFrame("Button", "BenillaGameMenuButtonSupport", GameMenuFrame,
|
||||
"GameMenuButtonTemplate")
|
||||
support:SetPoint("TOP", editMode, "BOTTOM", 0, 0)
|
||||
support:SetText("Support")
|
||||
support:SetText(BenillaUiText("Support"))
|
||||
-- The era's Support opens the help window, which 1.12 opens from its "?" micro button
|
||||
-- (`MainMenuBarMicroButtons.xml:217`); closing the menu first, as the Macros rung does.
|
||||
support:SetScript("OnClick", function()
|
||||
|
||||
@@ -471,7 +471,7 @@
|
||||
}
|
||||
-- Reset To Default confirms, as the era's does; our string, since 1.12 has none.
|
||||
StaticPopupDialogs["BENILLA_CONFIRM_RESET_KEYBINDINGS"] = {
|
||||
text = "Are you sure you want to reset all keybindings to their defaults?",
|
||||
text = BenillaUiText("Are you sure you want to reset all keybindings to their defaults?"),
|
||||
button1 = BenillaKeyBindings_String("OKAY", "Okay"),
|
||||
button2 = BenillaKeyBindings_String("CANCEL", "Cancel"),
|
||||
OnAccept = function()
|
||||
@@ -491,7 +491,7 @@
|
||||
for i = 1, GetNumBindings() do
|
||||
local command = GetBinding(i)
|
||||
if not BenillaKeyBindings_IsHeader(command) then
|
||||
local tag = string.upper(BenillaKeyBindings_String("BINDING_NAME_" .. command, command))
|
||||
local tag = BenillaUiUpper(BenillaKeyBindings_String("BINDING_NAME_" .. command, command))
|
||||
local s = BenillaOptionsSearch_Score(tag, words)
|
||||
if s then
|
||||
table.insert(out, { score = s, index = i })
|
||||
|
||||
@@ -118,6 +118,7 @@
|
||||
|
||||
-- The wash at the era atlas size, in the 1.14 hover steel-blue.
|
||||
function BenillaOptionsCategoryRow_OnLoad(row, key, label)
|
||||
label = BenillaUiText(label)
|
||||
row.categoryKey = key
|
||||
row.pageTitle = label
|
||||
row:SetText(label)
|
||||
@@ -180,7 +181,7 @@
|
||||
-- Results are the live rows, so writes work mid-search.
|
||||
|
||||
function BenillaOptionsSearch_Words(text)
|
||||
local up = string.upper(text)
|
||||
local up = BenillaUiUpper(text)
|
||||
local words = { up }
|
||||
for w in string.gfind(up, "([^, ]+)") do
|
||||
table.insert(words, w)
|
||||
@@ -345,7 +346,7 @@
|
||||
BenillaKeyBindingsPage.searchPainted = nil
|
||||
BenillaKeyBindings_SetSelected(nil)
|
||||
BenillaOptionsFrameContainerUnbind:Hide()
|
||||
BenillaOptionsFrameContainerTitle:SetText("Search Results")
|
||||
BenillaOptionsFrameContainerTitle:SetText(BenillaUiText("Search Results"))
|
||||
BenillaOptionsFrameContainerDefaults:Hide()
|
||||
|
||||
local order, groups = BenillaOptionsSearch_FindMatches(text)
|
||||
@@ -455,6 +456,24 @@
|
||||
.. "which it could only do in exclusive fullscreen. benilla applies it to the "
|
||||
.. "finished image instead, so it works in both display modes."
|
||||
|
||||
if GetLocale() == "ruRU" then
|
||||
BENILLA_TOOLTIP_RENDER_SCALE =
|
||||
"Меняет разрешение трёхмерного мира относительно размера окна. Интерфейс не меняется.\n\n"
|
||||
.. "Значения ниже 100% повышают частоту кадров, но снижают чёткость. "
|
||||
.. "Значения выше 100% сглаживают края за счёт производительности. "
|
||||
.. "Изменение вступает в силу после нажатия кнопки «Применить»."
|
||||
BENILLA_TOOLTIP_BACKGROUND_SOUND =
|
||||
"Продолжает воспроизведение звука игры, когда активно другое окно.\n\n"
|
||||
.. "Если выключено, при переключении в другое окно игра становится беззвучной. "
|
||||
.. "Звуки при этом продолжают идти и могут закончиться до вашего возвращения."
|
||||
BENILLA_TOOLTIP_DISPLAY_MODE =
|
||||
"Оконный режим на весь экран использует окно без рамки. Обычный оконный режим "
|
||||
.. "оставляет рамку и заголовок окна.\n\nЭксклюзивный полноэкранный режим не используется."
|
||||
BENILLA_TOOLTIP_BRIGHTNESS =
|
||||
"Делает изображение светлее или темнее, в том числе ночью, в пещерах и помещениях.\n\n"
|
||||
.. "Коррекция применяется к готовому изображению и работает в обоих режимах экрана."
|
||||
end
|
||||
|
||||
BENILLA_OPTIONS_PAGE_ROWS = {
|
||||
-- The era Controls order first; the rest follow their 1.12 box's columns.
|
||||
Controls = {
|
||||
@@ -514,9 +533,10 @@
|
||||
|
||||
-- `tip` is a GlobalStrings key, resolved at hover as UIOptionsFrame.lua:265 does.
|
||||
function BenillaOptionsRow_OnLoad(row, cvar, label, tip, child)
|
||||
label = BenillaUiText(label)
|
||||
row.cvar = cvar
|
||||
row.tip = tip
|
||||
row.searchTag = string.upper(label)
|
||||
row.searchTag = BenillaUiUpper(label)
|
||||
-- BenillaOptionsRow_SetEnabled's disabled font must keep the child size.
|
||||
row.child = child
|
||||
local l = getglobal(row:GetName() .. "Label")
|
||||
@@ -654,7 +674,7 @@
|
||||
local row = dd:GetParent()
|
||||
for _, e in ipairs(row.entries) do
|
||||
local info = {}
|
||||
info.text = e.text
|
||||
info.text = BenillaUiText(e.text)
|
||||
info.value = e.value
|
||||
info.func = BenillaOptionsDropdownEntry_OnClick
|
||||
UIDropDownMenu_AddButton(info)
|
||||
@@ -691,7 +711,7 @@
|
||||
end
|
||||
if match then
|
||||
dd.selectedValue = match.value
|
||||
UIDropDownMenu_SetText(match.text, dd)
|
||||
UIDropDownMenu_SetText(BenillaUiText(match.text), dd)
|
||||
-- As UIOptionsFrameCameraDropDown_OnClick retargets OPTION_TOOLTIP_CAMERA<id>.
|
||||
if match.tip then row.tip = match.tip end
|
||||
else
|
||||
@@ -3108,6 +3128,7 @@
|
||||
wheel stay off until a capsule is selected (BenillaKeyBindings_SetSelected). -->
|
||||
<OnLoad>
|
||||
this:EnableKeyboard(false)
|
||||
BenillaUiLocalize(this)
|
||||
this:EnableMouseWheel(false)
|
||||
</OnLoad>
|
||||
<OnKeyDown>BenillaKeyBindings_OnKeyDown()</OnKeyDown>
|
||||
|
||||
@@ -78,13 +78,13 @@
|
||||
|
||||
local summary
|
||||
if total == 0 then
|
||||
summary = "No problems this session."
|
||||
summary = BenillaUiText("No problems this session.")
|
||||
elseif total > shown then
|
||||
summary = format("%d problems (%d older not kept)", total, total - shown)
|
||||
summary = format(BenillaUiText("%d problems (%d older not kept)"), total, total - shown)
|
||||
elseif total == 1 then
|
||||
summary = "1 problem"
|
||||
summary = BenillaUiText("1 problem")
|
||||
else
|
||||
summary = format("%d problems", total)
|
||||
summary = format(BenillaUiText("%d problems"), total)
|
||||
end
|
||||
getglobal("BenillaScriptLogSummary"):SetText(summary)
|
||||
|
||||
@@ -369,7 +369,7 @@
|
||||
</Button>
|
||||
</Frames>
|
||||
<Scripts>
|
||||
<OnLoad>BenillaScriptLogFrame_OnLoad()</OnLoad>
|
||||
<OnLoad>BenillaUiLocalize(this); BenillaScriptLogFrame_OnLoad()</OnLoad>
|
||||
<!-- A spin bubbles up the parent chain; the detail pane's own handler wins there. -->
|
||||
<OnMouseWheel>BenillaScriptLogFrame_OnMouseWheel(arg1)</OnMouseWheel>
|
||||
<OnShow>BenillaScriptLog_Update()</OnShow>
|
||||
|
||||
@@ -7,6 +7,127 @@
|
||||
`UIPanelScrollBarTemplate` does (UIPanelTemplates.xml:156-158); an instance adds nothing.
|
||||
-->
|
||||
<Script><![CDATA[
|
||||
-- Shared captions for our layer: stock labels resolve from the installed GlobalStrings;
|
||||
-- only captions authored by benilla have translations here.
|
||||
local benillaLabelKeys = {
|
||||
["Action Bars"] = "ACTIONBAR_LABEL", ["Ambience Volume"] = "AMBIENCE_VOLUME",
|
||||
["Attack on assist"] = "ASSIST_ATTACK", ["Auto Clear AFK"] = "CLEAR_AFK",
|
||||
["Auto Self Cast"] = "AUTO_SELF_CAST_TEXT", ["Auto-Follow Speed"] = "AUTO_FOLLOW_SPEED",
|
||||
["Block Trades"] = "BLOCK_TRADES", ["Brightness"] = "OPTIONS_BRIGHTNESS", ["Chat"] = "CHAT_LABEL",
|
||||
["Click-to-Move"] = "CLICK_TO_MOVE", ["Close"] = "CLOSE",
|
||||
["Controls"] = "CONTROLS_LABEL", ["Defaults"] = "DEFAULTS",
|
||||
["Disable Spam Filter"] = "DISABLE_SPAM_FILTER", ["Enable All Sound"] = "ENABLE_ALL_SOUND",
|
||||
["Enable Ambience"] = "ENABLE_AMBIENCE", ["Enable Error Speech"] = "ENABLE_ERROR_SPEECH",
|
||||
["Enable Music"] = "ENABLE_MUSIC", ["Enhanced Tooltips"] = "USE_UBERTOOLTIPS",
|
||||
["Environment Detail"] = "ENVIRONMENT_DETAIL", ["Follow Terrain"] = "FOLLOW_TERRAIN",
|
||||
["Head Bob"] = "HEAD_BOB", ["Invert Mouse"] = "INVERT_MOUSE",
|
||||
["Keybindings"] = "KEY_BINDINGS", ["Master Volume"] = "MASTER_VOLUME",
|
||||
["Mouse Look Speed"] = "MOUSE_LOOK_SPEED", ["Mouse Sensitivity"] = "MOUSE_SENSITIVITY",
|
||||
["Music Volume"] = "MUSIC_VOLUME", ["NPC Names"] = "SHOW_NPC_NAMES",
|
||||
["Periodic Damage"] = "LOG_PERIODIC_EFFECTS", ["Pet Damage"] = "SHOW_PET_MELEE_DAMAGE",
|
||||
["Player Guild Names"] = "SHOW_GUILD_NAMES", ["Player Names"] = "SHOW_PLAYER_NAMES",
|
||||
["Player Titles"] = "SHOW_PLAYER_TITLES", ["Profanity Filter"] = "PROFANITY_FILTER",
|
||||
["Search"] = "SEARCH", ["Show Own Name"] = "SHOW_OWN_NAME",
|
||||
["Show Target Damage"] = "SHOW_DAMAGE_TEXT", ["Smart Pivot"] = "SMART_PIVOT",
|
||||
["Sound Volume"] = "SOUND_VOLUME", ["Sticky Targeting"] = "GAMEFIELD_DESELECT_TEXT",
|
||||
["Terrain Distance"] = "FARCLIP", ["UI Scale"] = "UI_SCALE",
|
||||
["Vertical Sync"] = "VERTICAL_SYNC", ["Water Collision"] = "WATER_COLLISION",
|
||||
["Weather Intensity"] = "WEATHER_DETAIL",
|
||||
["Smart"] = "CAMERA_SMART", ["Always"] = "ALWAYS", ["Never"] = "CAMERA_NEVER",
|
||||
["Raid"] = "RAID", ["Party"] = "PARTY", ["Solo"] = "SOLO",
|
||||
["Scroll Up"] = "COMBAT_TEXT_SCROLL_UP", ["Scroll Down"] = "COMBAT_TEXT_SCROLL_DOWN",
|
||||
["Arc"] = "COMBAT_TEXT_SCROLL_ARC",
|
||||
["Always Show ActionBars"] = "ALWAYS_SHOW_MULTIBARS_TEXT",
|
||||
["Automatic Quest Tracking"] = "AUTO_QUEST_WATCH_TEXT",
|
||||
["Buff Durations"] = "SHOW_BUFF_DURATION_TEXT",
|
||||
["Camera Following Style"] = "CAMERA_FOLLOWING_STYLE",
|
||||
["Combat Text Float Mode"] = "COMBAT_TEXT_FLOAT_MODE_LABEL",
|
||||
["Detailed Loot Information"] = "SHOW_LOOT_SPAM",
|
||||
["Enable Floating Combat Text"] = "SHOW_COMBAT_TEXT_TEXT",
|
||||
["Guild Member Alert"] = "GUILDMEMBER_ALERT",
|
||||
["Instant Quest Text"] = "SHOW_QUEST_FADING_TEXT",
|
||||
["Lock ActionBars"] = "LOCK_ACTIONBAR_TEXT", ["Max Camera Distance"] = "MAX_FOLLOW_DIST",
|
||||
["Remove Chat Hover Delay"] = "REMOVE_CHAT_DELAY_TEXT",
|
||||
["Show Auras"] = "COMBAT_TEXT_SHOW_AURAS_TEXT",
|
||||
["Show Chat Bubbles"] = "CHAT_BUBBLES_TEXT",
|
||||
["Show Combat State"] = "COMBAT_TEXT_SHOW_COMBAT_STATE_TEXT",
|
||||
["Show Combo Points"] = "COMBAT_TEXT_SHOW_COMBO_POINTS_TEXT",
|
||||
["Show Damage Reduction"] = "COMBAT_TEXT_SHOW_RESISTANCES_TEXT",
|
||||
["Show Detailed Tooltips"] = "SHOW_NEWBIE_TIPS_TEXT",
|
||||
["Show Dodge/Parries/Misses"] = "COMBAT_TEXT_SHOW_DODGE_PARRY_MISS_TEXT",
|
||||
["Show Energy Gains"] = "COMBAT_TEXT_SHOW_MANA_TEXT",
|
||||
["Show Fading Auras"] = "COMBAT_TEXT_SHOW_AURA_FADE_TEXT",
|
||||
["Show Friendly Healer Names"] = "COMBAT_TEXT_SHOW_FRIENDLY_NAMES_TEXT",
|
||||
["Show Honor Gained"] = "COMBAT_TEXT_SHOW_HONOR_GAINED_TEXT",
|
||||
["Show Loading Screen Tips"] = "SHOW_TIPOFTHEDAY_TEXT",
|
||||
["Show Low Mana and Health"] = "COMBAT_TEXT_SHOW_LOW_HEALTH_MANA_TEXT",
|
||||
["Show Party Chat Bubbles"] = "PARTY_CHAT_BUBBLES_TEXT",
|
||||
["Show Reactive Spells and Abilities"] = "COMBAT_TEXT_SHOW_REACTIVES_TEXT",
|
||||
["Show Reputation"] = "COMBAT_TEXT_SHOW_REPUTATION_TEXT",
|
||||
["Show Target of Target"] = "SHOW_TARGET_OF_TARGET_TEXT", ["Status Bar Text"] = "STATUS_BAR_TEXT",
|
||||
["Show Bottom Left ActionBar"] = "SHOW_MULTIBAR1_TEXT",
|
||||
["Show Bottom Right ActionBar"] = "SHOW_MULTIBAR2_TEXT",
|
||||
["Show Right ActionBar"] = "SHOW_MULTIBAR3_TEXT", ["Show Right ActionBar 2"] = "SHOW_MULTIBAR4_TEXT",
|
||||
["Show Cloak"] = "SHOW_CLOAK", ["Show Helm"] = "SHOW_HELM", ["Show Tutorials"] = "SHOW_TUTORIALS",
|
||||
}
|
||||
local benillaRussianLabels = {
|
||||
["Options"] = "Настройки", ["Game"] = "Игра", ["AddOns"] = "Аддоны",
|
||||
["Gameplay"] = "Игровой процесс", ["System"] = "Система",
|
||||
["Interface"] = "Интерфейс", ["Combat"] = "Бой", ["Graphics"] = "Графика",
|
||||
["Audio"] = "Звук", ["Nameplates"] = "Индикаторы здоровья",
|
||||
["Search Results"] = "Результаты поиска", ["No results found."] = "Ничего не найдено.",
|
||||
["Apply"] = "Применить", ["Auto Loot"] = "Автосбор добычи",
|
||||
["Display Mode"] = "Режим экрана", ["Render Scale"] = "Масштаб рендеринга",
|
||||
["Windowed"] = "Оконный", ["Windowed (Fullscreen)"] = "Оконный (на весь экран)",
|
||||
["Party or Raid"] = "Группа или рейд",
|
||||
["Enable Sound in Background"] = "Звук в фоне", ["Show When"] = "Показывать",
|
||||
["Enemy Name Plates"] = "Индикаторы врагов", ["Friendly Name Plates"] = "Индикаторы союзников",
|
||||
["On"] = "Вкл.", ["Off"] = "Выкл.",
|
||||
["Are you sure you want to reset all keybindings to their defaults?"] =
|
||||
"Сбросить все назначения клавиш к значениям по умолчанию?",
|
||||
["Edit Mode"] = "Режим редактирования", ["Support"] = "Поддержка",
|
||||
["Script Errors"] = "Ошибки скриптов", ["Clear"] = "Очистить",
|
||||
["No problems this session."] = "В этом сеансе ошибок нет.",
|
||||
["1 problem"] = "Одна ошибка", ["%d problems"] = "Ошибок: %d",
|
||||
["%d problems (%d older not kept)"] = "Ошибок: %d (старых не сохранено: %d)",
|
||||
}
|
||||
function BenillaUiText(text)
|
||||
if GetLocale() ~= "ruRU" then return text end
|
||||
local key = benillaLabelKeys[text]
|
||||
return (key and getglobal(key)) or benillaRussianLabels[text] or text
|
||||
end
|
||||
|
||||
-- Lua's byte-wise upper leaves UTF-8 Cyrillic unchanged. Both the labels and the query
|
||||
-- use this fold, so the options search matches Russian regardless of letter case.
|
||||
function BenillaUiUpper(text)
|
||||
local result = string.upper(text)
|
||||
if GetLocale() == "ruRU" then
|
||||
local lower = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
|
||||
local upper = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
|
||||
for i = 1, string.len(lower), 2 do
|
||||
result = string.gsub(result, string.sub(lower, i, i + 1), string.sub(upper, i, i + 1))
|
||||
end
|
||||
end
|
||||
return result
|
||||
end
|
||||
|
||||
-- Called at creation, after the children exist, for static captions owned by our windows.
|
||||
function BenillaUiLocalize(frame)
|
||||
if GetLocale() ~= "ruRU" then return end
|
||||
local function caption(object)
|
||||
if object.GetText and object.SetText then
|
||||
local text = object:GetText()
|
||||
if text then
|
||||
local translated = BenillaUiText(text)
|
||||
if translated ~= text then object:SetText(translated) end
|
||||
end
|
||||
end
|
||||
end
|
||||
caption(frame)
|
||||
for _, region in ipairs({frame:GetRegions()}) do caption(region) end
|
||||
for _, child in ipairs({frame:GetChildren()}) do BenillaUiLocalize(child) end
|
||||
end
|
||||
|
||||
-- One valueStep per step, where the reference's arrows and wheel move half the bar
|
||||
-- (UIPanelTemplates.xml:137/149, UIPanelTemplates.lua:150-157).
|
||||
-- Soundless: the reference plays UChatScrollButton on an arrow click, never on the wheel.
|
||||
|
||||
@@ -1311,7 +1311,8 @@ mod tests {
|
||||
|
||||
/// A locale that registers a row off its base moves the knob at load, so the state a player
|
||||
/// sees (Click-to-Move, windowed, maximized) is the registered default and not the knob's own
|
||||
/// initial value; a locale that does not leaves every knob where it was.
|
||||
/// initial value; a locale that does not leaves every knob where it was. A windowed run
|
||||
/// owns both video knobs for the session and takes precedence over the locale defaults.
|
||||
#[test]
|
||||
fn a_locale_default_reaches_its_knob_at_load() {
|
||||
let boot = |locale: usize| {
|
||||
@@ -1326,14 +1327,20 @@ mod tests {
|
||||
)
|
||||
};
|
||||
use crate::video::DisplayMode::{Fullscreen, Windowed};
|
||||
assert_eq!(boot(0), (Fullscreen, false, false), "enUS");
|
||||
assert_eq!(boot(1), (Fullscreen, false, true), "koKR: Click-to-Move");
|
||||
let session_windowed = crate::video::windowed_env();
|
||||
let initial_mode = if session_windowed {
|
||||
Windowed
|
||||
} else {
|
||||
Fullscreen
|
||||
};
|
||||
assert_eq!(boot(0), (initial_mode, false, false), "enUS");
|
||||
assert_eq!(boot(1), (initial_mode, false, true), "koKR: Click-to-Move");
|
||||
assert_eq!(
|
||||
boot(4),
|
||||
(Windowed, true, false),
|
||||
"zhCN: windowed and maximized"
|
||||
(Windowed, !session_windowed, false),
|
||||
"zhCN: windowed and maximized unless the session owns the video knobs"
|
||||
);
|
||||
assert_eq!(boot(5), (Fullscreen, false, false), "zhTW is not zhCN");
|
||||
assert_eq!(boot(5), (initial_mode, false, false), "zhTW is not zhCN");
|
||||
}
|
||||
|
||||
/// A session-owned row stays the session's: the announce does not overwrite the value an
|
||||
|
||||
@@ -161,7 +161,7 @@ pub(super) fn apply_roster_policy(
|
||||
match roster
|
||||
.chars
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case(&name))
|
||||
.find(|c| same_character_name(&c.name, &name))
|
||||
{
|
||||
Some(c) => {
|
||||
info!("char select: WOW_CHARSELECT_PICK={name} — selecting it");
|
||||
@@ -177,7 +177,7 @@ pub(super) fn apply_roster_policy(
|
||||
match roster
|
||||
.chars
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case(&name))
|
||||
.find(|c| same_character_name(&c.name, &name))
|
||||
{
|
||||
Some(c) => {
|
||||
info!("char select: WOW_CHAR={name} — fast path, by Enter World");
|
||||
@@ -273,3 +273,21 @@ pub(crate) fn test_character(guid: u64, name: &str) -> Character {
|
||||
pet_family: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The server recases names as Unicode, including Cyrillic.
|
||||
fn same_character_name(a: &str, b: &str) -> bool {
|
||||
a.chars()
|
||||
.flat_map(char::to_lowercase)
|
||||
.eq(b.chars().flat_map(char::to_lowercase))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod russian_name_tests {
|
||||
#[test]
|
||||
fn server_recased_cyrillic_names_match_the_typed_pick() {
|
||||
assert!(super::same_character_name("ЁЛОЧКА", "Ёлочка"));
|
||||
assert!(super::same_character_name("ёлочка", "Ёлочка"));
|
||||
assert!(super::same_character_name("ALICE", "Alice"));
|
||||
assert!(!super::same_character_name("Ёлочка", "Елочка"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -513,6 +513,7 @@ fn an_addon_frame_registered_in_uispecialframes_closes_on_escape() {
|
||||
load_xml(&s, r"Interface\FrameXML\UIPanelTemplates.xml");
|
||||
load_xml(&s, r"Interface\FrameXML\GameMenuFrame.xml");
|
||||
load_xml(&s, r"Interface\FrameXML\StaticPopup.xml");
|
||||
load_xml(&s, "ScrollTemplates.xml");
|
||||
load_xml(&s, "GameMenuAdapters.xml");
|
||||
|
||||
s.run(
|
||||
|
||||
@@ -26,6 +26,7 @@ fn harness_with(extra: &[&str]) -> UiScript {
|
||||
r"Interface\FrameXML\UIPanelTemplates.xml",
|
||||
r"Interface\FrameXML\GameMenuFrame.xml",
|
||||
"Interface\\FrameXML\\StaticPopup.xml",
|
||||
"ScrollTemplates.xml",
|
||||
"GameMenuAdapters.xml",
|
||||
];
|
||||
for file in super::test_ui::production_order(&[MENU, extra]) {
|
||||
|
||||
@@ -5,6 +5,111 @@ use benilla_ui::script::{GlueNotice, NoticeState, UiScript};
|
||||
|
||||
use super::glue::{load_glue, set_glue_screen, GlueScreen};
|
||||
|
||||
#[test]
|
||||
fn ruru_stock_glue_loads_and_keeps_cyrillic_character_names() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
let locale = benilla_formats::ClientLocale::RuRu;
|
||||
if locale.pack_folder(&data).is_none() {
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let chain = benilla_formats::Chain::open_localized(&data, locale).unwrap();
|
||||
let _selected = super::reference_ui::fixture::use_chain(chain);
|
||||
let mut script = UiScript::new_glue().unwrap();
|
||||
script.set_russian_language_pack(true);
|
||||
script.set_screen_size(1024.0, 768.0);
|
||||
let failures = load_glue(&mut script);
|
||||
assert!(failures.is_empty(), "{failures:?}");
|
||||
assert_eq!(script.eval::<String>("return GetLocale()").unwrap(), "ruRU");
|
||||
let login: String = script.eval("return LOGIN").unwrap();
|
||||
assert!(login
|
||||
.chars()
|
||||
.any(|c| ('\u{0400}'..='\u{04ff}').contains(&c)));
|
||||
let name = "Абвгдежзийкл";
|
||||
script
|
||||
.run(&format!("CharacterCreateNameEdit:SetText('{name}')"))
|
||||
.unwrap();
|
||||
let field: String = script
|
||||
.eval("return CharacterCreateNameEdit:GetText()")
|
||||
.unwrap();
|
||||
assert_eq!(field, name);
|
||||
assert_eq!(field.chars().count(), 12);
|
||||
assert_eq!(field.len(), 24);
|
||||
assert!(script.take_errors().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruru_delete_confirmation_accepts_typed_cyrillic_without_case_sensitivity() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
let locale = benilla_formats::ClientLocale::RuRu;
|
||||
if locale.pack_folder(&data).is_none() {
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let chain = benilla_formats::Chain::open_localized(&data, locale).unwrap();
|
||||
let _selected = super::reference_ui::fixture::use_chain(chain);
|
||||
let mut script = UiScript::new_glue().unwrap();
|
||||
script.set_russian_language_pack(true);
|
||||
script.set_screen_size(1024.0, 768.0);
|
||||
assert!(load_glue(&mut script).is_empty());
|
||||
// Offline only: exercise the stock buttons and Enter without requesting a real deletion.
|
||||
script
|
||||
.run(
|
||||
"GetCharacterInfo = function() return 'Probe', 'Human', 'Warrior', 1 end; \
|
||||
DELETE_REQUESTS = 0; \
|
||||
DeleteCharacter = function() DELETE_REQUESTS = DELETE_REQUESTS + 1 end; \
|
||||
CharacterSelect.selectedIndex = 1; GlueParent:Show()",
|
||||
)
|
||||
.unwrap();
|
||||
for (typed, accepted) in [
|
||||
("Удалить", true),
|
||||
("удалить", true),
|
||||
("УдАлИтЬ", true),
|
||||
("УДАЛИТЬ", true),
|
||||
("Удали", false),
|
||||
("Удалить!", false),
|
||||
(" Удалить", false),
|
||||
("DELETE", false),
|
||||
("", false),
|
||||
] {
|
||||
for enter in [false, true] {
|
||||
script
|
||||
.run(
|
||||
"CharacterDeleteDialog:Hide(); CharacterDeleteDialog:Show(); \
|
||||
CharacterDeleteEditBox:SetFocus()",
|
||||
)
|
||||
.unwrap();
|
||||
script.tick(0.01);
|
||||
assert_eq!(text(&script, "CharacterDeleteEditBox"), "");
|
||||
for c in typed.chars() {
|
||||
script.char_input(&c.to_string());
|
||||
}
|
||||
script.tick(0.01);
|
||||
assert_eq!(text(&script, "CharacterDeleteEditBox"), typed);
|
||||
assert_eq!(
|
||||
script
|
||||
.eval::<bool>("return CharacterDeleteButton1:IsEnabled() == 1")
|
||||
.unwrap(),
|
||||
accepted,
|
||||
"{typed:?}"
|
||||
);
|
||||
let before: i64 = script.eval("return DELETE_REQUESTS").unwrap();
|
||||
if enter {
|
||||
script.frame_key_input("ENTER");
|
||||
script.key_up("ENTER");
|
||||
} else {
|
||||
script.run("CharacterDeleteButton1:Click()").unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
script.eval::<i64>("return DELETE_REQUESTS").unwrap() - before,
|
||||
i64::from(accepted),
|
||||
"{typed:?}, enter={enter}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(script.take_errors().is_empty());
|
||||
}
|
||||
|
||||
/// The stock glue VM on `screen` with both agreements accepted, as a returning player's is.
|
||||
fn glue_on(screen: GlueScreen) -> UiScript {
|
||||
let mut s = UiScript::new_glue().unwrap();
|
||||
|
||||
@@ -138,6 +138,7 @@ fn new_vm<E: std::fmt::Display>(
|
||||
script.set_european_numbers(european_numbers);
|
||||
// `[0xc0e080]`, which start-up sets once from `Wow.ini`, so every VM answers `GetLocale` alike.
|
||||
script.set_locale(super::client_locale().index());
|
||||
script.set_russian_language_pack(super::client_locale().name() == "ruRU");
|
||||
// `[0x882730]`, `Wow.ini`'s `Region`, read once alike and handed to the name check.
|
||||
script.set_client_region(super::client_region());
|
||||
seed_vm_clock(world, &mut script);
|
||||
|
||||
@@ -8,6 +8,102 @@ fn harness() -> UiScript {
|
||||
harness_on(UiScript::new().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_russian_pack_localizes_the_window_search_and_dropdown_without_changing_values() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
if benilla_formats::ClientLocale::RuRu
|
||||
.pack_folder(&data)
|
||||
.is_none()
|
||||
{
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let mut s = UiScript::new_with_locale("ruRU").unwrap();
|
||||
s.register_cvars(crate::cvars::registered_pairs());
|
||||
s.set_cvar_host("gxWindow", "0");
|
||||
let mut s = harness_on(s);
|
||||
s.run("ShowUIPanel(BenillaOptionsFrame)").unwrap();
|
||||
let labels: Vec<String> = s.eval(r#"
|
||||
local labels = {}
|
||||
for page, rows in pairs(BENILLA_OPTIONS_PAGE_ROWS) do
|
||||
for _, row in ipairs(rows) do
|
||||
local label = getglobal("BenillaOptionsFrameContainerBody" .. page .. row .. "Label")
|
||||
if label then table.insert(labels, label:GetText() or "") end
|
||||
end
|
||||
end
|
||||
return labels
|
||||
"#).unwrap();
|
||||
assert!(labels.len() > 70, "the settings rows were enumerated");
|
||||
for label in labels {
|
||||
assert!(
|
||||
label
|
||||
.chars()
|
||||
.any(|c| ('\u{0400}'..='\u{04ff}').contains(&c)),
|
||||
"unlocalized settings label: {label}"
|
||||
);
|
||||
}
|
||||
assert!(s.eval::<bool>(
|
||||
"return BenillaOptionsFrameContainerTitle:GetText() == CONTROLS_LABEL and CONTROLS_LABEL ~= 'Controls'"
|
||||
).unwrap());
|
||||
assert_eq!(
|
||||
s.eval::<String>("return GameMenuButtonOptions:GetText()")
|
||||
.unwrap(),
|
||||
"Настройки"
|
||||
);
|
||||
assert_eq!(
|
||||
s.eval::<String>("return BenillaUiUpper('МуЗыКа ёж')")
|
||||
.unwrap(),
|
||||
"МУЗЫКА ЁЖ"
|
||||
);
|
||||
for query in ["музы", "МУЗЫ"] {
|
||||
s.run(&format!("BenillaOptionsFrameSearchBox:SetText('{query}')"))
|
||||
.unwrap();
|
||||
s.tick(0.0);
|
||||
assert_eq!(
|
||||
s.eval::<String>("return BenillaOptionsFrameContainerTitle:GetText()")
|
||||
.unwrap(),
|
||||
"Результаты поиска"
|
||||
);
|
||||
assert!(s
|
||||
.eval::<bool>("return BenillaOptionsFrameContainerBodyAudioRowMusic:IsVisible()")
|
||||
.unwrap());
|
||||
assert!(!s
|
||||
.eval::<bool>("return BenillaOptionsFrameContainerBodyNoResults:IsVisible()")
|
||||
.unwrap());
|
||||
}
|
||||
s.run("BenillaOptionsFrameCategoryListRowGraphics:Click()")
|
||||
.unwrap();
|
||||
// Clearing the search drains OnTextChanged on the next frame, restoring the hidden rows.
|
||||
s.tick(0.0);
|
||||
assert!(s.errors().is_empty(), "script errors: {:?}", s.errors());
|
||||
const ROW: &str = "BenillaOptionsFrameContainerBodyGraphicsRowDisplayMode";
|
||||
assert_eq!(
|
||||
s.eval::<String>(&format!("return {ROW}Label:GetText()"))
|
||||
.unwrap(),
|
||||
"Режим экрана"
|
||||
);
|
||||
assert_eq!(
|
||||
s.eval::<String>(&format!("return {ROW}DropdownText:GetText()"))
|
||||
.unwrap(),
|
||||
"Оконный (на весь экран)"
|
||||
);
|
||||
s.take_cvar_changes();
|
||||
s.run(&format!(
|
||||
"{ROW}DropdownButton:Click(); DropDownList1Button2:Click()"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
s.eval::<String>(&format!("return {ROW}DropdownText:GetText()"))
|
||||
.unwrap(),
|
||||
"Оконный"
|
||||
);
|
||||
assert_eq!(
|
||||
s.take_cvar_changes(),
|
||||
vec![("gxWindow".to_string(), "1".to_string())]
|
||||
);
|
||||
assert!(s.errors().is_empty(), "script errors: {:?}", s.errors());
|
||||
}
|
||||
|
||||
/// Load the manifest slice onto `s`, so a page test can seed CVars before the XML loads, as the
|
||||
/// app does. GameTooltip.xml precedes UIDropDownMenu.xml for the kit's `TOOLTIP_DEFAULT_COLOR`.
|
||||
fn harness_on(s: UiScript) -> UiScript {
|
||||
|
||||
@@ -148,7 +148,11 @@ fn open(data: Option<std::path::PathBuf>) -> (Option<Chain>, Option<Notice>) {
|
||||
)),
|
||||
);
|
||||
};
|
||||
match benilla_formats::open_chain(&data) {
|
||||
#[cfg(test)]
|
||||
let opened = Chain::open(&data);
|
||||
#[cfg(not(test))]
|
||||
let opened = Chain::open_client(&data);
|
||||
match opened {
|
||||
Ok(chain) => (Some(chain), None),
|
||||
Err(e) => (
|
||||
None,
|
||||
@@ -223,6 +227,7 @@ pub(super) mod fixture {
|
||||
|
||||
thread_local! {
|
||||
static OVERLAY: RefCell<HashMap<String, Option<Vec<u8>>>> = RefCell::new(HashMap::new());
|
||||
static SELECTED_CHAIN: RefCell<Option<benilla_formats::Chain>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
fn key(path: &str) -> String {
|
||||
@@ -243,7 +248,30 @@ pub(super) mod fixture {
|
||||
|
||||
/// The overlay's answer for `path`, `None` when it has no entry.
|
||||
pub(super) fn read(path: &str) -> Option<Option<Vec<u8>>> {
|
||||
OVERLAY.with(|o| o.borrow().get(&key(path)).cloned())
|
||||
OVERLAY
|
||||
.with(|o| o.borrow().get(&key(path)).cloned())
|
||||
.or_else(|| {
|
||||
SELECTED_CHAIN
|
||||
.with(|chain| chain.borrow().as_ref().map(|chain| chain.read(path).ok()))
|
||||
})
|
||||
}
|
||||
|
||||
/// Read a selected language chain through the production loader on this test thread.
|
||||
pub(in crate::ui_script) fn use_chain(chain: benilla_formats::Chain) -> ChainGuard {
|
||||
SELECTED_CHAIN.with(|selected| {
|
||||
let mut selected = selected.borrow_mut();
|
||||
assert!(selected.is_none(), "a chain fixture cannot nest");
|
||||
*selected = Some(chain);
|
||||
});
|
||||
ChainGuard
|
||||
}
|
||||
pub(in crate::ui_script) struct ChainGuard;
|
||||
impl Drop for ChainGuard {
|
||||
fn drop(&mut self) {
|
||||
SELECTED_CHAIN.with(|selected| {
|
||||
selected.borrow_mut().take();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the overlay on drop.
|
||||
|
||||
@@ -45,6 +45,54 @@ fn the_whole_shipped_manifest_loads_without_errors() {
|
||||
assert!(s.errors().is_empty(), "script errors: {:?}", s.errors());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_russian_pack_loads_the_complete_interface_and_takes_variables_loaded() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
let locale = benilla_formats::ClientLocale::RuRu;
|
||||
if locale.pack_folder(&data).is_none() {
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let chain = benilla_formats::Chain::open_localized(&data, locale).unwrap();
|
||||
let _selected = super::reference_ui::fixture::use_chain(chain);
|
||||
let mut s = benilla_ui::script::UiScript::new_with_locale(locale.code()).unwrap();
|
||||
s.set_screen_size(1024.0, 768.0);
|
||||
s.set_unit(
|
||||
"player",
|
||||
Some(benilla_ui::script::UnitState {
|
||||
exists: true,
|
||||
name: Some("Probefour".into()),
|
||||
level: 60,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
let failures = super::load_default_ui(&s);
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"Russian manifest load errors: {failures:#?}"
|
||||
);
|
||||
assert!(s
|
||||
.eval::<bool>("return GetLocale() == 'ruRU' and LOCALE_ruRU == true")
|
||||
.unwrap());
|
||||
let cancel = s.eval::<String>("return CANCEL").unwrap();
|
||||
assert!(cancel
|
||||
.chars()
|
||||
.any(|c| ('\u{0400}'..='\u{04ff}').contains(&c)));
|
||||
assert_eq!(
|
||||
s.eval::<String>("return GameMenuButtonOptions:GetText()")
|
||||
.unwrap(),
|
||||
"Настройки"
|
||||
);
|
||||
s.fire_event("VARIABLES_LOADED", vec![]);
|
||||
s.run("ShowUIPanel(BenillaOptionsFrame)").unwrap();
|
||||
s.resolve();
|
||||
assert!(
|
||||
s.errors().is_empty(),
|
||||
"Russian interface script errors: {:?}",
|
||||
s.errors()
|
||||
);
|
||||
}
|
||||
|
||||
/// Loading the UI makes no sound: a dropdown's OnLoad runs `UIDropDownMenu_Initialize`, which calls
|
||||
/// its init at once (`UIDropDownMenu.lua:50`), and a unit popup's init reaches `UnitPopup_ShowMenu`
|
||||
/// and its closing `PlaySound("igMainMenuOpen")` unless `UnitPopup_HideButtons` leaves only CANCEL
|
||||
|
||||
@@ -116,6 +116,26 @@ fn load_entry(s: &UiScript, entry: &str, strict_templates: bool, no_warnings: bo
|
||||
// The app registers its CVars before any file loads: stock `UIOptionsFrame.xml` reads two
|
||||
// camera CVars at `OnLoad` and raises on a nil. A value a test already set stands.
|
||||
s.register_cvars(crate::cvars::registered_pairs());
|
||||
// A localized VM reads the same selected patch chain as production; English kits keep the
|
||||
// raw reference chain, independent of the process's WOW_LOCALE.
|
||||
let chain = match s.eval::<String>("return GetLocale()").unwrap().as_str() {
|
||||
"ruRU" => Some(
|
||||
benilla_formats::Chain::open_localized(
|
||||
&benilla_formats::wow_data().expect("a localized kit needs client data"),
|
||||
benilla_formats::ClientLocale::RuRu,
|
||||
)
|
||||
.expect("the selected language pack"),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let read = |req: &str| {
|
||||
if let Some(chain) = &chain {
|
||||
if super::reference_ui::is_chain_entry(req) {
|
||||
return chain.read(req).ok();
|
||||
}
|
||||
}
|
||||
read(req)
|
||||
};
|
||||
let path = entry.replace('\\', "/");
|
||||
let bytes = read(&path).unwrap_or_else(|| panic!("{entry}: not found"));
|
||||
if path.to_ascii_lowercase().ends_with(".lua") {
|
||||
|
||||
@@ -53,6 +53,87 @@ fn roster_named(name: &str, guid: u64) -> Roster {
|
||||
Roster::with_pending_pick(vec![row], guid)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruru_player_names_reach_the_character_panel_and_live_units() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
if benilla_formats::ClientLocale::RuRu
|
||||
.pack_folder(&data)
|
||||
.is_none()
|
||||
{
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
for (locale, race, class, line) in [
|
||||
(
|
||||
benilla_formats::ClientLocale::RuRu,
|
||||
"Человек",
|
||||
"Воин",
|
||||
"Человек, Воин 60-го уровня",
|
||||
),
|
||||
(
|
||||
benilla_formats::ClientLocale::EnUs,
|
||||
"Human",
|
||||
"Warrior",
|
||||
"Level 60 Human Warrior",
|
||||
),
|
||||
] {
|
||||
let mut chain = benilla_formats::Chain::open_localized(&data, locale).unwrap();
|
||||
let races = benilla_formats::load_chr_races(&mut chain).unwrap();
|
||||
let classes = benilla_formats::load_chr_classes(&mut chain).unwrap();
|
||||
let names = crate::ui_unit::UnitNames {
|
||||
races: Some(&races),
|
||||
classes: Some(&classes),
|
||||
};
|
||||
let roster = roster_named("Александр", 7);
|
||||
let record = super::lifecycle::record_from_roster(&roster, names).unwrap();
|
||||
let mut seat = super::seat_from_roster(&roster, names).unwrap();
|
||||
seat.level = 60;
|
||||
let mut vm = benilla_ui::script::UiScript::new_with_locale(locale.code()).unwrap();
|
||||
vm.set_screen_size(1024.0, 768.0);
|
||||
vm.set_player_record(record);
|
||||
vm.set_unit("player", Some(seat));
|
||||
for file in super::test_ui::CHARACTER_UI {
|
||||
super::test_ui::load_ui_strict(&vm, file);
|
||||
}
|
||||
vm.run("PaperDollFrame_SetLevel()").unwrap();
|
||||
let shown: String = vm.eval("return CharacterLevelText:GetText()").unwrap();
|
||||
eprintln!("locale-panel: {} text={shown}", locale.code());
|
||||
assert_eq!(shown, line);
|
||||
assert_eq!(
|
||||
vm.eval::<(String, String)>("return UnitRace('player')")
|
||||
.unwrap(),
|
||||
(race.into(), "Human".into())
|
||||
);
|
||||
assert_eq!(
|
||||
vm.eval::<(String, String)>("return UnitClass('player')")
|
||||
.unwrap(),
|
||||
(class.into(), "WARRIOR".into())
|
||||
);
|
||||
// The descriptor path, including a /reload seat, and a different race/class on target.
|
||||
for (race_id, class_id) in [(1, 1), (6, 11)] {
|
||||
let store = crate::net::ObjectStore(benilla_protocol::ObjectFields::from_pairs(&[(
|
||||
36,
|
||||
race_id | (class_id << 8),
|
||||
)]));
|
||||
let state = crate::ui_unit::snapshot(&store, 8, None, 0, names, Default::default());
|
||||
assert_eq!(
|
||||
state.race.as_deref(),
|
||||
Some(names.race(race_id as u8).unwrap().0)
|
||||
);
|
||||
assert_eq!(
|
||||
state.class.as_deref(),
|
||||
Some(names.class(class_id as u8).unwrap().0)
|
||||
);
|
||||
vm.set_unit("target", Some(state));
|
||||
assert_eq!(
|
||||
vm.eval::<String>("return UnitClass('target')").unwrap(),
|
||||
names.class(class_id as u8).unwrap().0
|
||||
);
|
||||
}
|
||||
assert!(vm.take_errors().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
/// A hermetic state folder holding the probe addon, and the guards that point the client at it;
|
||||
/// every guard must outlive the world.
|
||||
fn hermetic_probe(tag: &str) -> (std::path::PathBuf, EnvGuard, EnvGuard) {
|
||||
|
||||
@@ -33,7 +33,7 @@ use cosmic_text::{
|
||||
Attrs, Buffer, CacheKey, CacheKeyFlags, Family, FontSystem, Metrics, Shaping, SwashCache, Wrap,
|
||||
};
|
||||
|
||||
use benilla_assets::WorldAssets;
|
||||
use benilla_assets::{LockRecover, WorldAssets};
|
||||
|
||||
use faces::{charmap_glyph, hhea_ascent_ratio, register_font, unicode_charmap, CLIENT_FONTS};
|
||||
pub(crate) use gpu::{FontAtlasInit, UiTextPlugin};
|
||||
@@ -162,15 +162,16 @@ pub(crate) struct TextEngine {
|
||||
/// face. A character its own face's charmap lacks draws and measures nothing, as in the reference
|
||||
/// ([`TextEngine::ensure_char`]). The locale only picks which language's family name a face
|
||||
/// answers to.
|
||||
fn client_font_system() -> FontSystem {
|
||||
FontSystem::new_with_locale_and_db("en-US".to_string(), fontdb::Database::new())
|
||||
fn client_font_system(locale: benilla_formats::Locale) -> FontSystem {
|
||||
let (language, country) = locale.name().split_at(2);
|
||||
FontSystem::new_with_locale_and_db(format!("{language}-{country}"), fontdb::Database::new())
|
||||
}
|
||||
|
||||
impl TextEngine {
|
||||
/// Register the client TTFs, each read as a font face opens ([`read_font_bytes`]); `None`, and
|
||||
/// no text, without Friz Quadrata.
|
||||
fn load(world_assets: &WorldAssets, images: &Assets<Image>, dpi: f32) -> Option<Self> {
|
||||
let mut font_system = client_font_system();
|
||||
let mut font_system = client_font_system(world_assets.chain.lock_recover().locale());
|
||||
let mut faces: Vec<Face> = Vec::new();
|
||||
let mut path_to_face = HashMap::new();
|
||||
let source = FontSource {
|
||||
@@ -749,7 +750,15 @@ fn read_font_bytes(source: &FontSource, path: &str) -> Option<Vec<u8>> {
|
||||
pub(super) fn test_engine(dpi: f32) -> Option<TextEngine> {
|
||||
let data = benilla_formats::wow_data()?;
|
||||
let chain = benilla_formats::open_chain(&data).ok()?;
|
||||
let mut font_system = client_font_system();
|
||||
test_engine_from_chain(chain, dpi)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn test_engine_from_chain(
|
||||
chain: benilla_formats::Chain,
|
||||
dpi: f32,
|
||||
) -> Option<TextEngine> {
|
||||
let mut font_system = client_font_system(chain.locale());
|
||||
let mut faces: Vec<Face> = Vec::new();
|
||||
let mut path_to_face = HashMap::new();
|
||||
for &path in CLIENT_FONTS {
|
||||
@@ -1160,6 +1169,38 @@ mod ppem_tests {
|
||||
use super::*;
|
||||
use benilla_assets::LockRecover;
|
||||
|
||||
#[test]
|
||||
fn the_russian_pack_rasterizes_cyrillic_in_every_client_face() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
let locale = benilla_formats::ClientLocale::RuRu;
|
||||
if locale.pack_folder(&data).is_none() {
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let chain = benilla_formats::Chain::open_localized(&data, locale).unwrap();
|
||||
let mut e = test_engine_from_chain(chain, 1.0).expect("localized client fonts");
|
||||
for &path in TEST_FACES {
|
||||
let face = e.face_for(Some(path));
|
||||
assert_eq!(e.faces[face].path, path);
|
||||
e.ensure_str(face, 16, 0, "АаЯяЁё");
|
||||
for ch in "АаЯяЁё".chars() {
|
||||
let shaped = e
|
||||
.char_cell(face, 16, ch)
|
||||
.expect("a Cyrillic character shaped");
|
||||
assert!(!shaped.glyphs.is_empty(), "{path}: {ch}");
|
||||
for glyph in &shaped.glyphs {
|
||||
assert_ne!(glyph.glyph_id, 0, "{path}: {ch} must not be .notdef");
|
||||
let cell = e.cell(face, 16, 0, glyph.glyph_id).expect("Cyrillic ink");
|
||||
assert!(cell.px_w > 0.0 && cell.px_h > 0.0, "{path}: {ch}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
e.substituted.is_empty(),
|
||||
"Cyrillic uses the selected client faces"
|
||||
);
|
||||
}
|
||||
|
||||
fn engine_or_skip() -> Option<TextEngine> {
|
||||
match test_engine(1.0) {
|
||||
Some(e) => Some(e),
|
||||
|
||||
@@ -65,8 +65,8 @@ pub(super) struct ViewCtx<'a, 'w, 's> {
|
||||
|
||||
/// Build one spell's tooltip view, every cell resolved here where the catalogs live, and what it
|
||||
/// read ([`Deps`]). The range, cast, cooldown, form and item cells fill their `GlobalStrings.lua`
|
||||
/// keys; the cost, reagents and chance cells are composed in English, where the reference fills
|
||||
/// `MANA_COST` and its kin, `SPELL_REAGENTS` and `CHANCE_TO_*`.
|
||||
/// keys, including the power-specific cost templates; the reagents and chance cells are composed
|
||||
/// in English, where the reference fills `SPELL_REAGENTS` and `CHANCE_TO_*`.
|
||||
pub(super) fn build_view(
|
||||
spell_id: u32,
|
||||
spells: &Spells,
|
||||
@@ -155,24 +155,27 @@ pub(super) fn build_view(
|
||||
let cost = {
|
||||
// The shared per-type divisor (`0x6e7130`), never a local `power_type == 1` test.
|
||||
let div = benilla_protocol::messages::power_display_scale(d.power_type);
|
||||
let unit = match d.power_type {
|
||||
0 => "Mana",
|
||||
1 => "Rage",
|
||||
2 => "Focus",
|
||||
3 => "Energy",
|
||||
4 => "Happiness",
|
||||
_ => "Health",
|
||||
let key = match d.power_type {
|
||||
0 => "MANA_COST",
|
||||
1 => "RAGE_COST",
|
||||
2 => "FOCUS_COST",
|
||||
3 => "ENERGY_COST",
|
||||
4 => "HAPPINESS_COST",
|
||||
_ => "HEALTH_COST",
|
||||
};
|
||||
if resolved_cost == 0 && d.mana_per_second == 0 {
|
||||
None
|
||||
} else if d.mana_per_second > 0 {
|
||||
Some(format!(
|
||||
"{} {unit}, plus {} per sec",
|
||||
resolved_cost / div,
|
||||
d.mana_per_second / div
|
||||
))
|
||||
keyed(
|
||||
vctx.get,
|
||||
&format!("{key}_PER_TIME"),
|
||||
&[
|
||||
Arg::from(resolved_cost / div),
|
||||
Arg::from(d.mana_per_second / div),
|
||||
],
|
||||
)
|
||||
} else {
|
||||
Some(format!("{} {unit}", resolved_cost / div))
|
||||
keyed(vctx.get, key, &[Arg::from(resolved_cost / div)])
|
||||
}
|
||||
};
|
||||
// The range cell: two attribute gates, `GetMinMaxRange` (`0x6e3480`, `0x52e9c2`), then
|
||||
|
||||
@@ -33,9 +33,13 @@ type Getter = dyn Fn(&str) -> Option<String>;
|
||||
|
||||
impl TestCtx {
|
||||
pub(super) fn new() -> Self {
|
||||
let (tx, rx) = crossbeam_channel::unbounded();
|
||||
let vm = benilla_ui::script::UiScript::new().expect("VM");
|
||||
crate::ui_script::load_ui_for_test(&vm, "Interface\\FrameXML\\GlobalStrings.lua");
|
||||
Self::with_vm(vm)
|
||||
}
|
||||
|
||||
fn with_vm(vm: benilla_ui::script::UiScript) -> Self {
|
||||
let (tx, rx) = crossbeam_channel::unbounded();
|
||||
Self {
|
||||
items: Items::default(),
|
||||
commands: NetCommands(tx),
|
||||
@@ -105,6 +109,63 @@ impl TestCtx {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruru_spell_costs_use_the_packs_templates() {
|
||||
let data = benilla_formats::wow_data_or_skip!();
|
||||
if benilla_formats::ClientLocale::RuRu
|
||||
.pack_folder(&data)
|
||||
.is_none()
|
||||
{
|
||||
benilla_formats::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let Some(spells) = real_spells() else { return };
|
||||
let mut objs = no_objects();
|
||||
let objects = objs.get();
|
||||
let store = ObjectStore(unit(60, 1000));
|
||||
for (locale, expected) in [
|
||||
(
|
||||
"ruRU",
|
||||
[
|
||||
"Мана: 30",
|
||||
"Ярость: 15",
|
||||
"Энергия: 45",
|
||||
"Здоровье: 11 плюс 5/сек.",
|
||||
],
|
||||
),
|
||||
(
|
||||
"enUS",
|
||||
[
|
||||
"30 Mana",
|
||||
"15 Rage",
|
||||
"45 Energy",
|
||||
"11 Health, plus 5 per sec",
|
||||
],
|
||||
),
|
||||
] {
|
||||
let vm = benilla_ui::script::UiScript::new_with_locale(locale).unwrap();
|
||||
crate::ui_script::load_ui_for_test(&vm, "Interface\\FrameXML\\GlobalStrings.lua");
|
||||
let mut t = TestCtx::with_vm(vm);
|
||||
for (id, expected) in [133, 78, 1752, 755].into_iter().zip(expected) {
|
||||
let view =
|
||||
spell_tooltip_view(id, &spells, &mut t.ctx_for(&objects, 0, None, Some(&store)))
|
||||
.unwrap();
|
||||
eprintln!("locale-cost: {locale} spell={id} cost={:?}", view.cost);
|
||||
assert_eq!(view.cost.as_deref(), Some(expected));
|
||||
}
|
||||
let view = spell_tooltip_view(
|
||||
100,
|
||||
&spells,
|
||||
&mut t.ctx_for(&objects, 0, None, Some(&store)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
view.cost, None,
|
||||
"Charge has no resource cost in either locale"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit's fields: level (34) and base mana (162).
|
||||
fn unit(level: u32, base_mana: u32) -> benilla_protocol::ObjectFields {
|
||||
benilla_protocol::ObjectFields::from_pairs(&[(22u16, 100u32), (34, level), (162, base_mana)])
|
||||
|
||||
@@ -85,6 +85,8 @@ const VERDICTS: &[(&str, Verdict)] = &[
|
||||
("CustomCursorImage", Plumbing),
|
||||
("InputPlugin", Plumbing),
|
||||
("WinitPlugin", Plumbing),
|
||||
// MoonWell's startup uses the native window handles to set icons, without reading input.
|
||||
("WINIT_WINDOWS", Plumbing),
|
||||
("InputSystems", Plumbing),
|
||||
("Key", Plumbing),
|
||||
("KeyCode", Plumbing),
|
||||
|
||||
@@ -71,7 +71,7 @@ impl MpqAssetReader {
|
||||
/// Open the patch chain from a `Data` directory or a single `.MPQ`.
|
||||
pub fn open(data_dir: &Path) -> Result<Self> {
|
||||
Ok(Self {
|
||||
chain: Arc::new(Chain::open(data_dir)?),
|
||||
chain: Arc::new(Chain::open_client(data_dir)?),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -575,7 +575,7 @@ mod tests {
|
||||
/// preset 1 by texel × fade.
|
||||
#[test]
|
||||
fn a_fade_twin_blends_by_the_stage_zero_alpha_op() {
|
||||
let src = include_str!("shaders/wow_model.wgsl");
|
||||
let src = include_str!("shaders/wow_model.wgsl").replace("\r\n", "\n");
|
||||
for (line, why) in [
|
||||
(
|
||||
"faded_alpha = stage_alpha(u32(m.stage1.z) - 1u, obj_fade, tex0_alpha);",
|
||||
|
||||
@@ -109,6 +109,38 @@ impl Chain {
|
||||
self.locale
|
||||
}
|
||||
|
||||
/// Deviation: the launcher selects a community pack through WOW_LOCALE, or auto-detects
|
||||
/// Data/ruRU. Without an override the stock Wow.ini locale remains authoritative.
|
||||
pub fn open_client(path: &Path) -> Result<Self> {
|
||||
match std::env::var("WOW_LOCALE") {
|
||||
Ok(code) if !code.eq_ignore_ascii_case("auto") => {
|
||||
Self::open_localized(path, crate::ClientLocale::from_code(&code)?)
|
||||
}
|
||||
Ok(_) | Err(std::env::VarError::NotPresent) => {
|
||||
if crate::ClientLocale::RuRu.pack_folder(path).is_some() {
|
||||
Self::open_localized(path, crate::ClientLocale::RuRu)
|
||||
} else {
|
||||
Self::open(path)
|
||||
}
|
||||
}
|
||||
Err(error) => Err(error).context("reading WOW_LOCALE"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Mount the requested language after the base archives, with its own authentication tag.
|
||||
/// Deviation: community ruRU archives overlay the 1.12 chain and use DBC string column zero.
|
||||
pub fn open_localized(path: &Path, pack: crate::ClientLocale) -> Result<Self> {
|
||||
let mut chain = Self::open(path)?;
|
||||
if pack == crate::ClientLocale::RuRu {
|
||||
let folder = pack
|
||||
.pack_folder(path)
|
||||
.context("ruRU language pack is not installed")?;
|
||||
chain.archives.extend(Self::open(&folder)?.archives);
|
||||
}
|
||||
chain.locale = Locale::for_language_pack(pack);
|
||||
Ok(chain)
|
||||
}
|
||||
|
||||
/// The same archives read as another locale, for a test of the column a loader reads.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_locale(mut self, locale: Locale) -> Self {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Localized display names from the 1.12 ChrRaces and ChrClasses name blocks.
|
||||
//! The community ruRU patch stores its translated names in locale slot zero.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use benilla_dbc::{FieldType, Schema, SchemaField};
|
||||
|
||||
use crate::dbc::{parse, str_at, u32_at};
|
||||
use crate::Chain;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
/// The display names, distinct from the unlocalized race/class file tokens.
|
||||
pub struct CharacterNames {
|
||||
races: HashMap<u32, String>,
|
||||
classes: HashMap<u32, String>,
|
||||
}
|
||||
|
||||
impl CharacterNames {
|
||||
pub fn load(chain: &mut Chain) -> Result<Self> {
|
||||
Ok(Self {
|
||||
races: load_names(chain, "ChrRaces", 29, 17)?,
|
||||
classes: load_names(chain, "ChrClasses", 17, 5)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn race(&self, id: u8) -> Option<&str> {
|
||||
self.races.get(&u32::from(id)).map(String::as_str)
|
||||
}
|
||||
|
||||
pub fn class(&self, id: u8) -> Option<&str> {
|
||||
self.classes.get(&u32::from(id)).map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn load_names(
|
||||
chain: &mut Chain,
|
||||
table: &str,
|
||||
fields: usize,
|
||||
name_field: usize,
|
||||
) -> Result<HashMap<u32, String>> {
|
||||
let path = format!("DBFilesClient\\{table}.dbc");
|
||||
let bytes = chain
|
||||
.read_file(&path)
|
||||
.with_context(|| format!("reading {path}"))?;
|
||||
let mut schema = Schema::new(table);
|
||||
for i in 0..fields {
|
||||
schema.add_field(SchemaField::new(
|
||||
format!("F{i}"),
|
||||
if i == name_field {
|
||||
FieldType::String
|
||||
} else {
|
||||
FieldType::UInt32
|
||||
},
|
||||
));
|
||||
}
|
||||
let rows = parse(&bytes, schema, table)?;
|
||||
Ok(rows
|
||||
.records()
|
||||
.iter()
|
||||
.filter_map(|r| {
|
||||
let id = u32_at(r, 0)?;
|
||||
let name = str_at(&rows, r, name_field)?;
|
||||
(!name.is_empty()).then_some((id, name))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ClientLocale;
|
||||
|
||||
#[test]
|
||||
fn character_names_follow_the_selected_patch_chain() {
|
||||
let data = crate::wow_data_or_skip!();
|
||||
let mut english = Chain::open(&data).unwrap();
|
||||
let names = CharacterNames::load(&mut english).unwrap();
|
||||
assert_eq!(names.race(1), Some("Human"));
|
||||
assert_eq!(names.class(1), Some("Warrior"));
|
||||
assert_eq!(names.race(255), None);
|
||||
assert_eq!(names.class(255), None);
|
||||
if ClientLocale::RuRu.pack_folder(&data).is_none() {
|
||||
crate::skipped_optional("no ruRU language pack", &[data.join("ruRU")]);
|
||||
return;
|
||||
}
|
||||
let mut russian = Chain::open_localized(&data, ClientLocale::RuRu).unwrap();
|
||||
let names = CharacterNames::load(&mut russian).unwrap();
|
||||
assert_eq!(names.race(1), Some("Человек"));
|
||||
assert_eq!(names.class(1), Some("Воин"));
|
||||
assert_eq!(names.race(6), Some("Таурен"));
|
||||
assert_eq!(names.class(11), Some("Друид"));
|
||||
for id in 1..=8 {
|
||||
assert!(names
|
||||
.race(id)
|
||||
.unwrap()
|
||||
.chars()
|
||||
.any(|c| ('\u{0400}'..='\u{04ff}').contains(&c)));
|
||||
}
|
||||
for id in [1, 2, 3, 4, 5, 7, 8, 9, 11] {
|
||||
assert!(names
|
||||
.class(id)
|
||||
.unwrap()
|
||||
.chars()
|
||||
.any(|c| ('\u{0400}'..='\u{04ff}').contains(&c)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,18 @@ pub fn skipped(what: &str, looked_in: &[PathBuf]) {
|
||||
what,
|
||||
looked_in,
|
||||
);
|
||||
log_skip(what);
|
||||
}
|
||||
|
||||
/// A test requiring optional data (such as a language pack) records a skip even when the base
|
||||
/// install is required. A pack that exists but fails to open must still fail its test.
|
||||
#[doc(hidden)]
|
||||
pub fn skipped_optional(what: &str, looked_in: &[PathBuf]) {
|
||||
skipped_under(false, what, looked_in);
|
||||
log_skip(what);
|
||||
}
|
||||
|
||||
fn log_skip(what: &str) {
|
||||
// `$BENILLA_SKIP_LOG`: libtest hides the line above, so the gate counts skips from this file.
|
||||
if let Some(log) = std::env::var_os("BENILLA_SKIP_LOG").filter(|p| !p.is_empty()) {
|
||||
use std::io::Write;
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! The language of the client data, Lua UI and realmd challenge.
|
||||
//!
|
||||
//! Deviation: the community 1.12 ruRU pack lives in `Data/ruRU` and overlays the vanilla chain.
|
||||
//! Its DBCs keep the 1.12 layout and put Russian strings in slot zero, like the base tables.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
|
||||
/// The supported language packs. English reads the original vanilla chain unchanged.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum ClientLocale {
|
||||
#[default]
|
||||
EnUs,
|
||||
RuRu,
|
||||
}
|
||||
|
||||
impl ClientLocale {
|
||||
/// The spelling returned by `GetLocale` and sent to realmd.
|
||||
pub const fn code(self) -> &'static str {
|
||||
match self {
|
||||
Self::EnUs => "enUS",
|
||||
Self::RuRu => "ruRU",
|
||||
}
|
||||
}
|
||||
|
||||
/// The four-character auth tag, before the protocol reverses its byte order.
|
||||
pub const fn auth_tag(self) -> [u8; 4] {
|
||||
match self {
|
||||
Self::EnUs => *b"enUS",
|
||||
Self::RuRu => *b"ruRU",
|
||||
}
|
||||
}
|
||||
|
||||
/// The optional language-pack folder under `Data`, found case-insensitively.
|
||||
pub fn pack_folder(self, data: &Path) -> Option<PathBuf> {
|
||||
locale_folder(data, self)
|
||||
}
|
||||
|
||||
/// The language tag used for localized font family names.
|
||||
pub const fn language_tag(self) -> &'static str {
|
||||
match self {
|
||||
Self::EnUs => "en-US",
|
||||
Self::RuRu => "ru-RU",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an explicit language; unknown values fail rather than silently loading another one.
|
||||
pub fn from_code(code: &str) -> Result<Self> {
|
||||
if code.eq_ignore_ascii_case("enUS") {
|
||||
Ok(Self::EnUs)
|
||||
} else if code.eq_ignore_ascii_case("ruRU") {
|
||||
Ok(Self::RuRu)
|
||||
} else {
|
||||
bail!("unsupported client locale {code:?}; expected enUS, ruRU or auto");
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime selection: `$WOW_LOCALE=enUS|ruRU|auto`; unset or `auto` uses an installed ruRU
|
||||
/// folder, otherwise English. Selection is made before any client resources load.
|
||||
pub fn for_install(data: &Path) -> Result<Self> {
|
||||
let selected = std::env::var("WOW_LOCALE").context("reading WOW_LOCALE");
|
||||
match selected {
|
||||
Ok(value) => Self::select(data, Some(&value)),
|
||||
Err(_) if std::env::var_os("WOW_LOCALE").is_none() => Self::select(data, None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn select(data: &Path, value: Option<&str>) -> Result<Self> {
|
||||
match value {
|
||||
Some(code) if !code.eq_ignore_ascii_case("auto") => Self::from_code(code),
|
||||
_ => Ok(if locale_folder(data, Self::RuRu).is_some() {
|
||||
Self::RuRu
|
||||
} else {
|
||||
Self::EnUs
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the locale directory case-insensitively, including on a case-sensitive filesystem.
|
||||
pub(crate) fn locale_folder(data: &Path, locale: ClientLocale) -> Option<PathBuf> {
|
||||
let mut folders: Vec<_> = std::fs::read_dir(data)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| {
|
||||
entry.path().is_dir()
|
||||
&& entry
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.eq_ignore_ascii_case(locale.code())
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
folders.sort();
|
||||
folders.into_iter().next()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selection_is_explicit_and_unknown_values_are_errors() {
|
||||
let absent = Path::new("/no-client-data-here");
|
||||
assert_eq!(
|
||||
ClientLocale::select(absent, None).unwrap(),
|
||||
ClientLocale::EnUs
|
||||
);
|
||||
assert_eq!(
|
||||
ClientLocale::select(absent, Some("auto")).unwrap(),
|
||||
ClientLocale::EnUs
|
||||
);
|
||||
assert_eq!(
|
||||
ClientLocale::select(absent, Some("RURU")).unwrap(),
|
||||
ClientLocale::RuRu
|
||||
);
|
||||
for invalid in ["", "frFR", "../ruRU"] {
|
||||
assert!(ClientLocale::select(absent, Some(invalid)).is_err());
|
||||
}
|
||||
assert_eq!(ClientLocale::RuRu.auth_tag(), *b"ruRU");
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,10 @@ pub use benilla_blp::BlpTexels;
|
||||
|
||||
mod chain;
|
||||
pub use chain::{Chain, ChainEntry};
|
||||
mod language_pack;
|
||||
pub use language_pack::ClientLocale;
|
||||
mod character_names;
|
||||
pub use character_names::CharacterNames;
|
||||
/// Loose `.tga` art, as addon folders ship it.
|
||||
mod tga;
|
||||
pub use tga::tga_to_rgba;
|
||||
@@ -20,7 +24,7 @@ pub use tga::tga_to_rgba;
|
||||
mod install;
|
||||
pub use install::{
|
||||
addon_corpus, addon_corpus_candidates, candidates, project_folder, set_project_folder, skipped,
|
||||
wow_data,
|
||||
skipped_optional, wow_data,
|
||||
};
|
||||
/// The install's loose files, asked before the archives by the opens that set the loose flag.
|
||||
mod loose;
|
||||
|
||||
@@ -17,6 +17,7 @@ pub const LOCALE_NAMES: [&str; 8] = [
|
||||
pub struct Locale {
|
||||
index: u8,
|
||||
tag: u32,
|
||||
community_ru: bool,
|
||||
}
|
||||
|
||||
impl Locale {
|
||||
@@ -37,6 +38,18 @@ impl Locale {
|
||||
Self {
|
||||
index: index as u8,
|
||||
tag,
|
||||
community_ru: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Deviation: the community ruRU overlay uses column zero, but Lua and authentication must
|
||||
/// name its actual language; ruRU is absent from the stock eight-column locale table.
|
||||
pub(crate) fn for_language_pack(pack: crate::ClientLocale) -> Self {
|
||||
let code = pack.code().as_bytes();
|
||||
Self {
|
||||
index: 0,
|
||||
tag: u32::from_be_bytes(code.try_into().expect("four-byte locale code")),
|
||||
community_ru: pack == crate::ClientLocale::RuRu,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +66,11 @@ impl Locale {
|
||||
|
||||
/// The name at the index, as `GetLocale` answers it (`0x48d8b0`).
|
||||
pub fn name(self) -> &'static str {
|
||||
LOCALE_NAMES[self.index()]
|
||||
if self.community_ru {
|
||||
"ruRU"
|
||||
} else {
|
||||
LOCALE_NAMES[self.index()]
|
||||
}
|
||||
}
|
||||
|
||||
/// The packed configured string, `[0xc2a2a4]`; 0 when `Wow.ini` named no locale.
|
||||
@@ -66,6 +83,16 @@ impl Locale {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn community_russian_keeps_column_zero_and_its_own_tag() {
|
||||
let russian = Locale::for_language_pack(crate::ClientLocale::RuRu);
|
||||
assert_eq!((russian.index(), russian.name()), (0, "ruRU"));
|
||||
assert_eq!(russian.tag(), u32::from_be_bytes(*b"ruRU"));
|
||||
let native = Locale::from_language_country(b"ru", b"RU");
|
||||
assert_eq!((native.index(), native.name()), (0, "enUS"));
|
||||
assert_eq!(Locale::from_language_country(b"de", b"DE").index(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_index_is_the_names_position_in_the_table() {
|
||||
let de = Locale::from_language_country(b"de", b"DE");
|
||||
@@ -94,7 +121,14 @@ mod tests {
|
||||
assert_eq!(gb.tag(), u32::from_be_bytes(*b"enGB"));
|
||||
assert_eq!(Locale::from_language_country(b"", b"").index(), 0);
|
||||
assert_eq!(Locale::from_language_country(b"", b"").tag(), 0);
|
||||
assert_eq!(Locale::default(), Locale { index: 0, tag: 0 });
|
||||
assert_eq!(
|
||||
Locale::default(),
|
||||
Locale {
|
||||
index: 0,
|
||||
tag: 0,
|
||||
community_ru: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// The five-byte buffer cuts the joined string at four characters before the compare: a long
|
||||
|
||||
@@ -73,6 +73,7 @@ const LATIN_1: u8 = 1;
|
||||
const HANGUL: u8 = 2;
|
||||
const CJK: u8 = 3;
|
||||
const ASCII_LETTERS: u8 = 4;
|
||||
const CYRILLIC: u8 = 5;
|
||||
|
||||
/// The two charsets `0x6c9a70` returns, the primary and the secondary; a name's first unit picks
|
||||
/// whichever takes it, primary first, and every later unit must be of that one.
|
||||
@@ -83,6 +84,14 @@ pub struct NameCharsets {
|
||||
}
|
||||
|
||||
impl NameCharsets {
|
||||
/// Deviation: the community ruRU pack accepts Russian names up to twelve letters, while
|
||||
/// retaining the stock Latin alternative. The server remains the naming-policy authority.
|
||||
pub(crate) fn for_russian_pack() -> Self {
|
||||
Self {
|
||||
primary: CYRILLIC,
|
||||
secondary: LATIN_1,
|
||||
}
|
||||
}
|
||||
/// What `Wow.ini`'s `Region` and the locale index give. A `Region` of 1 to 5 (signed,
|
||||
/// `0x6c9a78`-`0x6c9a80`; `0x402b7f` hands it over at start-up, `0x6c91b8` stores it) reads the
|
||||
/// pairs at `0x86c9e4`: 1 (1, 1), 2 (2, 4), 3 (1, 1), 4 (3, 1), 5 (3, 1). Any other reads the
|
||||
@@ -174,7 +183,7 @@ fn validate(name: Option<&str>, lists: &dyn NameLists, charsets: NameCharsets) -
|
||||
return RESERVED;
|
||||
}
|
||||
let cap = match chosen {
|
||||
LATIN_1 => LATIN_MAX_UNITS,
|
||||
LATIN_1 | CYRILLIC => LATIN_MAX_UNITS,
|
||||
CJK => CJK_MAX_UNITS,
|
||||
_ => OTHER_MAX_UNITS,
|
||||
};
|
||||
@@ -191,6 +200,7 @@ fn in_charset(set: u8, unit: u16) -> bool {
|
||||
HANGUL => hangul::is_listed(unit),
|
||||
CJK => in_cjk(unit),
|
||||
ASCII_LETTERS => matches!(unit, 0x41..=0x5a | 0x61..=0x7a),
|
||||
CYRILLIC => matches!(unit, 0x410..=0x44f | 0x401 | 0x451),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +310,7 @@ impl UiScript {
|
||||
/// Seat the install's locale index, which start-up reads from `Wow.ini` once (`0x402562`); an
|
||||
/// index past the table's eight names reads as 0.
|
||||
pub fn set_locale(&mut self, index: usize) {
|
||||
self.model_mut().community_ru = false;
|
||||
self.model_mut().locale = if index < crate::toc::LOCALES.len() {
|
||||
index
|
||||
} else {
|
||||
@@ -317,6 +318,32 @@ impl UiScript {
|
||||
};
|
||||
}
|
||||
|
||||
/// Deviation: ruRU is a community overlay over DBC column zero, outside the stock table.
|
||||
pub fn set_russian_language_pack(&mut self, enabled: bool) {
|
||||
let mut model = self.model_mut();
|
||||
model.community_ru = enabled;
|
||||
if enabled {
|
||||
model.locale = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an in-game VM for the selected stock locale or community ruRU overlay.
|
||||
pub fn new_with_locale(code: &str) -> mlua::Result<Self> {
|
||||
let mut script = Self::new()?;
|
||||
if code.eq_ignore_ascii_case("ruRU") {
|
||||
script.set_russian_language_pack(true);
|
||||
} else {
|
||||
let index = crate::toc::LOCALES
|
||||
.iter()
|
||||
.position(|name| name.eq_ignore_ascii_case(code))
|
||||
.ok_or_else(|| {
|
||||
mlua::Error::RuntimeError(format!("unsupported client locale {code:?}"))
|
||||
})?;
|
||||
script.set_locale(index);
|
||||
}
|
||||
Ok(script)
|
||||
}
|
||||
|
||||
/// `Wow.ini`'s `Region` as seated, 0 until the host seats the install's.
|
||||
pub fn client_region(&self) -> i32 {
|
||||
self.model_ref().client_region
|
||||
@@ -331,6 +358,9 @@ impl UiScript {
|
||||
|
||||
/// The locale name table `0x8558a4` at the VM's locale index, `GetLocale`'s answer in either state.
|
||||
pub(super) fn locale_name(lua: &Lua) -> &'static str {
|
||||
if lua.app_data_ref::<Model>().is_some_and(|m| m.community_ru) {
|
||||
return "ruRU";
|
||||
}
|
||||
let index = lua.app_data_ref::<Model>().map_or(0, |m| m.locale);
|
||||
crate::toc::LOCALES[index]
|
||||
}
|
||||
@@ -339,6 +369,41 @@ pub(super) fn locale_name(lua: &Lua) -> &'static str {
|
||||
mod tests {
|
||||
use crate::script::UiScript;
|
||||
|
||||
#[test]
|
||||
fn russian_pack_names_and_locale_work_in_both_vms() {
|
||||
use crate::script::{check_char_name, NoNameLists, CHAR_NAME_SUCCESS};
|
||||
for mut script in [UiScript::new().unwrap(), UiScript::new_glue().unwrap()] {
|
||||
script.set_russian_language_pack(true);
|
||||
assert_eq!(script.eval::<String>("return GetLocale()").unwrap(), "ruRU");
|
||||
let charsets = script.model_ref().name_charsets();
|
||||
for name in ["Александр", "Ёлочка", "Абвгдежзийкл", "Alice"]
|
||||
{
|
||||
assert_eq!(
|
||||
check_char_name(Some(name), &NoNameLists, charsets),
|
||||
CHAR_NAME_SUCCESS,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
for name in ["Абвгдежзийклм", "Алекс1", "Alexандр"] {
|
||||
assert_ne!(
|
||||
check_char_name(Some(name), &NoNameLists, charsets),
|
||||
CHAR_NAME_SUCCESS,
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
script.set_locale(0);
|
||||
assert_eq!(script.eval::<String>("return GetLocale()").unwrap(), "enUS");
|
||||
assert_ne!(
|
||||
check_char_name(
|
||||
Some("Ёлочка"),
|
||||
&NoNameLists,
|
||||
script.model_ref().name_charsets()
|
||||
),
|
||||
CHAR_NAME_SUCCESS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Three strings and no fourth, as the in-game registrar pushes (`0x4884a0`); this VM is the
|
||||
/// in-game one, not the glue (`0x46cd70`, five).
|
||||
#[test]
|
||||
|
||||
@@ -779,6 +779,8 @@ pub(crate) struct Model {
|
||||
/// The client's locale index, `[0xc0e080]` (0, enUS, until the host seats the install's): the
|
||||
/// name `GetLocale` answers is the table `0x8558a4` at it ([`crate::toc::LOCALES`]).
|
||||
pub(crate) locale: usize,
|
||||
/// Deviation: the community ruRU pack reads column zero but names its own language.
|
||||
pub(crate) community_ru: bool,
|
||||
/// `Wow.ini`'s `Region` as start-up hands it to the name check (`0x402b7f` → `0x6c91b8`,
|
||||
/// `[0x86c9e0]`): 0 until the host seats the install's.
|
||||
pub(crate) client_region: i32,
|
||||
@@ -1265,7 +1267,11 @@ pub(crate) struct Model {
|
||||
impl Model {
|
||||
/// The charsets the character name check holds a name to: this client's `Region` and locale.
|
||||
pub(crate) fn name_charsets(&self) -> super::NameCharsets {
|
||||
super::NameCharsets::for_client(self.client_region, self.locale)
|
||||
if self.community_ru {
|
||||
super::NameCharsets::for_russian_pack()
|
||||
} else {
|
||||
super::NameCharsets::for_client(self.client_region, self.locale)
|
||||
}
|
||||
}
|
||||
|
||||
/// The text a `SetText` stores (`0x771d80` with its expand flag): the separator pass
|
||||
@@ -1623,6 +1629,7 @@ impl Model {
|
||||
layout_mode: 0,
|
||||
european_numbers: false,
|
||||
locale: 0,
|
||||
community_ru: false,
|
||||
client_region: 0,
|
||||
slider_drag: None,
|
||||
color_drag: None,
|
||||
|
||||
@@ -325,6 +325,7 @@ sweep ldexp@macos-aarch64 err bad argument #1 to `?\' (number expected, got no v
|
||||
sweep deg err bad argument #1 to `?\' (number expected, got no value) | err bad argument #1 to `?\' (number expected, got no value) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | ok 85.943669269623484 | ok -171.88733853924697 | ok 0 | ok 572.95779513082323 | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | ok 114.59155902616465 | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got boolean) | err bad argument #1 to `?\' (number expected, got string) | ok 5.7295779513082321e+301 | ok -57.295779513082323 | ok 3724.225668350351 | err bad argument #1 to `?\' (number expected, got table)
|
||||
sweep rad err bad argument #1 to `?\' (number expected, got no value) | err bad argument #1 to `?\' (number expected, got no value) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | ok 0.026179938779914945 | ok -0.05235987755982989 | ok 0 | ok 0.17453292519943295 | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | err bad argument #1 to `?\' (number expected, got table) | ok 0.034906585039886591 | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got string) | err bad argument #1 to `?\' (number expected, got boolean) | err bad argument #1 to `?\' (number expected, got string) | ok 1.7453292519943297e+298 | ok -0.017453292519943295 | ok 1.1344640137963142 | err bad argument #1 to `?\' (number expected, got table)
|
||||
sweep sin err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | ok 0.026176948307873153 | ok -0.052335956242943835 | ok 0 | ok 0.17364817766693033 | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table) | ok 0.034899496702500969 | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got string) | ok -0.74635556214681953 | ok -0.017452406437283512 | ok 0.90630778703664994 | err [benilla wow stdlib]:49: bad argument #1 to `rad\' (number expected, got table)
|
||||
sweep cos err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok 0.99965732497555726 | ok 0.99862953475457383 | ok 1 | ok 0.98480775301220802 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | ok 0.99939082701909576 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok -0.66554742494619046 | ok 0.99984769515639127 | ok 0.42261826174069944 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table)
|
||||
sweep cos@linux-x86_64 err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok 0.99965732497555726 | ok 0.99862953475457383 | ok 1 | ok 0.98480775301220802 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | ok 0.99939082701909576 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok -0.66554742494619046 | ok 0.99984769515639127 | ok 0.42261826174069944 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table)
|
||||
sweep cos@windows-x86_64 err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok 0.99965732497555726 | ok 0.99862953475457383 | ok 1 | ok 0.98480775301220802 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table) | ok 0.99939082701909576 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got string) | ok -0.66554742494619035 | ok 0.99984769515639127 | ok 0.42261826174069944 | err [benilla wow stdlib]:50: bad argument #1 to `rad\' (number expected, got table)
|
||||
sweep tan@linux-x86_64 err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | ok 0.026185921569186931 | ok -0.05240777928304121 | ok 0 | ok 0.17632698070846498 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | ok 0.03492076949174773 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | ok 1.1214160466583767 | ok -0.017455064928217585 | ok 2.1445069205095586 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table)
|
||||
sweep tan@macos-aarch64 err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got nil) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | ok 0.026185921569186928 | ok -0.05240777928304121 | ok 0 | ok 0.17632698070846498 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table) | ok 0.03492076949174773 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got boolean) | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got string) | ok 1.1214160466583769 | ok -0.017455064928217585 | ok 2.1445069205095586 | err [benilla wow stdlib]:59: bad argument #1 to `rad\' (number expected, got table)
|
||||
|
||||
@@ -927,7 +927,8 @@ fn unescape(s: &str) -> String {
|
||||
|
||||
/// Cases whose answer on the C build depends on the platform's C library or compiler, so the
|
||||
/// golden file holds one answer per platform, `name@<os>-<arch>`, each blessed there:
|
||||
/// - the transcendental functions are the host libm's, rounded differently by glibc and Apple's;
|
||||
/// - the transcendental functions are the host libm's, rounded differently by glibc, Apple's and
|
||||
/// Windows' UCRT;
|
||||
/// - a NaN prints its sign under glibc (`-nan`), never under Apple's libc, and which NaN a
|
||||
/// function answers is the host libm's;
|
||||
/// - `luaL_checknumber` on two arguments in one C call (`fmod`, `pow`, `ldexp`, `atan2`) checked
|
||||
@@ -957,6 +958,8 @@ const PLATFORM_CASES: &[&str] = &[
|
||||
"sweep math.ldexp",
|
||||
"sweep ldexp",
|
||||
"sweep math.sin",
|
||||
// The original C VM also differs by one ulp for cos(1e300 degrees) on Windows and Linux.
|
||||
"sweep cos",
|
||||
"sweep math.tan",
|
||||
"sweep tan",
|
||||
"sweep math.asin",
|
||||
|
||||
@@ -6,7 +6,7 @@ use bevy::render::renderer::RenderDevice;
|
||||
|
||||
use crate::art_scope::{ArtScope, ArtSlot};
|
||||
use benilla_assets::{AssetSet, RenderConfig, WorldAssets};
|
||||
use benilla_formats::open_chain;
|
||||
use benilla_formats::Chain;
|
||||
|
||||
/// Opens the patch chain at startup and inserts the shared [`WorldAssets`] and [`RenderConfig`].
|
||||
pub(crate) struct AssetPlugin;
|
||||
@@ -65,8 +65,11 @@ fn open_world_assets(mut commands: Commands, device: Res<RenderDevice>) {
|
||||
.unwrap_or(1);
|
||||
commands.insert_resource(RenderConfig { unload_budget });
|
||||
|
||||
match open_chain(&data) {
|
||||
Ok(chain) => commands.insert_resource(WorldAssets::open(chain, light_buf)),
|
||||
match Chain::open_client(&data) {
|
||||
Ok(chain) => {
|
||||
info!("client data: locale {}", chain.locale().name());
|
||||
commands.insert_resource(WorldAssets::open(chain, light_buf));
|
||||
}
|
||||
Err(e) => error!("failed to open client data: {e:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "moonwell-deploy"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Build vanilla MPQ packages and publish MoonWell launcher manifests to S3"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
benilla-mpq = { path = "../benilla-mpq" }
|
||||
clap.workspace = true
|
||||
http = "1"
|
||||
md5 = "0.8"
|
||||
rust-s3 = { version = "0.37.2", default-features = false, features = ["sync-rustls-tls"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
walkdir = "2.5"
|
||||
wow-mpq = "0.6.4"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,134 @@
|
||||
# MoonWell deployment
|
||||
|
||||
`moonwell-deploy` builds MPQ patches, stages the Rust player client, generates
|
||||
the launcher manifest, and publishes it to S3. It uses the same `wow-mpq` Rust
|
||||
builder as MoonWellClientSources, with MPQ v1 and 4 KiB sectors for 1.12.1.
|
||||
Its small single-unit blocks are converted to stored/sectored blocks, preserving
|
||||
their bytes, because the current client reader rejects single-unit entries.
|
||||
The 3.3.5 source tree and its WarcraftXL DLLs are not vanilla client data.
|
||||
|
||||
The source project's `.env` is read directly with `--env-file`; credentials
|
||||
are never copied into the package or printed. Process environment values take
|
||||
precedence. Supported settings are `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
|
||||
optional `AWS_SESSION_TOKEN`, `AWS_DEFAULT_REGION`, `AWS_BUCKET`, `AWS_ENDPOINT`,
|
||||
and `AWS_USE_PATH_STYLE_ENDPOINT`. Unquoted Windows paths elsewhere in that file
|
||||
are ignored. `WOW_HOME` is never used as the vanilla data source.
|
||||
|
||||
## Windows pipeline
|
||||
|
||||
From the repository root:
|
||||
|
||||
```powershell
|
||||
# Build, stage and generate the local manifest; does not upload.
|
||||
.\scripts\deploy-moonwell.ps1 -DataPath 'D:\WoW-1.12.1\Data' `
|
||||
-IconPath 'D:\Branding\MoonWell.ico' -AuthHost 'login.example:3724'
|
||||
|
||||
# Check the S3 upload plan without changing any objects.
|
||||
.\scripts\deploy-moonwell.ps1 -DataPath 'D:\WoW-1.12.1\Data' `
|
||||
-IconPath 'D:\Branding\MoonWell.ico' -AuthHost 'login.example:3724' -DryRun
|
||||
|
||||
# Build and publish a complete vanilla distribution.
|
||||
.\scripts\deploy-moonwell.ps1 -DataPath 'D:\WoW-1.12.1\Data' `
|
||||
-IconPath 'D:\Branding\MoonWell.ico' -AuthHost 'login.example:3724' -Publish
|
||||
```
|
||||
|
||||
The default `.env` location is the sibling `MoonWellClientSources/.env`.
|
||||
Override it with `-EnvFile`. Every run creates a new `dist/moonwell-<timestamp>`
|
||||
directory; `-PackagePath` overrides it. The local manifest is adjacent to that
|
||||
directory, with the suffix `.manifest.json`. Staging never changes the source
|
||||
install or deletes an existing directory. With `-SkipClientBuild -BinaryPath`,
|
||||
provide an already built player executable. Debug instruments must be disabled
|
||||
in the binary distributed to players.
|
||||
|
||||
Optional `-PatchSource` points to your own source tree containing
|
||||
`Data/patch-M/`, `Data/patch-N/`, etc. The Rust builder produces `Data/patch-M.MPQ`
|
||||
and mounts them through the client's vanilla patch chain. A supplied patch
|
||||
source takes precedence over the same named patch in the input install.
|
||||
Locale subdirectories such as `Data/ruRU/patch-ruRU-5` are rejected because
|
||||
MoonWell currently has no locale selection or mounting support.
|
||||
|
||||
The Windows script includes `vcruntime140.dll` from Visual Studio's x64
|
||||
redistributable directory beside the game executable. `-VcRuntimePath` can
|
||||
select this directory explicitly. Windows 10/11 supplies the Universal CRT.
|
||||
When staging directly through the Rust CLI, include the required runtime DLL
|
||||
before generating or publishing the manifest.
|
||||
|
||||
Only vanilla archives that the client mounts are copied from the Data directory.
|
||||
All ten vanilla base archives are required. Input archives may use MPQ v1/v2,
|
||||
as supported by the client reader; the winning `Spell.dbc` must have 173 columns.
|
||||
These checks reject a normal 3.3.5 installation; they do not prove that a custom
|
||||
patch's models, Lua, or DBC rows are compatible with 1.12.1. Test custom content
|
||||
in the client before publishing it. Install content remains outside Git.
|
||||
|
||||
## S3 and Web API
|
||||
|
||||
```powershell
|
||||
cargo run -p moonwell-deploy -- inspect --env-file ..\MoonWellClientSources\.env
|
||||
cargo run -p moonwell-deploy -- check-storage --env-file ..\MoonWellClientSources\.env
|
||||
cargo run -p moonwell-deploy -- publish --dir dist\moonwell-package `
|
||||
--env-file ..\MoonWellClientSources\.env --dry-run
|
||||
```
|
||||
|
||||
`check-storage` uploads a temporary 10 MiB object under `moonwell-deploy-check/`,
|
||||
checks that its bytes round-trip correctly, then deletes that object. It does
|
||||
not change any release or active manifest.
|
||||
|
||||
The inventory is `{ "buildHash": "...", "files": [{ "path": "...",
|
||||
"size": 123, "sha256": "...", "objectKey": "..." }] }`. `buildHash` uses
|
||||
the existing Python/launcher contract: sort by path, join
|
||||
`path:size:sha256` with newline separators, then SHA-256 the UTF-8 bytes.
|
||||
State, `.env` files, launcher metadata and partial downloads are excluded.
|
||||
Symlinks and case-insensitive duplicate paths are rejected.
|
||||
|
||||
Files are streamed (multipart for large objects) into
|
||||
`World of Warcraft 1.12.1/releases/<buildHash>/<relative-path>`. The release's
|
||||
`manifest.json` is written after all files, and `manifest-1.12.1.json` is switched
|
||||
last. Upload failure leaves the active inventory unchanged. No old objects are
|
||||
deleted, so a download link already issued for an older release keeps working.
|
||||
Run one publisher at a time. To roll back, restore a previous release inventory
|
||||
as the active manifest; keep that release's objects.
|
||||
|
||||
Large files use four concurrent 8 MiB upload parts. The publisher checks each
|
||||
part's MD5 and the completed object's size and ETag before publishing the
|
||||
inventory. These ETag checks target the configured unencrypted Yandex S3
|
||||
objects; SHA-256 remains the launcher manifest's integrity check. Repeating
|
||||
`publish --dir <existing-package> --env-file .env` reuses completed objects
|
||||
only when their content ETag and size match. Interrupted multipart files are
|
||||
uploaded again; completed files are not transmitted again.
|
||||
Files unchanged from the active release retain their verified immutable
|
||||
`objectKey`, so publishing an executable or runtime update does not upload the
|
||||
game data again. Keep all releases whose objects are referenced by an inventory.
|
||||
|
||||
The Laravel web app resolves a requested path through the active manifest's
|
||||
`objectKey` and signs that S3 object. Its settings must match:
|
||||
|
||||
```dotenv
|
||||
MOONWELL_LAUNCHER_BASE_PATH="World of Warcraft 1.12.1"
|
||||
MOONWELL_LAUNCHER_MANIFEST_KEY=manifest-1.12.1.json
|
||||
```
|
||||
|
||||
The Flutter launcher keeps requesting the existing Web API endpoints. It has
|
||||
no S3 credentials. Inventories without `objectKey` retain the legacy
|
||||
`<base-path>/<relative-path>` resolution. The old 3.3.5 `manifest.json` and
|
||||
`World of Warcraft/` keys are reserved and cannot be publication targets.
|
||||
|
||||
Native macOS binaries must be built on a Mac and packaged with
|
||||
[`package_macos.py`](../moonwell/package_macos.py). `stage --binary MoonWell.app`
|
||||
can stage such a bundle, but publish it with separate `--manifest-key` and
|
||||
`--prefix` settings for a launcher distribution targeting macOS. The current
|
||||
API has one active inventory per configured distribution, not automatic OS
|
||||
selection. This Windows pipeline does not build or sign macOS applications.
|
||||
The current Flutter file downloader also does not restore Unix executable bits;
|
||||
install the `.app` as a bundle with its permissions preserved when testing macOS.
|
||||
|
||||
## Checks
|
||||
|
||||
```powershell
|
||||
cargo fmt -p moonwell-deploy -- --check
|
||||
cargo clippy -p moonwell-deploy --all-targets -- -D warnings
|
||||
cargo test -p moonwell-deploy
|
||||
```
|
||||
|
||||
Tests cover actual client MPQ readability, excluded state and secrets, the
|
||||
manifest contract, path validation, upload failures, dry runs and publication
|
||||
ordering. Live client login remains a separate check.
|
||||
@@ -0,0 +1,139 @@
|
||||
mod manifest;
|
||||
mod package;
|
||||
mod storage;
|
||||
mod vanilla_mpq;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(about = "Build and publish MoonWell 1.12.1 client packages")]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Command,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Command {
|
||||
/// Build vanilla MPQ archives from <source>/Data/patch-? directories.
|
||||
Pack {
|
||||
#[arg(long)]
|
||||
source: PathBuf,
|
||||
#[arg(long)]
|
||||
output: PathBuf,
|
||||
},
|
||||
/// Stage a player binary, read-only vanilla Data and optional patch sources.
|
||||
Stage {
|
||||
#[arg(long)]
|
||||
binary: PathBuf,
|
||||
#[arg(long)]
|
||||
data: PathBuf,
|
||||
#[arg(long)]
|
||||
output: PathBuf,
|
||||
#[arg(long)]
|
||||
source: Option<PathBuf>,
|
||||
#[arg(long)]
|
||||
auth_host: String,
|
||||
},
|
||||
/// Generate the launcher inventory of an existing distribution directory.
|
||||
Manifest {
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
#[arg(long)]
|
||||
output: PathBuf,
|
||||
},
|
||||
/// Inspect the remote manifest without writing anything.
|
||||
Inspect {
|
||||
#[arg(long)]
|
||||
env_file: PathBuf,
|
||||
#[arg(long, default_value = "manifest-1.12.1.json")]
|
||||
manifest_key: String,
|
||||
},
|
||||
/// Verify S3 multipart upload/read using a temporary object, then remove it.
|
||||
CheckStorage {
|
||||
#[arg(long)]
|
||||
env_file: PathBuf,
|
||||
},
|
||||
/// Upload a complete package to an immutable release; switch manifest last.
|
||||
Publish {
|
||||
#[arg(long)]
|
||||
dir: PathBuf,
|
||||
#[arg(long)]
|
||||
env_file: PathBuf,
|
||||
#[arg(long, default_value = "World of Warcraft 1.12.1")]
|
||||
prefix: String,
|
||||
#[arg(long, default_value = "manifest-1.12.1.json")]
|
||||
manifest_key: String,
|
||||
/// Read and report the upload plan without writing any S3 objects.
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
},
|
||||
}
|
||||
|
||||
fn run() -> Result<()> {
|
||||
match Cli::parse().command {
|
||||
Command::Pack { source, output } => package::pack(&source, &output),
|
||||
Command::Stage {
|
||||
binary,
|
||||
data,
|
||||
output,
|
||||
source,
|
||||
auth_host,
|
||||
} => package::stage(&binary, &data, &output, source.as_deref(), &auth_host),
|
||||
Command::Manifest { dir, output } => {
|
||||
package::validate_distribution(&dir)?;
|
||||
let m = manifest::scan(&dir)?;
|
||||
manifest::write(&m, &output)?;
|
||||
println!(
|
||||
"Manifest: {} files, buildHash={}",
|
||||
m.files.len(),
|
||||
m.build_hash
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Command::Inspect {
|
||||
env_file,
|
||||
manifest_key,
|
||||
} => {
|
||||
let store = storage::S3Store::from_env(&env_file)?;
|
||||
match storage::Store::get(&store, &manifest_key)? {
|
||||
None => println!("No remote manifest at {manifest_key}"),
|
||||
Some(bytes) => {
|
||||
let m: manifest::Manifest =
|
||||
serde_json::from_slice(&bytes).context("invalid remote manifest")?;
|
||||
manifest::validate(&m)?;
|
||||
println!(
|
||||
"Remote manifest: {} files, buildHash={}",
|
||||
m.files.len(),
|
||||
m.build_hash
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Command::CheckStorage { env_file } => {
|
||||
storage::S3Store::from_env(&env_file)?.check_storage()
|
||||
}
|
||||
Command::Publish {
|
||||
dir,
|
||||
env_file,
|
||||
prefix,
|
||||
manifest_key,
|
||||
dry_run,
|
||||
} => {
|
||||
package::validate_distribution(&dir)?;
|
||||
let m = manifest::scan(&dir)?;
|
||||
let store = storage::S3Store::from_env(&env_file)?;
|
||||
storage::publish(&store, &dir, m, &prefix, &manifest_key, dry_run)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("Error: {error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{bail, ensure, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Manifest {
|
||||
pub build_hash: String,
|
||||
pub files: Vec<ClientFile>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ClientFile {
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub object_key: Option<String>,
|
||||
}
|
||||
|
||||
pub fn valid_path(path: &str) -> bool {
|
||||
!path.is_empty()
|
||||
&& !path.contains(['\\', ':', '\r', '\n', '\0'])
|
||||
&& path.split('/').all(|p| !matches!(p, "" | "." | ".."))
|
||||
}
|
||||
|
||||
fn ignored(path: &Path) -> bool {
|
||||
path.components().any(|part| {
|
||||
let name = part.as_os_str().to_string_lossy().to_ascii_lowercase();
|
||||
matches!(
|
||||
name.as_str(),
|
||||
"cache"
|
||||
| "errors"
|
||||
| "logs"
|
||||
| "screenshots"
|
||||
| "wtf"
|
||||
| "benilla-config"
|
||||
| ".moonwell_launcher"
|
||||
| ".git"
|
||||
| ".vscode"
|
||||
| ".ds_store"
|
||||
| ".probe-identity"
|
||||
| "manifest.json"
|
||||
) || name.starts_with(".env")
|
||||
|| name.ends_with(".moonwell.part")
|
||||
})
|
||||
}
|
||||
|
||||
pub fn hash_file(path: &Path) -> Result<(u64, String)> {
|
||||
let mut file = File::open(path).with_context(|| format!("reading {}", path.display()))?;
|
||||
let mut hash = Sha256::new();
|
||||
let mut buffer = vec![0; 1024 * 1024];
|
||||
let mut size = 0;
|
||||
loop {
|
||||
let count = file.read(&mut buffer)?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
hash.update(&buffer[..count]);
|
||||
size += count as u64;
|
||||
}
|
||||
Ok((size, format!("{:x}", hash.finalize())))
|
||||
}
|
||||
|
||||
pub fn build_hash(files: &[ClientFile]) -> String {
|
||||
let mut entries: Vec<_> = files.iter().collect();
|
||||
entries.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
let lines: Vec<_> = entries
|
||||
.iter()
|
||||
.map(|f| format!("{}:{}:{}", f.path, f.size, f.sha256))
|
||||
.collect();
|
||||
format!("{:x}", Sha256::digest(lines.join("\n").as_bytes()))
|
||||
}
|
||||
|
||||
pub fn scan(root: &Path) -> Result<Manifest> {
|
||||
ensure!(root.is_dir(), "package directory does not exist");
|
||||
let mut files = Vec::new();
|
||||
let mut names = HashSet::new();
|
||||
for entry in WalkDir::new(root)
|
||||
.follow_links(false)
|
||||
.into_iter()
|
||||
.filter_entry(|e| {
|
||||
e.depth() == 0 || !ignored(e.path().strip_prefix(root).expect("walk root"))
|
||||
})
|
||||
{
|
||||
let entry = entry?;
|
||||
ensure!(
|
||||
!entry.path_is_symlink(),
|
||||
"symlinks are not supported in packages: {}",
|
||||
entry.path().display()
|
||||
);
|
||||
if !entry.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
let path = entry
|
||||
.path()
|
||||
.strip_prefix(root)?
|
||||
.to_str()
|
||||
.context("package path is not UTF-8")?
|
||||
.replace('\\', "/");
|
||||
ensure!(valid_path(&path), "invalid package path: {path}");
|
||||
ensure!(
|
||||
names.insert(path.to_ascii_lowercase()),
|
||||
"case-insensitive duplicate path: {path}"
|
||||
);
|
||||
let (size, sha256) = hash_file(entry.path())?;
|
||||
files.push(ClientFile {
|
||||
path,
|
||||
size,
|
||||
sha256,
|
||||
object_key: None,
|
||||
});
|
||||
}
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
ensure!(!files.is_empty(), "package is empty");
|
||||
Ok(Manifest {
|
||||
build_hash: build_hash(&files),
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn validate(manifest: &Manifest) -> Result<()> {
|
||||
ensure!(!manifest.files.is_empty(), "manifest is empty");
|
||||
let mut paths = HashSet::new();
|
||||
for f in &manifest.files {
|
||||
ensure!(valid_path(&f.path), "invalid manifest path");
|
||||
ensure!(
|
||||
paths.insert(f.path.to_ascii_lowercase()),
|
||||
"duplicate manifest path"
|
||||
);
|
||||
ensure!(
|
||||
f.sha256.len() == 64
|
||||
&& f.sha256
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()),
|
||||
"invalid file SHA-256"
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
manifest.build_hash == build_hash(&manifest.files),
|
||||
"manifest buildHash mismatch"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write(manifest: &Manifest, output: &Path) -> Result<()> {
|
||||
let mut data = serde_json::to_vec_pretty(manifest)?;
|
||||
data.push(b'\n');
|
||||
if let Some(parent) = output.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
// Do not truncate an existing release inventory if writing fails.
|
||||
let temp = output.with_extension("json.part");
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)?;
|
||||
file.write_all(&data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
if let Err(error) = fs::rename(&temp, output) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
bail!("cannot write manifest: {error}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_matches_the_existing_python_and_launcher_contract() {
|
||||
let f = ClientFile {
|
||||
path: "a".into(),
|
||||
size: 3,
|
||||
sha256: "abc".into(),
|
||||
object_key: None,
|
||||
};
|
||||
assert_eq!(
|
||||
build_hash(&[f]),
|
||||
format!("{:x}", Sha256::digest(b"a:3:abc"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_excludes_state_secrets_and_its_own_inventory() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in [
|
||||
"Data/patch-M.MPQ",
|
||||
"benilla-config/config.toml",
|
||||
"WTF/Config.wtf",
|
||||
".env",
|
||||
"manifest.json",
|
||||
] {
|
||||
let p = dir.path().join(name);
|
||||
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
fs::write(p, b"test").unwrap();
|
||||
}
|
||||
let m = scan(dir.path()).unwrap();
|
||||
assert_eq!(m.files.len(), 1);
|
||||
assert_eq!(m.files[0].path, "Data/patch-M.MPQ");
|
||||
validate(&m).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn traversal_and_protocol_delimiters_are_rejected() {
|
||||
for path in ["/a", "../a", "a/../b", "C:/a", "a\\b", "a\nb", "a//b"] {
|
||||
assert!(!valid_path(path), "{path}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use walkdir::WalkDir;
|
||||
use wow_mpq::compression::flags;
|
||||
use wow_mpq::{ArchiveBuilder, FormatVersion, ListfileOption};
|
||||
|
||||
const BASE_ARCHIVES: &[&str] = &[
|
||||
"dbc.mpq",
|
||||
"speech.mpq",
|
||||
"fonts.mpq",
|
||||
"interface.mpq",
|
||||
"misc.mpq",
|
||||
"sound.mpq",
|
||||
"wmo.mpq",
|
||||
"terrain.mpq",
|
||||
"texture.mpq",
|
||||
"model.mpq",
|
||||
];
|
||||
|
||||
// AccountLogin.xml's SimpleHTML file= attributes are loose Storm opens (0x78a2a0),
|
||||
// not members of the mounted base archives: omitting them leaves the agreement panes empty.
|
||||
const AGREEMENTS: &[&str] = &["eula.html", "tos.html", "scan.html", "contest.html"];
|
||||
|
||||
fn agreement_files(data: &Path) -> Result<Vec<(String, PathBuf)>> {
|
||||
let mut files = Vec::new();
|
||||
for name in AGREEMENTS {
|
||||
let mut found = None;
|
||||
for folder in data.parent().into_iter().chain([data]) {
|
||||
let entries = fs::read_dir(folder)?.collect::<std::io::Result<Vec<_>>>()?;
|
||||
for candidate in [name.to_string(), format!("{name}.MPQ")] {
|
||||
let matches: Vec<_> = entries
|
||||
.iter()
|
||||
.filter(|e| {
|
||||
e.file_name()
|
||||
.to_string_lossy()
|
||||
.eq_ignore_ascii_case(&candidate)
|
||||
})
|
||||
.collect();
|
||||
ensure!(matches.len() <= 1, "duplicate agreement: {candidate}");
|
||||
if let Some(entry) = matches.first() {
|
||||
let path = entry.path();
|
||||
ensure!(
|
||||
path.is_file(),
|
||||
"agreement must be a file: {}",
|
||||
path.display()
|
||||
);
|
||||
let bytes = if candidate.ends_with(".MPQ") {
|
||||
benilla_mpq::Archive::open(&path)?.read_file(name)?
|
||||
} else {
|
||||
fs::read(&path)?
|
||||
};
|
||||
ensure!(!bytes.is_empty(), "empty agreement: {}", path.display());
|
||||
found = Some((candidate, path));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Scan/contest are conditional on regional GlueLocalization flags; enUS ships neither.
|
||||
if found.is_none() && matches!(*name, "scan.html" | "contest.html") {
|
||||
continue;
|
||||
}
|
||||
files.push(found.with_context(|| {
|
||||
format!("missing {name} (or {name}.MPQ) in the install root or Data; cannot stage an empty agreement dialog")
|
||||
})?);
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn patch_name(name: &str) -> bool {
|
||||
let name = name.to_ascii_lowercase();
|
||||
name == "patch"
|
||||
|| name
|
||||
.strip_prefix("patch-")
|
||||
.is_some_and(|s| s.len() == 1 && s.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
fn mounted_archive(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
BASE_ARCHIVES.contains(&lower.as_str())
|
||||
|| lower == "speech2.mpq"
|
||||
|| lower.strip_suffix(".mpq").is_some_and(patch_name)
|
||||
}
|
||||
|
||||
fn valid_auth_host(host: &str) -> bool {
|
||||
let (name, port) = host
|
||||
.split_once(':')
|
||||
.map_or((host, None), |(name, port)| (name, Some(port)));
|
||||
name.as_bytes()
|
||||
.first()
|
||||
.is_some_and(u8::is_ascii_alphanumeric)
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
|
||||
&& port.is_none_or(|p| {
|
||||
p.len() <= 5
|
||||
&& p.bytes().all(|b| b.is_ascii_digit())
|
||||
&& p.parse::<u16>().is_ok_and(|p| p > 0)
|
||||
})
|
||||
}
|
||||
|
||||
fn mounted_archives(data: &Path) -> Result<Vec<std::path::PathBuf>> {
|
||||
ensure!(data.is_dir(), "Data directory was not found");
|
||||
let mut names = HashSet::new();
|
||||
let mut files = Vec::new();
|
||||
for entry in fs::read_dir(data)? {
|
||||
let entry = entry?;
|
||||
let name = entry
|
||||
.file_name()
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("non-UTF-8 archive name"))?;
|
||||
if !mounted_archive(&name) {
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
entry.file_type()?.is_file(),
|
||||
"archive must be a regular file: {name}"
|
||||
);
|
||||
ensure!(
|
||||
names.insert(name.to_ascii_lowercase()),
|
||||
"duplicate archive name: {name}"
|
||||
);
|
||||
let mut header = [0u8; 32];
|
||||
File::open(entry.path())?.read_exact(&mut header)?;
|
||||
ensure!(
|
||||
&header[..4] == b"MPQ\x1a" && u16::from_le_bytes([header[12], header[13]]) <= 1,
|
||||
"{name} is outside the client's MPQ v1/v2 envelope"
|
||||
);
|
||||
files.push(entry.path());
|
||||
}
|
||||
files.sort();
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn validate_data(data: &Path) -> Result<Vec<std::path::PathBuf>> {
|
||||
let files = mounted_archives(data)?;
|
||||
let names: HashSet<_> = files
|
||||
.iter()
|
||||
.map(|p| {
|
||||
p.file_name()
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase()
|
||||
})
|
||||
.collect();
|
||||
for base in BASE_ARCHIVES {
|
||||
ensure!(
|
||||
names.contains(*base),
|
||||
"missing vanilla base archive: {base}"
|
||||
);
|
||||
}
|
||||
// Modified installs can mimic vanilla archive names; check the winning 5875 Spell.dbc too.
|
||||
let mut spell_archives: Vec<_> = files.iter().collect();
|
||||
// Match benilla-formats' vanilla mount order, including speech2's final priority.
|
||||
spell_archives.sort_by_key(|p| {
|
||||
let name = p
|
||||
.file_name()
|
||||
.expect("archive name")
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase();
|
||||
let priority = BASE_ARCHIVES
|
||||
.iter()
|
||||
.position(|base| *base == name)
|
||||
.unwrap_or_else(|| {
|
||||
if name == "patch.mpq" {
|
||||
10
|
||||
} else if name == "speech2.mpq" {
|
||||
12
|
||||
} else {
|
||||
11
|
||||
}
|
||||
});
|
||||
(priority, name)
|
||||
});
|
||||
let mut found = false;
|
||||
for path in spell_archives.into_iter().rev() {
|
||||
let archive = benilla_mpq::Archive::open(path)?;
|
||||
if !archive.contains(r"DBFilesClient\Spell.dbc") {
|
||||
continue;
|
||||
}
|
||||
let mut stream = archive.open_file(r"DBFilesClient\Spell.dbc")?;
|
||||
let mut header = [0u8; 20];
|
||||
stream.read_exact(&mut header)?;
|
||||
ensure!(
|
||||
&header[..4] == b"WDBC"
|
||||
&& u32::from_le_bytes(header[8..12].try_into().expect("DBC fields")) == 173,
|
||||
"Spell.dbc is not the vanilla 5875 layout; 3.3.5 data cannot be deployed as 1.12.1"
|
||||
);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
ensure!(found, "vanilla Spell.dbc was not found");
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
/// Only mounted archives from the optional 1.12 Russian overlay; unrelated locale files stay out.
|
||||
fn russian_archives(data: &Path) -> Result<Vec<std::path::PathBuf>> {
|
||||
let mut folders = Vec::new();
|
||||
for entry in fs::read_dir(data)? {
|
||||
let entry = entry?;
|
||||
if entry
|
||||
.file_name()
|
||||
.to_string_lossy()
|
||||
.eq_ignore_ascii_case("ruRU")
|
||||
&& entry.path().is_dir()
|
||||
{
|
||||
folders.push(entry.path());
|
||||
}
|
||||
}
|
||||
ensure!(folders.len() <= 1, "duplicate ruRU language folders");
|
||||
let Some(folder) = folders.first() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let archives = mounted_archives(folder)?;
|
||||
ensure!(
|
||||
!archives.is_empty(),
|
||||
"ruRU language pack has no mounted archives"
|
||||
);
|
||||
for archive in &archives {
|
||||
let archive = benilla_mpq::Archive::open(archive)?;
|
||||
if archive.contains(r"DBFilesClient\Spell.dbc") {
|
||||
let bytes = archive.read_file(r"DBFilesClient\Spell.dbc")?;
|
||||
ensure!(
|
||||
bytes.len() >= 20
|
||||
&& &bytes[..4] == b"WDBC"
|
||||
&& u32::from_le_bytes(bytes[8..12].try_into().unwrap()) == 173,
|
||||
"ruRU Spell.dbc is not the vanilla 5875 layout"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(archives)
|
||||
}
|
||||
|
||||
fn ensure_outside(input: &Path, output: &Path) -> Result<()> {
|
||||
let input = input.canonicalize()?;
|
||||
let absolute = if output.is_absolute() {
|
||||
output.to_path_buf()
|
||||
} else {
|
||||
std::env::current_dir()?.join(output)
|
||||
};
|
||||
let parent = absolute
|
||||
.parent()
|
||||
.context("output needs a parent directory")?;
|
||||
let output = if absolute.exists() {
|
||||
absolute.canonicalize()?
|
||||
} else {
|
||||
// Resolve through the nearest existing ancestor without creating anything in an input.
|
||||
let mut existing = parent;
|
||||
while !existing.exists() {
|
||||
existing = existing
|
||||
.parent()
|
||||
.context("output has no existing ancestor")?;
|
||||
}
|
||||
let suffix = parent.strip_prefix(existing)?;
|
||||
ensure!(
|
||||
!suffix
|
||||
.components()
|
||||
.any(|c| matches!(c, std::path::Component::ParentDir)),
|
||||
"a nonexistent output parent cannot contain .."
|
||||
);
|
||||
existing
|
||||
.canonicalize()?
|
||||
.join(suffix)
|
||||
.join(absolute.file_name().context("output needs a filename")?)
|
||||
};
|
||||
ensure!(
|
||||
!output.starts_with(&input) && !input.starts_with(&output),
|
||||
"source and output directories must be separate"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Same wow-mpq builder as MoonWellClientSources, using vanilla's v1 format.
|
||||
pub fn pack(source: &Path, output: &Path) -> Result<()> {
|
||||
ensure_outside(source, output)?;
|
||||
let data = source.join("Data");
|
||||
ensure!(
|
||||
data.is_dir(),
|
||||
"patch sources must contain Data/patch-? directories"
|
||||
);
|
||||
let mut patches: Vec<_> = fs::read_dir(&data)?.collect::<std::io::Result<_>>()?;
|
||||
patches.sort_by_key(|e| e.file_name());
|
||||
let mut count = 0;
|
||||
for patch in patches {
|
||||
let name = patch
|
||||
.file_name()
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("non-UTF-8 patch name"))?;
|
||||
ensure!(
|
||||
patch.file_type()?.is_dir() && patch_name(&name),
|
||||
"unsupported vanilla patch source: {name}; expected a Data/patch-? source directory"
|
||||
);
|
||||
let target = output.join("Data").join(format!("{name}.MPQ"));
|
||||
ensure!(
|
||||
!target.exists(),
|
||||
"patch output already exists: {}",
|
||||
target.display()
|
||||
);
|
||||
let mut builder = ArchiveBuilder::new()
|
||||
.version(FormatVersion::V1)
|
||||
.block_size(3)
|
||||
.default_compression(flags::ZLIB)
|
||||
.listfile_option(ListfileOption::Generate);
|
||||
let mut files = Vec::new();
|
||||
let root = patch.path();
|
||||
for entry in WalkDir::new(&root).follow_links(false) {
|
||||
let entry = entry?;
|
||||
ensure!(
|
||||
!entry.path_is_symlink(),
|
||||
"symlinks are not supported in patch sources"
|
||||
);
|
||||
ensure!(
|
||||
entry.file_name() != "__mpqmeta__",
|
||||
"unresolved MPQ blocks cannot be rebuilt safely"
|
||||
);
|
||||
if entry.file_type().is_file() {
|
||||
let path = entry
|
||||
.path()
|
||||
.strip_prefix(&root)?
|
||||
.to_str()
|
||||
.context("non-UTF-8 patch path")?
|
||||
.replace('\\', "/");
|
||||
ensure!(crate::manifest::valid_path(&path), "invalid archive path");
|
||||
ensure!(
|
||||
!path.split('/').any(|p| p.starts_with(".env")),
|
||||
"patch contains an environment file"
|
||||
);
|
||||
files.push((path, entry.into_path()));
|
||||
}
|
||||
}
|
||||
ensure!(!files.is_empty(), "patch {name} is empty");
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let mut names = HashSet::new();
|
||||
for (path, source) in files {
|
||||
ensure!(
|
||||
names.insert(path.to_ascii_lowercase()),
|
||||
"duplicate archive path: {path}"
|
||||
);
|
||||
builder = builder.add_file(source, &path);
|
||||
}
|
||||
fs::create_dir_all(target.parent().expect("Data parent"))?;
|
||||
let temporary = target.with_extension("MPQ.part");
|
||||
ensure!(
|
||||
!temporary.exists(),
|
||||
"unfinished patch output already exists"
|
||||
);
|
||||
builder.build(&temporary)?;
|
||||
crate::vanilla_mpq::normalize(&temporary)?;
|
||||
fs::rename(&temporary, &target)?;
|
||||
println!("Built {}", target.display());
|
||||
count += 1;
|
||||
}
|
||||
ensure!(count > 0, "no patch sources found");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn validate_distribution(root: &Path) -> Result<()> {
|
||||
let windows = root.join("MoonWell.exe");
|
||||
let mac = root.join("MoonWell.app/Contents/MacOS/MoonWell");
|
||||
let linux = root.join("MoonWell");
|
||||
let binary = if windows.is_file() {
|
||||
windows
|
||||
} else if mac.is_file() {
|
||||
ensure!(
|
||||
root.join("MoonWell.app/Contents/MacOS/launch").is_file(),
|
||||
"macOS app launcher is missing"
|
||||
);
|
||||
mac
|
||||
} else {
|
||||
linux
|
||||
};
|
||||
let mut magic = [0; 4];
|
||||
File::open(&binary)
|
||||
.context("MoonWell player binary is missing")?
|
||||
.read_exact(&mut magic)?;
|
||||
ensure!(
|
||||
magic.starts_with(b"MZ")
|
||||
|| magic == *b"\x7fELF"
|
||||
|| [
|
||||
0xfeedfaceu32,
|
||||
0xfeedfacf,
|
||||
0xcefaedfe,
|
||||
0xcffaedfe,
|
||||
0xcafebabe,
|
||||
0xbebafeca
|
||||
]
|
||||
.contains(&u32::from_be_bytes(magic)),
|
||||
"MoonWell binary is not a native executable"
|
||||
);
|
||||
validate_data(&root.join("Data"))?;
|
||||
russian_archives(&root.join("Data"))?;
|
||||
agreement_files(&root.join("Data"))?;
|
||||
ensure!(
|
||||
root.join("realmlist.wtf").is_file(),
|
||||
"realmlist.wtf is missing"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stage(
|
||||
binary: &Path,
|
||||
data: &Path,
|
||||
output: &Path,
|
||||
source: Option<&Path>,
|
||||
host: &str,
|
||||
) -> Result<()> {
|
||||
let host = host.trim();
|
||||
ensure!(
|
||||
valid_auth_host(host),
|
||||
"auth host must be hostname or IPv4[:port]"
|
||||
);
|
||||
let archives = validate_data(data)?;
|
||||
let localized = russian_archives(data)?;
|
||||
let agreements = agreement_files(data)?;
|
||||
ensure_outside(data, output)?;
|
||||
if let Some(archive) = localized.first() {
|
||||
// A locale directory may point outside Data; it remains a read-only input as well.
|
||||
ensure_outside(archive.parent().context("language pack directory")?, output)?;
|
||||
}
|
||||
ensure_outside(binary, output)?;
|
||||
for (_, path) in &agreements {
|
||||
ensure_outside(path, output)?;
|
||||
}
|
||||
if let Some(source) = source {
|
||||
ensure_outside(source, output)?;
|
||||
}
|
||||
ensure!(
|
||||
!output.exists(),
|
||||
"staging output already exists; choose a new directory"
|
||||
);
|
||||
let name = binary.file_name().context("binary filename is missing")?;
|
||||
ensure!(
|
||||
matches!(
|
||||
name.to_str(),
|
||||
Some("MoonWell.exe" | "MoonWell" | "MoonWell.app")
|
||||
),
|
||||
"use a MoonWell player executable or .app"
|
||||
);
|
||||
fs::create_dir_all(output)?;
|
||||
if binary.is_dir() {
|
||||
for entry in WalkDir::new(binary).follow_links(false) {
|
||||
let entry = entry?;
|
||||
ensure!(
|
||||
!entry.path_is_symlink(),
|
||||
"bundle symlinks are not supported"
|
||||
);
|
||||
let dest = output.join(name).join(entry.path().strip_prefix(binary)?);
|
||||
if entry.file_type().is_dir() {
|
||||
fs::create_dir_all(dest)?;
|
||||
} else {
|
||||
fs::copy(entry.path(), dest)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fs::copy(binary, output.join(name))?;
|
||||
}
|
||||
let target_data = output.join("Data");
|
||||
fs::create_dir(&target_data)?;
|
||||
for (name, path) in agreements {
|
||||
fs::copy(path, target_data.join(name))?;
|
||||
}
|
||||
// Build custom patches first; an explicitly supplied source replaces that install's patch.
|
||||
if let Some(source) = source {
|
||||
pack(source, output)?;
|
||||
}
|
||||
let built_patches: HashSet<_> = fs::read_dir(&target_data)?
|
||||
.map(|e| e.map(|e| e.file_name().to_string_lossy().to_ascii_lowercase()))
|
||||
.collect::<std::io::Result<_>>()?;
|
||||
for archive in archives {
|
||||
let dest = target_data.join(archive.file_name().expect("archive name"));
|
||||
if !built_patches.contains(
|
||||
&archive
|
||||
.file_name()
|
||||
.expect("archive name")
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase(),
|
||||
) {
|
||||
fs::copy(&archive, dest)?;
|
||||
}
|
||||
}
|
||||
if !localized.is_empty() {
|
||||
let locale_data = target_data.join("ruRU");
|
||||
fs::create_dir(&locale_data)?;
|
||||
for archive in localized {
|
||||
fs::copy(
|
||||
&archive,
|
||||
locale_data.join(archive.file_name().expect("archive name")),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
fs::write(
|
||||
output.join("realmlist.wtf"),
|
||||
format!("set realmlist {host}\n"),
|
||||
)?;
|
||||
validate_distribution(output)?;
|
||||
println!("Staged {}", output.display());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn packed_archive_is_readable_by_the_actual_client_reader() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let source = temp.path().join("src");
|
||||
let patch = source.join("Data/patch-M/Interface");
|
||||
fs::create_dir_all(&patch).unwrap();
|
||||
let bytes = "-- MoonWell test: русский текст\n".repeat(500).into_bytes();
|
||||
fs::write(patch.join("Test.lua"), &bytes).unwrap();
|
||||
let small = b"-- compressed small file\n".repeat(50);
|
||||
fs::write(patch.join("Small.lua"), &small).unwrap();
|
||||
fs::write(patch.join("Tiny.lua"), b"hi").unwrap();
|
||||
fs::write(patch.join("Empty.lua"), b"").unwrap();
|
||||
let output = temp.path().join("dist");
|
||||
pack(&source, &output).unwrap();
|
||||
let archive = benilla_mpq::Archive::open(output.join("Data/patch-M.MPQ")).unwrap();
|
||||
assert_eq!(archive.read_file(r"Interface\Test.lua").unwrap(), bytes);
|
||||
assert_eq!(archive.read_file(r"Interface\Small.lua").unwrap(), small);
|
||||
assert_eq!(archive.read_file(r"Interface\Tiny.lua").unwrap(), b"hi");
|
||||
assert!(archive
|
||||
.read_file(r"Interface\Empty.lua")
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
assert!(pack(&source, &output).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrath_locale_source_is_rejected() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let source = temp.path().join("src");
|
||||
fs::create_dir_all(source.join("Data/ruRU/patch-ruRU-5")).unwrap();
|
||||
assert!(pack(&source, &temp.path().join("out")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_preserves_the_install_and_custom_sources_take_precedence() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let data = temp.path().join("install/Data");
|
||||
fs::create_dir_all(&data).unwrap();
|
||||
for name in AGREEMENTS {
|
||||
fs::write(
|
||||
data.join(name),
|
||||
format!("<html><body><p>Test {name}</p></body></html>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
for name in BASE_ARCHIVES.iter().chain([&"patch-m.mpq"]) {
|
||||
let mut spell = [0u8; 20];
|
||||
spell[..4].copy_from_slice(b"WDBC");
|
||||
spell[8..12].copy_from_slice(&173u32.to_le_bytes());
|
||||
ArchiveBuilder::new()
|
||||
.version(FormatVersion::V1)
|
||||
.add_file_data(b"old".to_vec(), "Test.txt")
|
||||
.add_file_data(spell.to_vec(), r"DBFilesClient\Spell.dbc")
|
||||
.build(data.join(name))
|
||||
.unwrap();
|
||||
crate::vanilla_mpq::normalize(&data.join(name)).unwrap();
|
||||
}
|
||||
let original = fs::read(data.join("patch-m.mpq")).unwrap();
|
||||
let locale = data.join("RURU");
|
||||
fs::create_dir(&locale).unwrap();
|
||||
fs::copy(data.join("dbc.mpq"), locale.join("patch-1.MPQ")).unwrap();
|
||||
fs::write(locale.join("notes.txt"), b"not a mounted archive").unwrap();
|
||||
let source = temp.path().join("src");
|
||||
fs::create_dir_all(source.join("Data/patch-M")).unwrap();
|
||||
fs::write(source.join("Data/patch-M/Test.txt"), b"custom").unwrap();
|
||||
let binary = temp.path().join("MoonWell.exe");
|
||||
fs::write(&binary, b"MZ\x00\x00 synthetic test executable").unwrap();
|
||||
let out = temp.path().join("out");
|
||||
stage(&binary, &data, &out, Some(&source), "127.0.0.1:3724").unwrap();
|
||||
for name in AGREEMENTS {
|
||||
assert_eq!(
|
||||
fs::read(out.join("Data").join(name)).unwrap(),
|
||||
fs::read(data.join(name)).unwrap()
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read(data.join("patch-m.mpq")).unwrap(), original);
|
||||
assert_eq!(
|
||||
fs::read(out.join("Data/ruRU/patch-1.MPQ")).unwrap(),
|
||||
fs::read(locale.join("patch-1.MPQ")).unwrap()
|
||||
);
|
||||
assert!(!out.join("Data/ruRU/notes.txt").exists());
|
||||
let archive = benilla_mpq::Archive::open(out.join("Data/patch-M.MPQ")).unwrap();
|
||||
assert_eq!(archive.read_file("Test.txt").unwrap(), b"custom");
|
||||
assert_eq!(
|
||||
fs::read_to_string(out.join("realmlist.wtf")).unwrap(),
|
||||
"set realmlist 127.0.0.1:3724\n"
|
||||
);
|
||||
assert!(stage(&binary, &data, &out, None, "127.0.0.1").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agreements_preserve_root_precedence_and_accept_loose_archives() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let data = temp.path().join("Data");
|
||||
fs::create_dir(&data).unwrap();
|
||||
assert!(agreement_files(&data)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("missing eula.html"));
|
||||
for name in AGREEMENTS {
|
||||
fs::write(data.join(name), b"test data agreement").unwrap();
|
||||
}
|
||||
fs::remove_file(data.join("scan.html")).unwrap();
|
||||
fs::remove_file(data.join("contest.html")).unwrap();
|
||||
assert_eq!(agreement_files(&data).unwrap().len(), 2);
|
||||
let root = temp.path().join("EULA.HTML");
|
||||
fs::write(&root, b"test root agreement").unwrap();
|
||||
fs::remove_file(data.join("tos.html")).unwrap();
|
||||
let archive = data.join("TOS.HTML.mpq");
|
||||
ArchiveBuilder::new()
|
||||
.version(FormatVersion::V1)
|
||||
.add_file_data(b"test archived agreement".to_vec(), "tos.html")
|
||||
.build(&archive)
|
||||
.unwrap();
|
||||
crate::vanilla_mpq::normalize(&archive).unwrap();
|
||||
let files = agreement_files(&data).unwrap();
|
||||
assert_eq!(files[0], ("eula.html".to_string(), root));
|
||||
assert_eq!(files[1], ("tos.html.MPQ".to_string(), archive.clone()));
|
||||
assert_eq!(
|
||||
benilla_mpq::Archive::open(archive)
|
||||
.unwrap()
|
||||
.read_file("tos.html")
|
||||
.unwrap(),
|
||||
b"test archived agreement"
|
||||
);
|
||||
fs::write(data.join("scan.html"), b"").unwrap();
|
||||
assert!(agreement_files(&data)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("empty agreement"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_auth_ports_and_wrath_archives_are_rejected() {
|
||||
for host in [
|
||||
"host:0",
|
||||
"host:65536",
|
||||
"host:abc",
|
||||
"host/path",
|
||||
"host\nset realm x",
|
||||
] {
|
||||
assert!(!valid_auth_host(host));
|
||||
}
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
ArchiveBuilder::new()
|
||||
.version(FormatVersion::V2)
|
||||
.add_file_data(b"test".to_vec(), "Test.txt")
|
||||
.build(temp.path().join("dbc.MPQ"))
|
||||
.unwrap();
|
||||
assert!(validate_data(temp.path()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrath_spell_table_in_a_russian_overlay_is_rejected() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let locale = temp.path().join("ruRU");
|
||||
fs::create_dir(&locale).unwrap();
|
||||
let mut spell = [0u8; 20];
|
||||
spell[..4].copy_from_slice(b"WDBC");
|
||||
spell[8..12].copy_from_slice(&234u32.to_le_bytes());
|
||||
let archive = locale.join("patch-1.MPQ");
|
||||
ArchiveBuilder::new()
|
||||
.version(FormatVersion::V1)
|
||||
.add_file_data(spell.to_vec(), r"DBFilesClient\Spell.dbc")
|
||||
.build(&archive)
|
||||
.unwrap();
|
||||
crate::vanilla_mpq::normalize(&archive).unwrap();
|
||||
assert!(russian_archives(temp.path())
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("5875 layout"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejecting_an_output_inside_an_input_creates_no_directories() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let input = temp.path().join("install");
|
||||
fs::create_dir(&input).unwrap();
|
||||
assert!(ensure_outside(&input, &input.join("scratch/out")).is_err());
|
||||
assert!(!input.join("scratch").exists());
|
||||
let outside = temp.path().join("new-parent/out");
|
||||
ensure_outside(&input, &outside).unwrap();
|
||||
assert!(
|
||||
!outside.parent().unwrap().exists(),
|
||||
"validation is read-only"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use s3::creds::Credentials;
|
||||
use s3::{Bucket, Region};
|
||||
|
||||
use crate::manifest::{self, Manifest};
|
||||
|
||||
pub trait Store {
|
||||
fn get(&self, key: &str) -> Result<Option<Vec<u8>>>;
|
||||
fn matches(&self, _key: &str, _file: &Path) -> Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
fn upload(&self, key: &str, file: &Path) -> Result<()>;
|
||||
fn put_manifest(&self, key: &str, data: &[u8]) -> Result<()>;
|
||||
}
|
||||
|
||||
pub struct S3Store {
|
||||
bucket: Box<Bucket>,
|
||||
}
|
||||
|
||||
const PART_BYTES: usize = s3::bucket::CHUNK_SIZE;
|
||||
const UPLOAD_WORKERS: usize = 4;
|
||||
|
||||
fn read_part(reader: &mut impl Read) -> Result<Vec<u8>> {
|
||||
let mut bytes = Vec::with_capacity(PART_BYTES);
|
||||
reader.take(PART_BYTES as u64).read_to_end(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
// Yandex's unencrypted S3 objects expose MD5 or MD5-of-parts ETags. SHA-256
|
||||
// remains the manifest's integrity contract; ETags allow verified upload reuse.
|
||||
fn file_etag(path: &Path) -> Result<(u64, String)> {
|
||||
let mut reader = File::open(path)?;
|
||||
let mut size = 0;
|
||||
let mut part_hashes = Vec::new();
|
||||
loop {
|
||||
let bytes = read_part(&mut reader)?;
|
||||
size += bytes.len() as u64;
|
||||
part_hashes.push(md5::compute(&bytes));
|
||||
if bytes.len() < PART_BYTES {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let etag = if part_hashes.len() == 1 {
|
||||
format!("{:x}", part_hashes[0])
|
||||
} else {
|
||||
let mut digest = md5::Context::new();
|
||||
for part in &part_hashes {
|
||||
digest.consume(part.0);
|
||||
}
|
||||
format!("{:x}-{}", digest.finalize(), part_hashes.len())
|
||||
};
|
||||
Ok((size, etag))
|
||||
}
|
||||
|
||||
fn read_aws_env(path: &Path) -> Result<HashMap<String, String>> {
|
||||
// The source project's .env permits unquoted Windows paths containing spaces.
|
||||
// Read only S3 settings with its existing literal-value semantics; do not interpolate secrets.
|
||||
let text = std::fs::read_to_string(path).context("cannot read deployment .env")?;
|
||||
let mut values = HashMap::new();
|
||||
for line in text.trim_start_matches('\u{feff}').lines() {
|
||||
let line = line.trim().strip_prefix("export ").unwrap_or(line.trim());
|
||||
let Some((name, value)) = line.split_once('=') else {
|
||||
continue;
|
||||
};
|
||||
let name = name.trim();
|
||||
if !name.starts_with("AWS_") {
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'),
|
||||
"invalid AWS environment variable name"
|
||||
);
|
||||
let value = value.trim();
|
||||
let value = if value.len() >= 2
|
||||
&& ((value.starts_with('"') && value.ends_with('"'))
|
||||
|| (value.starts_with('\'') && value.ends_with('\'')))
|
||||
{
|
||||
&value[1..value.len() - 1]
|
||||
} else {
|
||||
value
|
||||
};
|
||||
values.insert(name.into(), value.into());
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
impl S3Store {
|
||||
fn object_matches(&self, key: &str, size: u64, etag: &str) -> Result<bool> {
|
||||
let (head, status) = self
|
||||
.bucket
|
||||
.head_object(key)
|
||||
.map_err(|_| anyhow::anyhow!("S3 HEAD failed for {key}"))?;
|
||||
if status == 404 {
|
||||
return Ok(false);
|
||||
}
|
||||
ensure!(status == 200, "S3 HEAD {key}: HTTP {status}");
|
||||
Ok(head.content_length == i64::try_from(size).ok()
|
||||
&& head.e_tag.as_deref().map(|s| s.trim_matches('"')) == Some(etag))
|
||||
}
|
||||
|
||||
fn upload_parts(&self, key: &str, path: &Path, size: u64) -> Result<()> {
|
||||
let mut reader = File::open(path)?;
|
||||
if size < PART_BYTES as u64 {
|
||||
let bytes = read_part(&mut reader)?;
|
||||
let response = self
|
||||
.bucket
|
||||
.put_object(key, &bytes)
|
||||
.map_err(|_| anyhow::anyhow!("S3 upload failed for {key}"))?;
|
||||
ensure!(
|
||||
(200..300).contains(&response.status_code()),
|
||||
"S3 upload {key}: HTTP {}",
|
||||
response.status_code()
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let content_type = "application/octet-stream";
|
||||
let upload = self
|
||||
.bucket
|
||||
.initiate_multipart_upload(key, content_type)
|
||||
.map_err(|_| anyhow::anyhow!("S3 multipart start failed for {key}"))?;
|
||||
let result = (|| {
|
||||
let mut parts = Vec::new();
|
||||
let mut finished = false;
|
||||
let mut sent = 0_u64;
|
||||
while !finished {
|
||||
let batch = std::thread::scope(|scope| -> Result<Vec<s3::serde_types::Part>> {
|
||||
let mut handles = Vec::new();
|
||||
for _ in 0..UPLOAD_WORKERS {
|
||||
if finished {
|
||||
break;
|
||||
}
|
||||
let bytes = read_part(&mut reader)?;
|
||||
finished = bytes.len() < PART_BYTES;
|
||||
sent += bytes.len() as u64;
|
||||
let number = (parts.len() + handles.len() + 1) as u32;
|
||||
let upload_id = &upload.upload_id;
|
||||
handles.push(scope.spawn(move || {
|
||||
let expected = format!("{:x}", md5::compute(&bytes));
|
||||
let part = self
|
||||
.bucket
|
||||
.put_multipart_chunk(&bytes, key, number, upload_id, content_type)
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!(
|
||||
"S3 multipart upload failed for {key}, part {number}"
|
||||
)
|
||||
})?;
|
||||
ensure!(
|
||||
part.etag.trim_matches('"') == expected,
|
||||
"S3 part checksum mismatch for {key}, part {number}"
|
||||
);
|
||||
Ok(part)
|
||||
}));
|
||||
}
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|handle| {
|
||||
handle
|
||||
.join()
|
||||
.map_err(|_| anyhow::anyhow!("S3 upload worker failed for {key}"))?
|
||||
})
|
||||
.collect()
|
||||
})?;
|
||||
parts.extend(batch);
|
||||
println!("Uploading {key}: {sent}/{size} bytes");
|
||||
}
|
||||
let response = self
|
||||
.bucket
|
||||
.complete_multipart_upload(key, &upload.upload_id, parts)
|
||||
.map_err(|_| anyhow::anyhow!("S3 multipart completion failed for {key}"))?;
|
||||
ensure!(
|
||||
(200..300).contains(&response.status_code()),
|
||||
"S3 multipart completion {key}: HTTP {}",
|
||||
response.status_code()
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = self.bucket.abort_upload(key, &upload.upload_id);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn check_storage(&self) -> Result<()> {
|
||||
let nonce = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_nanos();
|
||||
let key = format!("moonwell-deploy-check/{nonce}/multipart test.bin");
|
||||
let manifest_key = format!("moonwell-deploy-check/{nonce}/manifest.json");
|
||||
let path = std::env::temp_dir().join(format!("moonwell-s3-check-{nonce}.bin"));
|
||||
let bytes: Vec<u8> = (0..10 * 1024 * 1024).map(|n| (n % 251) as u8).collect();
|
||||
std::fs::write(&path, &bytes)?;
|
||||
let result = (|| {
|
||||
self.upload(&key, &path)?;
|
||||
self.upload(&key, &path)?;
|
||||
let downloaded = self.get(&key)?.context("S3 check object disappeared")?;
|
||||
ensure!(downloaded == bytes, "S3 round-trip checksum mismatch");
|
||||
let mut changed = bytes.clone();
|
||||
changed[0] ^= 1;
|
||||
std::fs::write(&path, &changed)?;
|
||||
self.upload(&key, &path)?;
|
||||
ensure!(
|
||||
self.get(&key)?.as_deref() == Some(changed.as_slice()),
|
||||
"S3 same-size replacement checksum mismatch"
|
||||
);
|
||||
let inventory = b"{\"probe\":true}\n";
|
||||
self.put_manifest(&manifest_key, inventory)?;
|
||||
ensure!(
|
||||
self.get(&manifest_key)?.as_deref() == Some(inventory),
|
||||
"S3 JSON manifest round-trip mismatch"
|
||||
);
|
||||
Ok(())
|
||||
})();
|
||||
let cleanup = self
|
||||
.bucket
|
||||
.delete_object(&key)
|
||||
.map_err(|_| anyhow::anyhow!("cannot clean up S3 check object: {key}"))
|
||||
.and_then(|r| {
|
||||
ensure!(
|
||||
(200..300).contains(&r.status_code()),
|
||||
"cannot clean up S3 check object: {key}"
|
||||
);
|
||||
Ok(())
|
||||
});
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let manifest_cleanup = self
|
||||
.bucket
|
||||
.delete_object(&manifest_key)
|
||||
.map_err(|_| anyhow::anyhow!("cannot clean up S3 check inventory: {manifest_key}"))
|
||||
.and_then(|r| {
|
||||
ensure!(
|
||||
(200..300).contains(&r.status_code()),
|
||||
"cannot clean up S3 check inventory: {manifest_key}"
|
||||
);
|
||||
Ok(())
|
||||
});
|
||||
result?;
|
||||
cleanup?;
|
||||
manifest_cleanup?;
|
||||
println!("S3 check passed: 10 MiB multipart round-trip verified; temporary object removed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn from_env(path: &Path) -> Result<Self> {
|
||||
let values = read_aws_env(path)?;
|
||||
let get = |key: &str| {
|
||||
std::env::var(key)
|
||||
.ok()
|
||||
.filter(|v| !v.is_empty())
|
||||
.or_else(|| values.get(key).cloned().filter(|v| !v.is_empty()))
|
||||
};
|
||||
let required = |key: &str| get(key).with_context(|| format!("{key} is not set"));
|
||||
let credentials = Credentials::new(
|
||||
Some(&required("AWS_ACCESS_KEY_ID")?),
|
||||
Some(&required("AWS_SECRET_ACCESS_KEY")?),
|
||||
None,
|
||||
get("AWS_SESSION_TOKEN").as_deref(),
|
||||
None,
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("cannot initialize S3 credentials"))?;
|
||||
let endpoint = required("AWS_ENDPOINT")?;
|
||||
ensure!(
|
||||
endpoint.starts_with("https://"),
|
||||
"AWS_ENDPOINT must use HTTPS"
|
||||
);
|
||||
let bucket = Bucket::new(
|
||||
&required("AWS_BUCKET")?,
|
||||
Region::Custom {
|
||||
region: required("AWS_DEFAULT_REGION")?,
|
||||
endpoint,
|
||||
},
|
||||
credentials,
|
||||
)
|
||||
.map_err(|_| anyhow::anyhow!("cannot initialize S3 client"))?;
|
||||
let bucket = match get("AWS_USE_PATH_STYLE_ENDPOINT").as_deref() {
|
||||
Some("true" | "1") => bucket.with_path_style(),
|
||||
None | Some("false" | "0") => bucket,
|
||||
_ => anyhow::bail!("AWS_USE_PATH_STYLE_ENDPOINT must be true or false"),
|
||||
};
|
||||
Ok(Self { bucket })
|
||||
}
|
||||
}
|
||||
|
||||
impl Store for S3Store {
|
||||
fn matches(&self, key: &str, file: &Path) -> Result<bool> {
|
||||
let (size, etag) = file_etag(file)?;
|
||||
self.object_matches(key, size, &etag)
|
||||
}
|
||||
fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
|
||||
ensure!(manifest::valid_path(key), "invalid S3 key");
|
||||
let response = self
|
||||
.bucket
|
||||
.get_object(key)
|
||||
.map_err(|_| anyhow::anyhow!("S3 GET failed for {key}"))?;
|
||||
match response.status_code() {
|
||||
404 => Ok(None),
|
||||
200 => Ok(Some(response.to_vec())),
|
||||
code => anyhow::bail!("S3 GET {key}: HTTP {code}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(&self, key: &str, file: &Path) -> Result<()> {
|
||||
let (size, etag) = file_etag(file)?;
|
||||
if self.object_matches(key, size, &etag)? {
|
||||
println!("Reusing verified S3 object: {key}");
|
||||
return Ok(());
|
||||
}
|
||||
self.upload_parts(key, file, size)?;
|
||||
ensure!(
|
||||
self.object_matches(key, size, &etag)?,
|
||||
"S3 object checksum/size mismatch for {key}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn put_manifest(&self, key: &str, data: &[u8]) -> Result<()> {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
headers.insert(
|
||||
http::header::CACHE_CONTROL,
|
||||
"no-cache, no-store, must-revalidate".parse()?,
|
||||
);
|
||||
let response = self
|
||||
.bucket
|
||||
.put_object_with_content_type_and_headers(key, data, "application/json", Some(headers))
|
||||
.map_err(|_| anyhow::anyhow!("S3 manifest write failed for {key}"))?;
|
||||
ensure!(
|
||||
(200..300).contains(&response.status_code()),
|
||||
"S3 manifest {key}: HTTP {}",
|
||||
response.status_code()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn publish(
|
||||
store: &impl Store,
|
||||
dir: &Path,
|
||||
mut m: Manifest,
|
||||
prefix: &str,
|
||||
manifest_key: &str,
|
||||
dry_run: bool,
|
||||
) -> Result<()> {
|
||||
manifest::validate(&m)?;
|
||||
ensure!(
|
||||
manifest::valid_path(prefix) && manifest::valid_path(manifest_key),
|
||||
"invalid publication prefix or manifest key"
|
||||
);
|
||||
ensure!(
|
||||
prefix != "World of Warcraft" && manifest_key != "manifest.json",
|
||||
"the legacy 3.3.5 publication keys are reserved"
|
||||
);
|
||||
let release = format!("{prefix}/releases/{}", m.build_hash);
|
||||
for file in &mut m.files {
|
||||
file.object_key = Some(format!("{release}/{}", file.path));
|
||||
}
|
||||
println!(
|
||||
"Release: {release}; {} files; active manifest: {manifest_key}",
|
||||
m.files.len()
|
||||
);
|
||||
// Check credentials/read access before uploading anything, and refuse malformed active inventories.
|
||||
let previous = if let Some(previous) = store.get(manifest_key)? {
|
||||
let previous: Manifest = serde_json::from_slice(&previous)
|
||||
.context("invalid active manifest; publication stopped")?;
|
||||
manifest::validate(&previous)?;
|
||||
Some(previous)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for file in &mut m.files {
|
||||
let path = dir.join(&file.path);
|
||||
let (size, hash) = manifest::hash_file(&path)?;
|
||||
ensure!(
|
||||
size == file.size && hash == file.sha256,
|
||||
"package changed after hashing: {}",
|
||||
file.path
|
||||
);
|
||||
let reusable = previous
|
||||
.as_ref()
|
||||
.and_then(|previous| {
|
||||
previous.files.iter().find(|old| {
|
||||
old.path == file.path && old.size == file.size && old.sha256 == file.sha256
|
||||
})
|
||||
})
|
||||
.and_then(|old| old.object_key.as_deref())
|
||||
.filter(|key| key.starts_with(&format!("{prefix}/releases/")));
|
||||
let reused = if let Some(key) = reusable {
|
||||
if store.matches(key, &path)? {
|
||||
file.object_key = Some(key.into());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if !dry_run && !reused {
|
||||
store.upload(file.object_key.as_deref().expect("release key"), &path)?;
|
||||
}
|
||||
println!(
|
||||
"{} {} ({} bytes)",
|
||||
match (dry_run, reused) {
|
||||
(true, true) => "Would reuse",
|
||||
(true, false) => "Would upload",
|
||||
(false, true) => "Reused",
|
||||
(false, false) => "Uploaded",
|
||||
},
|
||||
file.path,
|
||||
size
|
||||
);
|
||||
}
|
||||
if dry_run {
|
||||
return Ok(());
|
||||
}
|
||||
// A concurrent editor or build must not produce a manifest describing different bytes.
|
||||
for file in &m.files {
|
||||
let (size, hash) = manifest::hash_file(&dir.join(&file.path))?;
|
||||
ensure!(
|
||||
size == file.size && hash == file.sha256,
|
||||
"package changed during upload: {}",
|
||||
file.path
|
||||
);
|
||||
}
|
||||
let mut bytes = serde_json::to_vec_pretty(&m)?;
|
||||
bytes.push(b'\n');
|
||||
store.put_manifest(&format!("{release}/manifest.json"), &bytes)?;
|
||||
store.put_manifest(manifest_key, &bytes)?;
|
||||
println!("Published {}", m.build_hash);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn etags_match_small_and_multipart_s3_golden_vectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("object");
|
||||
std::fs::write(&path, b"abc").unwrap();
|
||||
assert_eq!(
|
||||
file_etag(&path).unwrap(),
|
||||
(3, "900150983cd24fb0d6963f7d28e17f72".into())
|
||||
);
|
||||
std::fs::write(&path, []).unwrap();
|
||||
assert_eq!(
|
||||
file_etag(&path).unwrap(),
|
||||
(0, "d41d8cd98f00b204e9800998ecf8427e".into())
|
||||
);
|
||||
let mut bytes = vec![b'a'; PART_BYTES];
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
file_etag(&path).unwrap(),
|
||||
(8388608, "49bcf0ebc7b48b92488324fed7d003f9-2".into())
|
||||
);
|
||||
bytes.extend_from_slice(b"bc");
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
file_etag(&path).unwrap(),
|
||||
(8388610, "097020083a0e59701fcdfbc5edb191ba-2".into())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_dotenv_windows_paths_do_not_break_literal_credentials() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join(".env");
|
||||
std::fs::write(&path, "\u{feff}WOW_HOME=C:\\Games\\World of Warcraft 3.3.5\nexport AWS_SECRET_ACCESS_KEY='literal$not-expanded'\nAWS_BUCKET=client\n").unwrap();
|
||||
let values = read_aws_env(&path).unwrap();
|
||||
assert_eq!(values.len(), 2);
|
||||
assert_eq!(values["AWS_SECRET_ACCESS_KEY"], "literal$not-expanded");
|
||||
}
|
||||
use std::cell::RefCell;
|
||||
|
||||
struct FakeStore {
|
||||
operations: RefCell<Vec<String>>,
|
||||
fail_upload: bool,
|
||||
}
|
||||
impl Store for FakeStore {
|
||||
fn get(&self, _: &str) -> Result<Option<Vec<u8>>> {
|
||||
Ok(None)
|
||||
}
|
||||
fn upload(&self, key: &str, _: &Path) -> Result<()> {
|
||||
ensure!(!self.fail_upload, "simulated upload failure");
|
||||
self.operations.borrow_mut().push(key.into());
|
||||
Ok(())
|
||||
}
|
||||
fn put_manifest(&self, key: &str, _: &[u8]) -> Result<()> {
|
||||
self.operations.borrow_mut().push(key.into());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_upload_does_not_switch_manifest_and_dry_run_never_writes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("MoonWell.exe"), b"test").unwrap();
|
||||
let m = manifest::scan(dir.path()).unwrap();
|
||||
let store = FakeStore {
|
||||
operations: RefCell::new(vec![]),
|
||||
fail_upload: true,
|
||||
};
|
||||
assert!(publish(
|
||||
&store,
|
||||
dir.path(),
|
||||
m.clone(),
|
||||
"MoonWell",
|
||||
"active.json",
|
||||
false
|
||||
)
|
||||
.is_err());
|
||||
assert!(store.operations.borrow().is_empty());
|
||||
publish(&store, dir.path(), m, "MoonWell", "active.json", true).unwrap();
|
||||
assert!(store.operations.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_switch_follows_all_file_uploads_and_release_inventory() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("MoonWell.exe"), b"test").unwrap();
|
||||
let m = manifest::scan(dir.path()).unwrap();
|
||||
let store = FakeStore {
|
||||
operations: RefCell::new(vec![]),
|
||||
fail_upload: false,
|
||||
};
|
||||
publish(&store, dir.path(), m, "MoonWell", "active.json", false).unwrap();
|
||||
let ops = store.operations.borrow();
|
||||
assert!(ops[0].ends_with("/MoonWell.exe"));
|
||||
assert!(ops[1].ends_with("/manifest.json"));
|
||||
assert_eq!(ops[2], "active.json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unchanged_files_reuse_verified_objects_inside_the_release_prefix() {
|
||||
struct ReuseStore {
|
||||
previous: Vec<u8>,
|
||||
uploads: RefCell<Vec<String>>,
|
||||
published: RefCell<Option<Manifest>>,
|
||||
}
|
||||
impl Store for ReuseStore {
|
||||
fn get(&self, _: &str) -> Result<Option<Vec<u8>>> {
|
||||
Ok(Some(self.previous.clone()))
|
||||
}
|
||||
fn matches(&self, key: &str, _: &Path) -> Result<bool> {
|
||||
ensure!(
|
||||
key == "MoonWell/releases/old/MoonWell.exe",
|
||||
"unexpected source prefix"
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
fn upload(&self, key: &str, _: &Path) -> Result<()> {
|
||||
self.uploads.borrow_mut().push(key.into());
|
||||
Ok(())
|
||||
}
|
||||
fn put_manifest(&self, _: &str, bytes: &[u8]) -> Result<()> {
|
||||
*self.published.borrow_mut() = Some(serde_json::from_slice(bytes)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("MoonWell.exe"), b"game").unwrap();
|
||||
let mut old = manifest::scan(dir.path()).unwrap();
|
||||
old.files[0].object_key = Some("MoonWell/releases/old/MoonWell.exe".into());
|
||||
std::fs::write(dir.path().join("vcruntime140.dll"), b"runtime").unwrap();
|
||||
let new = manifest::scan(dir.path()).unwrap();
|
||||
for source in [
|
||||
"MoonWell/releases/old/MoonWell.exe",
|
||||
"Other/releases/old/MoonWell.exe",
|
||||
] {
|
||||
old.files[0].object_key = Some(source.into());
|
||||
let store = ReuseStore {
|
||||
previous: serde_json::to_vec(&old).unwrap(),
|
||||
uploads: RefCell::new(vec![]),
|
||||
published: RefCell::new(None),
|
||||
};
|
||||
publish(
|
||||
&store,
|
||||
dir.path(),
|
||||
new.clone(),
|
||||
"MoonWell",
|
||||
"active.json",
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let result = store.published.borrow();
|
||||
let result = result.as_ref().unwrap();
|
||||
assert_eq!(result.build_hash, new.build_hash);
|
||||
let game = result
|
||||
.files
|
||||
.iter()
|
||||
.find(|file| file.path == "MoonWell.exe")
|
||||
.unwrap();
|
||||
if source.starts_with("MoonWell/") {
|
||||
assert_eq!(store.uploads.borrow().len(), 1);
|
||||
assert_eq!(game.object_key.as_deref(), Some(source));
|
||||
} else {
|
||||
assert_eq!(store.uploads.borrow().len(), 2);
|
||||
assert!(game
|
||||
.object_key
|
||||
.as_deref()
|
||||
.unwrap()
|
||||
.starts_with(&format!("MoonWell/releases/{}/", new.build_hash)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Normalize wow-mpq's small-file blocks to the stored/sectored envelope read by benilla-mpq.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Seek, SeekFrom, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{ensure, Result};
|
||||
use wow_mpq::crypto::{decrypt_block, encrypt_block, hash_string, hash_type};
|
||||
|
||||
pub fn normalize(path: &Path) -> Result<()> {
|
||||
let mut file = OpenOptions::new().read(true).write(true).open(path)?;
|
||||
let original_size = file.metadata()?.len();
|
||||
let mut header = [0u8; 32];
|
||||
file.read_exact(&mut header)?;
|
||||
ensure!(
|
||||
&header[..4] == b"MPQ\x1a" && header[12..14] == [0, 0],
|
||||
"expected generated MPQ v1"
|
||||
);
|
||||
let word =
|
||||
|offset| u32::from_le_bytes(header[offset..offset + 4].try_into().expect("header word"));
|
||||
let table_pos = word(20) as u64;
|
||||
let count = word(28) as usize;
|
||||
ensure!(
|
||||
table_pos <= original_size && count as u64 <= (original_size - table_pos) / 16,
|
||||
"invalid generated block table"
|
||||
);
|
||||
let mut table_bytes = vec![0; count * 16];
|
||||
file.seek(SeekFrom::Start(table_pos))?;
|
||||
file.read_exact(&mut table_bytes)?;
|
||||
let mut table: Vec<u32> = table_bytes
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| u32::from_le_bytes(*c))
|
||||
.collect();
|
||||
let key = hash_string("(block table)", hash_type::FILE_KEY);
|
||||
decrypt_block(&mut table, key);
|
||||
const SINGLE_UNIT: u32 = 0x0100_0000;
|
||||
const COMPRESS: u32 = 0x0000_0200;
|
||||
for block in table.as_chunks_mut::<4>().0 {
|
||||
if block[3] & SINGLE_UNIT == 0 {
|
||||
continue;
|
||||
}
|
||||
ensure!(
|
||||
block[3] & (0x0001_0000 | 0x0400_0000) == 0,
|
||||
"unexpected encrypted or CRC block"
|
||||
);
|
||||
if block[3] & COMPRESS != 0 {
|
||||
// wow-mpq chooses single-unit only for <= one sector. Preserve compressed bytes,
|
||||
// prepend the one-sector offset table, and redirect this block to the appended copy.
|
||||
ensure!(
|
||||
block[2] <= 4096 && u64::from(block[0]) + u64::from(block[1]) <= original_size,
|
||||
"invalid small-file block"
|
||||
);
|
||||
let mut bytes = vec![0; block[1] as usize];
|
||||
file.seek(SeekFrom::Start(block[0] as u64))?;
|
||||
file.read_exact(&mut bytes)?;
|
||||
let pos = file.seek(SeekFrom::End(0))?;
|
||||
block[0] = u32::try_from(pos)?;
|
||||
block[1] = block[1]
|
||||
.checked_add(8)
|
||||
.ok_or_else(|| anyhow::anyhow!("MPQ size overflow"))?;
|
||||
file.write_all(&8u32.to_le_bytes())?;
|
||||
file.write_all(&block[1].to_le_bytes())?;
|
||||
file.write_all(&bytes)?;
|
||||
}
|
||||
block[3] &= !SINGLE_UNIT;
|
||||
}
|
||||
encrypt_block(&mut table, key);
|
||||
file.seek(SeekFrom::Start(table_pos))?;
|
||||
for word in table {
|
||||
file.write_all(&word.to_le_bytes())?;
|
||||
}
|
||||
let size = u32::try_from(file.metadata()?.len())?;
|
||||
file.seek(SeekFrom::Start(8))?;
|
||||
file.write_all(&size.to_le_bytes())?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "moonwell"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "The MoonWell launcher: platform branding on top of benilla"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["dev"]
|
||||
dev = ["benilla-app/dev"]
|
||||
tracy = ["benilla-app/tracy"]
|
||||
trace_chrome = ["benilla-app/trace_chrome"]
|
||||
|
||||
[dependencies]
|
||||
benilla-app = { path = "../benilla-app", default-features = false }
|
||||
bevy.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
image = { version = "0.25", default-features = false, features = ["ico"] }
|
||||
winit = { version = "0.30", default-features = false }
|
||||
|
||||
[build-dependencies]
|
||||
benilla-buildstamp = { path = "../benilla-buildstamp" }
|
||||
winresource = "0.1.31"
|
||||
|
||||
[[bin]]
|
||||
name = "MoonWell"
|
||||
path = "src/main.rs"
|
||||
test = false
|
||||
@@ -0,0 +1,43 @@
|
||||
# MoonWell
|
||||
|
||||
MoonWell starts benilla through `run_with` and adds its own window title and platform
|
||||
branding. The client build banner identifies it as `extended`.
|
||||
|
||||
For player package staging, Rust MPQ builds, launcher manifests and S3 publication,
|
||||
see [MoonWell deployment](../moonwell-deploy/README.md).
|
||||
|
||||
Build the player executable on Windows:
|
||||
|
||||
```powershell
|
||||
cargo build -p moonwell --release --no-default-features
|
||||
```
|
||||
|
||||
The executable is `target/release/MoonWell.exe`. Provide your own WoW 1.12.1
|
||||
`Data/` or `WoW/Data/` beside it, or set `WOW_DATA` to your install's Data folder.
|
||||
Local client state is in `benilla-config/` beside the executable.
|
||||
|
||||
For development, run `cargo run -p moonwell --profile play`. The `dev` feature
|
||||
forwards benilla's instruments; disable it for a player build.
|
||||
|
||||
Replace `crates/moonwell/assets/moonwell.ico` with your own multi-resolution Windows icon and
|
||||
rebuild to update both the executable's icon and the running window's icons.
|
||||
The icon is embedded; the player does not need the source `.ico` file.
|
||||
|
||||
On macOS, build and package a player app from the repository root (Python 3.11+):
|
||||
|
||||
```sh
|
||||
cargo build -p moonwell --release --no-default-features
|
||||
python3 crates/moonwell/package_macos.py \
|
||||
--binary target/release/MoonWell \
|
||||
--icon /path/to/MoonWell.icns
|
||||
```
|
||||
|
||||
This creates `target/release/bundle/MoonWell.app` with the MoonWell name and app
|
||||
icon. Packaging requires a macOS executable and an ICNS icon; it does not convert a
|
||||
Windows EXE into a Mac application. Build natively on each target Mac architecture.
|
||||
Pass `--output` to choose a different destination and `--bundle-id` to set your
|
||||
application identifier. An existing destination is never overwritten.
|
||||
|
||||
Launch the `.app` from Finder. Its launcher finds your own `Data/` or `WoW/Data/`
|
||||
beside `MoonWell.app` and keeps `benilla-config/` there too, outside the bundle.
|
||||
Explicit `WOW_DATA` and `BENILLA_HOME` values take priority.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 165 KiB |
@@ -0,0 +1,17 @@
|
||||
//! Stamp the build and embed MoonWell's Windows icon and product metadata.
|
||||
|
||||
fn main() {
|
||||
benilla_buildstamp::emit();
|
||||
println!("cargo::rerun-if-changed=assets/moonwell.ico");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||
winresource::WindowsResource::new()
|
||||
.set_icon("assets/moonwell.ico")
|
||||
.set("ProductName", "MoonWell")
|
||||
.set("FileDescription", "MoonWell")
|
||||
.set("InternalName", "MoonWell")
|
||||
.set("OriginalFilename", "MoonWell.exe")
|
||||
.compile()
|
||||
.expect("compile MoonWell's Windows resources");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package a macOS player build and an ICNS icon as MoonWell.app."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import plistlib
|
||||
import shutil
|
||||
import struct
|
||||
import tomllib
|
||||
|
||||
|
||||
# Keep the install and writable client state beside the app, outside the bundle.
|
||||
LAUNCHER = '''#!/bin/sh
|
||||
set -eu
|
||||
macos_dir=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
|
||||
player_dir=$(CDPATH= cd -- "$macos_dir/../../.." && pwd)
|
||||
if [ "${BENILLA_HOME+x}" != x ]; then
|
||||
export BENILLA_HOME="$player_dir/benilla-config"
|
||||
fi
|
||||
if [ "${WOW_DATA+x}" != x ]; then
|
||||
for data_dir in "$player_dir/Data" "$player_dir/WoW/Data"; do
|
||||
if [ -d "$data_dir" ]; then
|
||||
export WOW_DATA="$data_dir"
|
||||
break
|
||||
fi
|
||||
done
|
||||
fi
|
||||
exec "$macos_dir/MoonWell" "$@"
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--binary", type=Path, required=True,
|
||||
help="MoonWell binary built on macOS without default features")
|
||||
parser.add_argument("--icon", type=Path, required=True, help="application icon in .icns format")
|
||||
parser.add_argument("--output", type=Path, default=Path("target/release/bundle/MoonWell.app"))
|
||||
parser.add_argument("--bundle-id", default="org.moonwell.client")
|
||||
args = parser.parse_args()
|
||||
|
||||
with args.binary.open("rb") as binary:
|
||||
magic = binary.read(4)
|
||||
if magic not in (b"\xfe\xed\xfa\xce", b"\xce\xfa\xed\xfe",
|
||||
b"\xfe\xed\xfa\xcf", b"\xcf\xfa\xed\xfe",
|
||||
b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca",
|
||||
b"\xca\xfe\xba\xbf", b"\xbf\xba\xfe\xca"):
|
||||
parser.error("--binary must be a macOS Mach-O executable, not a Windows EXE")
|
||||
with args.icon.open("rb") as icon:
|
||||
header = icon.read(8)
|
||||
if len(header) != 8 or header[:4] != b"icns" or struct.unpack(">I", header[4:])[0] != args.icon.stat().st_size:
|
||||
parser.error("--icon must be an ICNS file with a valid container header")
|
||||
if args.output.suffix != ".app":
|
||||
parser.error("--output must end in .app")
|
||||
if args.output.exists():
|
||||
parser.error("--output already exists; choose a new path or remove the old bundle first")
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
with (root / "Cargo.toml").open("rb") as manifest:
|
||||
version = tomllib.load(manifest)["workspace"]["package"]["version"]
|
||||
|
||||
contents = args.output / "Contents"
|
||||
macos = contents / "MacOS"
|
||||
resources = contents / "Resources"
|
||||
macos.mkdir(parents=True)
|
||||
resources.mkdir()
|
||||
shutil.copyfile(args.binary, macos / "MoonWell")
|
||||
(macos / "MoonWell").chmod(0o755)
|
||||
(macos / "launch").write_text(LAUNCHER, encoding="utf-8", newline="\n")
|
||||
(macos / "launch").chmod(0o755)
|
||||
shutil.copyfile(args.icon, resources / "MoonWell.icns")
|
||||
with (contents / "Info.plist").open("wb") as plist:
|
||||
plistlib.dump({
|
||||
"CFBundleName": "MoonWell",
|
||||
"CFBundleDisplayName": "MoonWell",
|
||||
"CFBundleExecutable": "launch",
|
||||
"CFBundleIconFile": "MoonWell.icns",
|
||||
"CFBundleIdentifier": args.bundle_id,
|
||||
"CFBundleInfoDictionaryVersion": "6.0",
|
||||
"CFBundlePackageType": "APPL",
|
||||
"CFBundleShortVersionString": version,
|
||||
"CFBundleVersion": version,
|
||||
"NSHighResolutionCapable": True,
|
||||
}, plist)
|
||||
print(os.fspath(args.output.resolve()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
//! MoonWell's branding lives in this launcher, on top of the stock client.
|
||||
|
||||
use benilla_app::BuildId;
|
||||
use bevy::prelude::*;
|
||||
use bevy::window::PrimaryWindow;
|
||||
|
||||
struct MoonWellPlugin;
|
||||
|
||||
impl Plugin for MoonWellPlugin {
|
||||
fn build(&self, app: &mut App) {
|
||||
let world = app.world_mut();
|
||||
for mut window in world
|
||||
.query_filtered::<&mut Window, With<PrimaryWindow>>()
|
||||
.iter_mut(world)
|
||||
{
|
||||
window.title = "MoonWell".into();
|
||||
window.name = Some("MoonWell".into());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
app.add_systems(Startup, set_window_icon);
|
||||
}
|
||||
}
|
||||
|
||||
/// An exclusive system keeps winit's thread-local window access on the main thread.
|
||||
#[cfg(windows)]
|
||||
fn set_window_icon(world: &mut World) {
|
||||
use winit::platform::windows::WindowExtWindows;
|
||||
|
||||
let image = image::load_from_memory_with_format(
|
||||
include_bytes!("../assets/moonwell.ico"),
|
||||
image::ImageFormat::Ico,
|
||||
)
|
||||
.expect("decode MoonWell's embedded icon")
|
||||
.into_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let icon = winit::window::Icon::from_rgba(image.into_raw(), width, height)
|
||||
.expect("create MoonWell's window icon");
|
||||
|
||||
let entity = world
|
||||
.query_filtered::<Entity, With<PrimaryWindow>>()
|
||||
.single(world)
|
||||
.expect("the client has one primary window");
|
||||
bevy::winit::WINIT_WINDOWS.with_borrow(|windows| {
|
||||
let window = windows
|
||||
.get_window(entity)
|
||||
.expect("the primary window exists before Startup");
|
||||
window.set_window_icon(Some(icon.clone()));
|
||||
window.set_taskbar_icon(Some(icon));
|
||||
});
|
||||
}
|
||||
|
||||
fn main() -> benilla_app::AppExit {
|
||||
benilla_app::run_with(
|
||||
BuildId {
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
describe: env!("BENILLA_GIT_DESCRIBE"),
|
||||
sha: env!("BENILLA_GIT_SHA"),
|
||||
short: env!("BENILLA_GIT_SHORT"),
|
||||
date: env!("BENILLA_GIT_DATE"),
|
||||
profile: env!("BENILLA_PROFILE"),
|
||||
project_dir: env!("BENILLA_PROJECT_DIR"),
|
||||
..Default::default()
|
||||
},
|
||||
|app| {
|
||||
app.add_plugins(MoonWellPlugin);
|
||||
},
|
||||
)
|
||||
}
|
||||
+26
-13
@@ -32,11 +32,11 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- [benilla-app](#benilla-app): 234
|
||||
- [benilla-assets](#benilla-assets): 6
|
||||
- [benilla-blp](#benilla-blp): 1
|
||||
- [benilla-formats](#benilla-formats): 17
|
||||
- [benilla-formats](#benilla-formats): 21
|
||||
- [benilla-lua](#benilla-lua): 11
|
||||
- [benilla-protocol](#benilla-protocol): 22
|
||||
- [benilla-srp](#benilla-srp): 2
|
||||
- [benilla-ui](#benilla-ui): 120
|
||||
- [benilla-ui](#benilla-ui): 123
|
||||
- [benilla-world](#benilla-world): 49
|
||||
|
||||
### benilla-app
|
||||
@@ -57,15 +57,15 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- The spacer headers BLANK, BLANK2 and BLANK3 over multibars 2-4 (Bindings.xml:883/967/1051), which 1.12 draws blank (BINDING\_HEADER\_BLANK is " ", the other two are not defined), continue the section above, because this page's sections are named and collapsible. ([`assets/ui/KeyBindingsPage.xml:123`](../crates/benilla-app/assets/ui/KeyBindingsPage.xml#L123))
|
||||
- The 1.15 era client's single settings window replaces the 1.12 four-panel family, which is much worse to use; the 1.12 frames still load, hidden, for addons. ([`assets/ui/OptionsFrame.xml:3`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L3))
|
||||
- AUTO\_QUEST\_WATCH is the string "1". 1.12 assigns the number 1 (l.122) but every consumer compares against "1" (QuestLogFrame.lua:64/68); 1 ~= "1" in Lua 5.0. ([`assets/ui/OptionsFrame.xml:31`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L31))
|
||||
- The bar toggles precede the lock, which 1.12's box leads with, so what is on screen reads first. ([`assets/ui/OptionsFrame.xml:498`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L498))
|
||||
- A named ladder reads out its stop; 1.12's slider labels only its ends, and a bare index would mean nothing to a player. ([`assets/ui/OptionsFrame.xml:631`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L631))
|
||||
- 1.12 returns early here; a mute row hides the last plate, so a neighbour's text cannot stand when its OnLeave was missed. ([`assets/ui/OptionsFrame.xml:746`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L746))
|
||||
- Ships "1" where 1.12 registers "0": off, a friendly cast falls into the targeting cursor, which is not modelled. ([`assets/ui/OptionsFrame.xml:1611`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L1611))
|
||||
- No partner write of cameraPitchSmoothSpeed, which has no reader: the follow here has one rate. ([`assets/ui/OptionsFrame.xml:1700`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L1700))
|
||||
- Modern Classic's two-entry Display Mode, as there is no exclusive fullscreen; gxWindow "0" is the borderless window. ([`assets/ui/OptionsFrame.xml:1986`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L1986))
|
||||
- Our own row (the reference draws to the backbuffer), and no Multisampling, which misses alpha-tested cutouts. ([`assets/ui/OptionsFrame.xml:2015`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L2015))
|
||||
- The bar toggles precede the lock, which 1.12's box leads with, so what is on screen reads first. ([`assets/ui/OptionsFrame.xml:517`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L517))
|
||||
- A named ladder reads out its stop; 1.12's slider labels only its ends, and a bare index would mean nothing to a player. ([`assets/ui/OptionsFrame.xml:651`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L651))
|
||||
- 1.12 returns early here; a mute row hides the last plate, so a neighbour's text cannot stand when its OnLeave was missed. ([`assets/ui/OptionsFrame.xml:766`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L766))
|
||||
- Ships "1" where 1.12 registers "0": off, a friendly cast falls into the targeting cursor, which is not modelled. ([`assets/ui/OptionsFrame.xml:1631`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L1631))
|
||||
- No partner write of cameraPitchSmoothSpeed, which has no reader: the follow here has one rate. ([`assets/ui/OptionsFrame.xml:1720`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L1720))
|
||||
- Modern Classic's two-entry Display Mode, as there is no exclusive fullscreen; gxWindow "0" is the borderless window. ([`assets/ui/OptionsFrame.xml:2006`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L2006))
|
||||
- Our own row (the reference draws to the backbuffer), and no Multisampling, which misses alpha-tested cutouts. ([`assets/ui/OptionsFrame.xml:2035`](../crates/benilla-app/assets/ui/OptionsFrame.xml#L2035))
|
||||
- 1.12 has no `/reload` (later clients added it; 1.12 reloads through `/console reloadui`); kept so a player can reload the interface after toggling addons. ([`assets/ui/ScriptLogFrame.xml:381`](../crates/benilla-app/assets/ui/ScriptLogFrame.xml#L381))
|
||||
- A three-slice where the reference overlaps two quads, since two quads reach only 362 units and a page here is 563 tall. ([`assets/ui/ScrollTemplates.xml:188`](../crates/benilla-app/assets/ui/ScrollTemplates.xml#L188))
|
||||
- A three-slice where the reference overlaps two quads, since two quads reach only 362 units and a page here is 563 tall. ([`assets/ui/ScrollTemplates.xml:309`](../crates/benilla-app/assets/ui/ScrollTemplates.xml#L309))
|
||||
- The pet page's autocast widgets take the pet bar button's proportions, so the shine and the corner brackets sit on the button's edge and share its centre. ([`assets/ui/SpellBookAdapters.xml:3`](../crates/benilla-app/assets/ui/SpellBookAdapters.xml#L3))
|
||||
|
||||
#### aura_visual
|
||||
@@ -426,7 +426,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- The reference's size callback only re-scales `GlueParent` and re-lays it out (`0x46ac51`, `0x46ac56`), as its root keeps `gxResolution`'s aspect until a rebuild (`0x41ad10` at `0x46a828`) and its window keeps that shape while dragged (`0x5989d7`); here the root is the window's, which takes any shape, so the box follows it on every resize, where a rebuild would reset the screen (the create screen's character and name, the typed password, the selection). ([`src/ui_script/glue.rs:296`](../crates/benilla-app/src/ui_script/glue.rs#L296))
|
||||
- The reference's handler completes whichever operation is current; here only the character list's does, in state 3, and a reply of another cause (a roster nothing of the screen asked for) or of another link (before a realm change) completes nothing. ([`src/ui_script/glue_mgr.rs:1362`](../crates/benilla-app/src/ui_script/glue_mgr.rs#L1362))
|
||||
- The character is the platform's Unicode text, so a player can type any language on any platform. ([`src/ui_script/input.rs:466`](../crates/benilla-app/src/ui_script/input.rs#L466))
|
||||
- A capture run (`scenario_active`) keeps the CRT's default seed, 1, so its frames reproduce. ([`src/ui_script/lifecycle.rs:144`](../crates/benilla-app/src/ui_script/lifecycle.rs#L144))
|
||||
- A capture run (`scenario_active`) keeps the CRT's default seed, 1, so its frames reproduce. ([`src/ui_script/lifecycle.rs:145`](../crates/benilla-app/src/ui_script/lifecycle.rs#L145))
|
||||
- The files are under `benilla-config/Logs/`, since the install is read-only. ([`src/ui_script/load_log.rs:5`](../crates/benilla-app/src/ui_script/load_log.rs#L5))
|
||||
- `FULLSCREEN_QUADS_RESEAT` re-sizes the full-screen quads, which the stock files size only in their OnLoads, because a resize here keeps the loaded UI and the blackout would stop short of the new screen. ([`src/ui_script/manifest.rs:64`](../crates/benilla-app/src/ui_script/manifest.rs#L64))
|
||||
- No `FrameXML.toc` signature check, where `UI_Init` loads on a failed one and then quits (`0x401560(0xa)` at `0x48ff90`), because the check verifies Blizzard's signature with a key carried in the client binary, which benilla does not ship, and a modified interface file is loaded rather than refused. ([`src/ui_script/manifest.rs:161`](../crates/benilla-app/src/ui_script/manifest.rs#L161))
|
||||
@@ -448,8 +448,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
|
||||
- Text the reference magnifies from a smaller raster is rasterized at its true size here: a `SetTextHeight` size (the bit cleared at `0x771600`), an em past 32 px, and 3-D unit names (`UNIT_NAME_FONT`, em 32, string flag `0x80`), because the 32 px cap is a raster-memory budget that blurs big text on a modern display (`super::FONTSTRING_EM_CAP`). ([`src/ui_text/engine/mod.rs:8`](../crates/benilla-app/src/ui_text/engine/mod.rs#L8))
|
||||
- The reference flushes every glyph cache on a window resize (`0x5c2b50` → `0x5ca6f0`); this keeps the old cells, because nameplate meshes bake UVs and a flush would rebuild them every resize frame. ([`src/ui_text/engine/mod.rs:13`](../crates/benilla-app/src/ui_text/engine/mod.rs#L13))
|
||||
- The reference's measure kernels (`0x5c6940`, `0x5c6b70`, `0x5c6c50`, `0x5c7300`, `0x5c7470`) rasterize each character, but the step law reads only the advance, so skipping the bitmap changes no width. ([`src/ui_text/engine/mod.rs:362`](../crates/benilla-app/src/ui_text/engine/mod.rs#L362))
|
||||
- The reference evicts the least recently used glyph and repacks its hole (`0x5cad2b`, over `[CGxFont+0x64..0x6c]`); this drops every cell, because a shelf allocator cannot reclaim an interior cell and the sheet is far larger than the reference's 256×256 pages. ([`src/ui_text/engine/mod.rs:652`](../crates/benilla-app/src/ui_text/engine/mod.rs#L652))
|
||||
- The reference's measure kernels (`0x5c6940`, `0x5c6b70`, `0x5c6c50`, `0x5c7300`, `0x5c7470`) rasterize each character, but the step law reads only the advance, so skipping the bitmap changes no width. ([`src/ui_text/engine/mod.rs:363`](../crates/benilla-app/src/ui_text/engine/mod.rs#L363))
|
||||
- The reference evicts the least recently used glyph and repacks its hole (`0x5cad2b`, over `[CGxFont+0x64..0x6c]`); this drops every cell, because a shelf allocator cannot reclaim an interior cell and the sheet is far larger than the reference's 256×256 pages. ([`src/ui_text/engine/mod.rs:653`](../crates/benilla-app/src/ui_text/engine/mod.rs#L653))
|
||||
- Every UI text block sits 1 px below the reference's row, because at that row UI text reads high. ([`src/ui_text/layout/mod.rs:115`](../crates/benilla-app/src/ui_text/layout/mod.rs#L115))
|
||||
- The cap is 32 logical units, not 32 device px, because the reference's raster-memory ceiling draws all big text at the same 32 device px on a modern display; at the 768-tall design height the two agree. ([`src/ui_text/mod.rs:54`](../crates/benilla-app/src/ui_text/mod.rs#L54))
|
||||
- `r × round(dpi)` passes, so the ring keeps its logical weight on a high-DPI raster. ([`src/ui_text/outline.rs:60`](../crates/benilla-app/src/ui_text/outline.rs#L60))
|
||||
@@ -507,6 +507,8 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
#### chain
|
||||
|
||||
- An archive that fails to open is an error, where the reference logs `"Failed to open archive"` and goes on, because a skipped corrupt archive surfaces only as missing files far downstream. ([`src/chain.rs:67`](../crates/benilla-formats/src/chain.rs#L67))
|
||||
- The launcher selects a community pack through WOW\_LOCALE, or auto-detects Data/ruRU. ([`src/chain.rs:112`](../crates/benilla-formats/src/chain.rs#L112))
|
||||
- Community ruRU archives overlay the 1.12 chain and use DBC string column zero. ([`src/chain.rs:131`](../crates/benilla-formats/src/chain.rs#L131))
|
||||
|
||||
#### characters
|
||||
|
||||
@@ -525,6 +527,14 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- A language with no words keeps the line, where the reference drops every word, because a missing pool is a broken install and blank chat would hide it. ([`src/garble.rs:150`](../crates/benilla-formats/src/garble.rs#L150))
|
||||
- It stops at a codepoint boundary where the reference's byte copy can split one, because a `&str` must stay UTF-8. ([`src/garble.rs:257`](../crates/benilla-formats/src/garble.rs#L257))
|
||||
|
||||
#### language_pack
|
||||
|
||||
- The community 1.12 ruRU pack lives in `Data/ruRU` and overlays the vanilla chain. ([`src/language_pack.rs:3`](../crates/benilla-formats/src/language_pack.rs#L3))
|
||||
|
||||
#### locale
|
||||
|
||||
- The community ruRU overlay uses column zero, but Lua and authentication must name its actual language; ruRU is absent from the stock eight-column locale table. ([`src/locale.rs:45`](../crates/benilla-formats/src/locale.rs#L45))
|
||||
|
||||
#### loose
|
||||
|
||||
- A folder is listed the first time a key reaches it, where the reference lists every folder at the first open (`0x646ea0`), so a file added to a folder no key has reached is found before the index empties; the whole walk takes minutes and gigabytes where the install folder holds or links a large tree, as a Wine prefix's `z:` drive links `/`. ([`src/loose.rs:31`](../crates/benilla-formats/src/loose.rs#L31))
|
||||
@@ -667,11 +677,13 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- The disabled-checked leg (`0x785380`) tests and reloads the checked slot (`[+0x4e0]`, `0x785388`/`0x7853a5`), a copy of the checked leg's (`0x785270`), so in 1.12.1 a check box with a checked texture repaints that one and never gets its disabled-checked texture from a path. benilla tests and reloads the slot the method names. ([`src/script/button.rs:581`](../crates/benilla-ui/src/script/button.rs#L581))
|
||||
- The slot is read before the handler, where the reference reads it after (`[esi+0x4dc]`), because reading first keeps the borrow simple and no stock handler re-slots its row. ([`src/script/button.rs:1166`](../crates/benilla-ui/src/script/button.rs#L1166))
|
||||
- The reference composes the Shortcut with `GetRealZoneText` alone (`0x49efe8`), so in a capital `/leave Trade` sends `Trade - Stormwind City` and leaves nothing; ours uses the join's city-aware name, because the reference's form cannot leave the channel it joined. ([`src/script/channel.rs:480`](../crates/benilla-ui/src/script/channel.rs#L480))
|
||||
- The community ruRU pack accepts Russian names up to twelve letters, while retaining the stock Latin alternative. ([`src/script/char_name.rs:87`](../crates/benilla-ui/src/script/char_name.rs#L87))
|
||||
- The frame's bottom-left origin is snapped onto the device grid so the border art blits 1:1; the reference ceils the anchor point itself onto it (`0x7666a0`, `0x766750`). ([`src/script/chat_bubble.rs:476`](../crates/benilla-ui/src/script/chat_bubble.rs#L476))
|
||||
- No truncation at 255 characters (`0x49f604`), because vmangos refuses a longer line itself (`Chat.cpp:2177`): it is dropped where the reference sends its first 255. ([`src/script/chat_send.rs:23`](../crates/benilla-ui/src/script/chat_send.rs#L23))
|
||||
- A value outside 0..1 clamps, where the reference keeps the low byte (alpha 2.0 stores 254, -1.0 stores 1), because no FrameXML or addon caller passes one. ([`src/script/chat_window.rs:17`](../crates/benilla-ui/src/script/chat_window.rs#L17))
|
||||
- An id outside the seven built windows raises, where the reference serves ten records and silently ignores any other id (`0x4a0be1`), because benilla keeps only the seven and every caller loops `1, NUM_CHAT_WINDOWS`. ([`src/script/chat_window.rs:220`](../crates/benilla-ui/src/script/chat_window.rs#L220))
|
||||
- One past `i32::MAX` clamps where the reference keeps the low 32 bits, for the colours' reason. ([`src/script/chat_window.rs:430`](../crates/benilla-ui/src/script/chat_window.rs#L430))
|
||||
- ruRU is a community overlay over DBC column zero, outside the stock table. ([`src/script/client.rs:321`](../crates/benilla-ui/src/script/client.rs#L321))
|
||||
- The reference reads the clock live at each call (`0x42c010`); ours is the session clock the tick advances by the paced frame step, one value per frame, so `GetTime()` deltas and the `elapsed` handed to OnUpdate agree, as FrameXML (CastingBarFrame and kin) assumes. ([`src/script/clock.rs:53`](../crates/benilla-ui/src/script/clock.rs#L53))
|
||||
- With no wheel it scales by the strip's, because the reference reads the missing wheel unguarded. ([`src/script/colorselect.rs:356`](../crates/benilla-ui/src/script/colorselect.rs#L356))
|
||||
- The reference's `set` registers an unknown name as a new category-5 record (`0x63d569`-`0x63d582`); benilla refuses it, because nothing would read the row and `config.toml` keeps an unknown key anyway. ([`src/script/console_exec.rs:120`](../crates/benilla-ui/src/script/console_exec.rs#L120))
|
||||
@@ -708,6 +720,7 @@ Each entry is the first sentence of a `Deviation:` comment, linking to where it
|
||||
- An addon file whose first binding has no header opens a `HEADER_<addon>` row, where the reference files those rows under the previous file's last header, because under a foreign header the player could not find them. ([`src/script/keybind.rs:297`](../crates/benilla-ui/src/script/keybind.rs#L297))
|
||||
- The handle's value is the address of a `CGxTex` (`SMemAlloc(0x54)`, `0x594a96`), which benilla cannot reproduce; each texture ranks instead by a creation stamp, one global sequence number taken when its cache key is first created and taken anew once its last region has let go of it (`super::texel::Texels`). ([`src/script/layer_batch.rs:9`](../crates/benilla-ui/src/script/layer_batch.rs#L9))
|
||||
- The client's Lua has no such bound, as nothing sets a hook (`lua_sethook`, `0x6fba40`, has no caller and no pointer to it), so a load that never ends hangs it. ([`src/script/mod.rs:799`](../crates/benilla-ui/src/script/mod.rs#L799))
|
||||
- The community ruRU pack reads column zero but names its own language. ([`src/script/model.rs:782`](../crates/benilla-ui/src/script/model.rs#L782))
|
||||
- A path that does not resolve is stored, where the reference raises `Invalid model file: %s` (`0x878b44`), because the file loads asynchronously here and the call cannot know yet. ([`src/script/modelframe.rs:341`](../crates/benilla-ui/src/script/modelframe.rs#L341))
|
||||
- Benilla plays no pre-rendered movie (#968), so `StartMovie` answers nil, the reference's "could not start" (`0x78d861`), which the stock `MovieFrame_PlayMovie` answers by hiding the frame and so by returning to the login screen. ([`src/script/movieframe.rs:4`](../crates/benilla-ui/src/script/movieframe.rs#L4))
|
||||
- The reference's free list is FIFO; either keeps every index stable, all an addon can observe. ([`src/script/nameplate.rs:431`](../crates/benilla-ui/src/script/nameplate.rs#L431))
|
||||
|
||||
+20
-16
@@ -27,6 +27,8 @@
|
||||
- **benilla-world** (Bevy) — The world renderer: terrain, water, sky, weather, models, lighting, collision and the frame ladder; everything needed to put something in a world and ask the world about itself, with no game attached
|
||||
- **benilla-worldview** (no Bevy) — The world viewer: the engine with no game attached, which keeps the engine and game split honest
|
||||
- **benilla** (no Bevy) — The launcher: build.rs stamps the git build id and main() hands it to benilla-app, so a new commit rebuilds this package and not the app crate
|
||||
- **moonwell-deploy** (no Bevy) — Build vanilla MPQ packages and publish MoonWell launcher manifests to S3
|
||||
- **moonwell** (Bevy) — The MoonWell launcher: platform branding on top of benilla
|
||||
|
||||
## App subsystems — Bevy plugins in load order (`crates/benilla-app/src/lib.rs`)
|
||||
|
||||
@@ -108,7 +110,7 @@
|
||||
- **benilla-adt** (lib.rs): combined_alpha
|
||||
- **benilla-app** (lib.rs): addon_harness area area_poi area_trigger asset_churn aura_visual bindings blob_shadow bowstring camera_shake capture chat_bubble chr_classes cinematic client_state combat_log combat_text console crash creature_anim creature_type cursor cvars death debug_panel dev devtools doodad_events entities field_watch fishing_line footprints game_plugins game_tip glue_session go_anim go_templates hover_log item_watch items loading_screen local_state minimap name_persist nameplates names net no_install npc_text opaque2d perf pipe_warm player poi_marker portrait preflight probe_shield query_cache quest_markers raid_marks ranged_flex realmlist run_mode screen_fade screenshot script_calls shaders shutdown smart_rect sound spell swing_refusal target test_support text_filter textinput transport tutorial ui_action ui_auction ui_aura ui_bank ui_battlefield ui_battlefield_positions ui_battlefield_score ui_billing ui_bind_confirm ui_binder ui_cast ui_char ui_chat ui_craft ui_dialog_verbs ui_dressup ui_duel ui_follow ui_gamma ui_gm_ticket ui_gossip ui_guild ui_honor ui_inspect ui_instance ui_item_text ui_items ui_layout ui_logout ui_loot ui_loot_roll ui_macro ui_mail ui_memory ui_merchant ui_mirror ui_models ui_net ui_panes ui_party ui_pass ui_pet ui_pet_book ui_pet_doll ui_pet_stats ui_petition ui_quest ui_quest_log ui_quest_share ui_reputation ui_saved ui_script ui_session ui_shapeshift ui_social ui_spellbook ui_stable ui_summon ui_tabard ui_talent ui_talent_wipe ui_taxi ui_text ui_tooltip ui_trade ui_tradeskill ui_trainer ui_unit ui_world_map video vplates weapon_trail world_backdrop world_state world_state_ui
|
||||
- **benilla-assets** (lib.rs): adt anim_rng blp column_grid coords gpu_blp m2 materials minimap_grid model spatial_cache terrain tex_filter trace wdt wmo world_assets
|
||||
- **benilla-formats** (lib.rs): anim_data area_poi area_sound area_table area_trigger auction_house bank_bag_slot_prices camera_shakes cfg_categories cfg_configs chain characters chat_channels chr_classes chr_races cinematics creature_families creature_sound creature_types creatures dbc death_thud durability elevators emit_timing emote_text emotes environmental_damage exhaustion factions footsteps game_tips gameobjects garble gm_survey gm_ticket_category ground_effects install item_random_properties item_sounds item_visuals itembagfamily itemclass items itemsets itemsubclass languages lfg_dungeons light liquid loading_screen locale locale_routing lock lock_type loose macro_icons maps material minimap_translate models npc_greeting packages page_text_material particles pet_stats quest_headers quest_info race_creature_type race_pvp_team race_sound ribbons server_messages sheathe skill_lines skill_tiers sound_entries sound_provider sound_water spell_focus spell_mechanic spell_visual spells stable_slot_prices stationery talents taxi taxi_nodes taxi_path terrain text_filter_lists tga transport_period transports unit_blood value_track vocal_ui_sounds wdl weapon_impact weapon_swing wmo_area world_map_area world_map_continent world_map_overlay world_state_ui wow_ini zone_map
|
||||
- **benilla-formats** (lib.rs): anim_data area_poi area_sound area_table area_trigger auction_house bank_bag_slot_prices camera_shakes cfg_categories cfg_configs chain character_names characters chat_channels chr_classes chr_races cinematics creature_families creature_sound creature_types creatures dbc death_thud durability elevators emit_timing emote_text emotes environmental_damage exhaustion factions footsteps game_tips gameobjects garble gm_survey gm_ticket_category ground_effects install item_random_properties item_sounds item_visuals itembagfamily itemclass items itemsets itemsubclass language_pack languages lfg_dungeons light liquid loading_screen locale locale_routing lock lock_type loose macro_icons maps material minimap_translate models npc_greeting packages page_text_material particles pet_stats quest_headers quest_info race_creature_type race_pvp_team race_sound ribbons server_messages sheathe skill_lines skill_tiers sound_entries sound_provider sound_water spell_focus spell_mechanic spell_visual spells stable_slot_prices stationery talents taxi taxi_nodes taxi_path terrain text_filter_lists tga transport_period transports unit_blood value_track vocal_ui_sounds wdl weapon_impact weapon_swing wmo_area world_map_area world_map_continent world_map_overlay world_state_ui wow_ini zone_map
|
||||
- **benilla-lua** (lib.rs): api cfmt compile heap lex lib_base lib_math lib_string lib_table number parse pools proto reload table value vm
|
||||
- **benilla-m2** (lib.rs): error model skin tests track
|
||||
- **benilla-mlua** (lib.rs): conv error
|
||||
@@ -118,6 +120,7 @@
|
||||
- **benilla-ui** (lib.rs): bindings_xml civil color framexml justify layout loader markup messages order script source status strings toc widget
|
||||
- **benilla-visual** (lib.rs): relight
|
||||
- **benilla-world** (lib.rs): art_scope assets bgwin billboard boot build_id clouds clutter collision decal dev_state doodad_anim entity_shade exterior_cull ffx_glow final_pass frame_pace ground_fx instance_tint interact interior layout_keys lighting liquid log_ring mac_quit map_proj mat_anim_table mesh_tag model_fade model_forms model_render modkeys particles ribbons ride_frame rig_anim rig_palette rig_rider schedule shaders sky sky_order skybox static_gx static_merge straddle sun surface terrain_stream thread_qos view vis_chain water_fx wdl weather wmo_portal world_census world_map world_plugins world_point world_unit worldview zfill
|
||||
- **moonwell-deploy** (main.rs): manifest package storage vanilla_mpq
|
||||
|
||||
## CLI binaries
|
||||
|
||||
@@ -141,8 +144,8 @@
|
||||
- `embedded://benilla_world/shaders/celestial.wgsl`
|
||||
- `embedded://benilla_world/shaders/cloud.wgsl`
|
||||
- `embedded://benilla_world/shaders/ffx_glow.wgsl`
|
||||
- `embedded://benilla_world/shaders/sky_vertex.wgsl`
|
||||
- `embedded://benilla_world/shaders/sky.wgsl`
|
||||
- `embedded://benilla_world/shaders/sky_vertex.wgsl`
|
||||
- `embedded://benilla_world/shaders/star.wgsl`
|
||||
- `embedded://benilla_world/shaders/static_gx.wgsl`
|
||||
- `embedded://benilla_world/shaders/wow_effect.wgsl`
|
||||
@@ -204,8 +207,8 @@
|
||||
- `WOW_CRASH_INJECT` — benilla-app/src/perf/crash_inject.rs
|
||||
- `WOW_CREATE_SPLINE` — benilla-app/src/net/motion/spline.rs
|
||||
- `WOW_CREATE_TEST` — benilla-app/src/portrait/glue_booth.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_CULL_TRACE` — benilla-world/src/exterior_cull.rs
|
||||
- `WOW_CULLDUMP` — benilla-world/src/wmo_portal/mod.rs
|
||||
- `WOW_CULL_TRACE` — benilla-world/src/exterior_cull.rs
|
||||
- `WOW_CURSOR_TRACE` — benilla-app/src/cursor.rs
|
||||
- `WOW_DATA` — benilla-app/src/local_state.rs, benilla-app/src/no_install.rs, benilla-formats/src/install.rs, benilla-formats/tests/project_folder.rs, benilla-formats/tests/wow_data_env.rs, benilla-formats/tests/wow_data_none.rs
|
||||
- `WOW_DEMO_BOTTOM_BARS` — benilla-app/src/ui_script/mod.rs
|
||||
@@ -296,6 +299,7 @@
|
||||
- `WOW_LIVE_SHOT_AT` — benilla-app/src/capture/live_shot.rs
|
||||
- `WOW_LIVE_SHOT_COUNT` — benilla-app/src/capture/live_shot.rs
|
||||
- `WOW_LIVE_SHOT_EVERY` — benilla-app/src/capture/live_shot.rs
|
||||
- `WOW_LOCALE` — benilla-formats/src/chain.rs, benilla-formats/src/language_pack.rs
|
||||
- `WOW_LOGIN_SHOT` — benilla-world/src/bgwin.rs
|
||||
- `WOW_LOGIN_SHOT_OUT` — benilla-app/src/glue_session/login.rs
|
||||
- `WOW_LOGOUT_SMOKE` — benilla-app/src/glue_session/logout_smoke.rs, benilla-world/src/bgwin.rs
|
||||
@@ -303,10 +307,10 @@
|
||||
- `WOW_MATANIM_DUTY` — benilla-world/src/doodad_anim/mat_anim.rs
|
||||
- `WOW_MATANIM_LIVE` — benilla-world/src/doodad_anim/mat_anim.rs
|
||||
- `WOW_MATANIM_PROBE` — benilla-world/src/doodad_anim/mat_anim.rs
|
||||
- `WOW_MERGE_CENSUS` — benilla-world/src/static_merge.rs
|
||||
- `WOW_MERGE_FADERS` — benilla-world/src/terrain_stream/merge.rs
|
||||
- `WOW_MERGED_FADE` — benilla-assets/src/materials.rs
|
||||
- `WOW_MERGED_SLOT` — benilla-assets/src/materials.rs
|
||||
- `WOW_MERGE_CENSUS` — benilla-world/src/static_merge.rs
|
||||
- `WOW_MERGE_FADERS` — benilla-world/src/terrain_stream/merge.rs
|
||||
- `WOW_MESH_EVENTS` — benilla-app/src/perf/mod.rs
|
||||
- `WOW_MESH_HOLDERS` — benilla-app/src/perf/mod.rs
|
||||
- `WOW_MESH_TOUCH` — benilla-app/src/perf/mod.rs
|
||||
@@ -327,6 +331,10 @@
|
||||
- `WOW_NAME_DIST` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_NAME_EL` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_NAME_H` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_NODE_PROBE` — benilla-app/src/capture/probes/world_census.rs, benilla-app/src/dev.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_NOPORTALCULL` — benilla-world/src/dev_state.rs
|
||||
- `WOW_NOSOUND` — benilla-app/src/sound/mod.rs
|
||||
- `WOW_NOVSYNC` — benilla-app/src/video.rs, benilla-world/src/worldview.rs
|
||||
- `WOW_NO_ALPHATEST` — benilla-world/src/model_render.rs
|
||||
- `WOW_NO_ANIM_LOD` — benilla-app/src/creature_anim/lod.rs, benilla-app/src/lib.rs
|
||||
- `WOW_NO_BC` — benilla-assets/src/gpu_blp.rs
|
||||
@@ -346,18 +354,14 @@
|
||||
- `WOW_NO_TILE_CELLS` — benilla-world/src/terrain_stream/furnish.rs
|
||||
- `WOW_NO_TILE_DROP` — benilla-world/src/terrain_stream.rs
|
||||
- `WOW_NO_TWIST` — benilla-app/src/creature_anim/twist.rs
|
||||
- `WOW_NODE_PROBE` — benilla-app/src/capture/probes/world_census.rs, benilla-app/src/dev.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_NOPORTALCULL` — benilla-world/src/dev_state.rs
|
||||
- `WOW_NOSOUND` — benilla-app/src/sound/mod.rs
|
||||
- `WOW_NOVSYNC` — benilla-app/src/video.rs, benilla-world/src/worldview.rs
|
||||
- `WOW_OCEAN_DEPTH_DIV` — benilla-formats/src/liquid.rs
|
||||
- `WOW_PANEL` — benilla-world/src/dev_state.rs
|
||||
- `WOW_PART_CHURN` — benilla-app/src/perf/mod.rs
|
||||
- `WOW_PARTICLE_CENSUS` — benilla-app/src/capture/probes/particle_census.rs, benilla-app/src/dev.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_PARTICLE_DEPTHDUMP` — benilla-world/src/particles/depthdump.rs
|
||||
- `WOW_PARTICLE_DEPTHDUMP_BONES` — benilla-world/src/particles/depthdump.rs
|
||||
- `WOW_PARTICLE_FLAT` — benilla-world/src/particles/render.rs
|
||||
- `WOW_PARTICLE_NODEPTH` — benilla-world/src/particles/render.rs
|
||||
- `WOW_PART_CHURN` — benilla-app/src/perf/mod.rs
|
||||
- `WOW_PASS` — benilla-app/src/glue_session/login.rs, benilla-app/src/net.rs, benilla-app/src/run_mode.rs, benilla-protocol/examples/login_refusal_probe.rs, benilla-protocol/examples/park_probe.rs
|
||||
- `WOW_PERF_HUD` — benilla-app/src/perf/hud.rs
|
||||
- `WOW_PHASE` — benilla-app/src/capture/phase_probe.rs, benilla-app/src/dev.rs, benilla-world/src/bgwin.rs
|
||||
@@ -388,8 +392,8 @@
|
||||
- `WOW_PROBE_AUCTION` — benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_BANK` — benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_BG` — benilla-app/src/capture/probe_bg.rs, benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_BG_SAMPLES` — benilla-app/src/capture/probe_bg.rs
|
||||
- `WOW_PROBE_BGQUEUE` — benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_BG_SAMPLES` — benilla-app/src/capture/probe_bg.rs
|
||||
- `WOW_PROBE_BINDER` — benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_BOOK` — benilla-app/src/dev.rs
|
||||
- `WOW_PROBE_CAM` — benilla-app/src/capture/probe_cam.rs
|
||||
@@ -443,8 +447,8 @@
|
||||
- `WOW_REMOTE_IDLE_GATE` — benilla-app/src/net/motion/remote.rs
|
||||
- `WOW_REMOTE_SNAP` — benilla-app/src/net/motion/remote.rs
|
||||
- `WOW_RENDER_SCALE` — benilla-app/src/cvars/mod.rs, benilla-app/src/world_backdrop.rs
|
||||
- `WOW_RES_CENSUS` — benilla-app/src/perf/census.rs
|
||||
- `WOW_RESIZE` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_RES_CENSUS` — benilla-app/src/perf/census.rs
|
||||
- `WOW_REVEAL` — benilla-app/src/capture/probes/reveal.rs, benilla-app/src/dev.rs
|
||||
- `WOW_RIG` — benilla-app/src/capture/probe_rig.rs, benilla-app/src/dev.rs, benilla-app/src/glue_session/login.rs, benilla-app/src/glue_session/realm_smoke.rs, benilla-app/src/local_state.rs, benilla-app/src/net.rs, benilla-app/src/probe_shield.rs, benilla-app/src/run_mode.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_RIG_CENSUS` — benilla-world/src/rig_palette.rs
|
||||
@@ -467,8 +471,8 @@
|
||||
- `WOW_STATIC_MERGE` — benilla-world/src/terrain_stream/merge.rs
|
||||
- `WOW_STOCK_UI` — benilla-app/src/ui_script/manifest.rs
|
||||
- `WOW_STREAM_TRACE` — benilla-app/src/perf/mod.rs
|
||||
- `WOW_TAB_TRACE` — benilla-app/src/target/scan.rs
|
||||
- `WOW_TABHOVER` — benilla-app/src/capture/fixtures.rs
|
||||
- `WOW_TAB_TRACE` — benilla-app/src/target/scan.rs
|
||||
- `WOW_TEARDOWN_INJECT` — benilla-app/src/perf/stall.rs
|
||||
- `WOW_TEXT_PROBE` — benilla-app/src/ui_script/extract/text.rs
|
||||
- `WOW_THREADS` — benilla-world/src/boot.rs
|
||||
@@ -479,6 +483,7 @@
|
||||
- `WOW_TRAIL_CENSUS` — benilla-app/src/capture/probes/trail_census.rs, benilla-app/src/dev.rs
|
||||
- `WOW_TRILINEAR` — benilla-app/src/cvars/mod.rs, benilla-assets/src/tex_filter.rs
|
||||
- `WOW_TWIST_GAP` — benilla-app/src/player/body_pose.rs
|
||||
- `WOW_UISCRIPT_DUMP` — benilla-app/tests/ui_script_wall.rs
|
||||
- `WOW_UI_COST` — benilla-app/src/ui_script/extract/mod.rs
|
||||
- `WOW_UI_DIFF` — benilla-app/src/ui_pass.rs, benilla-app/src/ui_script/extract/mod.rs
|
||||
- `WOW_UI_GATE` — benilla-app/src/ui_script/extract/mod.rs
|
||||
@@ -487,18 +492,17 @@
|
||||
- `WOW_UI_PROBE` — benilla-app/src/ui_pass.rs
|
||||
- `WOW_UI_SCALE` — benilla-app/src/cvars/mod.rs, benilla-app/src/ui_script/mod.rs
|
||||
- `WOW_UI_SPLICE_VERIFY` — benilla-app/src/ui_script/extract/mod.rs
|
||||
- `WOW_UISCRIPT_DUMP` — benilla-app/tests/ui_script_wall.rs
|
||||
- `WOW_UNATTENDED` — benilla-app/src/glue_session/login.rs, benilla-app/src/local_state.rs, benilla-app/src/net.rs, benilla-app/src/net/session.rs, benilla-app/src/run_mode.rs, benilla-world/src/bgwin.rs
|
||||
- `WOW_UNIT_VISUALS` — benilla-app/src/capture/probes/visual_census.rs, benilla-app/src/dev.rs
|
||||
- `WOW_UNIT_VISUALS_RADIUS` — benilla-app/src/capture/probes/visual_census.rs
|
||||
- `WOW_UPLOAD_BUDGET` — benilla-world/src/world_plugins.rs
|
||||
- `WOW_USER` — benilla-app/src/glue_session/login.rs, benilla-app/src/net.rs, benilla-app/src/run_mode.rs, benilla-protocol/examples/login_refusal_probe.rs, benilla-protocol/examples/park_probe.rs
|
||||
- `WOW_VIS_DUMP` — benilla-app/src/capture/probes/live_fps.rs
|
||||
- `WOW_VIS_TRACE` — benilla-world/src/model_render/visibility.rs
|
||||
- `WOW_VISTA_AT` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_VISTA_FACE` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_VISTA_MIN` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_VISTA_PITCH` — benilla-app/src/capture/mod.rs
|
||||
- `WOW_VIS_DUMP` — benilla-app/src/capture/probes/live_fps.rs
|
||||
- `WOW_VIS_TRACE` — benilla-world/src/model_render/visibility.rs
|
||||
- `WOW_VPLATE_TRACE` — benilla-app/src/vplates.rs
|
||||
- `WOW_WARM_SLICE` — benilla-app/src/pipe_warm/mod.rs
|
||||
- `WOW_WATER_CLIP` — benilla-assets/src/materials.rs
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$DataPath = '',
|
||||
[string]$IconPath = '',
|
||||
[string]$PatchSource = '',
|
||||
[string]$AuthHost = '',
|
||||
[string]$EnvFile = '',
|
||||
[string]$PackagePath = '',
|
||||
[string]$BinaryPath = '',
|
||||
[string]$VcRuntimePath = '',
|
||||
[string]$Prefix = 'World of Warcraft 1.12.1',
|
||||
[string]$ManifestKey = 'manifest-1.12.1.json',
|
||||
[switch]$Publish,
|
||||
[switch]$DryRun,
|
||||
[switch]$SkipClientBuild
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$repoRoot = Split-Path $PSScriptRoot -Parent
|
||||
if (-not $EnvFile) {
|
||||
$EnvFile = Join-Path (Split-Path $repoRoot -Parent) 'MoonWellClientSources\.env'
|
||||
}
|
||||
if (-not $PackagePath) {
|
||||
$PackagePath = Join-Path $repoRoot ('dist\moonwell-' + (Get-Date -Format 'yyyyMMdd-HHmmss'))
|
||||
}
|
||||
if (-not $BinaryPath) { $BinaryPath = Join-Path $repoRoot 'target\release\MoonWell.exe' }
|
||||
if ($BinaryPath.EndsWith('.exe', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
if (-not $VcRuntimePath) {
|
||||
$vswherePath = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
|
||||
$vsInstall = (& $vswherePath -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath).Trim()
|
||||
if ($LASTEXITCODE -ne 0 -or -not $vsInstall) { throw 'Visual Studio C++ runtime was not found; pass -VcRuntimePath.' }
|
||||
$redistVersion = Get-ChildItem -LiteralPath (Join-Path $vsInstall 'VC\Redist\MSVC') -Directory |
|
||||
Where-Object { $_.Name -match '^\d+\.\d+\.\d+$' } |
|
||||
Sort-Object { [version]$_.Name } -Descending | Select-Object -First 1
|
||||
$VcRuntimePath = Join-Path $redistVersion.FullName 'x64\Microsoft.VC143.CRT'
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $VcRuntimePath 'vcruntime140.dll') -PathType Leaf)) {
|
||||
throw 'The x64 Visual C++ redistributable vcruntime140.dll was not found.'
|
||||
}
|
||||
}
|
||||
if (-not $DataPath -or -not $AuthHost) {
|
||||
throw 'Pass -DataPath pointing to WoW 1.12.1 Data and -AuthHost host[:port]. WOW_HOME from the old .env is deliberately not used.'
|
||||
}
|
||||
if ($Publish -and $DryRun) { throw 'Choose -Publish or -DryRun.' }
|
||||
if (Test-Path -LiteralPath $PackagePath) { throw 'PackagePath already exists; choose a new staging directory.' }
|
||||
if (($Publish -or $DryRun) -and -not (Test-Path -LiteralPath $EnvFile -PathType Leaf)) {
|
||||
throw 'Deployment .env was not found.'
|
||||
}
|
||||
|
||||
Push-Location $repoRoot
|
||||
try {
|
||||
if (-not $SkipClientBuild) {
|
||||
$embeddedIcon = Join-Path $repoRoot 'crates\moonwell\assets\moonwell.ico'
|
||||
if ($IconPath) {
|
||||
$sourceIcon = (Resolve-Path -LiteralPath $IconPath).Path
|
||||
New-Item -ItemType Directory -Path (Split-Path $embeddedIcon -Parent) -Force | Out-Null
|
||||
if ($sourceIcon -ne $embeddedIcon) { Copy-Item -LiteralPath $sourceIcon -Destination $embeddedIcon }
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $embeddedIcon -PathType Leaf)) {
|
||||
throw 'Provide the MoonWell icon with -IconPath or place it in crates/moonwell/assets/moonwell.ico.'
|
||||
}
|
||||
& cargo build -p moonwell --release --no-default-features --locked
|
||||
if ($LASTEXITCODE -ne 0) { throw 'MoonWell player build failed.' }
|
||||
}
|
||||
|
||||
& cargo build -p moonwell-deploy --release --locked
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Rust deployment tool build failed.' }
|
||||
$toolPath = Join-Path $repoRoot 'target\release\moonwell-deploy.exe'
|
||||
$stageArguments = @('stage', '--binary', $BinaryPath, '--data', $DataPath,
|
||||
'--output', $PackagePath, '--auth-host', $AuthHost)
|
||||
if ($PatchSource) { $stageArguments += @('--source', $PatchSource) }
|
||||
& $toolPath @stageArguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Package staging failed.' }
|
||||
if ($BinaryPath.EndsWith('.exe', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
Copy-Item -LiteralPath (Join-Path $VcRuntimePath 'vcruntime140.dll') -Destination (Join-Path $PackagePath 'vcruntime140.dll')
|
||||
}
|
||||
|
||||
# The local inventory lives outside the package, so it cannot list itself.
|
||||
$inventoryPath = $PackagePath + '.manifest.json'
|
||||
& $toolPath manifest --dir $PackagePath --output $inventoryPath
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Manifest generation failed.' }
|
||||
|
||||
if ($Publish -or $DryRun) {
|
||||
$publishArguments = @('publish', '--dir', $PackagePath, '--env-file', $EnvFile,
|
||||
'--prefix', $Prefix, '--manifest-key', $ManifestKey)
|
||||
if ($DryRun) { $publishArguments += '--dry-run' }
|
||||
& $toolPath @publishArguments
|
||||
if ($LASTEXITCODE -ne 0) { throw 'S3 publication failed.' }
|
||||
}
|
||||
Write-Host "Package: $PackagePath"
|
||||
Write-Host "Local manifest: $inventoryPath"
|
||||
} finally {
|
||||
Pop-Location
|
||||
}
|
||||
Vendored
+192
-192
@@ -1,192 +1,192 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
name = "kira"
|
||||
version = "0.12.4"
|
||||
authors = ["Andrew Minnich <aminnich3@gmail.com>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Expressive audio library for games"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"gamedev",
|
||||
"audio",
|
||||
"music",
|
||||
]
|
||||
categories = [
|
||||
"game-development",
|
||||
"multimedia::audio",
|
||||
]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/tesselode/kira"
|
||||
resolver = "2"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
|
||||
[features]
|
||||
aac = [
|
||||
"symphonia",
|
||||
"symphonia/aac",
|
||||
]
|
||||
adpcm = [
|
||||
"symphonia",
|
||||
"symphonia/adpcm",
|
||||
]
|
||||
aiff = [
|
||||
"symphonia",
|
||||
"symphonia/aiff",
|
||||
]
|
||||
alac = [
|
||||
"symphonia",
|
||||
"symphonia/alac",
|
||||
]
|
||||
caf = [
|
||||
"symphonia",
|
||||
"symphonia/caf",
|
||||
]
|
||||
cpal-realtime = [
|
||||
"cpal",
|
||||
"cpal/realtime",
|
||||
]
|
||||
cpal-realtime-dbus = [
|
||||
"cpal",
|
||||
"cpal/realtime-dbus",
|
||||
]
|
||||
default = [
|
||||
"cpal",
|
||||
"cpal-realtime",
|
||||
"cpal-realtime-dbus",
|
||||
"mp3",
|
||||
"ogg",
|
||||
"vorbis",
|
||||
"flac",
|
||||
"wav",
|
||||
"pcm",
|
||||
]
|
||||
flac = [
|
||||
"symphonia",
|
||||
"symphonia/flac",
|
||||
]
|
||||
isomp4 = [
|
||||
"symphonia",
|
||||
"symphonia/isomp4",
|
||||
]
|
||||
mkv = [
|
||||
"symphonia",
|
||||
"symphonia/mkv",
|
||||
]
|
||||
mp1 = [
|
||||
"symphonia",
|
||||
"symphonia/mp1",
|
||||
]
|
||||
mp2 = [
|
||||
"symphonia",
|
||||
"symphonia/mp2",
|
||||
]
|
||||
mp3 = [
|
||||
"symphonia",
|
||||
"symphonia/mp3",
|
||||
]
|
||||
mpa = [
|
||||
"symphonia",
|
||||
"symphonia/mpa",
|
||||
]
|
||||
ogg = [
|
||||
"symphonia",
|
||||
"symphonia/ogg",
|
||||
]
|
||||
pcm = [
|
||||
"symphonia",
|
||||
"symphonia/pcm",
|
||||
]
|
||||
vorbis = [
|
||||
"symphonia",
|
||||
"symphonia/vorbis",
|
||||
]
|
||||
wav = [
|
||||
"symphonia",
|
||||
"symphonia/wav",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "kira"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "change_sample_rate"
|
||||
path = "tests/change_sample_rate.rs"
|
||||
|
||||
[[test]]
|
||||
name = "streaming_sound_stops_on_error"
|
||||
path = "tests/streaming_sound_stops_on_error.rs"
|
||||
|
||||
[[test]]
|
||||
name = "sync_send"
|
||||
path = "tests/sync_send.rs"
|
||||
|
||||
[dependencies.assert_no_alloc]
|
||||
version = "1.1.2"
|
||||
optional = true
|
||||
|
||||
[dependencies.atomic-arena]
|
||||
version = "0.1.2"
|
||||
|
||||
[dependencies.glam]
|
||||
version = "0.33.0"
|
||||
features = ["mint"]
|
||||
|
||||
[dependencies.mint]
|
||||
version = "0.5.9"
|
||||
|
||||
[dependencies.pastey]
|
||||
version = "0.2.1"
|
||||
|
||||
[dependencies.rtrb]
|
||||
version = "0.3.2"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.0.219"
|
||||
features = ["derive"]
|
||||
optional = true
|
||||
|
||||
[dependencies.symphonia]
|
||||
version = "0.6.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.triple_buffer]
|
||||
version = "9.0.0"
|
||||
|
||||
[dev-dependencies.approx]
|
||||
version = "0.5.1"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.cpal]
|
||||
version = "0.18.1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.cpal]
|
||||
version = "0.18.1"
|
||||
features = ["wasm-bindgen"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.send_wrapper]
|
||||
version = "0.6.0"
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
name = "kira"
|
||||
version = "0.12.4"
|
||||
authors = ["Andrew Minnich <aminnich3@gmail.com>"]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Expressive audio library for games"
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"gamedev",
|
||||
"audio",
|
||||
"music",
|
||||
]
|
||||
categories = [
|
||||
"game-development",
|
||||
"multimedia::audio",
|
||||
]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/tesselode/kira"
|
||||
resolver = "2"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
|
||||
[features]
|
||||
aac = [
|
||||
"symphonia",
|
||||
"symphonia/aac",
|
||||
]
|
||||
adpcm = [
|
||||
"symphonia",
|
||||
"symphonia/adpcm",
|
||||
]
|
||||
aiff = [
|
||||
"symphonia",
|
||||
"symphonia/aiff",
|
||||
]
|
||||
alac = [
|
||||
"symphonia",
|
||||
"symphonia/alac",
|
||||
]
|
||||
caf = [
|
||||
"symphonia",
|
||||
"symphonia/caf",
|
||||
]
|
||||
cpal-realtime = [
|
||||
"cpal",
|
||||
"cpal/realtime",
|
||||
]
|
||||
cpal-realtime-dbus = [
|
||||
"cpal",
|
||||
"cpal/realtime-dbus",
|
||||
]
|
||||
default = [
|
||||
"cpal",
|
||||
"cpal-realtime",
|
||||
"cpal-realtime-dbus",
|
||||
"mp3",
|
||||
"ogg",
|
||||
"vorbis",
|
||||
"flac",
|
||||
"wav",
|
||||
"pcm",
|
||||
]
|
||||
flac = [
|
||||
"symphonia",
|
||||
"symphonia/flac",
|
||||
]
|
||||
isomp4 = [
|
||||
"symphonia",
|
||||
"symphonia/isomp4",
|
||||
]
|
||||
mkv = [
|
||||
"symphonia",
|
||||
"symphonia/mkv",
|
||||
]
|
||||
mp1 = [
|
||||
"symphonia",
|
||||
"symphonia/mp1",
|
||||
]
|
||||
mp2 = [
|
||||
"symphonia",
|
||||
"symphonia/mp2",
|
||||
]
|
||||
mp3 = [
|
||||
"symphonia",
|
||||
"symphonia/mp3",
|
||||
]
|
||||
mpa = [
|
||||
"symphonia",
|
||||
"symphonia/mpa",
|
||||
]
|
||||
ogg = [
|
||||
"symphonia",
|
||||
"symphonia/ogg",
|
||||
]
|
||||
pcm = [
|
||||
"symphonia",
|
||||
"symphonia/pcm",
|
||||
]
|
||||
vorbis = [
|
||||
"symphonia",
|
||||
"symphonia/vorbis",
|
||||
]
|
||||
wav = [
|
||||
"symphonia",
|
||||
"symphonia/wav",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "kira"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[test]]
|
||||
name = "change_sample_rate"
|
||||
path = "tests/change_sample_rate.rs"
|
||||
|
||||
[[test]]
|
||||
name = "streaming_sound_stops_on_error"
|
||||
path = "tests/streaming_sound_stops_on_error.rs"
|
||||
|
||||
[[test]]
|
||||
name = "sync_send"
|
||||
path = "tests/sync_send.rs"
|
||||
|
||||
[dependencies.assert_no_alloc]
|
||||
version = "1.1.2"
|
||||
optional = true
|
||||
|
||||
[dependencies.atomic-arena]
|
||||
version = "0.1.2"
|
||||
|
||||
[dependencies.glam]
|
||||
version = "0.33.0"
|
||||
features = ["mint"]
|
||||
|
||||
[dependencies.mint]
|
||||
version = "0.5.9"
|
||||
|
||||
[dependencies.pastey]
|
||||
version = "0.2.1"
|
||||
|
||||
[dependencies.rtrb]
|
||||
version = "0.3.2"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.0.219"
|
||||
features = ["derive"]
|
||||
optional = true
|
||||
|
||||
[dependencies.symphonia]
|
||||
version = "0.6.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.triple_buffer]
|
||||
version = "9.0.0"
|
||||
|
||||
[dev-dependencies.approx]
|
||||
version = "0.5.1"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.cpal]
|
||||
version = "0.18.1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.cpal]
|
||||
version = "0.18.1"
|
||||
features = ["wasm-bindgen"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies.send_wrapper]
|
||||
version = "0.6.0"
|
||||
|
||||
Vendored
+201
-201
@@ -1,201 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021 Andrew Minnich
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021 Andrew Minnich
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
Vendored
+7
-7
@@ -1,7 +1,7 @@
|
||||
Copyright 2021 Andrew Minnich
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
Copyright 2021 Andrew Minnich
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
+101
-101
@@ -1,101 +1,101 @@
|
||||
use std::convert::TryInto;
|
||||
|
||||
use crate::{
|
||||
frame::Frame,
|
||||
sound::{FromFileError, symphonia::load_frames_from_buffer_ref},
|
||||
};
|
||||
use symphonia::core::{
|
||||
codecs::{CodecParameters, audio::AudioDecoder},
|
||||
formats::{FormatReader, SeekMode, SeekTo, TrackType, probe::Hint},
|
||||
io::{MediaSource, MediaSourceStream},
|
||||
units::Timestamp,
|
||||
};
|
||||
|
||||
pub(crate) struct SymphoniaDecoder {
|
||||
format_reader: Box<dyn FormatReader>,
|
||||
decoder: Box<dyn AudioDecoder>,
|
||||
sample_rate: u32,
|
||||
num_frames: usize,
|
||||
track_id: u32,
|
||||
}
|
||||
|
||||
impl SymphoniaDecoder {
|
||||
pub(crate) fn new(media_source: Box<dyn MediaSource>) -> Result<Self, FromFileError> {
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
let probe = symphonia::default::get_probe();
|
||||
let mss = MediaSourceStream::new(media_source, Default::default());
|
||||
let format_reader = probe.probe(
|
||||
&Hint::default(),
|
||||
mss,
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)?;
|
||||
let default_track = format_reader
|
||||
.default_track(TrackType::Audio)
|
||||
.ok_or(FromFileError::NoDefaultTrack)?;
|
||||
let audio_params = match default_track.codec_params.as_ref() {
|
||||
Some(CodecParameters::Audio(p)) => p,
|
||||
_ => return Err(FromFileError::NoDefaultTrack),
|
||||
};
|
||||
let sample_rate = audio_params
|
||||
.sample_rate
|
||||
.ok_or(FromFileError::UnknownSampleRate)?;
|
||||
let num_frames = default_track
|
||||
.num_frames
|
||||
.ok_or(FromFileError::UnknownSampleRate)?
|
||||
.try_into()
|
||||
.expect("could not convert u64 into usize");
|
||||
let decoder = codecs.make_audio_decoder(audio_params, &Default::default())?;
|
||||
let track_id = default_track.id;
|
||||
Ok(Self {
|
||||
format_reader,
|
||||
decoder,
|
||||
sample_rate,
|
||||
num_frames,
|
||||
track_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Decoder for SymphoniaDecoder {
|
||||
type Error = FromFileError;
|
||||
|
||||
fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
fn num_frames(&self) -> usize {
|
||||
self.num_frames
|
||||
}
|
||||
|
||||
fn decode(&mut self) -> Result<Vec<Frame>, Self::Error> {
|
||||
let packet = loop {
|
||||
match self.format_reader.next_packet()? {
|
||||
Some(packet) if packet.track_id == self.track_id => break packet,
|
||||
Some(_) => continue,
|
||||
// benilla: the end of the packets is an error, as it was on symphonia 0.5, so a
|
||||
// stream whose reported length runs past its last packet stops there. An empty
|
||||
// chunk instead leaves `DecodeScheduler::frame_at_index` looping on it forever.
|
||||
None => return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof).into()),
|
||||
}
|
||||
};
|
||||
let buffer = self.decoder.decode(&packet)?;
|
||||
load_frames_from_buffer_ref(&buffer)
|
||||
}
|
||||
|
||||
fn seek(&mut self, index: usize) -> Result<usize, Self::Error> {
|
||||
let seeked_to = self.format_reader.seek(
|
||||
SeekMode::Accurate,
|
||||
SeekTo::Timestamp {
|
||||
ts: Timestamp::new(index as i64),
|
||||
track_id: self.track_id,
|
||||
},
|
||||
)?;
|
||||
let actual = seeked_to.actual_ts.get();
|
||||
Ok(if actual < 0 {
|
||||
0
|
||||
} else {
|
||||
(actual as usize).min(self.num_frames)
|
||||
})
|
||||
}
|
||||
}
|
||||
use std::convert::TryInto;
|
||||
|
||||
use crate::{
|
||||
frame::Frame,
|
||||
sound::{FromFileError, symphonia::load_frames_from_buffer_ref},
|
||||
};
|
||||
use symphonia::core::{
|
||||
codecs::{CodecParameters, audio::AudioDecoder},
|
||||
formats::{FormatReader, SeekMode, SeekTo, TrackType, probe::Hint},
|
||||
io::{MediaSource, MediaSourceStream},
|
||||
units::Timestamp,
|
||||
};
|
||||
|
||||
pub(crate) struct SymphoniaDecoder {
|
||||
format_reader: Box<dyn FormatReader>,
|
||||
decoder: Box<dyn AudioDecoder>,
|
||||
sample_rate: u32,
|
||||
num_frames: usize,
|
||||
track_id: u32,
|
||||
}
|
||||
|
||||
impl SymphoniaDecoder {
|
||||
pub(crate) fn new(media_source: Box<dyn MediaSource>) -> Result<Self, FromFileError> {
|
||||
let codecs = symphonia::default::get_codecs();
|
||||
let probe = symphonia::default::get_probe();
|
||||
let mss = MediaSourceStream::new(media_source, Default::default());
|
||||
let format_reader = probe.probe(
|
||||
&Hint::default(),
|
||||
mss,
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)?;
|
||||
let default_track = format_reader
|
||||
.default_track(TrackType::Audio)
|
||||
.ok_or(FromFileError::NoDefaultTrack)?;
|
||||
let audio_params = match default_track.codec_params.as_ref() {
|
||||
Some(CodecParameters::Audio(p)) => p,
|
||||
_ => return Err(FromFileError::NoDefaultTrack),
|
||||
};
|
||||
let sample_rate = audio_params
|
||||
.sample_rate
|
||||
.ok_or(FromFileError::UnknownSampleRate)?;
|
||||
let num_frames = default_track
|
||||
.num_frames
|
||||
.ok_or(FromFileError::UnknownSampleRate)?
|
||||
.try_into()
|
||||
.expect("could not convert u64 into usize");
|
||||
let decoder = codecs.make_audio_decoder(audio_params, &Default::default())?;
|
||||
let track_id = default_track.id;
|
||||
Ok(Self {
|
||||
format_reader,
|
||||
decoder,
|
||||
sample_rate,
|
||||
num_frames,
|
||||
track_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Decoder for SymphoniaDecoder {
|
||||
type Error = FromFileError;
|
||||
|
||||
fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
fn num_frames(&self) -> usize {
|
||||
self.num_frames
|
||||
}
|
||||
|
||||
fn decode(&mut self) -> Result<Vec<Frame>, Self::Error> {
|
||||
let packet = loop {
|
||||
match self.format_reader.next_packet()? {
|
||||
Some(packet) if packet.track_id == self.track_id => break packet,
|
||||
Some(_) => continue,
|
||||
// benilla: the end of the packets is an error, as it was on symphonia 0.5, so a
|
||||
// stream whose reported length runs past its last packet stops there. An empty
|
||||
// chunk instead leaves `DecodeScheduler::frame_at_index` looping on it forever.
|
||||
None => return Err(std::io::Error::from(std::io::ErrorKind::UnexpectedEof).into()),
|
||||
}
|
||||
};
|
||||
let buffer = self.decoder.decode(&packet)?;
|
||||
load_frames_from_buffer_ref(&buffer)
|
||||
}
|
||||
|
||||
fn seek(&mut self, index: usize) -> Result<usize, Self::Error> {
|
||||
let seeked_to = self.format_reader.seek(
|
||||
SeekMode::Accurate,
|
||||
SeekTo::Timestamp {
|
||||
ts: Timestamp::new(index as i64),
|
||||
track_id: self.track_id,
|
||||
},
|
||||
)?;
|
||||
let actual = seeked_to.actual_ts.get();
|
||||
Ok(if actual < 0 {
|
||||
0
|
||||
} else {
|
||||
(actual as usize).min(self.num_frames)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+491
-491
@@ -1,491 +1,491 @@
|
||||
mod builder;
|
||||
mod handle;
|
||||
mod spatial_builder;
|
||||
mod spatial_handle;
|
||||
|
||||
pub use builder::*;
|
||||
pub use handle::*;
|
||||
pub use spatial_builder::*;
|
||||
pub use spatial_handle::*;
|
||||
|
||||
use std::{error::Error, f32::consts::FRAC_PI_8, fmt::Display, sync::Arc};
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
|
||||
use crate::{
|
||||
Decibels, Easing, Frame, Parameter, StartTime, Tween, Tweenable,
|
||||
backend::resources::{
|
||||
ResourceStorage, clocks::Clocks, listeners::Listeners, modulators::Modulators,
|
||||
},
|
||||
command::ValueChangeCommand,
|
||||
command_writers_and_readers,
|
||||
effect::Effect,
|
||||
info::{Info, SpatialTrackInfo},
|
||||
listener::ListenerId,
|
||||
playback_state_manager::PlaybackStateManager,
|
||||
sound::Sound,
|
||||
};
|
||||
|
||||
use super::{SendTrack, SendTrackId, SendTrackRoute, TrackShared};
|
||||
|
||||
/// An error that's returned when trying to change the volume of a track route
|
||||
/// that did not exist originally.
|
||||
#[derive(Debug)]
|
||||
pub struct NonexistentRoute;
|
||||
|
||||
impl Display for NonexistentRoute {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Cannot change the volume of a track route that did not exist originally")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for NonexistentRoute {}
|
||||
|
||||
pub(crate) struct Track {
|
||||
shared: Arc<TrackShared>,
|
||||
command_readers: CommandReaders,
|
||||
volume: Parameter<Decibels>,
|
||||
sounds: ResourceStorage<Box<dyn Sound>>,
|
||||
sub_tracks: ResourceStorage<Track>,
|
||||
effects: Vec<Box<dyn Effect>>,
|
||||
sends: Vec<(SendTrackId, SendTrackRoute)>,
|
||||
persist_until_sounds_finish: bool,
|
||||
spatial_data: Option<SpatialData>,
|
||||
playback_state_manager: PlaybackStateManager,
|
||||
temp_buffer: Vec<Frame>,
|
||||
internal_buffer_size: usize,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
fn update_shared_playback_state(&mut self) {
|
||||
self.shared
|
||||
.set_state(self.playback_state_manager.playback_state());
|
||||
}
|
||||
|
||||
fn pause(&mut self, fade_out_tween: Tween) {
|
||||
self.playback_state_manager.pause(fade_out_tween);
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
|
||||
fn resume(&mut self, start_time: StartTime, fade_in_tween: Tween) {
|
||||
self.playback_state_manager
|
||||
.resume(start_time, fade_in_tween);
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
|
||||
pub fn init_effects(&mut self, sample_rate: u32) {
|
||||
for effect in &mut self.effects {
|
||||
effect.init(sample_rate, self.internal_buffer_size);
|
||||
}
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.init_effects(sample_rate);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_change_sample_rate(&mut self, sample_rate: u32) {
|
||||
for effect in &mut self.effects {
|
||||
effect.on_change_sample_rate(sample_rate);
|
||||
}
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.on_change_sample_rate(sample_rate);
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn shared(&self) -> Arc<TrackShared> {
|
||||
self.shared.clone()
|
||||
}
|
||||
|
||||
pub fn should_be_removed(&self) -> bool {
|
||||
if self
|
||||
.sub_tracks
|
||||
.iter()
|
||||
.any(|(_, sub_track)| !sub_track.should_be_removed())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if self.persist_until_sounds_finish {
|
||||
self.shared().is_marked_for_removal() && self.sounds.is_empty()
|
||||
} else {
|
||||
self.shared().is_marked_for_removal()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_start_processing(&mut self) {
|
||||
self.read_commands();
|
||||
self.sounds.remove_and_add(|sound| sound.finished());
|
||||
for (_, sound) in &mut self.sounds {
|
||||
sound.on_start_processing();
|
||||
}
|
||||
self.sub_tracks
|
||||
.remove_and_add(|sub_track| sub_track.should_be_removed());
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.on_start_processing();
|
||||
}
|
||||
for effect in &mut self.effects {
|
||||
effect.on_start_processing();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn process(
|
||||
&mut self,
|
||||
out: &mut [Frame],
|
||||
dt: f64,
|
||||
clocks: &Clocks,
|
||||
modulators: &Modulators,
|
||||
listeners: &Listeners,
|
||||
parent_spatial_track_info: Option<SpatialTrackInfo>,
|
||||
send_tracks: &mut ResourceStorage<SendTrack>,
|
||||
) {
|
||||
// get info
|
||||
let spatial_track_info = self
|
||||
.spatial_data
|
||||
.as_ref()
|
||||
.map(|spatial_data| SpatialTrackInfo {
|
||||
position: spatial_data.position.value(),
|
||||
listener_id: spatial_data.listener_id,
|
||||
})
|
||||
.or(parent_spatial_track_info);
|
||||
let info = Info::new(
|
||||
&clocks.0.resources,
|
||||
&modulators.0.resources,
|
||||
&listeners.0.resources,
|
||||
spatial_track_info,
|
||||
);
|
||||
|
||||
// update volume parameters
|
||||
self.volume.update(dt * out.len() as f64, &info);
|
||||
for (_, route) in &mut self.sends {
|
||||
route.volume.update(dt * out.len() as f64, &info);
|
||||
}
|
||||
|
||||
// update playback state
|
||||
let changed_playback_state = self
|
||||
.playback_state_manager
|
||||
.update(dt * out.len() as f64, &info);
|
||||
if changed_playback_state {
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
if !self.playback_state_manager.playback_state().is_advancing() {
|
||||
out.fill(Frame::ZERO);
|
||||
return;
|
||||
}
|
||||
|
||||
let num_frames = out.len();
|
||||
|
||||
// process sub tracks
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.process(
|
||||
&mut self.temp_buffer[..out.len()],
|
||||
dt,
|
||||
clocks,
|
||||
modulators,
|
||||
listeners,
|
||||
spatial_track_info,
|
||||
send_tracks,
|
||||
);
|
||||
for (summed_out, track_out) in out.iter_mut().zip(self.temp_buffer.iter().copied()) {
|
||||
*summed_out += track_out;
|
||||
}
|
||||
self.temp_buffer.fill(Frame::ZERO);
|
||||
}
|
||||
|
||||
// process sounds
|
||||
for (_, sound) in &mut self.sounds {
|
||||
sound.process(&mut self.temp_buffer[..out.len()], dt, &info);
|
||||
for (summed_out, sound_out) in out.iter_mut().zip(self.temp_buffer.iter().copied()) {
|
||||
*summed_out += sound_out;
|
||||
}
|
||||
self.temp_buffer.fill(Frame::ZERO);
|
||||
}
|
||||
|
||||
// apply effects
|
||||
for effect in &mut self.effects {
|
||||
effect.process(out, dt, &info);
|
||||
}
|
||||
|
||||
// apply spatialization, then the volume fade.
|
||||
//
|
||||
// benilla: the spatial gains and the volume are evaluated at the CHUNK's two ends and
|
||||
// interpolated linearly across it, not recomputed per frame. Upstream spatialized every
|
||||
// frame — two vector normalizes, a length, an attenuation curve and a dB→amplitude
|
||||
// `powf` per frame per spatial track, and two more `powf`s for the volume tween — which
|
||||
// made a dozen voices cost ~1 ms of every 60 Hz frame on the audio thread. A chunk is
|
||||
// the output device's buffer (~10 ms); the pan and attenuation of a moving source change
|
||||
// negligibly across it, and the mixer this backend stands in for (FMOD 3) updates them
|
||||
// per mixer update, not per sample. See `third_party/kira/BENILLA.md`.
|
||||
if let Some(spatial_data) = &mut self.spatial_data {
|
||||
spatial_data.position.update(dt * out.len() as f64, &info);
|
||||
spatial_data
|
||||
.spatialization_strength
|
||||
.update(dt * out.len() as f64, &info);
|
||||
if let Some(listener_info) = info.listener_info() {
|
||||
let gains_at = |t: f64| {
|
||||
spatial_data.spatial_gains(
|
||||
listener_info.interpolated_position(t as f32).into(),
|
||||
listener_info.interpolated_orientation(t as f32).into(),
|
||||
t,
|
||||
)
|
||||
};
|
||||
let g0 = gains_at(0.0);
|
||||
let g1 = gains_at(1.0);
|
||||
let inv = 1.0 / num_frames as f32;
|
||||
for (i, frame) in out.iter_mut().enumerate() {
|
||||
let t = i as f32 * inv;
|
||||
let g = g0.lerp(&g1, t);
|
||||
*frame = g.apply(*frame);
|
||||
}
|
||||
} else {
|
||||
out.fill(Frame::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let amplitude_at = |t: f64| {
|
||||
self.volume.interpolated_value(t).as_amplitude()
|
||||
* self
|
||||
.playback_state_manager
|
||||
.interpolated_fade_volume(t)
|
||||
.as_amplitude()
|
||||
};
|
||||
let a0 = amplitude_at(0.0);
|
||||
let a1 = amplitude_at(1.0);
|
||||
if a0 == a1 {
|
||||
if a0 != 1.0 {
|
||||
for frame in out.iter_mut() {
|
||||
*frame *= a0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let inv = 1.0 / num_frames as f32;
|
||||
for (i, frame) in out.iter_mut().enumerate() {
|
||||
let t = (i + 1) as f32 * inv;
|
||||
*frame *= a0 + (a1 - a0) * t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// output to send tracks
|
||||
for (send_track_id, SendTrackRoute { volume, .. }) in &self.sends {
|
||||
let Some(send_track) = send_tracks.get_mut(send_track_id.0) else {
|
||||
continue;
|
||||
};
|
||||
send_track.add_input(out, volume.value());
|
||||
}
|
||||
}
|
||||
|
||||
fn read_commands(&mut self) {
|
||||
self.volume
|
||||
.read_command(&mut self.command_readers.set_volume);
|
||||
for (_, route) in &mut self.sends {
|
||||
route.read_commands();
|
||||
}
|
||||
if let Some(SpatialData {
|
||||
position,
|
||||
spatialization_strength,
|
||||
..
|
||||
}) = &mut self.spatial_data
|
||||
{
|
||||
position.read_command(&mut self.command_readers.set_position);
|
||||
spatialization_strength
|
||||
.read_command(&mut self.command_readers.set_spatialization_strength);
|
||||
}
|
||||
if let Some(tween) = self.command_readers.pause.read() {
|
||||
self.pause(tween);
|
||||
}
|
||||
if let Some((start_time, tween)) = self.command_readers.resume.read() {
|
||||
self.resume(start_time, tween);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SpatialData {
|
||||
listener_id: ListenerId,
|
||||
position: Parameter<Vec3>,
|
||||
/// The distances from a listener at which the track is loudest and quietest.
|
||||
distances: SpatialTrackDistances,
|
||||
/// How the track's volume will change with distance.
|
||||
///
|
||||
/// If `None`, the track will output at a constant volume.
|
||||
attenuation_function: Option<Easing>,
|
||||
/// How much the track's output should be panned left or right depending on its
|
||||
/// direction from the listener.
|
||||
///
|
||||
/// This value should be between `0.0` and `1.0`. `0.0` disables spatialization
|
||||
/// entirely.
|
||||
spatialization_strength: Parameter<f32>,
|
||||
}
|
||||
|
||||
impl SpatialData {
|
||||
/// benilla: the gains [`Self::spatialize`] applies, as a value — so a chunk can evaluate
|
||||
/// them twice and lerp instead of recomputing them per frame.
|
||||
fn spatial_gains(
|
||||
&self,
|
||||
listener_position: Vec3,
|
||||
listener_orientation: Quat,
|
||||
time_in_chunk: f64,
|
||||
) -> SpatialGains {
|
||||
let position = self.position.interpolated_value(time_in_chunk);
|
||||
let spatialization_strength = self
|
||||
.spatialization_strength
|
||||
.interpolated_value(time_in_chunk)
|
||||
.clamp(0.0, 1.0);
|
||||
let min_ear_amplitude = 1.0 - spatialization_strength;
|
||||
let attenuation = match self.attenuation_function {
|
||||
Some(attenuation_function) => {
|
||||
let distance = (listener_position - position).length();
|
||||
let relative_distance = self.distances.relative_distance(distance);
|
||||
let relative_volume =
|
||||
attenuation_function.apply((1.0 - relative_distance).into()) as f32;
|
||||
Tweenable::interpolate(
|
||||
Decibels::SILENCE,
|
||||
Decibels::IDENTITY,
|
||||
relative_volume.into(),
|
||||
)
|
||||
.as_amplitude()
|
||||
}
|
||||
None => 1.0,
|
||||
};
|
||||
let (left, right) = if spatialization_strength != 0.0 {
|
||||
let (left_ear_position, right_ear_position) =
|
||||
listener_ear_positions(listener_position, listener_orientation);
|
||||
let (left_ear_direction, right_ear_direction) =
|
||||
listener_ear_directions(listener_orientation);
|
||||
let emitter_direction_relative_to_left_ear =
|
||||
(position - left_ear_position).normalize_or_zero();
|
||||
let emitter_direction_relative_to_right_ear =
|
||||
(position - right_ear_position).normalize_or_zero();
|
||||
let left_ear_volume =
|
||||
(left_ear_direction.dot(emitter_direction_relative_to_left_ear) + 1.0) / 2.0;
|
||||
let right_ear_volume =
|
||||
(right_ear_direction.dot(emitter_direction_relative_to_right_ear) + 1.0) / 2.0;
|
||||
(
|
||||
min_ear_amplitude + (1.0 - min_ear_amplitude) * left_ear_volume,
|
||||
min_ear_amplitude + (1.0 - min_ear_amplitude) * right_ear_volume,
|
||||
)
|
||||
} else {
|
||||
(1.0, 1.0)
|
||||
};
|
||||
SpatialGains {
|
||||
attenuation,
|
||||
left,
|
||||
right,
|
||||
mono: spatialization_strength != 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn spatialize(
|
||||
&self,
|
||||
input: Frame,
|
||||
listener_position: Vec3,
|
||||
listener_orientation: Quat,
|
||||
time_in_chunk: f64,
|
||||
) -> Frame {
|
||||
let position = self.position.interpolated_value(time_in_chunk);
|
||||
let spatialization_strength = self
|
||||
.spatialization_strength
|
||||
.interpolated_value(time_in_chunk)
|
||||
.clamp(0.0, 1.0);
|
||||
let min_ear_amplitude = 1.0 - spatialization_strength;
|
||||
|
||||
let mut output = input;
|
||||
// attenuate volume
|
||||
if let Some(attenuation_function) = self.attenuation_function {
|
||||
let distance = (listener_position - position).length();
|
||||
let relative_distance = self.distances.relative_distance(distance);
|
||||
let relative_volume =
|
||||
attenuation_function.apply((1.0 - relative_distance).into()) as f32;
|
||||
let amplitude = Tweenable::interpolate(
|
||||
Decibels::SILENCE,
|
||||
Decibels::IDENTITY,
|
||||
relative_volume.into(),
|
||||
)
|
||||
.as_amplitude();
|
||||
output *= amplitude;
|
||||
}
|
||||
// apply spatialization
|
||||
if spatialization_strength != 0.0 {
|
||||
output = output.as_mono();
|
||||
let (left_ear_position, right_ear_position) =
|
||||
listener_ear_positions(listener_position, listener_orientation);
|
||||
let (left_ear_direction, right_ear_direction) =
|
||||
listener_ear_directions(listener_orientation);
|
||||
let emitter_direction_relative_to_left_ear =
|
||||
(position - left_ear_position).normalize_or_zero();
|
||||
let emitter_direction_relative_to_right_ear =
|
||||
(position - right_ear_position).normalize_or_zero();
|
||||
let left_ear_volume =
|
||||
(left_ear_direction.dot(emitter_direction_relative_to_left_ear) + 1.0) / 2.0;
|
||||
let right_ear_volume =
|
||||
(right_ear_direction.dot(emitter_direction_relative_to_right_ear) + 1.0) / 2.0;
|
||||
output.left *= min_ear_amplitude + (1.0 - min_ear_amplitude) * left_ear_volume;
|
||||
output.right *= min_ear_amplitude + (1.0 - min_ear_amplitude) * right_ear_volume;
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
/// benilla: what [`SpatialData::spatialize`] does to a frame, factored out of the per-frame
|
||||
/// loop — attenuation, then (for a spatialized track) mono-fold and per-ear gain.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SpatialGains {
|
||||
attenuation: f32,
|
||||
left: f32,
|
||||
right: f32,
|
||||
mono: bool,
|
||||
}
|
||||
|
||||
impl SpatialGains {
|
||||
fn lerp(&self, other: &Self, t: f32) -> Self {
|
||||
Self {
|
||||
attenuation: self.attenuation + (other.attenuation - self.attenuation) * t,
|
||||
left: self.left + (other.left - self.left) * t,
|
||||
right: self.right + (other.right - self.right) * t,
|
||||
// The fold is a state, not a gain: a chunk whose strength crosses zero folds for
|
||||
// the whole chunk, exactly as upstream would at every frame past the crossing.
|
||||
mono: self.mono || other.mono,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&self, input: Frame) -> Frame {
|
||||
let mut output = input * self.attenuation;
|
||||
if self.mono {
|
||||
output = output.as_mono();
|
||||
output.left *= self.left;
|
||||
output.right *= self.right;
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn listener_ear_positions(listener_position: Vec3, listener_orientation: Quat) -> (Vec3, Vec3) {
|
||||
const EAR_DISTANCE: f32 = 0.1;
|
||||
let position = listener_position;
|
||||
let orientation = listener_orientation;
|
||||
let left = position + orientation * (Vec3::NEG_X * EAR_DISTANCE);
|
||||
let right = position + orientation * (Vec3::X * EAR_DISTANCE);
|
||||
(left, right)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn listener_ear_directions(listener_orientation: Quat) -> (Vec3, Vec3) {
|
||||
const EAR_ANGLE_FROM_HEAD: f32 = FRAC_PI_8;
|
||||
let left_ear_direction_relative_to_head =
|
||||
Quat::from_rotation_y(-EAR_ANGLE_FROM_HEAD) * Vec3::NEG_X;
|
||||
let right_ear_direction_relative_to_head = Quat::from_rotation_y(EAR_ANGLE_FROM_HEAD) * Vec3::X;
|
||||
let orientation = listener_orientation;
|
||||
let left = orientation * left_ear_direction_relative_to_head;
|
||||
let right = orientation * right_ear_direction_relative_to_head;
|
||||
(left, right)
|
||||
}
|
||||
|
||||
command_writers_and_readers! {
|
||||
set_volume: ValueChangeCommand<Decibels>,
|
||||
set_position: ValueChangeCommand<Vec3>,
|
||||
set_spatialization_strength: ValueChangeCommand<f32>,
|
||||
pause: Tween,
|
||||
resume: (StartTime, Tween),
|
||||
}
|
||||
mod builder;
|
||||
mod handle;
|
||||
mod spatial_builder;
|
||||
mod spatial_handle;
|
||||
|
||||
pub use builder::*;
|
||||
pub use handle::*;
|
||||
pub use spatial_builder::*;
|
||||
pub use spatial_handle::*;
|
||||
|
||||
use std::{error::Error, f32::consts::FRAC_PI_8, fmt::Display, sync::Arc};
|
||||
|
||||
use glam::{Quat, Vec3};
|
||||
|
||||
use crate::{
|
||||
Decibels, Easing, Frame, Parameter, StartTime, Tween, Tweenable,
|
||||
backend::resources::{
|
||||
ResourceStorage, clocks::Clocks, listeners::Listeners, modulators::Modulators,
|
||||
},
|
||||
command::ValueChangeCommand,
|
||||
command_writers_and_readers,
|
||||
effect::Effect,
|
||||
info::{Info, SpatialTrackInfo},
|
||||
listener::ListenerId,
|
||||
playback_state_manager::PlaybackStateManager,
|
||||
sound::Sound,
|
||||
};
|
||||
|
||||
use super::{SendTrack, SendTrackId, SendTrackRoute, TrackShared};
|
||||
|
||||
/// An error that's returned when trying to change the volume of a track route
|
||||
/// that did not exist originally.
|
||||
#[derive(Debug)]
|
||||
pub struct NonexistentRoute;
|
||||
|
||||
impl Display for NonexistentRoute {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Cannot change the volume of a track route that did not exist originally")
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for NonexistentRoute {}
|
||||
|
||||
pub(crate) struct Track {
|
||||
shared: Arc<TrackShared>,
|
||||
command_readers: CommandReaders,
|
||||
volume: Parameter<Decibels>,
|
||||
sounds: ResourceStorage<Box<dyn Sound>>,
|
||||
sub_tracks: ResourceStorage<Track>,
|
||||
effects: Vec<Box<dyn Effect>>,
|
||||
sends: Vec<(SendTrackId, SendTrackRoute)>,
|
||||
persist_until_sounds_finish: bool,
|
||||
spatial_data: Option<SpatialData>,
|
||||
playback_state_manager: PlaybackStateManager,
|
||||
temp_buffer: Vec<Frame>,
|
||||
internal_buffer_size: usize,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
fn update_shared_playback_state(&mut self) {
|
||||
self.shared
|
||||
.set_state(self.playback_state_manager.playback_state());
|
||||
}
|
||||
|
||||
fn pause(&mut self, fade_out_tween: Tween) {
|
||||
self.playback_state_manager.pause(fade_out_tween);
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
|
||||
fn resume(&mut self, start_time: StartTime, fade_in_tween: Tween) {
|
||||
self.playback_state_manager
|
||||
.resume(start_time, fade_in_tween);
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
|
||||
pub fn init_effects(&mut self, sample_rate: u32) {
|
||||
for effect in &mut self.effects {
|
||||
effect.init(sample_rate, self.internal_buffer_size);
|
||||
}
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.init_effects(sample_rate);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_change_sample_rate(&mut self, sample_rate: u32) {
|
||||
for effect in &mut self.effects {
|
||||
effect.on_change_sample_rate(sample_rate);
|
||||
}
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.on_change_sample_rate(sample_rate);
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn shared(&self) -> Arc<TrackShared> {
|
||||
self.shared.clone()
|
||||
}
|
||||
|
||||
pub fn should_be_removed(&self) -> bool {
|
||||
if self
|
||||
.sub_tracks
|
||||
.iter()
|
||||
.any(|(_, sub_track)| !sub_track.should_be_removed())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if self.persist_until_sounds_finish {
|
||||
self.shared().is_marked_for_removal() && self.sounds.is_empty()
|
||||
} else {
|
||||
self.shared().is_marked_for_removal()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_start_processing(&mut self) {
|
||||
self.read_commands();
|
||||
self.sounds.remove_and_add(|sound| sound.finished());
|
||||
for (_, sound) in &mut self.sounds {
|
||||
sound.on_start_processing();
|
||||
}
|
||||
self.sub_tracks
|
||||
.remove_and_add(|sub_track| sub_track.should_be_removed());
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.on_start_processing();
|
||||
}
|
||||
for effect in &mut self.effects {
|
||||
effect.on_start_processing();
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn process(
|
||||
&mut self,
|
||||
out: &mut [Frame],
|
||||
dt: f64,
|
||||
clocks: &Clocks,
|
||||
modulators: &Modulators,
|
||||
listeners: &Listeners,
|
||||
parent_spatial_track_info: Option<SpatialTrackInfo>,
|
||||
send_tracks: &mut ResourceStorage<SendTrack>,
|
||||
) {
|
||||
// get info
|
||||
let spatial_track_info = self
|
||||
.spatial_data
|
||||
.as_ref()
|
||||
.map(|spatial_data| SpatialTrackInfo {
|
||||
position: spatial_data.position.value(),
|
||||
listener_id: spatial_data.listener_id,
|
||||
})
|
||||
.or(parent_spatial_track_info);
|
||||
let info = Info::new(
|
||||
&clocks.0.resources,
|
||||
&modulators.0.resources,
|
||||
&listeners.0.resources,
|
||||
spatial_track_info,
|
||||
);
|
||||
|
||||
// update volume parameters
|
||||
self.volume.update(dt * out.len() as f64, &info);
|
||||
for (_, route) in &mut self.sends {
|
||||
route.volume.update(dt * out.len() as f64, &info);
|
||||
}
|
||||
|
||||
// update playback state
|
||||
let changed_playback_state = self
|
||||
.playback_state_manager
|
||||
.update(dt * out.len() as f64, &info);
|
||||
if changed_playback_state {
|
||||
self.update_shared_playback_state();
|
||||
}
|
||||
if !self.playback_state_manager.playback_state().is_advancing() {
|
||||
out.fill(Frame::ZERO);
|
||||
return;
|
||||
}
|
||||
|
||||
let num_frames = out.len();
|
||||
|
||||
// process sub tracks
|
||||
for (_, sub_track) in &mut self.sub_tracks {
|
||||
sub_track.process(
|
||||
&mut self.temp_buffer[..out.len()],
|
||||
dt,
|
||||
clocks,
|
||||
modulators,
|
||||
listeners,
|
||||
spatial_track_info,
|
||||
send_tracks,
|
||||
);
|
||||
for (summed_out, track_out) in out.iter_mut().zip(self.temp_buffer.iter().copied()) {
|
||||
*summed_out += track_out;
|
||||
}
|
||||
self.temp_buffer.fill(Frame::ZERO);
|
||||
}
|
||||
|
||||
// process sounds
|
||||
for (_, sound) in &mut self.sounds {
|
||||
sound.process(&mut self.temp_buffer[..out.len()], dt, &info);
|
||||
for (summed_out, sound_out) in out.iter_mut().zip(self.temp_buffer.iter().copied()) {
|
||||
*summed_out += sound_out;
|
||||
}
|
||||
self.temp_buffer.fill(Frame::ZERO);
|
||||
}
|
||||
|
||||
// apply effects
|
||||
for effect in &mut self.effects {
|
||||
effect.process(out, dt, &info);
|
||||
}
|
||||
|
||||
// apply spatialization, then the volume fade.
|
||||
//
|
||||
// benilla: the spatial gains and the volume are evaluated at the CHUNK's two ends and
|
||||
// interpolated linearly across it, not recomputed per frame. Upstream spatialized every
|
||||
// frame — two vector normalizes, a length, an attenuation curve and a dB→amplitude
|
||||
// `powf` per frame per spatial track, and two more `powf`s for the volume tween — which
|
||||
// made a dozen voices cost ~1 ms of every 60 Hz frame on the audio thread. A chunk is
|
||||
// the output device's buffer (~10 ms); the pan and attenuation of a moving source change
|
||||
// negligibly across it, and the mixer this backend stands in for (FMOD 3) updates them
|
||||
// per mixer update, not per sample. See `third_party/kira/BENILLA.md`.
|
||||
if let Some(spatial_data) = &mut self.spatial_data {
|
||||
spatial_data.position.update(dt * out.len() as f64, &info);
|
||||
spatial_data
|
||||
.spatialization_strength
|
||||
.update(dt * out.len() as f64, &info);
|
||||
if let Some(listener_info) = info.listener_info() {
|
||||
let gains_at = |t: f64| {
|
||||
spatial_data.spatial_gains(
|
||||
listener_info.interpolated_position(t as f32).into(),
|
||||
listener_info.interpolated_orientation(t as f32).into(),
|
||||
t,
|
||||
)
|
||||
};
|
||||
let g0 = gains_at(0.0);
|
||||
let g1 = gains_at(1.0);
|
||||
let inv = 1.0 / num_frames as f32;
|
||||
for (i, frame) in out.iter_mut().enumerate() {
|
||||
let t = i as f32 * inv;
|
||||
let g = g0.lerp(&g1, t);
|
||||
*frame = g.apply(*frame);
|
||||
}
|
||||
} else {
|
||||
out.fill(Frame::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let amplitude_at = |t: f64| {
|
||||
self.volume.interpolated_value(t).as_amplitude()
|
||||
* self
|
||||
.playback_state_manager
|
||||
.interpolated_fade_volume(t)
|
||||
.as_amplitude()
|
||||
};
|
||||
let a0 = amplitude_at(0.0);
|
||||
let a1 = amplitude_at(1.0);
|
||||
if a0 == a1 {
|
||||
if a0 != 1.0 {
|
||||
for frame in out.iter_mut() {
|
||||
*frame *= a0;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let inv = 1.0 / num_frames as f32;
|
||||
for (i, frame) in out.iter_mut().enumerate() {
|
||||
let t = (i + 1) as f32 * inv;
|
||||
*frame *= a0 + (a1 - a0) * t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// output to send tracks
|
||||
for (send_track_id, SendTrackRoute { volume, .. }) in &self.sends {
|
||||
let Some(send_track) = send_tracks.get_mut(send_track_id.0) else {
|
||||
continue;
|
||||
};
|
||||
send_track.add_input(out, volume.value());
|
||||
}
|
||||
}
|
||||
|
||||
fn read_commands(&mut self) {
|
||||
self.volume
|
||||
.read_command(&mut self.command_readers.set_volume);
|
||||
for (_, route) in &mut self.sends {
|
||||
route.read_commands();
|
||||
}
|
||||
if let Some(SpatialData {
|
||||
position,
|
||||
spatialization_strength,
|
||||
..
|
||||
}) = &mut self.spatial_data
|
||||
{
|
||||
position.read_command(&mut self.command_readers.set_position);
|
||||
spatialization_strength
|
||||
.read_command(&mut self.command_readers.set_spatialization_strength);
|
||||
}
|
||||
if let Some(tween) = self.command_readers.pause.read() {
|
||||
self.pause(tween);
|
||||
}
|
||||
if let Some((start_time, tween)) = self.command_readers.resume.read() {
|
||||
self.resume(start_time, tween);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SpatialData {
|
||||
listener_id: ListenerId,
|
||||
position: Parameter<Vec3>,
|
||||
/// The distances from a listener at which the track is loudest and quietest.
|
||||
distances: SpatialTrackDistances,
|
||||
/// How the track's volume will change with distance.
|
||||
///
|
||||
/// If `None`, the track will output at a constant volume.
|
||||
attenuation_function: Option<Easing>,
|
||||
/// How much the track's output should be panned left or right depending on its
|
||||
/// direction from the listener.
|
||||
///
|
||||
/// This value should be between `0.0` and `1.0`. `0.0` disables spatialization
|
||||
/// entirely.
|
||||
spatialization_strength: Parameter<f32>,
|
||||
}
|
||||
|
||||
impl SpatialData {
|
||||
/// benilla: the gains [`Self::spatialize`] applies, as a value — so a chunk can evaluate
|
||||
/// them twice and lerp instead of recomputing them per frame.
|
||||
fn spatial_gains(
|
||||
&self,
|
||||
listener_position: Vec3,
|
||||
listener_orientation: Quat,
|
||||
time_in_chunk: f64,
|
||||
) -> SpatialGains {
|
||||
let position = self.position.interpolated_value(time_in_chunk);
|
||||
let spatialization_strength = self
|
||||
.spatialization_strength
|
||||
.interpolated_value(time_in_chunk)
|
||||
.clamp(0.0, 1.0);
|
||||
let min_ear_amplitude = 1.0 - spatialization_strength;
|
||||
let attenuation = match self.attenuation_function {
|
||||
Some(attenuation_function) => {
|
||||
let distance = (listener_position - position).length();
|
||||
let relative_distance = self.distances.relative_distance(distance);
|
||||
let relative_volume =
|
||||
attenuation_function.apply((1.0 - relative_distance).into()) as f32;
|
||||
Tweenable::interpolate(
|
||||
Decibels::SILENCE,
|
||||
Decibels::IDENTITY,
|
||||
relative_volume.into(),
|
||||
)
|
||||
.as_amplitude()
|
||||
}
|
||||
None => 1.0,
|
||||
};
|
||||
let (left, right) = if spatialization_strength != 0.0 {
|
||||
let (left_ear_position, right_ear_position) =
|
||||
listener_ear_positions(listener_position, listener_orientation);
|
||||
let (left_ear_direction, right_ear_direction) =
|
||||
listener_ear_directions(listener_orientation);
|
||||
let emitter_direction_relative_to_left_ear =
|
||||
(position - left_ear_position).normalize_or_zero();
|
||||
let emitter_direction_relative_to_right_ear =
|
||||
(position - right_ear_position).normalize_or_zero();
|
||||
let left_ear_volume =
|
||||
(left_ear_direction.dot(emitter_direction_relative_to_left_ear) + 1.0) / 2.0;
|
||||
let right_ear_volume =
|
||||
(right_ear_direction.dot(emitter_direction_relative_to_right_ear) + 1.0) / 2.0;
|
||||
(
|
||||
min_ear_amplitude + (1.0 - min_ear_amplitude) * left_ear_volume,
|
||||
min_ear_amplitude + (1.0 - min_ear_amplitude) * right_ear_volume,
|
||||
)
|
||||
} else {
|
||||
(1.0, 1.0)
|
||||
};
|
||||
SpatialGains {
|
||||
attenuation,
|
||||
left,
|
||||
right,
|
||||
mono: spatialization_strength != 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn spatialize(
|
||||
&self,
|
||||
input: Frame,
|
||||
listener_position: Vec3,
|
||||
listener_orientation: Quat,
|
||||
time_in_chunk: f64,
|
||||
) -> Frame {
|
||||
let position = self.position.interpolated_value(time_in_chunk);
|
||||
let spatialization_strength = self
|
||||
.spatialization_strength
|
||||
.interpolated_value(time_in_chunk)
|
||||
.clamp(0.0, 1.0);
|
||||
let min_ear_amplitude = 1.0 - spatialization_strength;
|
||||
|
||||
let mut output = input;
|
||||
// attenuate volume
|
||||
if let Some(attenuation_function) = self.attenuation_function {
|
||||
let distance = (listener_position - position).length();
|
||||
let relative_distance = self.distances.relative_distance(distance);
|
||||
let relative_volume =
|
||||
attenuation_function.apply((1.0 - relative_distance).into()) as f32;
|
||||
let amplitude = Tweenable::interpolate(
|
||||
Decibels::SILENCE,
|
||||
Decibels::IDENTITY,
|
||||
relative_volume.into(),
|
||||
)
|
||||
.as_amplitude();
|
||||
output *= amplitude;
|
||||
}
|
||||
// apply spatialization
|
||||
if spatialization_strength != 0.0 {
|
||||
output = output.as_mono();
|
||||
let (left_ear_position, right_ear_position) =
|
||||
listener_ear_positions(listener_position, listener_orientation);
|
||||
let (left_ear_direction, right_ear_direction) =
|
||||
listener_ear_directions(listener_orientation);
|
||||
let emitter_direction_relative_to_left_ear =
|
||||
(position - left_ear_position).normalize_or_zero();
|
||||
let emitter_direction_relative_to_right_ear =
|
||||
(position - right_ear_position).normalize_or_zero();
|
||||
let left_ear_volume =
|
||||
(left_ear_direction.dot(emitter_direction_relative_to_left_ear) + 1.0) / 2.0;
|
||||
let right_ear_volume =
|
||||
(right_ear_direction.dot(emitter_direction_relative_to_right_ear) + 1.0) / 2.0;
|
||||
output.left *= min_ear_amplitude + (1.0 - min_ear_amplitude) * left_ear_volume;
|
||||
output.right *= min_ear_amplitude + (1.0 - min_ear_amplitude) * right_ear_volume;
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
/// benilla: what [`SpatialData::spatialize`] does to a frame, factored out of the per-frame
|
||||
/// loop — attenuation, then (for a spatialized track) mono-fold and per-ear gain.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SpatialGains {
|
||||
attenuation: f32,
|
||||
left: f32,
|
||||
right: f32,
|
||||
mono: bool,
|
||||
}
|
||||
|
||||
impl SpatialGains {
|
||||
fn lerp(&self, other: &Self, t: f32) -> Self {
|
||||
Self {
|
||||
attenuation: self.attenuation + (other.attenuation - self.attenuation) * t,
|
||||
left: self.left + (other.left - self.left) * t,
|
||||
right: self.right + (other.right - self.right) * t,
|
||||
// The fold is a state, not a gain: a chunk whose strength crosses zero folds for
|
||||
// the whole chunk, exactly as upstream would at every frame past the crossing.
|
||||
mono: self.mono || other.mono,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&self, input: Frame) -> Frame {
|
||||
let mut output = input * self.attenuation;
|
||||
if self.mono {
|
||||
output = output.as_mono();
|
||||
output.left *= self.left;
|
||||
output.right *= self.right;
|
||||
}
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn listener_ear_positions(listener_position: Vec3, listener_orientation: Quat) -> (Vec3, Vec3) {
|
||||
const EAR_DISTANCE: f32 = 0.1;
|
||||
let position = listener_position;
|
||||
let orientation = listener_orientation;
|
||||
let left = position + orientation * (Vec3::NEG_X * EAR_DISTANCE);
|
||||
let right = position + orientation * (Vec3::X * EAR_DISTANCE);
|
||||
(left, right)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
fn listener_ear_directions(listener_orientation: Quat) -> (Vec3, Vec3) {
|
||||
const EAR_ANGLE_FROM_HEAD: f32 = FRAC_PI_8;
|
||||
let left_ear_direction_relative_to_head =
|
||||
Quat::from_rotation_y(-EAR_ANGLE_FROM_HEAD) * Vec3::NEG_X;
|
||||
let right_ear_direction_relative_to_head = Quat::from_rotation_y(EAR_ANGLE_FROM_HEAD) * Vec3::X;
|
||||
let orientation = listener_orientation;
|
||||
let left = orientation * left_ear_direction_relative_to_head;
|
||||
let right = orientation * right_ear_direction_relative_to_head;
|
||||
(left, right)
|
||||
}
|
||||
|
||||
command_writers_and_readers! {
|
||||
set_volume: ValueChangeCommand<Decibels>,
|
||||
set_position: ValueChangeCommand<Vec3>,
|
||||
set_spatialization_strength: ValueChangeCommand<f32>,
|
||||
pause: Tween,
|
||||
resume: (StartTime, Tween),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user