From ee5da0b2c0e51973f9865f26e82eed80b5c317e5 Mon Sep 17 00:00:00 2001 From: kibradev <62299912+kibradev@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:53:12 +0300 Subject: [PATCH] Preserve skinning in model GLB exports --- crates/openrage-app/src/gta6_models.rs | 29 +++- crates/openrage-app/src/models.rs | 3 +- crates/openrage-cli/src/cmd/view.rs | 9 ++ crates/rage-formats/src/gltf.rs | 199 ++++++++++++++++++++++--- 4 files changed, 220 insertions(+), 20 deletions(-) diff --git a/crates/openrage-app/src/gta6_models.rs b/crates/openrage-app/src/gta6_models.rs index 7f654a6..c9310b3 100644 --- a/crates/openrage-app/src/gta6_models.rs +++ b/crates/openrage-app/src/gta6_models.rs @@ -98,8 +98,10 @@ fn base_skeletons(game: &Path) -> Skeletons { fn read_base_skeletons(game: &Path) -> Result> { use rayon::prelude::*; - let (node, _) = rage_mods::resolve(game, BASE_SKELETONS, None)?; - let rage_rpf::vfs::Node::Rpf9Dir(rpf, _) = node else { bail!("no archive") }; + let rpf = match rage_mods::resolve(game, BASE_SKELETONS, None) { + Ok((rage_rpf::vfs::Node::Rpf9Dir(rpf, _), _)) => rpf, + _ => recovered_base_archive(game)?, + }; let entries = rpf.entries()?; let mut found: Vec<(String, Skeleton)> = (0..entries.len()) .into_par_iter() @@ -114,6 +116,29 @@ fn read_base_skeletons(game: &Path) -> Result> { Ok(found) } +/// The recovery view exposes nested archives by offset rather than their original paths. +fn recovered_base_archive(game: &Path) -> Result> { + use rayon::prelude::*; + + let (rage_rpf::vfs::Node::Rpf9Dir(packs, _), _) = rage_mods::resolve(game, "packs.rpf", None)? else { + bail!("no packs archive"); + }; + packs + .entries()? + .par_iter() + .filter(|entry| packs.is_archive(entry)) + .find_map_any(|entry| { + let child = packs.open_child(entry).ok()?; + let entries = child.entries().ok()?; + let has_body = entries.iter().any(|entry| { + let path = child.entry_name(entry); + path.rsplit('/').next().is_some_and(|name| name.eq_ignore_ascii_case("ambient_femalebody.#ft")) + }); + has_body.then(|| Arc::new(child)) + }) + .context("base skeleton archive not found in packs.rpf") +} + /// Binds meshes that name bones of another skeleton (parts of people and /// animals) to it, and gives that skeleton. `None` if there are none, or the /// game has no skeleton for them. diff --git a/crates/openrage-app/src/models.rs b/crates/openrage-app/src/models.rs index 2cdcc7d..e2deaa0 100644 --- a/crates/openrage-app/src/models.rs +++ b/crates/openrage-app/src/models.rs @@ -1221,12 +1221,13 @@ pub fn to_glb(model: &LoadedModel, name: &str, look: &Look) -> Option> { if nodes.is_empty() { return None; } - Some(rage_formats::gltf::write_glb_scene( + Some(rage_formats::gltf::write_glb_scene_with_skins( name, &meshes, &nodes, &|d, t| model.texture(&model.drawables[d].1, t), &|d, s| model.tint(look, d, s as u16), + &|d| model.skeleton.as_ref().or(model.drawables[d].1.skeleton.as_ref()), )) } diff --git a/crates/openrage-cli/src/cmd/view.rs b/crates/openrage-cli/src/cmd/view.rs index d8d585c..98caced 100644 --- a/crates/openrage-cli/src/cmd/view.rs +++ b/crates/openrage-cli/src/cmd/view.rs @@ -40,6 +40,15 @@ pub(crate) fn cmd_model( d.triangle_count(), d.shaders.len() ); + let bones = model.skeleton.as_ref().or(d.skeleton.as_ref()).map_or(0, |s| s.bones.len()); + let weighted: usize = d + .meshes + .iter() + .filter(|mesh| rage_formats::gltf::has_skin_weights(mesh, bones)) + .map(|mesh| mesh.positions.len()) + .sum(); + let decoded: usize = d.meshes.iter().map(|mesh| mesh.bone_indices.len().min(mesh.bone_weights.len())).sum(); + outln!(" skin weights: {decoded} decoded, {weighted}/{} vertices ready for export", d.vertex_count()); for (i, s) in d.shaders.iter().enumerate() { let base = s.base_texture().unwrap_or("-"); let found = if base == "-" || model.texture(d, base).is_some() { "" } else { " (not found)" }; diff --git a/crates/rage-formats/src/gltf.rs b/crates/rage-formats/src/gltf.rs index 14d6b14..83f66db 100644 --- a/crates/rage-formats/src/gltf.rs +++ b/crates/rage-formats/src/gltf.rs @@ -6,8 +6,8 @@ use std::fmt::Write; -use crate::drawable::Drawable; -use crate::math::Mat4; +use crate::drawable::{Drawable, Mesh, Skeleton}; +use crate::math::{self, Mat4}; use crate::texture::Texture; fn esc(s: &str) -> String { @@ -72,6 +72,25 @@ impl Builder { self.accessors.len() - 1 } + fn joints(&mut self, data: &[[u16; 4]]) -> usize { + let bytes: Vec = data.iter().flatten().flat_map(|v| v.to_le_bytes()).collect(); + self.skin_accessor(&bytes, data.len(), "VEC4", 5123, Some(34962)) + } + + fn inverse_bind_matrices(&mut self, skeleton: &Skeleton) -> usize { + let transforms = skeleton.world_transforms(); + let bytes: Vec = transforms.iter().flat_map(math::inverse_affine).flat_map(f32::to_le_bytes).collect(); + self.skin_accessor(&bytes, transforms.len(), "MAT4", 5126, None) + } + + fn skin_accessor(&mut self, bytes: &[u8], count: usize, kind: &str, component: u32, target: Option) -> usize { + let view = self.view(bytes, target); + self.accessors.push(format!( + "{{\"bufferView\":{view},\"componentType\":{component},\"count\":{count},\"type\":\"{kind}\"}}", + )); + self.accessors.len() - 1 + } + fn indices(&mut self, data: &[u32]) -> usize { let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); let view = self.view(&bytes, Some(34963)); @@ -99,10 +118,54 @@ fn matrix_json(m: &Mat4) -> String { m.iter().map(|v| format!("{}", finite(*v))).collect::>().join(",") } +/// A mesh can be bound when all its vertices have usable, resolved influences. +pub fn has_skin_weights(mesh: &Mesh, bones: usize) -> bool { + !mesh.positions.is_empty() + && mesh.bone_tags.is_empty() + && mesh.bone_hashes.is_empty() + && mesh.bone_indices.len() == mesh.positions.len() + && mesh.bone_weights.len() == mesh.positions.len() + && mesh.bone_indices.iter().zip(&mesh.bone_weights).all(|(joints, weights)| { + let sum: f32 = weights.iter().sum(); + sum.is_finite() + && sum > 0.0 + && joints.iter().zip(weights).all(|(&joint, &weight)| { + weight.is_finite() && weight >= 0.0 && (weight == 0.0 || usize::from(joint) < bones) + }) + }) +} + +fn joint_nodes(skeleton: &Skeleton, first_joint: usize) -> (Vec, Vec) { + let mut roots = Vec::new(); + let mut children = vec![Vec::new(); skeleton.bones.len()]; + for (i, bone) in skeleton.bones.iter().enumerate() { + if let Some(parent) = usize::try_from(bone.parent).ok().filter(|&parent| parent < i) { + children[parent].push((first_joint + i).to_string()); + } else { + roots.push(first_joint + i); + } + } + let nodes = skeleton + .bones + .iter() + .zip(children) + .map(|(bone, children)| { + let name = esc(&bone.name); + let local = math::from_trs(bone.translation, bone.rotation, bone.scale); + let children = + if children.is_empty() { String::new() } else { format!(",\"children\":[{}]", children.join(",")) }; + format!("{{\"name\":\"{name}\",\"matrix\":[{}]{children}}}", matrix_json(&local)) + }) + .collect(); + (roots, nodes) +} + /// Writes a single drawable as `.glb`. pub fn write_glb<'a>(d: &Drawable, name: &str, lookup: &dyn Fn(&str) -> Option<&'a Texture>) -> Vec { let node = Node { name: name.to_owned(), mesh: 0, transform: crate::math::IDENTITY }; - write_glb_scene(name, &[(name, d)], &[node], &|_, t| lookup(t), &|_, _| Some([1.0; 4])) + write_glb_scene_with_skins(name, &[(name, d)], &[node], &|_, t| lookup(t), &|_, _| Some([1.0; 4]), &|_| { + d.skeleton.as_ref() + }) } /// Writes drawables placed by `nodes` as one `.glb` scene. `lookup` resolves @@ -116,6 +179,18 @@ pub fn write_glb_scene<'a>( nodes: &[Node], lookup: &dyn Fn(usize, &str) -> Option<&'a Texture>, material: &dyn Fn(usize, usize) -> Option<[f32; 4]>, +) -> Vec { + write_glb_scene_with_skins(name, drawables, nodes, lookup, material, &|_| None) +} + +/// Writes a model scene, resolving the skeleton that each drawable's indices refer to. +pub fn write_glb_scene_with_skins<'a, 's>( + name: &str, + drawables: &[(&str, &Drawable)], + nodes: &[Node], + lookup: &dyn Fn(usize, &str) -> Option<&'a Texture>, + material: &dyn Fn(usize, usize) -> Option<[f32; 4]>, + skeleton: &dyn Fn(usize) -> Option<&'s Skeleton>, ) -> Vec { let mut b = Builder::default(); let mut materials = Vec::new(); @@ -124,7 +199,8 @@ pub fn write_glb_scene<'a>( let mut image_of: Vec<(String, usize)> = Vec::new(); let mut meshes_json = Vec::new(); // glTF mesh index per drawable (only drawables that nodes use). - let mut mesh_of: Vec> = vec![None; drawables.len()]; + let mut mesh_of = vec![[None; 2]; drawables.len()]; + let mut binds = vec![None; drawables.len()]; for (di, (dname, d)) in drawables.iter().enumerate() { if !nodes.iter().any(|n| n.mesh == di) { @@ -168,7 +244,8 @@ pub fn write_glb_scene<'a>( )); } - let mut primitives = Vec::new(); + let rig = skeleton(di).filter(|rig| !rig.bones.is_empty()); + let mut primitives = [Vec::new(), Vec::new()]; for mesh in &d.meshes { if mesh.positions.is_empty() || mesh.indices.is_empty() || material(di, mesh.shader as usize).is_none() { continue; @@ -191,32 +268,75 @@ pub fn write_glb_scene<'a>( if mesh.colors.len() == mesh.positions.len() { attrs.push_str(&format!(",\"COLOR_0\":{}", b.floats(&mesh.colors, "VEC4", false))); } + let skinned = rig.is_some_and(|rig| has_skin_weights(mesh, rig.bones.len())); + if skinned { + let mut joints = mesh.bone_indices.clone(); + let mut weights = mesh.bone_weights.clone(); + for (joints, weights) in joints.iter_mut().zip(&mut weights) { + let sum: f32 = weights.iter().sum(); + // Palette remapping can collapse multiple influences into the same joint. + for i in 1..joints.len() { + if let Some(j) = (0..i).find(|&j| joints[j] == joints[i]) { + weights[j] += weights[i]; + weights[i] = 0.0; + } + } + for (joint, weight) in joints.iter_mut().zip(weights) { + if *weight == 0.0 { + *joint = 0; + } + *weight /= sum; + } + } + let joints = b.joints(&joints); + let weights = b.floats(&weights, "VEC4", false); + let _ = write!(attrs, ",\"JOINTS_0\":{joints},\"WEIGHTS_0\":{weights}"); + } let idx = b.indices(&mesh.indices); let material = if (mesh.shader as usize) < d.shaders.len() { format!(",\"material\":{}", first_material + mesh.shader as usize) } else { String::new() }; - primitives.push(format!("{{\"attributes\":{{{attrs}}},\"indices\":{idx}{material}}}")); + primitives[usize::from(skinned)] + .push(format!("{{\"attributes\":{{{attrs}}},\"indices\":{idx}{material}}}")); } - if primitives.is_empty() { - continue; + for (group, primitives) in primitives.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + mesh_of[di][group] = Some(meshes_json.len()); + meshes_json.push(format!("{{\"name\":\"{}\",\"primitives\":[{}]}}", esc(dname), primitives.join(","))); + } + if let Some(rig) = rig.filter(|_| mesh_of[di][1].is_some()) { + binds[di] = Some((rig, b.inverse_bind_matrices(rig))); } - mesh_of[di] = Some(meshes_json.len()); - meshes_json.push(format!("{{\"name\":\"{}\",\"primitives\":[{}]}}", esc(dname), primitives.join(","))); } - // Node 0 is the root converting to Y-up; part nodes are its children. + // Node 0 converts to Y-up. Put the mesh and its joints under the same placement. let mut nodes_json = Vec::new(); let mut children = Vec::new(); + let mut skins = Vec::new(); for n in nodes { - let Some(mesh) = mesh_of.get(n.mesh).copied().flatten() else { continue }; + let Some(&[rigid, skinned]) = mesh_of.get(n.mesh) else { continue }; + if rigid.is_none() && skinned.is_none() { + continue; + } children.push((nodes_json.len() + 1).to_string()); - nodes_json.push(format!( - "{{\"name\":\"{}\",\"mesh\":{mesh},\"matrix\":[{}]}}", - esc(&n.name), - matrix_json(&n.transform) - )); + let mesh = rigid.map(|i| format!(",\"mesh\":{i}")).unwrap_or_default(); + let mut placement = format!("\"name\":\"{}\",\"matrix\":[{}]{mesh}", esc(&n.name), matrix_json(&n.transform)); + if let (Some(mesh), Some((rig, inverse_bind))) = (skinned, binds[n.mesh]) { + let mesh_node = nodes_json.len() + 2; + let first_joint = mesh_node + 1; + let (roots, bone_nodes) = joint_nodes(rig, first_joint); + let roots = std::iter::once(mesh_node).chain(roots).map(|i| i.to_string()).collect::>().join(","); + let _ = write!(placement, ",\"children\":[{roots}]"); + let joints = + (first_joint..first_joint + rig.bones.len()).map(|i| i.to_string()).collect::>().join(","); + skins.push(format!("{{\"joints\":[{joints}],\"inverseBindMatrices\":{inverse_bind}}}")); + nodes_json.push(format!("{{{placement}}}")); + nodes_json.push(format!("{{\"name\":\"{}\",\"mesh\":{mesh},\"skin\":{}}}", esc(&n.name), skins.len() - 1)); + nodes_json.extend(bone_nodes); + } else { + nodes_json.push(format!("{{{placement}}}")); + } } let root = format!( "{{\"name\":\"{}\",\"matrix\":[{}],\"children\":[{}]}}", @@ -234,6 +354,9 @@ pub fn write_glb_scene<'a>( nodes_json.join(","), meshes_json.join(",") ); + if !skins.is_empty() { + let _ = write!(json, ",\"skins\":[{}]", skins.join(",")); + } if !materials.is_empty() { let _ = write!(json, ",\"materials\":[{}]", materials.join(",")); } @@ -304,4 +427,46 @@ mod tests { assert!(json.contains("\"min\":[0,0,0],\"max\":[1,1,0]"), "{json}"); assert!(json.contains("\"matrix\":[1,0,0,0,0,0,-1,0,0,1,0,0,0,0,0,1]"), "{json}"); } + #[test] + fn writes_skin_and_keeps_unweighted_primitives_rigid() { + use crate::drawable::Bone; + let mut rigid = Mesh { + positions: vec![[0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + indices: vec![0, 1, 2], + ..Default::default() + }; + let mut skinned = rigid.clone(); + rigid.bone_indices = vec![[9, 0, 0, 0]; 3]; + rigid.bone_weights = vec![[1.0, 0.0, 0.0, 0.0]; 3]; + skinned.bone_indices = vec![[0, 1, 1, 9]; 3]; + skinned.bone_weights = vec![[0.25, 0.25, 0.5, 0.0]; 3]; + let bone = |name: &str, parent, translation| Bone { + name: name.into(), + parent, + translation, + rotation: [0.0, 0.0, 0.0, 1.0], + scale: [1.0; 3], + ..Default::default() + }; + let d = Drawable { + meshes: vec![rigid, skinned], + skeleton: Some(Skeleton { bones: vec![bone("root", -1, [0.0; 3]), bone("tip", 0, [1.0, 0.0, 0.0])] }), + ..Default::default() + }; + let glb = write_glb(&d, "tri", &|_| None); + let json_len = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize; + let json = std::str::from_utf8(&glb[20..20 + json_len]).unwrap(); + assert_eq!(json.matches("\"JOINTS_0\"").count(), 1); + assert_eq!(json.matches("\"WEIGHTS_0\"").count(), 1); + assert!( + json.contains("\"name\":\"root\",\"matrix\":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],\"children\":[4]"), + "{json}" + ); + assert!(json.contains("\"skins\":[{\"joints\":[3,4],\"inverseBindMatrices\":6}]"), "{json}"); + let bin = &glb[28 + json_len..]; + assert_eq!(&bin[84..92], &[0, 0, 1, 0, 0, 0, 0, 0]); + let get_f32 = |offset| f32::from_le_bytes(bin[offset..offset + 4].try_into().unwrap()); + assert_eq!((get_f32(108), get_f32(112), get_f32(116)), (0.25, 0.75, 0.0)); + assert_eq!(get_f32(280), -1.0); + } }