Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions crates/openrage-app/src/gta6_models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,10 @@ fn base_skeletons(game: &Path) -> Skeletons {

fn read_base_skeletons(game: &Path) -> Result<Vec<(String, Skeleton)>> {
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()
Expand All @@ -114,6 +116,29 @@ fn read_base_skeletons(game: &Path) -> Result<Vec<(String, Skeleton)>> {
Ok(found)
}

/// The recovery view exposes nested archives by offset rather than their original paths.
fn recovered_base_archive(game: &Path) -> Result<Arc<Rpf9>> {
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.
Expand Down
3 changes: 2 additions & 1 deletion crates/openrage-app/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1221,12 +1221,13 @@ pub fn to_glb(model: &LoadedModel, name: &str, look: &Look) -> Option<Vec<u8>> {
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()),
))
}

Expand Down
9 changes: 9 additions & 0 deletions crates/openrage-cli/src/cmd/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)" };
Expand Down
199 changes: 182 additions & 17 deletions crates/rage-formats/src/gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -72,6 +72,25 @@
self.accessors.len() - 1
}

fn joints(&mut self, data: &[[u16; 4]]) -> usize {
let bytes: Vec<u8> = 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<u8> = 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<u32>) -> 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<u8> = data.iter().flat_map(|v| v.to_le_bytes()).collect();
let view = self.view(&bytes, Some(34963));
Expand Down Expand Up @@ -99,10 +118,54 @@
m.iter().map(|v| format!("{}", finite(*v))).collect::<Vec<_>>().join(",")
}

/// A mesh can be bound when all its vertices have usable, resolved influences.
pub fn has_skin_weights(mesh: &Mesh, bones: usize) -> bool {

Check notice on line 122 in crates/rage-formats/src/gltf.rs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

crates/rage-formats/src/gltf.rs#L122

Method has_skin_weights has a cyclomatic complexity of 11 (limit is 10)
!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<usize>, Vec<String>) {
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<u8> {
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
Expand All @@ -116,6 +179,18 @@
nodes: &[Node],
lookup: &dyn Fn(usize, &str) -> Option<&'a Texture>,
material: &dyn Fn(usize, usize) -> Option<[f32; 4]>,
) -> Vec<u8> {
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>(

Check notice on line 187 in crates/rage-formats/src/gltf.rs

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

crates/rage-formats/src/gltf.rs#L187

Method write_glb_scene_with_skins has a cyclomatic complexity of 41 (limit is 10)
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<u8> {
let mut b = Builder::default();
let mut materials = Vec::new();
Expand All @@ -124,7 +199,8 @@
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<Option<usize>> = 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) {
Expand Down Expand Up @@ -168,7 +244,8 @@
));
}

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;
Expand All @@ -191,32 +268,75 @@
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::<Vec<_>>().join(",");
let _ = write!(placement, ",\"children\":[{roots}]");
let joints =
(first_joint..first_joint + rig.bones.len()).map(|i| i.to_string()).collect::<Vec<_>>().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\":[{}]}}",
Expand All @@ -234,6 +354,9 @@
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(","));
}
Expand Down Expand Up @@ -304,4 +427,46 @@
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);
}
}