feat(moonwell): добавить смену моделей Reforged без перезапуска

This commit is contained in:
2026-11-24 13:54:02 +04:00
parent 8e9e717cc8
commit 53f52dc1da
18 changed files with 879 additions and 216 deletions
+13 -4
View File
@@ -56,6 +56,7 @@ pub(crate) mod corpse;
mod live_display;
use live_display::{refresh_live_display, tick_scale_ease};
pub(crate) mod appearance;
pub(crate) use live_display::{AppliedDisplay, DisplayRebuilt, DisplaySwapped};
/// Terrain conform: a model flagged `GlobalModelFlags & 3 ∈ {1,3}` tilts to the ground.
@@ -738,7 +739,7 @@ impl Plugin for EntitiesPlugin {
// `Update` (`attach::glue_stage`).
update_display_models.in_set(DisplayBuildSet),
// The dressing room's preview, assembled from the display built just above.
build_dressup_preview,
(appearance::refresh_units, build_dressup_preview).chain(),
attach_entity_visuals,
// A WMO GameObject's doodad props, spawned as each M2 lands.
resolve_wmo_gameobject_props,
@@ -981,6 +982,7 @@ fn setup_entities(
catalog,
models: HashMap::new(),
races,
source: benilla_assets::MPQ_SOURCE,
});
}
Err(e) => warn!("item displays unavailable, units hold nothing: {e:#}"),
@@ -1065,7 +1067,10 @@ fn update_display_models(
char_create: Option<Res<CharCreate>>,
// The character panes' creature displays (`SetPetStablePaperdoll`, `0x4cb870` → `0x505a70`),
// with no wire entity.
pane_displays: Option<Res<crate::portrait::PaneDisplays>>,
panes: (
Option<Res<crate::portrait::PaneDisplays>>,
Option<Res<appearance::AppearanceSource>>,
),
) {
if !mats.ready() {
return; // no lighting yet → no materials to build
@@ -1117,7 +1122,7 @@ fn update_display_models(
}
// A character pane's creature display, a plain creature too; a repeat is free.
for &display in pane_displays.iter().flat_map(|d| &d.0) {
for &display in panes.0.iter().flat_map(|d| &d.0) {
actives.push((EntityKind::Unit, display));
}
@@ -1139,7 +1144,11 @@ fn update_display_models(
continue;
};
if !cr.models.contains_key(&disp) {
let dm = new_creature_display(&cr.catalog, disp, &asset_server);
let source = panes
.1
.as_deref()
.map_or(benilla_assets::MPQ_SOURCE, |p| p.0);
let dm = new_creature_display(&cr.catalog, disp, &asset_server, source);
cr.models.insert(disp, dm);
}
if let Some(dm) = cr.models.get_mut(&disp) {
@@ -0,0 +1,205 @@
//! Optional character and equipment archive variants for launchers on top of benilla.
use std::sync::{Arc, Mutex};
use benilla_formats::{Chain, CharCreateCatalog, CharSections, CharacterGeosets};
use benilla_protocol::EntityKind;
use bevy::asset::LoadState;
use bevy::ecs::entity::EntityHashSet;
use bevy::prelude::*;
use crate::net::{NetEntity, ObjectStore};
use super::{
corpse, live_display, spell_fx, CharCreate, Characters, Creatures, ItemDisplays, ModelHandle,
SkinComposites, SkinSections, VisualAttached,
};
/// A fixed archive chain for character and equipment art. Separate asset source names keep
/// variant handles and concurrent asset loads independent.
pub struct AppearanceProfile {
source: &'static str,
chain: Arc<Chain>,
}
impl AppearanceProfile {
/// Register the variant during the launcher's pre-asset setup.
pub fn register(app: &mut App, source: &'static str, chain: Chain) -> Self {
let chain = Arc::new(chain);
benilla_assets::register_mpq_variant(app, source, chain.clone());
Self { source, chain }
}
/// Read the rendering catalogs together before changing the active source.
pub fn prepare(&self) -> anyhow::Result<PreparedAppearance> {
let mut chain = (*self.chain).clone();
let creatures = benilla_formats::load_creature_catalog(&mut chain)?;
let items = benilla_formats::load_item_display_catalog(&mut chain)?;
let races = benilla_formats::load_chr_races(&mut chain)?;
let geosets = CharacterGeosets::load(&mut chain)?;
let sections = CharSections::load(&mut chain)?;
let char_create = CharCreateCatalog::load(&mut chain)?;
Ok(PreparedAppearance {
source: self.source,
creatures: Creatures {
catalog: creatures,
models: default(),
},
items: ItemDisplays {
catalog: items,
models: default(),
races,
source: self.source,
},
characters: Characters(geosets),
sections: SkinSections::with_source(sections, Arc::new(Mutex::new(chain)), self.source),
char_create: CharCreate(char_create),
})
}
}
/// A validated appearance ready to replace the live rendering catalogs.
pub struct PreparedAppearance {
source: &'static str,
creatures: Creatures,
items: ItemDisplays,
characters: Characters,
sections: SkinSections,
char_create: CharCreate,
}
impl PreparedAppearance {
/// Swap the character catalogs and invalidate composite atlases. The normal display lane
/// rebuilds units in their existing sessions as the new models arrive.
pub fn activate(self, world: &mut World) {
world.insert_resource(self.creatures);
world.insert_resource(self.items);
world.insert_resource(self.characters);
world.insert_resource(self.sections);
world.insert_resource(self.char_create);
world.insert_resource(SkinComposites::default());
world.insert_resource(AppearanceSource(self.source));
}
}
#[derive(Resource)]
pub(crate) struct AppearanceSource(pub(crate) &'static str);
fn body_display(net: &NetEntity, store: Option<&ObjectStore>) -> Option<u32> {
match net.kind {
EntityKind::Unit | EntityKind::Player => net.display_id,
EntityKind::Corpse => match corpse::corpse_model(net, store) {
Some(corpse::CorpseModel::Flesh(display)) => Some(display),
_ => None,
},
_ => None,
}
}
#[allow(clippy::type_complexity)] // Only the already drawn units may be rebuilt here.
pub(super) fn refresh_units(
mut commands: Commands,
source: Option<Res<AppearanceSource>>,
creatures: Option<Res<Creatures>>,
entities: Query<
(Entity, &NetEntity, Option<&ObjectStore>),
(
With<VisualAttached>,
Without<benilla_world::model_fade::DespawnFade>,
),
>,
mut state: Local<(&'static str, EntityHashSet)>,
assets: Res<AssetServer>,
mut fx: spell_fx::RebuildFx,
) {
let (Some(source), Some(creatures)) = (source, creatures) else {
return;
};
let (previous, pending) = &mut *state;
if *previous != source.0 {
*previous = source.0;
pending.clear();
pending.extend(
entities
.iter()
.filter_map(|(entity, net, store)| body_display(net, store).map(|_| entity)),
);
}
let mut remaining = live_display::HEAL_PER_FRAME;
pending.retain(|&entity| {
let Ok((_, net, store)) = entities.get(entity) else {
return false;
};
let Some(display) = body_display(net, store).and_then(|id| creatures.models.get(&id)) else {
return false;
};
if !display.is_character_body {
return false;
}
if matches!(
&display.handle,
ModelHandle::M2(handle) if matches!(assets.load_state(handle.id()), LoadState::Failed(_))
) {
return false;
}
if display.parts.is_none() || remaining == 0 {
return true;
}
remaining -= 1;
fx.end_all(&mut commands, entity, spell_fx::Rebuild::Heal);
live_display::rebuild_visual(commands.entity(entity)).insert(live_display::ShownRebuild);
false
});
}
#[cfg(test)]
mod tests {
use super::*;
use crate::net::Guid;
#[test]
fn a_character_keeps_its_visual_until_the_next_appearance_is_ready() {
let mut app = App::new();
app.add_plugins((MinimalPlugins, AssetPlugin::default()))
.add_systems(Update, refresh_units);
let mut display = super::super::empty_shell();
display.is_character_body = true;
app.insert_resource(Creatures {
catalog: Default::default(),
models: [(42, display)].into(),
})
.insert_resource(AppearanceSource("alternate"));
let unit = app
.world_mut()
.spawn((
Guid(7),
NetEntity {
kind: EntityKind::Player,
display_id: Some(42),
scale: 1.0,
},
VisualAttached,
))
.id();
let child = app.world_mut().spawn(ChildOf(unit)).id();
app.update();
assert!(app.world().get_entity(child).is_ok());
assert!(app.world().get::<VisualAttached>(unit).is_some());
app.world_mut()
.resource_mut::<Creatures>()
.models
.get_mut(&42)
.unwrap()
.parts = Some(Vec::new());
app.update();
assert!(app.world().get_entity(child).is_err());
assert!(app.world().get::<VisualAttached>(unit).is_none());
assert!(app
.world()
.get::<live_display::ShownRebuild>(unit)
.is_some());
assert_eq!(app.world().get::<Guid>(unit).unwrap().0, 7);
}
}
@@ -100,8 +100,9 @@ const CHAR_TEXTURE_WRAP: (bool, bool) = (false, false);
/// The `mpq://` URL of a baked NPC atlas under `Textures\BakedNpcTextures\`, its name resolved as
/// `TextureCreate` resolves one (`0x449d90`): a bare bake name is the `.blp` or `.tga` there.
fn baked_npc_url(bake_name: &str) -> String {
benilla_assets::texture_url(
fn baked_npc_url(source: &str, bake_name: &str) -> String {
benilla_assets::texture_url_on(
source,
&format!("Textures\\BakedNpcTextures\\{bake_name}"),
CHAR_TEXTURE_WRAP,
)
@@ -301,7 +302,10 @@ pub(super) fn body_atlas(
asset_server: &AssetServer,
) -> BodyAtlas {
if let BodySkin::Baked(name) = &look.body {
return BodyAtlas::Ready(Some(asset_server.load::<Image>(baked_npc_url(name))));
let source = sections.map_or(benilla_assets::MPQ_SOURCE, |s| s.source);
return BodyAtlas::Ready(Some(
asset_server.load::<Image>(baked_npc_url(source, name)),
));
}
match (key, sections) {
(Some(key), Some(sections)) => {
@@ -323,7 +327,8 @@ pub(super) fn forced_body_atlas(
images: &mut Assets<Image>,
) -> Option<Handle<Image>> {
if let BodySkin::Baked(name) = &look.body {
return Some(asset_server.load::<Image>(baked_npc_url(name)));
let source = sections.map_or(benilla_assets::MPQ_SOURCE, |s| s.source);
return Some(asset_server.load::<Image>(baked_npc_url(source, name)));
}
let (key, sections) = (key?, sections?);
composites.force(
@@ -386,8 +391,11 @@ pub(super) fn build_char_skin_materials(
let hair_part = parts
.iter()
.find(|p| p.char_slot == Some(CharSkinSlot::Hair))?;
let tex =
asset_server.load::<Image>(benilla_assets::texture_url(path, CHAR_TEXTURE_WRAP));
let tex = asset_server.load::<Image>(benilla_assets::texture_url_on(
sections.source,
path,
CHAR_TEXTURE_WRAP,
));
mats.char_variants(tex, hair_part.blend, hair_part.two_sided)
.map(&quint)
});
@@ -402,7 +410,8 @@ pub(super) fn build_char_skin_materials(
.iter()
.find(|p| p.char_slot == Some(CharSkinSlot::Object))?;
let tex = asset_server.load::<Image>(format!(
"mpq://item/objectcomponents/cape/{}.blp",
"{}://item/objectcomponents/cape/{}.blp",
sections.source,
tex_name.to_ascii_lowercase()
));
mats.char_variants(tex, part.blend, part.two_sided)
@@ -416,8 +425,11 @@ pub(super) fn build_char_skin_materials(
.tables
.skin_extra_texture(look.race, look.sex, look.skin)
.map_or((None, None), |path| {
let tex =
asset_server.load::<Image>(benilla_assets::texture_url(path, CHAR_TEXTURE_WRAP));
let tex = asset_server.load::<Image>(benilla_assets::texture_url_on(
sections.source,
path,
CHAR_TEXTURE_WRAP,
));
let mut quint_for = |two_sided: bool| {
let part = parts.iter().find(|p| {
p.char_slot == Some(CharSkinSlot::SkinExtra) && p.two_sided == two_sided
@@ -434,16 +446,17 @@ pub(super) fn build_char_skin_materials(
#[cfg(test)]
mod baked_url_tests {
use super::baked_npc_url;
use benilla_assets::MPQ_SOURCE;
/// A server's bare bake name resolves as `TextureCreate` resolves it (`0x449d90`): the same
/// atlas as the spelled-out `.blp`.
#[test]
fn a_bare_bake_name_is_the_atlas_the_blp_spelling_names() {
let blp = "mpq://textures/bakednpctextures/northwindbutcher@cc.blp";
assert_eq!(baked_npc_url("Northwindbutcher"), blp);
assert_eq!(baked_npc_url("Northwindbutcher.blp"), blp);
assert_eq!(baked_npc_url(MPQ_SOURCE, "Northwindbutcher"), blp);
assert_eq!(baked_npc_url(MPQ_SOURCE, "Northwindbutcher.blp"), blp);
assert_eq!(
baked_npc_url("CREATURE\\Sub\\Bake.BLP"),
baked_npc_url(MPQ_SOURCE, "CREATURE\\Sub\\Bake.BLP"),
"mpq://textures/bakednpctextures/creature/sub/bake@cc.blp"
);
}
@@ -139,6 +139,12 @@ pub(in crate::entities) fn build_glue_preview(
state.built = false;
state.emblem = None;
}
if sections
.as_ref()
.is_some_and(|sections| sections.is_changed())
{
state.built = false;
}
state.watch_crest(
preview.look,
displays.as_deref(),
@@ -307,6 +313,12 @@ pub(in crate::entities) fn build_dressup_preview(
state.last_look = preview.look;
state.built = false;
}
if sections
.as_ref()
.is_some_and(|sections| sections.is_changed())
{
state.built = false;
}
if state.built {
return;
}
+27 -13
View File
@@ -14,7 +14,7 @@ use bevy::mesh::skinning::SkinnedMeshInverseBindposes;
use bevy::prelude::*;
use benilla_assets::materials::WowModelMaterial;
use benilla_assets::{m2_url, skin_url, wmo_url};
use benilla_assets::{m2_url, m2_url_on, skin_url_on, wmo_url, MPQ_SOURCE};
/// A display's model asset: an M2 (creatures, most GameObjects), a WMO (building GameObjects), or
/// none when the display names no model.
@@ -114,6 +114,7 @@ impl EntityPart {
/// `None` while the asset loads, and empty for a model with no geometry.
pub(crate) struct DisplayModel {
pub(crate) handle: ModelHandle,
pub(super) source: &'static str,
/// The model's directory, where its skin textures live.
pub(super) dir: String,
/// The creature's `Monster1/2/3` skin variation names.
@@ -224,19 +225,29 @@ pub(super) fn new_creature_display(
catalog: &CreatureCatalog,
display_id: u32,
asset_server: &AssetServer,
source: &'static str,
) -> DisplayModel {
match catalog.model(display_id) {
Some(m) if m.scale > 0.0 => DisplayModel {
handle: ModelHandle::M2(asset_server.load(m2_url(&m.model_path))),
dir: model_dir(&m.model_path).to_string(),
skins: m.textures,
npc_appearance: m.npc_appearance,
is_character_body: m
Some(m) if m.scale > 0.0 => {
let is_character_body = m
.model_path
.get(..10)
.is_some_and(|p| p.eq_ignore_ascii_case("character\\")),
..empty_shell()
},
.is_some_and(|p| p.eq_ignore_ascii_case("character\\"));
let source = if is_character_body {
source
} else {
MPQ_SOURCE
};
DisplayModel {
handle: ModelHandle::M2(asset_server.load(m2_url_on(source, &m.model_path))),
source,
dir: model_dir(&m.model_path).to_string(),
skins: m.textures,
npc_appearance: m.npc_appearance,
is_character_body,
..empty_shell()
}
}
_ => empty_display(),
}
}
@@ -265,6 +276,7 @@ pub(super) fn new_gameobject_display(
pub(crate) fn empty_shell() -> DisplayModel {
DisplayModel {
handle: ModelHandle::None,
source: MPQ_SOURCE,
dir: String::new(),
skins: Default::default(),
npc_appearance: None,
@@ -400,6 +412,7 @@ pub(super) fn build_parts(
.map(|(pi, sub)| {
let texture = resolve_skin(
sub,
dm.source,
&dm.dir,
&dm.skins,
dm.object_texture.as_deref(),
@@ -544,20 +557,21 @@ fn model_local_collider(hull: &CollisionMesh) -> Option<Collider> {
/// type 2); `None` draws the material's muted fallback.
fn resolve_skin(
sub: &ModelSubmesh,
source: &str,
dir: &str,
skins: &[Option<String>; 3],
object_texture: Option<&str>,
asset_server: &AssetServer,
) -> Option<Handle<Image>> {
if sub.char_slot == Some(CharSkinSlot::Object) {
return object_texture.map(|t| asset_server.load(skin_url(dir, t)));
return object_texture.map(|t| asset_server.load(skin_url_on(source, dir, t)));
}
match (&sub.texture, sub.skin_slot) {
(Some(t), _) => Some(t.clone()),
(None, Some(slot)) => skins
.get(slot as usize)
.and_then(|o| o.as_ref())
.map(|name| asset_server.load(skin_url(dir, name))),
.map(|name| asset_server.load(skin_url_on(source, dir, name))),
(None, None) => None,
}
}
@@ -601,7 +615,7 @@ mod tests {
app.init_asset::<bevy::animation::graph::AnimationGraph>();
register_asset_loaders(&mut app);
let server = app.world().resource::<AssetServer>().clone();
let display = new_creature_display(&catalog, 4, &server);
let display = new_creature_display(&catalog, 4, &server, MPQ_SOURCE);
assert!(display.names_a_model());
let ModelHandle::M2(handle) = display.handle else {
panic!("display 4 names an M2");
@@ -10,7 +10,7 @@ use benilla_formats::ItemDisplayCatalog;
use bevy::prelude::*;
use super::{DisplayModel, ModelHandle};
use benilla_assets::m2_url;
use benilla_assets::m2_url_on;
mod resolve;
pub(in crate::entities) use resolve::placement;
@@ -60,6 +60,7 @@ pub(crate) struct ItemDisplays {
pub(super) models: HashMap<(u32, ItemModelKind), DisplayModel>,
/// `ChrRaces.dbc`, whose client prefix names a helm's model per race (`0x479a21`).
pub(crate) races: benilla_formats::ChrRaces,
pub(super) source: &'static str,
}
#[cfg(test)]
@@ -69,6 +70,7 @@ impl ItemDisplays {
catalog,
models: HashMap::new(),
races: benilla_formats::ChrRaces::default(),
source: benilla_assets::MPQ_SOURCE,
}
}
}
@@ -439,7 +441,10 @@ pub(in crate::entities) fn ensure_item_model(
d.model_texture[col]
);
DisplayModel {
handle: ModelHandle::M2(asset_server.load(m2_url(&format!("{dir}\\{model}")))),
handle: ModelHandle::M2(
asset_server.load(m2_url_on(held.source, &format!("{dir}\\{model}"))),
),
source: held.source,
// The runtime object skin, bound to the model's type-2 batches.
object_texture: d.model_texture[col].clone(),
dir,
+33 -51
View File
@@ -157,31 +157,7 @@ pub(super) fn refresh_live_display(
entity,
at,
);
// `attach_entity_visuals` rebuilds from scratch, fade-skipped by `Reattached`.
commands
.entity(entity)
.despawn_related::<Children>()
.remove::<(
VisualAttached,
AppliedDisplay,
super::equipment::AppliedEquipment,
super::mount::AppliedMount,
super::mount::MountChild,
AnimationPlayer,
bevy::animation::transition::AnimationTransitions,
AnimationGraphHandle,
benilla_assets::ModelAnimations,
crate::creature_anim::AnimDriver,
(
benilla_world::rig_anim::RigPose,
crate::creature_anim::BodyTwist,
benilla_world::rig_anim::GlobalSeqDrive,
),
benilla_world::rig_palette::RigSkin,
super::BoneAttach,
super::equipment::HeldAttached,
)>()
.insert(super::equipment::Reattached);
rebuild_visual(commands.entity(entity));
}
// ── The scale ease ───────────────────────────────────────────────────────────────────
@@ -228,6 +204,34 @@ pub(super) fn refresh_live_display(
}
}
/// Strip a body's visual so it attaches again without the arrival fade.
pub(super) fn rebuild_visual(mut entity: EntityCommands) -> EntityCommands {
entity
.despawn_related::<Children>()
.remove::<(
VisualAttached,
AppliedDisplay,
super::equipment::AppliedEquipment,
super::mount::AppliedMount,
super::mount::MountChild,
AnimationPlayer,
bevy::animation::transition::AnimationTransitions,
AnimationGraphHandle,
benilla_assets::ModelAnimations,
crate::creature_anim::AnimDriver,
(
benilla_world::rig_anim::RigPose,
crate::creature_anim::BodyTwist,
benilla_world::rig_anim::GlobalSeqDrive,
),
benilla_world::rig_palette::RigSkin,
super::BoneAttach,
super::equipment::HeldAttached,
)>()
.insert(super::equipment::Reattached);
entity
}
/// Tick every [`ScaleEase`], `from + (to − from) · (0.5 − 0.5·cos(π·t/2 s))` (`0x614bbf`), then
/// land exactly on the target.
pub(super) fn tick_scale_ease(
@@ -257,7 +261,7 @@ pub(super) struct ShownRebuild;
const HEAL_MIN_HEADROOM: usize = 128;
/// Rebuilds per frame, so a starved stream-in burst heals over a second or two, not in one spike.
const HEAL_PER_FRAME: usize = 2;
pub(super) const HEAL_PER_FRAME: usize = 2;
/// Rebuild units whose attach was denied a palette rig (`RigStarved`), which otherwise stay at bind
/// pose: the display swap's teardown, fade-skipped; a table full again re-marks them.
@@ -284,31 +288,9 @@ pub(super) fn heal_rig_starved(
guid.0
);
fx.end_all(&mut commands, entity, super::spell_fx::Rebuild::Heal);
commands
.entity(entity)
.despawn_related::<Children>()
.remove::<(
VisualAttached,
AppliedDisplay,
super::equipment::AppliedEquipment,
super::mount::AppliedMount,
super::mount::MountChild,
AnimationPlayer,
bevy::animation::transition::AnimationTransitions,
AnimationGraphHandle,
benilla_assets::ModelAnimations,
crate::creature_anim::AnimDriver,
(
benilla_world::rig_anim::RigPose,
crate::creature_anim::BodyTwist,
benilla_world::rig_anim::GlobalSeqDrive,
),
benilla_world::rig_palette::RigSkin,
super::BoneAttach,
super::equipment::HeldAttached,
benilla_world::rig_palette::RigStarved,
)>()
.insert((super::equipment::Reattached, ShownRebuild));
rebuild_visual(commands.entity(entity))
.remove::<benilla_world::rig_palette::RigStarved>()
.insert(ShownRebuild);
}
}
@@ -21,11 +21,24 @@ use bevy::tasks::{block_on, futures_lite::future, AsyncComputeTaskPool, Task};
pub(super) struct SkinSections {
pub(super) tables: CharSections,
chain: Arc<Mutex<Chain>>,
pub(super) source: &'static str,
}
impl SkinSections {
pub(super) fn new(tables: CharSections, chain: Arc<Mutex<Chain>>) -> Self {
Self { tables, chain }
Self::with_source(tables, chain, benilla_assets::MPQ_SOURCE)
}
pub(super) fn with_source(
tables: CharSections,
chain: Arc<Mutex<Chain>>,
source: &'static str,
) -> Self {
Self {
tables,
chain,
source,
}
}
}
+1
View File
@@ -55,6 +55,7 @@ mod dev;
mod devtools;
mod doodad_events;
mod entities;
pub use entities::appearance::{AppearanceProfile, PreparedAppearance};
pub use entities::spell_fx::{
AreaEffectLight, EffectLightEnd, EffectLightSource, GroundEffectLight, SuppressEffectLight,
};
@@ -1753,7 +1753,10 @@ pub(super) fn sync_glue_booth(
standing_rigs
.get(booth.root)
.ok()
.filter(|(_, _, player)| *player)
// An appearance source can replace the skeleton under the same display id.
.filter(|(skin, _, player)| {
*player && rig.inverse_bindposes.as_ref() == Some(skin.ibp())
})
} else {
None
};
+16 -2
View File
@@ -323,12 +323,17 @@ pub fn wmo_url(raw: &str) -> String {
/// A creature skin variation's `mpq://` URL, `<model-dir>/<name>.blp`: the `Monster1/2/3` skins
/// live beside the model.
pub fn skin_url(model_dir: &str, name: &str) -> String {
skin_url_on(MPQ_SOURCE, model_dir, name)
}
/// A creature or equipment skin on the same source as its model.
pub fn skin_url_on(source: &str, model_dir: &str, name: &str) -> String {
let dir = model_dir.replace('\\', "/").to_ascii_lowercase();
let name = name.to_ascii_lowercase();
if dir.is_empty() {
format!("mpq://{name}.blp")
format!("{source}://{name}.blp")
} else {
format!("mpq://{dir}/{name}.blp")
format!("{source}://{dir}/{name}.blp")
}
}
@@ -395,6 +400,15 @@ pub fn register_mpq_source(app: &mut App, data_dir: &Path) -> Result<()> {
Ok(())
}
/// Register an independent archive chain under a distinct Bevy asset source before AssetPlugin.
pub fn register_mpq_variant(app: &mut App, source: &'static str, chain: Arc<Chain>) {
let reader = MpqAssetReader { chain };
app.register_asset_source(
source,
AssetSourceBuilder::new(move || -> Box<dyn ErasedAssetReader> { Box::new(reader.clone()) }),
);
}
/// Register benilla's asset loaders on `app`, after `AssetPlugin`, into its live `AssetServer`.
pub fn register_asset_loaders(app: &mut App) {
app.init_asset::<M2Model>();
+3 -4
View File
@@ -249,10 +249,9 @@ impl AssetLoader for M2ModelLoader {
.filter(|c| !c.is_empty());
// The textures open as the model did (`0x71da64` pushes the model's own flag).
let source = match ctx.path().source() {
bevy::asset::io::AssetSourceId::Name(name) if &**name == crate::MPQ_LOOSE_SOURCE => {
crate::MPQ_LOOSE_SOURCE
}
let source_id = ctx.path().source().clone_owned();
let source = match &source_id {
bevy::asset::io::AssetSourceId::Name(name) => &**name,
_ => crate::MPQ_SOURCE,
};
let mut submeshes = Vec::with_capacity(subs.len());
+21 -3
View File
@@ -231,11 +231,12 @@ impl Header<'_> {
fn level_data<'b>(&self, bytes: &'b [u8], level: usize) -> Result<Option<&'b [u8]>> {
let off = self.offsets[level] as usize;
let sz = self.sizes[level] as usize;
if level > 0 && (sz == 0 || off == 0) {
// A mip whose offset is exactly EOF has no payload, even if its length slot is stale.
if level > 0 && (sz == 0 || off == 0 || off == bytes.len()) {
return Ok(None);
}
bytes
.get(off..off + sz)
off.checked_add(sz)
.and_then(|end| bytes.get(off..end))
.map(Some)
.ok_or(Error::OutOfBounds { level })
}
@@ -498,6 +499,23 @@ mod tests {
assert!(matches!(decode(b"not a blp at all"), Err(Error::NotBlp2)));
}
#[test]
fn a_tail_mip_pointing_at_eof_keeps_the_authored_prefix() {
let base = (HEADER_SIZE + PALETTE_SIZE) as u32;
let end = base + 2;
let mut offsets = [0; 16];
offsets[..2].copy_from_slice(&[base, end]);
let mut sizes = [0; 16];
sizes[..2].copy_from_slice(&[2, 0u32.wrapping_sub(end)]);
let mut b = header(1, 0, 0, 1, 2, 1, offsets, sizes);
b.resize(end as usize, 0);
assert_eq!(decode(&b).unwrap().mips.len(), 1);
assert_eq!(decode_native(&b).unwrap().mips.len(), 1);
b[24..28].copy_from_slice(&(end + 1).to_le_bytes());
assert!(matches!(decode(&b), Err(Error::OutOfBounds { level: 1 })));
}
/// A DXTC BLP (compression 2) with an 8x8 to 1x1 chain, so the tail levels are sub-block.
fn dxt_blp(alpha_type: u8, block_bytes: usize) -> Vec<u8> {
let mut offsets = [0u32; 16];
+17 -3
View File
@@ -18,6 +18,7 @@ pub struct ChainEntry {
}
/// A priority-ordered patch chain of MPQ archives (`Send + Sync`; reads are `&self` and lock-free).
#[derive(Clone)]
pub struct Chain {
/// Ascending priority: later archives win.
archives: Vec<Archive>,
@@ -194,9 +195,14 @@ impl Chain {
/// language pack ([`crate::ClientLocale::for_install`]); without one the stock `Wow.ini`
/// locale stands, because MoonWell supports the community language pack alongside stock data.
pub fn open_client(path: &Path) -> Result<Self> {
Self::open_client_without(path, left_out())
}
/// Open an independent client chain, omitting the named Data archives.
pub fn open_client_without(path: &Path, skip: &[String]) -> Result<Self> {
match crate::ClientLocale::for_install(path)? {
Some(pack) => Self::open_localized(path, pack),
None => Self::open_without(path, left_out()),
Some(pack) => Self::open_localized_without(path, pack, skip),
None => Self::open_without(path, skip),
}
}
@@ -205,7 +211,15 @@ impl Chain {
/// after the base chain, from `Data/ruRU`, because that community pack keeps its localized
/// overrides there instead of in the stock chain.
pub fn open_localized(path: &Path, pack: crate::ClientLocale) -> Result<Self> {
let mut chain = Self::open_without(path, left_out())?;
Self::open_localized_without(path, pack, left_out())
}
fn open_localized_without(
path: &Path,
pack: crate::ClientLocale,
skip: &[String],
) -> Result<Self> {
let mut chain = Self::open_without(path, skip)?;
if pack == crate::ClientLocale::RuRu {
let folder = pack
.pack_folder(path)
+94 -10
View File
@@ -555,6 +555,19 @@ local descriptions = RU and {
local widgets, pages, tabs = {}, {}, {}
local frame, status, selected, apply, style
local page_title, quality_heading, choose_style_hint
local model_menu, model_label
local model_quality, committed_model_quality = 0, 0
local model_names = RU and { "Классика", "Project Reforged", "Project Reforged HD", "Project Reforged Ultra" }
or { "Classic", "Project Reforged", "Project Reforged HD", "Project Reforged Ultra" }
local model_targets = { 0, 0, 1, 2, 3 }
local function model_available(quality)
return quality == 0 or (MoonWell_IsModelQualityAvailable and MoonWell_IsModelQualityAvailable(quality))
end
local function preset_models(s, level)
local quality = s == 2 and model_targets[level] or 0
while not model_available(quality) do quality = quality - 1 end
return quality
end
local viewport_height = 338
local style_context
local rows = {}
@@ -578,13 +591,15 @@ end
local function current_preset()
if style_context then
for level = 1, table.getn(presets[style_context]) do
if equal(values, presets[style_context][level]) then return style_context, level end
if model_quality == preset_models(style_context, level) and equal(values, presets[style_context][level]) then
return style_context, level
end
end
return nil
end
for s = 1, 2 do
for level = 1, table.getn(presets[s]) do
if equal(values, presets[s][level]) then return s, level end
if model_quality == preset_models(s, level) and equal(values, presets[s][level]) then return s, level end
end
end
end
@@ -602,6 +617,7 @@ local function refresh_status()
local shown_style = s or style_context
quality_heading:SetText((RU and "Качество" or "Quality") .. (shown_style and " — " .. styles[shown_style] or ""))
if shown_style then choose_style_hint:Hide() else choose_style_hint:Show() end
UIDropDownMenu_SetText(model_names[model_quality + 1], model_menu)
for i = 1, 5 do
local row = rows[i]
if shown_style and (shown_style ~= 1 or i == 1) then
@@ -616,7 +632,7 @@ local function refresh_status()
end
else row:Hide() end
end
if equal(values, committed) then
if equal(values, committed) and model_quality == committed_model_quality then
apply:Disable()
status:SetText(RU and "Нет изменений" or "No pending changes")
else
@@ -661,6 +677,7 @@ end
local function select_preset(s, level)
preset_chosen = 1
style_context = s
model_quality = preset_models(s, level)
copy(presets[s][level], values)
sync_widgets()
end
@@ -719,11 +736,13 @@ up:SetScript("OnClick", function() bar:SetValue(bar:GetValue() - 34) end)
down:SetScript("OnClick", function() bar:SetValue(bar:GetValue() + 34) end)
scroll:EnableMouseWheel(1)
scroll:SetScript("OnMouseWheel", function() bar:SetValue(bar:GetValue() - arg1 * 40) end)
local function close_style_menu()
if UIDROPDOWNMENU_OPEN_MENU == style:GetName() then CloseDropDownMenus() end
local function close_overview_menus()
if UIDROPDOWNMENU_OPEN_MENU == style:GetName() or UIDROPDOWNMENU_OPEN_MENU == model_menu:GetName() then
CloseDropDownMenus()
end
end
local function show_page(n)
close_style_menu()
close_overview_menus()
for i = 1, 5 do
if i == n then pages[i]:Show() else pages[i]:Hide() end
local tab = tabs[i]
@@ -794,7 +813,7 @@ choose_style_hint:SetJustifyH("LEFT")
choose_style_hint:SetText(RU and "Выберите стиль, чтобы увидеть уровни качества." or "Choose a style to see its quality levels.")
for i = 1, 5 do
local row = CreateFrame("Button", "MoonWellGraphicsQuality" .. i, overview)
row:SetWidth(420); row:SetHeight(48); row:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -77 - (i - 1) * 48)
row:SetWidth(420); row:SetHeight(44); row:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -77 - (i - 1) * 44)
row.surface = row:CreateTexture(nil, "BACKGROUND"); row.surface:SetAllPoints(row)
row.surface:SetTexture(1, 1, 1, 1); row.surface:SetGradientAlpha("HORIZONTAL", 0.35, 0.22, 0.12, 0.75, 0.12, 0.09, 0.07, 0.25)
row.check = row:CreateTexture(nil, "ARTWORK")
@@ -810,7 +829,25 @@ for i = 1, 5 do
row.index = i; rows[i] = row
row:SetScript("OnClick", function() if style_context then select_preset(style_context, this.index) end end)
end
overview.height = 325
model_label = overview:CreateFontString(nil, "ARTWORK", "GameFontNormal")
model_label:SetPoint("TOPLEFT", overview, "TOPLEFT", 12, -309)
model_label:SetText(RU and "Модели и броня" or "Models and armor")
model_menu = CreateFrame("Frame", "MoonWellGraphicsModels", overview, "UIDropDownMenuTemplate")
model_menu:SetPoint("TOPLEFT", overview, "TOPLEFT", 150, -298)
UIDropDownMenu_SetWidth(210, model_menu)
UIDropDownMenu_Initialize(model_menu, function()
for quality = 0, 3 do
if model_available(quality) then
local info = { text = model_names[quality + 1], value = quality, checked = model_quality == quality }
info.func = function()
model_quality = this.value
refresh_status()
end
UIDropDownMenu_AddButton(info)
end
end
end)
overview.height = 330
local section_group = { 2, 2, 3, 5, 2, 2, 2, 4, 3 }
local section, group = 0, 1
for i = 1, table.getn(items) do
@@ -888,7 +925,7 @@ apply:SetWidth(110); apply:SetHeight(24); apply:SetPoint("BOTTOMRIGHT", frame, "
if kit and kit.RedButton then kit.RedButton(apply, "128-redbutton") end
apply:SetText(RU and "Применить" or "Apply")
apply:SetScript("OnClick", function()
if equal(values, committed) then return end
if equal(values, committed) and model_quality == committed_model_quality then return end
local out = ""
for i = 1, table.getn(items) do
local key = items[i].key
@@ -902,6 +939,16 @@ apply:SetScript("OnClick", function()
return
end
for key, value in string.gfind(result, "([^=;]+)=([^;]+);") do committed[key] = tonumber(value) end
if model_quality ~= committed_model_quality then
if not (MoonWell_SetModelQuality and MoonWell_SetModelQuality(model_quality)) then
copy(committed, values); preset_chosen = nil
model_quality = committed_model_quality
sync_widgets()
status:SetText(RU and "Графика сохранена. Не удалось переключить модели" or "Graphics saved. Could not switch models")
return
end
committed_model_quality = model_quality
end
copy(committed, values); preset_chosen = nil; sync_widgets()
status:SetText(RU and "Сохранено" or "Saved")
end)
@@ -925,10 +972,14 @@ frame:SetScript("OnShow", function()
if snapshot then
for key, value in string.gfind(snapshot, "([^=;]+)=([^;]+);") do committed[key] = tonumber(value) end
end
committed_model_quality = MoonWell_GetModelQuality and MoonWell_GetModelQuality() or 0
model_quality = committed_model_quality
if model_available(1) then model_menu:Show(); model_label:Show()
else model_menu:Hide(); model_label:Hide() end
copy(committed, values); preset_chosen = nil; style_context = nil; sync_widgets(); show_page(1); fit_window(1)
if not snapshot then status:SetText(RU and "Ошибка чтения настроек" or "Cannot read settings") end
end)
frame:SetScript("OnHide", close_style_menu)
frame:SetScript("OnHide", close_overview_menus)
local fit_elapsed = 0
frame:SetScript("OnUpdate", function()
fit_elapsed = fit_elapsed + arg1
@@ -1625,6 +1676,39 @@ mod tests {
assert_eq!(back, flat(&GfxSettings::forever()), "{cvar}");
assert_eq!(back.get("post.volumetric"), Some(&1.0));
assert_eq!(back.get("grass.enabled"), Some(&1.0));
lua.load(r#"
local model = 0
local allowed = { [0] = true, [1] = true, [3] = true }
function MoonWell_GetModelQuality() return model end
function MoonWell_IsModelQualityAvailable(n) return allowed[n] end
function MoonWell_SetModelQuality(n)
assert(allowed[n], "the addon never applies an unavailable tier")
model = n
return true
end
local function reopen()
MoonWellGraphicsFrame:Hide()
SlashCmdList["MOONWELLGFX"]()
end
reopen()
assert(MoonWellGraphicsModels:IsVisible(), "installed packs expose the model selector")
SelectStyle(2)
SelectQuality(4)
assert(MoonWellGraphicsModels.text == "Project Reforged", "missing HD falls back to Reforged")
assert(model == 0, "the model choice stays a draft until Apply")
MoonWellGraphicsApply.OnClick()
assert(model == 1, "the graphics preset applies its available model tier")
SelectQuality(5)
MoonWellGraphicsApply.OnClick()
assert(model == 3, "Ultra selects the installed Ultra pack")
MENU_ITEMS = {}; MoonWellGraphicsModels.fill()
assert(table.getn(MENU_ITEMS) == 3, "only installed tiers appear")
this = MENU_ITEMS[1]; this.func()
MoonWellGraphicsApply.OnClick()
assert(model == 0, "the selector changes models with no graphics changes")
reopen()
assert(MoonWellGraphicsModels.text == "Классика", "the window reflects the current tier")
"#).set_name("model presets").exec().expect("model presets");
}
/// The generated rows and values are well-formed Lua table entries for every row.
+6
View File
@@ -24,6 +24,12 @@ 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.
## Модели персонажей и броня
В меню игры откройте «Графика MoonWell». Графический пресет задаёт детализацию персонажей и брони. Поле «Модели и броня» позволяет выбрать её отдельно. Кнопка «Применить» меняет модели в текущем сеансе и сохраняет выбор в `benilla-config/moonwell-models.toml`.
Для Project Reforged положите Patch A и Patch G в `Data/`. Можно добавить один из вариантов Patch L. Уровень HD требует Patch T Standard, уровень Ultra требует Patch T Ultra Base вместе с Patch U. В списке видны доступные уровни. Если уровень пресета недоступен, применяется ближайший доступный уровень ниже. [Архивы Project Reforged для 1.12](https://projectreforged.github.io/vanilla/downloads/)
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.
+7 -2
View File
@@ -60,7 +60,7 @@ fn set_window_icon(world: &mut World) {
}
fn main() -> benilla_app::AppExit {
models::choose_archives(env!("BENILLA_PROJECT_DIR"));
let reforged = models::choose_archives(env!("BENILLA_PROJECT_DIR"));
// MoonWell UI (patch-F) draws its interface from atlas sheets up to 2048².
benilla_formats::raise_ui_texture_side(4096);
benilla_app::run_with_render_setup(
@@ -74,7 +74,12 @@ fn main() -> benilla_app::AppExit {
project_dir: env!("BENILLA_PROJECT_DIR"),
..Default::default()
},
moonwell_gfx::register_render_backend,
move |app| {
moonwell_gfx::register_render_backend(app);
if let Some(pack) = reforged {
models::register_sources(app, pack);
}
},
|app| {
app.add_plugins((
MoonWellPlugin,
+374 -108
View File
@@ -1,171 +1,437 @@
//! Character models, SD or HD: the install's HD archives ([`HD_ARCHIVES`]: playable-race models,
//! their gear and textures and the NPCs baked from them, with their own DBCs) are mounted or left
//! out of the chain.
//! The chain opens once, so a change takes a restart: the interface asks for it through two Lua
//! functions this module adds to the glue and the in-game VMs, and the client closes, to be started
//! again through the launcher (a login ticket does not survive a restart).
//!
//! The choice is `benilla-config/moonwell-models.toml` (`characters = "sd"` or `"hd"`; HD when
//! absent). A capture keeps no state and mounts the pack, unless `$MOONWELL_MODELS` (`sd` or `hd`)
//! names the mode for the run.
//! MoonWell's character and equipment presets, applied to the running client.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use benilla_app::{AppearanceProfile, PreparedAppearance};
use benilla_formats::Chain;
use benilla_ui::mlua;
use benilla_ui::script::UiScript;
use bevy::prelude::*;
/// The HD archives in the install's `Data` directory: Project Reforged's character set, A
/// (characters and NPCs), G (gear), L (female body), T and U (high-resolution character and gear
/// textures). Its other letters (world, creatures, interface, sound) stay mounted either way.
const HD_ARCHIVES: [&str; 5] = [
"patch-A.MPQ",
"patch-G.MPQ",
"patch-L.MPQ",
"patch-T.MPQ",
"patch-U.MPQ",
const ARCHIVES: [&str; 5] = [
"patch-A.mpq",
"patch-G.mpq",
"patch-L.mpq",
"patch-T.mpq",
"patch-U.mpq",
];
const SETTINGS_FILE: &str = "moonwell-models.toml";
/// Set by `MoonWell_SetCharacterModels` once the new choice is saved; [`restart`] acts on it.
static RESTART: AtomicBool = AtomicBool::new(false);
/// Whether the install has any HD archive.
fn pack_present() -> bool {
benilla_formats::wow_data().is_some_and(|data| !archives_in(&data).is_empty())
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
enum Quality {
#[default]
Classic,
Reforged,
Hd,
Ultra,
}
/// The HD archives present in `data`, by their names on disk, matched in any case as the chain
/// matches them.
fn archives_in(data: &Path) -> Vec<String> {
let Ok(dir) = std::fs::read_dir(data) else {
return Vec::new();
impl Quality {
const ALL: [Self; 4] = [Self::Classic, Self::Reforged, Self::Hd, Self::Ultra];
fn name(self) -> &'static str {
match self {
Self::Classic => "classic",
Self::Reforged => "reforged",
Self::Hd => "reforged-hd",
Self::Ultra => "reforged-ultra",
}
}
fn parse(mode: &str) -> Option<Self> {
match mode.to_ascii_lowercase().as_str() {
"sd" | "classic" => Some(Self::Classic),
"reforged" => Some(Self::Reforged),
"reforged-hd" => Some(Self::Hd),
"hd" | "ultra" | "reforged-ultra" => Some(Self::Ultra),
_ => None,
}
}
fn archive_count(self) -> usize {
match self {
Self::Classic => 0,
Self::Reforged => 3,
Self::Hd => 4,
Self::Ultra => 5,
}
}
fn from_number(value: usize) -> Option<Self> {
Self::ALL.get(value).copied()
}
fn best(self, available: &[bool; 4]) -> Self {
Self::ALL
.into_iter()
.rev()
.find(|&q| q <= self && available[q as usize])
.unwrap_or_default()
}
}
pub struct InstalledPack {
data: PathBuf,
present: [bool; 5],
available: [bool; 4],
}
impl InstalledPack {
fn excluded(&self, quality: Quality) -> Vec<String> {
ARCHIVES
.iter()
.zip(self.present)
.skip(quality.archive_count())
.filter(|(_, present)| *present)
.map(|(name, _)| (*name).to_string())
.collect()
}
}
/// Keep the main chain as the classic base. The alternate sources own their appearance archives.
pub fn choose_archives(project_dir: &str) -> Option<InstalledPack> {
benilla_formats::set_project_folder(project_dir);
if std::env::var_os("BENILLA_STOCK_CHAIN").is_some_and(|v| !v.is_empty()) {
return None;
}
let data = benilla_formats::wow_data()?;
let titles = archives_in(&data).map(|archive| patch_title(archive.as_deref()?));
let present = titles.each_ref().map(Option::is_some);
let [a, g, _, t, u] = present;
if !a || !g {
return None;
}
let patch_t = titles[3].as_deref().and_then(patch_t_kind);
if u && patch_t != Some(Quality::Ultra) {
eprintln!("moonwell-models: Patch U requires the Ultra Base variant of Patch T");
}
if t && patch_t.is_none() {
eprintln!("moonwell-models: unrecognized Patch T variant");
}
let pack = InstalledPack {
data,
present,
available: [
true,
true,
patch_t == Some(Quality::Hd),
u && patch_t == Some(Quality::Ultra),
],
};
dir.filter_map(Result::ok)
.filter_map(|e| e.file_name().into_string().ok())
.filter(|name| HD_ARCHIVES.iter().any(|hd| hd.eq_ignore_ascii_case(name)))
.collect()
benilla_formats::leave_out_archives(pack.excluded(Quality::Classic));
Some(pack)
}
/// The archives found in Data, case-insensitively as in the client.
fn archives_in(data: &Path) -> [Option<PathBuf>; 5] {
let mut paths = std::fs::read_dir(data)
.into_iter()
.flatten()
.filter_map(Result::ok)
.filter(|entry| entry.path().is_file())
.map(|entry| entry.path())
.collect::<Vec<_>>();
paths.sort();
ARCHIVES.map(|name| {
paths
.iter()
.find(|p| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(name)))
.cloned()
})
}
fn settings_path() -> Option<PathBuf> {
benilla_app::config_dir().map(|d| d.join(SETTINGS_FILE))
}
/// The saved choice, or `$MOONWELL_MODELS`'s: `true` for HD, the default.
fn saved_hd() -> bool {
fn configured_quality() -> Quality {
if let Ok(mode) = std::env::var("MOONWELL_MODELS") {
return !mode.eq_ignore_ascii_case("sd");
if let Some(quality) = Quality::parse(&mode) {
return quality;
}
}
let Some(text) = settings_path().and_then(|p| std::fs::read_to_string(p).ok()) else {
return true;
};
text.parse::<toml::Table>()
.ok()
.and_then(|t| {
t.get("characters")
.and_then(|v| v.as_str().map(str::to_owned))
})
.is_none_or(|v| !v.eq_ignore_ascii_case("sd"))
settings_path()
.and_then(|path| std::fs::read_to_string(path).ok())
.and_then(|text| text.parse::<toml::Table>().ok())
.and_then(|table| Quality::parse(table.get("characters")?.as_str()?))
.unwrap_or(Quality::Ultra)
}
fn save(hd: bool) -> std::io::Result<()> {
let path = settings_path().ok_or_else(|| std::io::Error::other("no state folder"))?;
fn save(quality: Quality) -> std::io::Result<()> {
let Some(path) = settings_path() else {
return Ok(()); // capture mode keeps no state
};
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("toml.tmp");
std::fs::write(
&tmp,
format!(
"# MoonWell character models: \"hd\" mounts the HD archives, \"sd\" leaves them out.\n\
characters = \"{}\"\n",
if hd { "hd" } else { "sd" }
),
)?;
std::fs::write(&tmp, format!("characters = \"{}\"\n", quality.name()))?;
std::fs::rename(tmp, path)
}
/// Before anything opens the chain: leave the HD pack out when SD is chosen. `project_dir` is the
/// launcher's build stamp, so a dev build finds its state folder this early.
pub fn choose_archives(project_dir: &str) {
benilla_formats::set_project_folder(project_dir);
// fixed now: a choice saved later applies to the next start
if running_mode() == Some("sd") {
if let Some(data) = benilla_formats::wow_data() {
benilla_formats::leave_out_archives(archives_in(&data));
}
#[derive(Default)]
struct Selection {
active: Quality,
requested: Option<(Quality, PreparedAppearance)>,
available: [bool; 4],
}
impl Selection {
fn selected(&self) -> Quality {
self.requested
.as_ref()
.map_or(self.active, |(quality, _)| *quality)
}
}
/// The mode this process runs with: `"hd"`, `"sd"`, or `None` without the pack.
fn running_mode() -> Option<&'static str> {
static MODE: std::sync::OnceLock<Option<&'static str>> = std::sync::OnceLock::new();
*MODE.get_or_init(|| pack_present().then(|| if saved_hd() { "hd" } else { "sd" }))
#[derive(Resource, Clone)]
struct Models {
profiles: Arc<[Option<AppearanceProfile>; 4]>,
selection: Arc<Mutex<Selection>>,
}
fn patch_title(path: &Path) -> Option<String> {
let toc = Chain::open(path).ok()?.read("patch.toc").ok()?;
let text = std::str::from_utf8(&toc)
.ok()?
.trim_start_matches('\u{feff}');
text.lines()
.find_map(|line| line.strip_prefix("## Title: "))
.map(|title| title.trim().to_ascii_lowercase())
.filter(|title| title.starts_with("project reforged"))
}
fn patch_t_kind(title: &str) -> Option<Quality> {
if title.ends_with("(standard)") {
Some(Quality::Hd)
} else if title.ends_with("(ultra-base)") {
Some(Quality::Ultra)
} else {
None
}
}
/// Register each available variant before Bevy builds the asset server.
pub fn register_sources(app: &mut App, pack: InstalledPack) {
let profiles = Quality::ALL.map(|quality| {
if !pack.available[quality as usize] {
return None;
}
match Chain::open_client_without(&pack.data, &pack.excluded(quality)) {
Ok(chain) => Some(AppearanceProfile::register(app, quality.name(), chain)),
Err(e) => {
warn!("moonwell-models: {} unavailable: {e:#}", quality.name());
None
}
}
});
let available = profiles.each_ref().map(Option::is_some);
if available[0] {
app.insert_resource(Models {
profiles: Arc::new(profiles),
selection: Arc::new(Mutex::new(Selection {
available,
..default()
})),
});
}
}
pub struct ModelsPlugin;
impl Plugin for ModelsPlugin {
fn build(&self, app: &mut App) {
// Before the session's ticks, so a VM rebuilt this frame has the functions before its
// scripts run their next handler.
app.add_systems(First, (install_functions, restart));
app.add_systems(PostStartup, activate_initial)
.add_systems(First, (apply_request, install_functions).chain());
}
}
/// `MoonWell_GetCharacterModels()` answers `"hd"`, `"sd"`, or nil without the pack;
/// `MoonWell_SetCharacterModels("hd" | "sd")` saves a different choice and closes the client,
/// answering true, or answers nil when it changes nothing or cannot save. Added to each VM once,
/// a new VM (glue rebuild, world entry) getting them again.
fn install_functions(script: Option<NonSend<UiScript>>, mut seen: Local<Option<u64>>) {
let Some(script) = script else { return };
fn activate_initial(world: &mut World) {
let Some(models) = world.get_resource::<Models>() else {
return;
};
let mut quality = configured_quality().best(&models.selection.lock().unwrap().available);
while quality != Quality::Classic {
let models = world.resource::<Models>();
if let Some(prepared) = prepare(models, quality) {
activate(world, quality, prepared);
break;
}
quality = Quality::ALL[quality as usize - 1].best(
&world
.resource::<Models>()
.selection
.lock()
.unwrap()
.available,
);
}
}
fn apply_request(world: &mut World) {
let Some(models) = world.get_resource::<Models>() else {
return;
};
let requested = models.selection.lock().unwrap().requested.take();
if let Some((quality, prepared)) = requested {
activate(world, quality, prepared);
}
}
fn prepare(models: &Models, quality: Quality) -> Option<PreparedAppearance> {
let profile = models.profiles[quality as usize].as_ref()?;
match profile.prepare() {
Ok(prepared) => Some(prepared),
Err(e) => {
error!("moonwell-models: loading {}: {e:#}", quality.name());
models.selection.lock().unwrap().available[quality as usize] = false;
None
}
}
}
fn activate(world: &mut World, quality: Quality, prepared: PreparedAppearance) {
prepared.activate(world);
world.resource::<Models>().selection.lock().unwrap().active = quality;
if let Some(script) = world.get_non_send_resource::<UiScript>() {
refresh_legacy_controls(script);
}
info!("moonwell-models: applied {}", quality.name());
}
fn request(models: &Models, quality: Quality) -> bool {
{
let selection = models.selection.lock().unwrap();
if !selection.available[quality as usize] {
return false;
}
if selection.selected() == quality {
return true;
}
}
let Some(prepared) = prepare(models, quality) else {
return false;
};
if let Err(e) = save(quality) {
error!("moonwell-models: saving {}: {e}", quality.name());
return false;
}
models.selection.lock().unwrap().requested = Some((quality, prepared));
true
}
/// A new glue or world VM receives the same live selection, including the legacy SD/HD API.
fn install_functions(
script: Option<NonSend<UiScript>>,
models: Option<Res<Models>>,
mut seen: Local<Option<u64>>,
) {
let (Some(script), Some(models)) = (script, models) else {
return;
};
if *seen == Some(script.session()) {
return;
}
*seen = Some(script.session());
let lua = script.lua();
let install = || -> mlua::Result<()> {
let globals = lua.globals();
let selection = models.selection.clone();
globals.set(
"MoonWell_GetModelQuality",
lua.create_function(move |_, ()| Ok(selection.lock().unwrap().selected() as usize))?,
)?;
let selection = models.selection.clone();
globals.set(
"MoonWell_IsModelQualityAvailable",
lua.create_function(move |_, n: usize| {
Ok(selection
.lock()
.unwrap()
.available
.get(n)
.copied()
.unwrap_or(false))
})?,
)?;
let quality_models = models.clone();
globals.set(
"MoonWell_SetModelQuality",
lua.create_function(move |_, n: usize| {
Ok(
Quality::from_number(n)
.is_some_and(|quality| request(&quality_models, quality)),
)
})?,
)?;
let selection = models.selection.clone();
globals.set(
"MoonWell_GetCharacterModels",
lua.create_function(|_, ()| Ok(running_mode()))?,
lua.create_function(move |_, ()| {
let state = selection.lock().unwrap();
let active = if state.selected() == Quality::Classic {
"sd"
} else {
"hd"
};
Ok(state.available[1..].contains(&true).then_some(active))
})?,
)?;
let legacy_models = models.clone();
globals.set(
"MoonWell_SetCharacterModels",
lua.create_function(|_, mode: String| {
let Some(running) = running_mode() else {
return Ok(None);
lua.create_function(move |_, mode: String| {
let Some(quality) = Quality::parse(&mode) else {
return Ok(false);
};
let hd = match mode.to_ascii_lowercase().as_str() {
"hd" => true,
"sd" => false,
_ => return Ok(None),
};
if (running == "hd") == hd {
return Ok(None);
}
if let Err(e) = save(hd) {
error!("moonwell-models: saving the choice: {e}");
return Ok(None);
}
RESTART.store(true, Ordering::SeqCst);
Ok(Some(true))
let quality = quality.best(&legacy_models.selection.lock().unwrap().available);
Ok(request(&legacy_models, quality))
})?,
)?;
Ok(())
};
if let Err(e) = install() {
error!("moonwell-models: adding the Lua functions: {e}");
match install() {
Ok(()) => {
*seen = Some(script.session());
refresh_legacy_controls(&script);
}
Err(e) => error!("moonwell-models: adding the Lua functions: {e}"),
}
}
/// A saved change: the client closes; the player starts it again through the launcher, which
/// issues the login ticket a restarted process could not reuse.
fn restart(mut exit: MessageWriter<AppExit>) {
if !RESTART.swap(false, Ordering::SeqCst) {
return;
/// Installed MoonWell UI patches have SD/HD controls of their own on both screens.
fn refresh_legacy_controls(script: &UiScript) {
let result = script.lua().load(r#"
local mode = MoonWell_GetCharacterModels and MoonWell_GetCharacterModels()
if not mode then return end
local text = GetLocale() == "ruRU" and "Переключить модели персонажей на %s?"
or "Switch character models to %s?"
local popup = StaticPopupDialogs and StaticPopupDialogs.MOONWELLUI_MODELS
if popup then popup.text = text end
if MoonWellUIGameMenuButtonModels and MOONWELLUI_TEXT then
MoonWellUIGameMenuButtonModels:SetText(format(MOONWELLUI_TEXT.MODELS_BUTTON, string.upper(mode)))
end
if ForeverUIGlue and ForeverUIGlue.L and CharacterCreateFrame then
ForeverUIGlue.L.MOONWELL_MODELS_CONFIRM = text
local function refresh(frame)
for _, child in ipairs({frame:GetChildren()}) do
local key = child.mode
if (key == "sd" or key == "hd") and child.State and child.label
and child.label:GetText() == string.upper(key) then
local selected = (key == mode)
child:State(selected, true)
if selected then child.label:SetTextColor(1, 0.82, 0)
else child.label:SetTextColor(1, 1, 1) end
end
refresh(child)
end
end
refresh(CharacterCreateFrame)
end
"#).exec();
if let Err(e) = result {
warn!("moonwell-models: refreshing legacy controls: {e}");
}
info!("moonwell-models: closing for the new character models");
exit.write(AppExit::Success);
}