pub use crate::morph_target::MorphTarget;
use crate::{BuildError, MaterialId, NodeId, SkinId, TextureId, Transform};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrimitiveTopology {
Points,
Lines,
LineStrip,
Triangles,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SkinningSet {
joints: Vec<[u16; 4]>,
weights: Vec<[f32; 4]>,
}
impl SkinningSet {
pub fn new(joints: Vec<[u16; 4]>, weights: Vec<[f32; 4]>) -> Self {
Self { joints, weights }
}
pub fn joints(&self) -> &[[u16; 4]] {
&self.joints
}
pub fn weights(&self) -> &[[f32; 4]] {
&self.weights
}
}
#[derive(Debug, Clone)]
pub struct RenderPrimitive {
node_index: u32,
world_transform: Transform,
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
indices: Vec<u32>,
skinning_sets: Vec<SkinningSet>,
morph_targets: Vec<MorphTarget>,
texcoord_sets: Vec<Vec<[f32; 2]>>,
tangents: Vec<[f32; 4]>,
colors: Vec<[f32; 4]>,
texture_index: Option<usize>,
material_index: Option<usize>,
topology: PrimitiveTopology,
morph_weights: Vec<f32>,
base_morph_weights: Vec<f32>,
flat_normals: bool,
skin_index: Option<usize>,
base_color_texcoord: u32,
}
#[derive(Debug, Clone)]
pub struct MorphedVertices {
pub positions: Vec<[f32; 3]>,
pub normals: Vec<[f32; 3]>,
pub tangents: Vec<[f32; 4]>,
}
#[derive(Debug, Clone)]
pub struct RenderPrimitiveBuilder {
node_id: NodeId,
world_transform: Transform,
positions: Vec<[f32; 3]>,
normals: Option<Vec<[f32; 3]>>,
indices: Vec<u32>,
skinning_sets: Vec<SkinningSet>,
morph_targets: Vec<MorphTarget>,
texcoord_sets: Vec<Vec<[f32; 2]>>,
tangents: Option<Vec<[f32; 4]>>,
colors: Option<Vec<[f32; 4]>>,
texture: Option<(TextureId, u32)>,
material_id: Option<MaterialId>,
topology: PrimitiveTopology,
morph_weights: Option<Vec<f32>>,
skin_id: Option<SkinId>,
}
impl RenderPrimitiveBuilder {
pub fn new(node_id: NodeId, positions: Vec<[f32; 3]>, indices: Vec<u32>) -> Self {
Self {
node_id,
world_transform: Transform::IDENTITY,
positions,
normals: None,
indices,
skinning_sets: Vec::new(),
morph_targets: Vec::new(),
texcoord_sets: Vec::new(),
tangents: None,
colors: None,
texture: None,
material_id: None,
topology: PrimitiveTopology::Triangles,
morph_weights: None,
skin_id: None,
}
}
pub const fn with_world_transform(mut self, transform: Transform) -> Self {
self.world_transform = transform;
self
}
pub fn with_normals(mut self, normals: Vec<[f32; 3]>) -> Self {
self.normals = Some(normals);
self
}
pub fn with_skinning(mut self, joints: Vec<[u16; 4]>, weights: Vec<[f32; 4]>) -> Self {
self.skinning_sets = vec![SkinningSet::new(joints, weights)];
self
}
pub fn with_skinning_sets(mut self, skinning_sets: Vec<SkinningSet>) -> Self {
self.skinning_sets = skinning_sets;
self
}
pub const fn with_skin(mut self, skin_id: SkinId) -> Self {
self.skin_id = Some(skin_id);
self
}
pub fn with_morph_target(
mut self,
position_deltas: Vec<[f32; 3]>,
normal_deltas: Option<Vec<[f32; 3]>>,
tangent_deltas: Option<Vec<[f32; 3]>>,
) -> Self {
self.morph_targets.push(MorphTarget::new(
position_deltas,
normal_deltas,
tangent_deltas,
));
self
}
pub fn with_morph_targets(mut self, morph_targets: Vec<MorphTarget>) -> Self {
self.morph_targets = morph_targets;
self
}
pub fn with_morph_weights(mut self, morph_weights: Vec<f32>) -> Self {
self.morph_weights = Some(morph_weights);
self
}
pub fn with_texcoords(mut self, texcoords: Vec<[f32; 2]>) -> Self {
if self.texcoord_sets.is_empty() {
self.texcoord_sets.push(texcoords);
} else {
self.texcoord_sets[0] = texcoords;
}
self
}
pub fn with_secondary_texcoords(mut self, texcoords: Vec<[f32; 2]>) -> Self {
while self.texcoord_sets.len() < 2 {
self.texcoord_sets.push(Vec::new());
}
self.texcoord_sets[1] = texcoords;
self
}
pub fn with_texcoord_sets(mut self, texcoord_sets: Vec<Vec<[f32; 2]>>) -> Self {
self.texcoord_sets = texcoord_sets;
self
}
pub fn with_tangents(mut self, tangents: Vec<[f32; 4]>) -> Self {
self.tangents = Some(tangents);
self
}
pub fn with_colors(mut self, colors: Vec<[f32; 4]>) -> Self {
self.colors = Some(colors);
self
}
pub const fn with_material(mut self, material_id: MaterialId) -> Self {
self.material_id = Some(material_id);
self
}
pub const fn with_base_color_texture(mut self, texture_id: TextureId, tex_coord: u32) -> Self {
self.texture = Some((texture_id, tex_coord));
self
}
pub const fn with_topology(mut self, topology: PrimitiveTopology) -> Self {
self.topology = topology;
self
}
pub fn build(self) -> Result<RenderPrimitive, BuildError> {
self.validate()?;
let Self {
node_id,
world_transform,
positions,
normals,
indices,
skinning_sets,
morph_targets,
texcoord_sets,
tangents,
colors,
texture,
material_id,
topology,
morph_weights,
skin_id,
} = self;
let vertex_count = positions.len();
let has_normals = normals.is_some();
let vertex = VertexBuffers {
positions,
texcoord_sets,
colors: colors.unwrap_or_else(|| vec![[1.0, 1.0, 1.0, 1.0]; vertex_count]),
skinning_sets,
morph_targets,
};
let (vertex, normals, indices, flat_normals) =
resolve_normals(vertex, indices, normals, topology);
let tangents = resolve_tangents(
tangents,
has_normals,
None,
&vertex,
&normals,
&indices,
topology,
);
let morph_weights = morph_weights.unwrap_or_else(|| vec![0.0; vertex.morph_targets.len()]);
let (texture_index, base_color_texcoord) = texture
.map(|(texture_id, tex_coord)| (Some(texture_id.index()), tex_coord))
.unwrap_or((None, 0));
let skin_index = skin_id.map(SkinId::index);
Ok(RenderPrimitive::new_with_sets(
node_id.index() as u32,
if skin_index.is_some() {
Transform::IDENTITY
} else {
world_transform
},
vertex.positions,
normals,
indices,
vertex.skinning_sets,
vertex.morph_targets,
vertex.texcoord_sets,
tangents,
vertex.colors,
texture_index,
material_id.map(MaterialId::index),
topology,
morph_weights,
flat_normals,
skin_index,
base_color_texcoord,
))
}
fn validate(&self) -> Result<(), BuildError> {
let invalid = |message: &str| {
BuildError::InvalidAsset(format!("invalid render primitive: {message}"))
};
let vertex_count = self.positions.len();
if self
.positions
.iter()
.flatten()
.any(|component| !component.is_finite())
{
return Err(invalid("positions must be finite"));
}
if self
.world_transform
.matrix()
.iter()
.flatten()
.any(|component| !component.is_finite())
{
return Err(invalid("the world transform must be finite"));
}
if self
.indices
.iter()
.any(|index| *index as usize >= vertex_count)
{
return Err(invalid("an index is outside the position buffer"));
}
match self.topology {
PrimitiveTopology::Triangles if !self.indices.len().is_multiple_of(3) => {
return Err(invalid("triangle indices must be a multiple of three"));
}
PrimitiveTopology::Lines if !self.indices.len().is_multiple_of(2) => {
return Err(invalid("line indices must be a multiple of two"));
}
_ => {}
}
for (name, length) in [
("normal", self.normals.as_ref().map(Vec::len)),
("tangent", self.tangents.as_ref().map(Vec::len)),
("color", self.colors.as_ref().map(Vec::len)),
] {
if length.is_some_and(|length| length != vertex_count) {
return Err(invalid(&format!(
"the {name} buffer must contain one value per position"
)));
}
}
for (set, texcoords) in self.texcoord_sets.iter().enumerate() {
if texcoords.len() != vertex_count {
return Err(invalid(&format!(
"UV set {set} must contain one value per position"
)));
}
}
for (set, skinning) in self.skinning_sets.iter().enumerate() {
if skinning.joints.len() != vertex_count || skinning.weights.len() != vertex_count {
return Err(invalid(&format!(
"skinning set {set} must contain one joint and weight value per position"
)));
}
}
let all_finite = self
.normals
.iter()
.flatten()
.flatten()
.chain(
self.skinning_sets
.iter()
.flat_map(|set| set.weights.iter().flatten()),
)
.chain(self.texcoord_sets.iter().flatten().flatten())
.chain(self.tangents.iter().flatten().flatten())
.chain(self.colors.iter().flatten().flatten())
.all(|component| component.is_finite());
if !all_finite {
return Err(invalid("vertex attributes must be finite"));
}
if self
.skinning_sets
.iter()
.any(|set| set.weights.iter().flatten().any(|weight| *weight < 0.0))
{
return Err(invalid("skinning weights must be non-negative"));
}
if (0..vertex_count).any(|vertex| {
let sum: f32 = self
.skinning_sets
.iter()
.flat_map(|set| set.weights[vertex])
.sum();
sum != 0.0 && (sum - 1.0).abs() > 1.0e-3
}) {
return Err(invalid(
"non-zero skinning weights must sum to one per vertex",
));
}
for vertex in 0..vertex_count {
let mut weighted_joints = Vec::new();
for set in &self.skinning_sets {
for (&joint, &weight) in set.joints[vertex].iter().zip(&set.weights[vertex]) {
if weight > 0.0 && weighted_joints.contains(&joint) {
return Err(invalid(
"a joint must not have more than one non-zero weight per vertex",
));
}
if weight > 0.0 {
weighted_joints.push(joint);
}
}
}
}
for target in &self.morph_targets {
if target.position_deltas().len() != vertex_count
|| target
.normal_deltas()
.is_some_and(|values| values.len() != vertex_count)
|| target
.tangent_deltas()
.is_some_and(|values| values.len() != vertex_count)
{
return Err(invalid(
"each morph target buffer must contain one value per position",
));
}
if target
.position_deltas()
.iter()
.flatten()
.chain(target.normal_deltas().into_iter().flatten().flatten())
.chain(target.tangent_deltas().into_iter().flatten().flatten())
.any(|component| !component.is_finite())
{
return Err(invalid("morph target deltas must be finite"));
}
}
if self
.morph_weights
.as_ref()
.is_some_and(|weights| weights.len() != self.morph_targets.len())
{
return Err(invalid("there must be one weight per morph target"));
}
if self
.morph_weights
.iter()
.flatten()
.any(|weight| !weight.is_finite())
{
return Err(invalid("morph weights must be finite"));
}
Ok(())
}
}
impl RenderPrimitive {
pub fn builder(
node_id: NodeId,
positions: Vec<[f32; 3]>,
indices: Vec<u32>,
) -> RenderPrimitiveBuilder {
RenderPrimitiveBuilder::new(node_id, positions, indices)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn new_with_sets(
node_index: u32,
world_transform: Transform,
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
indices: Vec<u32>,
skinning_sets: Vec<SkinningSet>,
morph_targets: Vec<MorphTarget>,
texcoord_sets: Vec<Vec<[f32; 2]>>,
tangents: Vec<[f32; 4]>,
colors: Vec<[f32; 4]>,
texture_index: Option<usize>,
material_index: Option<usize>,
topology: PrimitiveTopology,
morph_weights: Vec<f32>,
flat_normals: bool,
skin_index: Option<usize>,
base_color_texcoord: u32,
) -> Self {
let base_morph_weights = morph_weights.clone();
Self {
node_index,
world_transform,
positions,
normals,
indices,
skinning_sets,
morph_targets,
texcoord_sets,
tangents,
colors,
texture_index,
material_index,
topology,
morph_weights,
base_morph_weights,
flat_normals,
skin_index,
base_color_texcoord,
}
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
node_index: u32,
world_transform: Transform,
positions: Vec<[f32; 3]>,
normals: Vec<[f32; 3]>,
indices: Vec<u32>,
joints: Vec<[u16; 4]>,
weights: Vec<[f32; 4]>,
morph_targets: Vec<MorphTarget>,
texcoords: Vec<[f32; 2]>,
tangents: Vec<[f32; 4]>,
colors: Vec<[f32; 4]>,
secondary_texcoords: Vec<[f32; 2]>,
texture_index: Option<usize>,
material_index: Option<usize>,
topology: PrimitiveTopology,
morph_weights: Vec<f32>,
flat_normals: bool,
skin_index: Option<usize>,
base_color_texcoord: u32,
) -> Self {
Self::new_with_sets(
node_index,
world_transform,
positions,
normals,
indices,
vec![SkinningSet::new(joints, weights)],
morph_targets,
vec![texcoords, secondary_texcoords],
tangents,
colors,
texture_index,
material_index,
topology,
morph_weights,
flat_normals,
skin_index,
base_color_texcoord,
)
}
pub fn node_index(&self) -> u32 {
self.node_index
}
pub fn node_id(&self) -> NodeId {
NodeId::from_index(self.node_index as usize)
}
pub fn world_transform(&self) -> &Transform {
&self.world_transform
}
pub fn positions(&self) -> &[[f32; 3]] {
&self.positions
}
pub fn normals(&self) -> &[[f32; 3]] {
&self.normals
}
pub fn indices(&self) -> &[u32] {
&self.indices
}
pub fn joints(&self) -> &[[u16; 4]] {
self.skinning_sets
.first()
.map(SkinningSet::joints)
.unwrap_or(&[])
}
pub fn weights(&self) -> &[[f32; 4]] {
self.skinning_sets
.first()
.map(SkinningSet::weights)
.unwrap_or(&[])
}
pub fn skinning_sets(&self) -> &[SkinningSet] {
&self.skinning_sets
}
pub fn morph_targets(&self) -> &[MorphTarget] {
&self.morph_targets
}
pub fn texcoords(&self) -> &[[f32; 2]] {
self.texcoord_set(0).unwrap_or(&[])
}
pub fn texcoord_sets(&self) -> &[Vec<[f32; 2]>] {
&self.texcoord_sets
}
pub fn texcoord_set(&self, set: u32) -> Option<&[[f32; 2]]> {
self.texcoord_sets.get(set as usize).map(Vec::as_slice)
}
pub fn tangents(&self) -> &[[f32; 4]] {
&self.tangents
}
pub fn colors(&self) -> &[[f32; 4]] {
&self.colors
}
pub fn secondary_texcoords(&self) -> &[[f32; 2]] {
self.texcoord_set(1).unwrap_or(&[])
}
pub fn texture_index(&self) -> Option<usize> {
self.texture_index
}
pub fn texture_id(&self) -> Option<TextureId> {
self.texture_index.map(TextureId::from_index)
}
pub fn material_index(&self) -> Option<usize> {
self.material_index
}
pub fn material_id(&self) -> Option<MaterialId> {
self.material_index.map(MaterialId::from_index)
}
pub fn topology(&self) -> PrimitiveTopology {
self.topology
}
pub fn morph_weights(&self) -> &[f32] {
&self.morph_weights
}
pub fn base_morph_weights(&self) -> &[f32] {
&self.base_morph_weights
}
pub fn set_morph_weights(&mut self, weights: &[f32]) {
self.morph_weights.clear();
self.morph_weights
.extend(weights.iter().copied().take(self.morph_targets.len()));
self.morph_weights.resize(self.morph_targets.len(), 0.0);
}
pub fn apply_morph_update(&mut self, target_index: u32, weight: f32) {
if target_index as usize >= self.morph_targets.len() {
return;
}
self.morph_weights.resize(self.morph_targets.len(), 0.0);
self.morph_weights[target_index as usize] = weight.clamp(0.0, 1.0);
}
pub fn reset_morph_weights(&mut self) {
self.morph_weights.clear();
self.morph_weights
.extend(self.base_morph_weights.iter().copied());
self.morph_weights.resize(self.morph_targets.len(), 0.0);
}
pub fn morphed_vertices(&self) -> MorphedVertices {
self.morphed_vertices_with_weights(&self.morph_weights)
}
pub fn morphed_vertices_with_weights(&self, morph_weights: &[f32]) -> MorphedVertices {
let mut positions = self.positions.clone();
let mut normals = self.normals.clone();
let mut tangents = self.tangents.clone();
for (weight, target) in morph_weights.iter().zip(&self.morph_targets) {
let weight = *weight;
if weight == 0.0 {
continue;
}
for (position, delta) in positions.iter_mut().zip(target.position_deltas()) {
*position = [
position[0] + weight * delta[0],
position[1] + weight * delta[1],
position[2] + weight * delta[2],
];
}
if let Some(normal_deltas) = target.normal_deltas() {
for (normal, delta) in normals.iter_mut().zip(normal_deltas) {
*normal = [
normal[0] + weight * delta[0],
normal[1] + weight * delta[1],
normal[2] + weight * delta[2],
];
}
}
if let Some(tangent_deltas) = target.tangent_deltas() {
for (tangent, delta) in tangents.iter_mut().zip(tangent_deltas) {
tangent[0] += weight * delta[0];
tangent[1] += weight * delta[1];
tangent[2] += weight * delta[2];
}
}
}
if self.flat_normals {
normals = compute_flat_normals(&positions, &self.indices);
} else {
for normal in &mut normals {
*normal = glam::Vec3::from_array(*normal)
.normalize_or_zero()
.to_array();
}
}
for tangent in &mut tangents {
let xyz = glam::Vec3::from_array([tangent[0], tangent[1], tangent[2]]);
let normalized = xyz.normalize_or_zero();
tangent[0] = normalized.x;
tangent[1] = normalized.y;
tangent[2] = normalized.z;
}
MorphedVertices {
positions,
normals,
tangents,
}
}
pub fn skin_index(&self) -> Option<usize> {
self.skin_index
}
pub fn skin_id(&self) -> Option<SkinId> {
self.skin_index.map(SkinId::from_index)
}
pub fn base_color_texcoord(&self) -> u32 {
self.base_color_texcoord
}
}
pub(crate) fn load_primitives(
document: &gltf::Document,
buffers: &[gltf::buffer::Data],
) -> Result<Vec<RenderPrimitive>, crate::LoadError> {
let mut primitives = Vec::new();
let Some(scene) = document
.default_scene()
.or_else(|| document.scenes().next())
else {
return Ok(primitives);
};
let mut stack = scene
.nodes()
.collect::<Vec<_>>()
.into_iter()
.rev()
.map(|node| (node, Transform::IDENTITY))
.collect::<Vec<_>>();
while let Some((node, parent_transform)) = stack.pop() {
let world_transform =
parent_transform.multiply(Transform::from_matrix(node.transform().matrix()));
if let Some(mesh) = node.mesh() {
for primitive in mesh.primitives() {
load_primitive(
&node,
&mesh,
primitive,
world_transform,
buffers,
&mut primitives,
)?;
}
}
let children = node.children().collect::<Vec<_>>();
stack.extend(
children
.into_iter()
.rev()
.map(|child| (child, world_transform)),
);
}
Ok(primitives)
}
pub(crate) fn validate_referenced_primitive_positions(
root: &gltf::json::Root,
) -> Result<(), crate::LoadError> {
for (node_index, node) in root.nodes.iter().enumerate() {
let Some(mesh_index) = node.mesh.map(|index| index.value()) else {
continue;
};
let Some(mesh) = root.meshes.get(mesh_index) else {
continue;
};
for (primitive_index, primitive) in mesh.primitives.iter().enumerate() {
let has_positions = primitive.attributes.keys().any(|semantic| {
matches!(
semantic,
gltf::json::validation::Checked::Valid(gltf::json::mesh::Semantic::Positions)
)
});
if !has_positions {
return Err(missing_position_error(
node_index,
mesh_index,
primitive_index,
));
}
}
}
Ok(())
}
fn missing_position_error(
node_index: usize,
mesh_index: usize,
primitive_index: usize,
) -> crate::LoadError {
crate::LoadError::InvalidVrm(format!(
"node {} references mesh {} primitive {}, which is missing the mandatory POSITION attribute",
node_index, mesh_index, primitive_index
))
}
fn load_primitive(
node: &gltf::Node<'_>,
mesh: &gltf::Mesh<'_>,
primitive: gltf::Primitive<'_>,
world_transform: Transform,
buffers: &[gltf::buffer::Data],
primitives: &mut Vec<RenderPrimitive>,
) -> Result<(), crate::LoadError> {
let reader = primitive.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()));
let Some(positions) = reader.read_positions() else {
return Err(missing_position_error(
node.index(),
mesh.index(),
primitive.index(),
));
};
let positions: Vec<[f32; 3]> = positions.collect();
let base_vertex_count = positions.len();
validate_f32_attribute(
"POSITION",
&positions,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
let source_indices: Vec<u32> = match reader.read_indices() {
Some(indices) => indices.into_u32().collect(),
None => (0..base_vertex_count as u32).collect(),
};
if let Some(index) = source_indices
.iter()
.copied()
.find(|&index| index as usize >= base_vertex_count)
{
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} has element index {index} outside its {base_vertex_count}-element POSITION buffer",
mesh.index(),
primitive.index()
)));
}
let (topology, indices) = normalize_topology(primitive.mode(), source_indices);
let supplied_normals = reader
.read_normals()
.map(|normals| normals.collect::<Vec<_>>());
let stored_tangents = reader
.read_tangents()
.map(|tangents| tangents.collect::<Vec<_>>());
if let Some(normals) = supplied_normals.as_deref() {
validate_f32_attribute(
"NORMAL",
normals,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
}
if let Some(tangents) = stored_tangents.as_deref() {
validate_f32_attribute(
"TANGENT",
tangents,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
}
let has_normals = supplied_normals.is_some();
let IndexedAttributeSets {
texcoords: texcoord_indices,
joints: joint_indices,
weights: weight_indices,
} = indexed_attribute_sets(&primitive, base_vertex_count)?;
if joint_indices != weight_indices {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} must contain equal JOINTS_n and WEIGHTS_n sets",
mesh.index(),
primitive.index()
)));
}
let texcoord_sets = texcoord_indices
.iter()
.map(|&set| {
read_texcoords(reader.read_tex_coords(set), base_vertex_count).ok_or_else(|| {
crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} could not decode TEXCOORD_{set}",
mesh.index(),
primitive.index()
))
})
})
.collect::<Result<Vec<_>, _>>()?;
for (set, texcoords) in texcoord_sets.iter().enumerate() {
validate_f32_attribute(
&format!("TEXCOORD_{set}"),
texcoords,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
}
let mut skinning_sets = joint_indices
.iter()
.map(|&set| {
let joints = read_joints(reader.read_joints(set), base_vertex_count).ok_or_else(|| {
crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} could not decode JOINTS_{set}",
mesh.index(),
primitive.index()
))
})?;
let weights =
read_weights(reader.read_weights(set), base_vertex_count).ok_or_else(|| {
crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} could not decode WEIGHTS_{set}",
mesh.index(),
primitive.index()
))
})?;
if joints.len() != base_vertex_count || weights.len() != base_vertex_count {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {} primitive {} skinning set {set} does not contain one value per position",
mesh.index(),
primitive.index()
)));
}
Ok(SkinningSet::new(joints, weights))
})
.collect::<Result<Vec<_>, crate::LoadError>>()?;
let skin = node
.skin()
.map(|skin| (skin.index(), skin.joints().count()));
validate_and_normalize_skinning_sets(
&mut skinning_sets,
skin,
mesh.index(),
primitive.index(),
base_vertex_count,
)?;
let colors = read_colors(reader.read_colors(0), base_vertex_count);
validate_f32_attribute(
"COLOR_0",
&colors,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
let morph_targets = read_morph_targets(&reader, base_vertex_count);
validate_morph_targets(
&morph_targets,
base_vertex_count,
mesh.index(),
primitive.index(),
)?;
let vertex = VertexBuffers {
positions,
texcoord_sets,
colors,
skinning_sets,
morph_targets,
};
let material = primitive.material();
let (texture_index, base_color_texcoord) = base_color_texture(&material);
let material_index = material.index();
let normal_texture_texcoord = normal_texture_texcoord(&material);
let (vertex, normals, indices, flat_normals) =
resolve_normals(vertex, indices, supplied_normals, topology);
let tangents = resolve_loaded_tangents(
stored_tangents,
has_normals,
normal_texture_texcoord,
&vertex,
&normals,
&indices,
topology,
);
let morph_weights = resolve_morph_weights(
node.weights(),
mesh.weights(),
vertex.morph_targets.len(),
node.index(),
mesh.index(),
primitive.index(),
)?;
let skin_index = node.skin().map(|skin| skin.index());
primitives.push(RenderPrimitive::new_with_sets(
node.index() as u32,
if skin_index.is_some() {
Transform::IDENTITY
} else {
world_transform
},
vertex.positions,
normals,
indices,
vertex.skinning_sets,
vertex.morph_targets,
vertex.texcoord_sets,
tangents,
vertex.colors,
texture_index,
material_index,
topology,
morph_weights,
flat_normals,
skin_index,
base_color_texcoord,
));
Ok(())
}
fn resolve_morph_weights(
node_weights: Option<&[f32]>,
mesh_weights: Option<&[f32]>,
target_count: usize,
node_index: usize,
mesh_index: usize,
primitive_index: usize,
) -> Result<Vec<f32>, crate::LoadError> {
let Some((source, weights)) = node_weights
.map(|weights| ("node", weights))
.or_else(|| mesh_weights.map(|weights| ("mesh", weights)))
else {
return Ok(vec![0.0; target_count]);
};
if weights.len() != target_count {
return Err(crate::LoadError::InvalidVrm(format!(
"node {node_index} mesh {mesh_index} primitive {primitive_index} has {source} morph weights with {} weights for {target_count} morph target{}",
weights.len(),
if target_count == 1 { "" } else { "s" }
)));
}
if weights.iter().any(|weight| !weight.is_finite()) {
return Err(crate::LoadError::InvalidVrm(format!(
"node {node_index} mesh {mesh_index} primitive {primitive_index} has a non-finite value in its {source} morph weights"
)));
}
Ok(weights.to_vec())
}
struct VertexBuffers {
positions: Vec<[f32; 3]>,
texcoord_sets: Vec<Vec<[f32; 2]>>,
colors: Vec<[f32; 4]>,
skinning_sets: Vec<SkinningSet>,
morph_targets: Vec<MorphTarget>,
}
impl VertexBuffers {
fn expand(self, indices: &[u32]) -> (Self, Vec<u32>) {
let expanded = Self {
positions: remap(self.positions, indices),
texcoord_sets: self
.texcoord_sets
.into_iter()
.map(|set| remap(set, indices))
.collect(),
colors: remap(self.colors, indices),
skinning_sets: self
.skinning_sets
.into_iter()
.map(|set| {
SkinningSet::new(remap(set.joints, indices), remap(set.weights, indices))
})
.collect(),
morph_targets: remap_morph_targets(self.morph_targets, indices),
};
let expanded_indices: Vec<u32> = (0..expanded.positions.len() as u32).collect();
(expanded, expanded_indices)
}
}
fn resolve_normals(
vertex: VertexBuffers,
indices: Vec<u32>,
supplied_normals: Option<Vec<[f32; 3]>>,
topology: PrimitiveTopology,
) -> (VertexBuffers, Vec<[f32; 3]>, Vec<u32>, bool) {
match (supplied_normals, topology) {
(Some(normals), _) => (vertex, normals, indices, false),
(None, PrimitiveTopology::Triangles) => {
let (vertex, indices) = vertex.expand(&indices);
let normals = compute_flat_normals(&vertex.positions, &indices);
(vertex, normals, indices, true)
}
(None, _) => {
let normals = vec![[0.0, 0.0, 0.0]; vertex.positions.len()];
(vertex, normals, indices, false)
}
}
}
fn resolve_tangents(
supplied_tangents: Option<Vec<[f32; 4]>>,
has_normals: bool,
normal_texture_texcoord: Option<u32>,
vertex: &VertexBuffers,
normals: &[[f32; 3]],
indices: &[u32],
topology: PrimitiveTopology,
) -> Vec<[f32; 4]> {
match (supplied_tangents, has_normals) {
(Some(supplied), true) => supplied,
_ => compute_mikkts_tangents(
&vertex.positions,
Some(normals),
normal_texture_texcoord,
&vertex.texcoord_sets,
indices,
topology,
vertex.positions.len(),
),
}
}
#[allow(clippy::too_many_arguments)]
fn resolve_loaded_tangents(
_stored_tangents: Option<Vec<[f32; 4]>>,
has_normals: bool,
normal_texture_texcoord: Option<u32>,
vertex: &VertexBuffers,
normals: &[[f32; 3]],
indices: &[u32],
topology: PrimitiveTopology,
) -> Vec<[f32; 4]> {
resolve_tangents(
None,
has_normals,
normal_texture_texcoord,
vertex,
normals,
indices,
topology,
)
}
fn normal_texture_texcoord(material: &gltf::Material<'_>) -> Option<u32> {
material.normal_texture().map(|info| {
let (_, transformed_tex_coord) =
crate::material::extension_transform(info.extension_value("KHR_texture_transform"));
transformed_tex_coord.unwrap_or_else(|| info.tex_coord())
})
}
fn base_color_texture(material: &gltf::Material<'_>) -> (Option<usize>, u32) {
let base_color_texture = material.pbr_metallic_roughness().base_color_texture();
let texture_index = base_color_texture
.as_ref()
.map(|info| info.texture().index());
let base_color_texcoord = base_color_texture
.as_ref()
.map(|info| {
info.texture_transform()
.and_then(|transform| transform.tex_coord())
.unwrap_or_else(|| info.tex_coord())
})
.unwrap_or(0);
(texture_index, base_color_texcoord)
}
fn validate_f32_attribute<const N: usize>(
name: &str,
values: &[[f32; N]],
vertex_count: usize,
mesh_index: usize,
primitive_index: usize,
) -> Result<(), crate::LoadError> {
if values.len() != vertex_count {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} {name} has {} values for {vertex_count} positions",
values.len()
)));
}
if values.iter().flatten().any(|value| !value.is_finite()) {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} {name} contains a non-finite value"
)));
}
Ok(())
}
fn validate_morph_targets(
targets: &[MorphTarget],
vertex_count: usize,
mesh_index: usize,
primitive_index: usize,
) -> Result<(), crate::LoadError> {
for (target, morph) in targets.iter().enumerate() {
validate_f32_attribute(
&format!("morph target {target} POSITION"),
morph.position_deltas(),
vertex_count,
mesh_index,
primitive_index,
)?;
if let Some(normals) = morph.normal_deltas() {
validate_f32_attribute(
&format!("morph target {target} NORMAL"),
normals,
vertex_count,
mesh_index,
primitive_index,
)?;
}
if let Some(tangents) = morph.tangent_deltas() {
validate_f32_attribute(
&format!("morph target {target} TANGENT"),
tangents,
vertex_count,
mesh_index,
primitive_index,
)?;
}
}
Ok(())
}
struct IndexedAttributeSets {
texcoords: Vec<u32>,
joints: Vec<u32>,
weights: Vec<u32>,
}
fn indexed_attribute_sets(
primitive: &gltf::Primitive<'_>,
vertex_count: usize,
) -> Result<IndexedAttributeSets, crate::LoadError> {
use gltf::Semantic;
use gltf::accessor::{DataType, Dimensions};
let mut texcoords = Vec::new();
let mut joints = Vec::new();
let mut weights = Vec::new();
for (semantic, accessor) in primitive.attributes() {
let valid = match semantic {
Semantic::TexCoords(set) => {
texcoords.push(set);
accessor.dimensions() == Dimensions::Vec2
&& matches!(
(accessor.data_type(), accessor.normalized()),
(DataType::F32, false) | (DataType::U8 | DataType::U16, true)
)
}
Semantic::Joints(set) => {
joints.push(set);
accessor.dimensions() == Dimensions::Vec4
&& matches!(accessor.data_type(), DataType::U8 | DataType::U16)
&& !accessor.normalized()
}
Semantic::Weights(set) => {
weights.push(set);
accessor.dimensions() == Dimensions::Vec4
&& matches!(
(accessor.data_type(), accessor.normalized()),
(DataType::F32, false) | (DataType::U8 | DataType::U16, true)
)
}
_ => continue,
};
if !valid || accessor.count() != vertex_count {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh primitive {} has an invalid {semantic:?} accessor",
primitive.index()
)));
}
}
for (name, sets) in [
("TEXCOORD", &mut texcoords),
("JOINTS", &mut joints),
("WEIGHTS", &mut weights),
] {
sets.sort_unstable();
if sets
.iter()
.copied()
.enumerate()
.any(|(expected, actual)| actual as usize != expected)
{
return Err(crate::LoadError::InvalidVrm(format!(
"mesh primitive {} {name}_n indices must start at zero and be consecutive",
primitive.index()
)));
}
}
Ok(IndexedAttributeSets {
texcoords,
joints,
weights,
})
}
fn validate_and_normalize_skinning_sets(
skinning_sets: &mut [SkinningSet],
skin: Option<(usize, usize)>,
mesh_index: usize,
primitive_index: usize,
vertex_count: usize,
) -> Result<(), crate::LoadError> {
if skin.is_some() && skinning_sets.is_empty() {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} is skinned but lacks JOINTS_0 and WEIGHTS_0"
)));
}
for vertex in 0..vertex_count {
let mut weighted_joints = Vec::new();
let mut total_weight = 0.0_f32;
for set in skinning_sets.iter() {
for (&joint, &weight) in set.joints[vertex].iter().zip(&set.weights[vertex]) {
if !weight.is_finite() || weight < 0.0 {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} vertex {vertex} has an invalid skinning weight"
)));
}
total_weight += weight;
if weight == 0.0 {
continue;
}
if let Some((skin_index, joint_count)) = skin
&& joint as usize >= joint_count
{
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} vertex {vertex} has weighted joint {joint} outside skin {skin_index}"
)));
}
if weighted_joints.contains(&joint) {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} vertex {vertex} assigns joint {joint} more than one positive weight"
)));
}
weighted_joints.push(joint);
}
}
if !total_weight.is_finite() {
return Err(crate::LoadError::InvalidVrm(format!(
"mesh {mesh_index} primitive {primitive_index} vertex {vertex} has a non-finite total skinning weight"
)));
}
if total_weight > 0.0 {
for set in skinning_sets.iter_mut() {
for weight in &mut set.weights[vertex] {
*weight /= total_weight;
}
}
}
}
Ok(())
}
fn read_texcoords(
texcoords: Option<gltf::mesh::util::ReadTexCoords<'_>>,
_vertex_count: usize,
) -> Option<Vec<[f32; 2]>> {
texcoords.map(|texcoords| texcoords.into_f32().collect())
}
fn read_colors(
colors: Option<gltf::mesh::util::ReadColors<'_>>,
vertex_count: usize,
) -> Vec<[f32; 4]> {
colors
.map(|colors| colors.into_rgba_f32().collect())
.unwrap_or_else(|| vec![[1.0, 1.0, 1.0, 1.0]; vertex_count])
}
fn read_joints(
joints: Option<gltf::mesh::util::ReadJoints<'_>>,
_vertex_count: usize,
) -> Option<Vec<[u16; 4]>> {
joints.map(|joints| joints.into_u16().collect())
}
fn read_weights(
weights: Option<gltf::mesh::util::ReadWeights<'_>>,
_vertex_count: usize,
) -> Option<Vec<[f32; 4]>> {
weights.map(|weights| weights.into_f32().collect())
}
fn read_morph_targets<'a, 's, F>(
reader: &gltf::mesh::Reader<'a, 's, F>,
vertex_count: usize,
) -> Vec<MorphTarget>
where
F: Clone + Fn(gltf::Buffer<'a>) -> Option<&'s [u8]>,
{
reader
.read_morph_targets()
.map(|(target_positions, target_normals, _target_tangents)| {
let position_deltas = target_positions
.map(|deltas| deltas.collect())
.unwrap_or_else(|| vec![[0.0, 0.0, 0.0]; vertex_count]);
MorphTarget::new(
position_deltas,
target_normals.map(|deltas| deltas.collect()),
None,
)
})
.collect()
}
fn normalize_topology(mode: gltf::mesh::Mode, indices: Vec<u32>) -> (PrimitiveTopology, Vec<u32>) {
use gltf::mesh::Mode;
match mode {
Mode::Points => (PrimitiveTopology::Points, indices),
Mode::Lines => (PrimitiveTopology::Lines, indices),
Mode::LineStrip => (PrimitiveTopology::LineStrip, indices),
Mode::LineLoop => {
let mut indices = indices;
if let Some(first) = indices.first().copied() {
indices.push(first);
}
(PrimitiveTopology::LineStrip, indices)
}
Mode::Triangles => (PrimitiveTopology::Triangles, indices),
Mode::TriangleStrip => {
let mut triangles = Vec::with_capacity(indices.len().saturating_sub(2) * 3);
for i in 0..indices.len().saturating_sub(2) {
if i % 2 == 0 {
triangles.extend_from_slice(&[indices[i], indices[i + 1], indices[i + 2]]);
} else {
triangles.extend_from_slice(&[indices[i + 1], indices[i], indices[i + 2]]);
}
}
(PrimitiveTopology::Triangles, triangles)
}
Mode::TriangleFan => {
let mut triangles = Vec::with_capacity(indices.len().saturating_sub(2) * 3);
for i in 1..indices.len().saturating_sub(1) {
triangles.extend_from_slice(&[indices[0], indices[i], indices[i + 1]]);
}
(PrimitiveTopology::Triangles, triangles)
}
}
}
fn remap<T: Clone>(values: Vec<T>, indices: &[u32]) -> Vec<T> {
indices
.iter()
.map(|&i| values[i as usize].clone())
.collect()
}
fn remap_morph_targets(mut morph_targets: Vec<MorphTarget>, indices: &[u32]) -> Vec<MorphTarget> {
for target in &mut morph_targets {
let positions: Vec<[f32; 3]> = indices
.iter()
.map(|&i| target.position_deltas()[i as usize])
.collect();
let normals: Option<Vec<[f32; 3]>> = target
.normal_deltas()
.map(|values| indices.iter().map(|&i| values[i as usize]).collect());
*target = MorphTarget::new(positions, normals, None);
}
morph_targets
}
fn compute_flat_normals(positions: &[[f32; 3]], indices: &[u32]) -> Vec<[f32; 3]> {
let mut normals = vec![[0.0, 0.0, 0.0]; positions.len()];
for tri in indices.chunks_exact(3) {
if let [a, b, c] = *tri {
let p0 = glam::Vec3::from_array(positions[a as usize]);
let p1 = glam::Vec3::from_array(positions[b as usize]);
let p2 = glam::Vec3::from_array(positions[c as usize]);
let n = (p1 - p0).cross(p2 - p0).normalize_or_zero();
normals[a as usize] = n.to_array();
normals[b as usize] = n.to_array();
normals[c as usize] = n.to_array();
}
}
normals
}
#[allow(clippy::too_many_arguments)]
fn compute_mikkts_tangents(
positions: &[[f32; 3]],
normals: Option<&[[f32; 3]]>,
normal_texture_texcoord: Option<u32>,
texcoord_sets: &[Vec<[f32; 2]>],
indices: &[u32],
topology: PrimitiveTopology,
vertex_count: usize,
) -> Vec<[f32; 4]> {
let placeholder = || vec![[1.0, 0.0, 0.0, 1.0]; vertex_count];
if topology != PrimitiveTopology::Triangles {
return placeholder();
}
let Some(normals) = normals else {
return placeholder();
};
let Some(normal_texcoord) = normal_texture_texcoord else {
return placeholder();
};
let Some(uvs) = texcoord_sets
.get(normal_texcoord as usize)
.map(Vec::as_slice)
else {
return placeholder();
};
let mut geometry = MikktsGeometry {
positions,
normals,
uvs,
indices,
tangents: vec![[1.0, 0.0, 0.0, 1.0]; vertex_count],
};
if mikktspace::generate_tangents(&mut geometry) {
geometry.tangents
} else {
placeholder()
}
}
struct MikktsGeometry<'a> {
positions: &'a [[f32; 3]],
normals: &'a [[f32; 3]],
uvs: &'a [[f32; 2]],
indices: &'a [u32],
tangents: Vec<[f32; 4]>,
}
impl mikktspace::Geometry for MikktsGeometry<'_> {
fn num_faces(&self) -> usize {
self.indices.len() / 3
}
fn num_vertices_of_face(&self, _face: usize) -> usize {
3
}
fn position(&self, face: usize, vert: usize) -> [f32; 3] {
self.positions[self.indices[face * 3 + vert] as usize]
}
fn normal(&self, face: usize, vert: usize) -> [f32; 3] {
self.normals[self.indices[face * 3 + vert] as usize]
}
fn tex_coord(&self, face: usize, vert: usize) -> [f32; 2] {
self.uvs[self.indices[face * 3 + vert] as usize]
}
fn set_tangent(
&mut self,
tangent: [f32; 3],
_bi_tangent: [f32; 3],
_f_mag_s: f32,
_f_mag_t: f32,
bi_tangent_preserves_orientation: bool,
face: usize,
vert: usize,
) {
let index = self.indices[face * 3 + vert] as usize;
let w = if bi_tangent_preserves_orientation {
1.0
} else {
-1.0
};
self.tangents[index] = [tangent[0], tangent[1], tangent[2], w];
}
}
#[cfg(test)]
mod tests {
use super::{
MorphTarget, MorphedVertices, PrimitiveTopology, RenderPrimitive, base_color_texture,
compute_flat_normals, compute_mikkts_tangents, load_primitives, normal_texture_texcoord,
normalize_topology, resolve_loaded_tangents, resolve_morph_weights,
};
use crate::Transform;
#[test]
fn flat_normals_follow_triangle_winding() {
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
let indices = vec![0u32, 1, 2];
let normals = compute_flat_normals(&positions, &indices);
for n in &normals {
assert_eq!(n, &[0.0, 0.0, 1.0], "CCW winding should face +Z");
}
}
#[test]
fn flat_normals_are_unit_length() {
let positions = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 0.0, 2.0]];
let indices = vec![0u32, 1, 2];
let normals = compute_flat_normals(&positions, &indices);
for n in &normals {
let len = (n[0].powi(2) + n[1].powi(2) + n[2].powi(2)).sqrt();
assert!(
(len - 1.0).abs() < 1e-6,
"normal should have unit length: {n:?}"
);
}
}
#[test]
fn degenerate_triangle_yields_zero_normal() {
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]];
let indices = vec![0u32, 1, 2];
let normals = compute_flat_normals(&positions, &indices);
assert_eq!(normals[0], [0.0, 0.0, 0.0]);
}
#[test]
fn triangle_strip_is_normalized_with_gl_tf_winding() {
let (topology, indices) =
normalize_topology(gltf::mesh::Mode::TriangleStrip, vec![0, 1, 2, 3]);
assert_eq!(topology, PrimitiveTopology::Triangles);
assert_eq!(indices, vec![0, 1, 2, 2, 1, 3]);
}
#[test]
fn line_loop_becomes_closed_line_strip() {
let (topology, indices) = normalize_topology(gltf::mesh::Mode::LineLoop, vec![4, 5, 6]);
assert_eq!(topology, PrimitiveTopology::LineStrip);
assert_eq!(indices, vec![4, 5, 6, 4]);
}
#[test]
fn primitive_traversal_handles_a_deep_node_chain_iteratively() {
const NODE_COUNT: usize = 20_000;
let nodes = (0..NODE_COUNT)
.map(|index| {
if index + 1 == NODE_COUNT {
serde_json::json!({})
} else {
serde_json::json!({ "children": [index + 1] })
}
})
.collect::<Vec<_>>();
let bytes = serde_json::to_vec(&serde_json::json!({
"asset": { "version": "2.0" },
"nodes": nodes,
"scenes": [{ "nodes": [0] }],
"scene": 0
}))
.expect("the deep glTF fixture must serialize");
let gltf = gltf::Gltf::from_slice_without_validation(&bytes)
.expect("the deep glTF fixture must parse");
let primitives = load_primitives(&gltf.document, &[])
.expect("iterative traversal must not overflow the call stack");
assert!(primitives.is_empty());
}
#[test]
fn loaded_morph_weights_must_be_finite() {
let error = resolve_morph_weights(Some(&[f32::NAN]), None, 1, 2, 3, 4)
.expect_err("non-finite node morph weights must be rejected");
assert!(
matches!(
error,
crate::LoadError::InvalidVrm(ref message)
if message.contains("node 2 mesh 3 primitive 4")
&& message.contains("non-finite")
&& message.contains("node morph weights")
),
"{error}"
);
}
#[test]
fn mikkts_generates_tangent_from_uv_layout() {
let positions = [
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
];
let normals = [[0.0, 0.0, 1.0]; 4];
let texcoords = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
let indices = vec![0u32, 1, 2, 0, 2, 3];
let tangents = compute_mikkts_tangents(
&positions,
Some(&normals),
Some(2),
&[
vec![[0.0, 0.0]; positions.len()],
vec![[0.0, 0.0]; positions.len()],
texcoords.to_vec(),
],
&indices,
PrimitiveTopology::Triangles,
positions.len(),
);
for t in &tangents {
assert!(
(t[0] - 1.0).abs() < 1e-4 && t[1].abs() < 1e-4 && t[2].abs() < 1e-4,
"tangent should point along +X: {t:?}"
);
assert_eq!(t[3], 1.0, "frame should be right-handed");
}
}
#[test]
fn mikkts_skips_without_normals_or_uv_set() {
let positions = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
let indices = vec![0u32, 1, 2];
let tangents = compute_mikkts_tangents(
&positions,
None,
Some(0),
&[vec![[0.0, 0.0]; 3]],
&indices,
PrimitiveTopology::Triangles,
positions.len(),
);
assert_eq!(tangents, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
let tangents = compute_mikkts_tangents(
&positions,
Some(&[[0.0, 0.0, 1.0]; 3]),
Some(2),
&[vec![[0.0, 0.0]; 3], vec![[0.0, 0.0]; 3]],
&indices,
PrimitiveTopology::Triangles,
positions.len(),
);
assert_eq!(tangents, vec![[1.0, 0.0, 0.0, 1.0]; 3]);
}
#[test]
fn loaded_tangent_policy_ignores_the_stored_stream() {
let vertex = super::VertexBuffers {
positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
texcoord_sets: vec![vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]],
colors: vec![[1.0; 4]; 3],
skinning_sets: Vec::new(),
morph_targets: Vec::new(),
};
let normals = [[0.0, 0.0, 1.0]; 3];
let stored = vec![[-1.0, 0.0, 0.0, -1.0]; 3];
let tangents = resolve_loaded_tangents(
Some(stored),
true,
Some(0),
&vertex,
&normals,
&[0, 1, 2],
PrimitiveTopology::Triangles,
);
for tangent in tangents {
assert!(tangent[0] > 0.99, "MikkTSpace should replace stored data");
assert_eq!(tangent[3], 1.0);
}
}
#[test]
fn normal_texture_transform_uv_override_drives_tangent_generation() {
let document = serde_json::json!({
"asset": { "version": "2.0" },
"extensionsUsed": ["KHR_texture_transform"],
"images": [{ "uri": "normal.png" }],
"textures": [{ "source": 0 }],
"materials": [{
"normalTexture": {
"index": 0,
"texCoord": 0,
"extensions": {
"KHR_texture_transform": { "texCoord": 1 }
}
}
}]
});
let bytes = serde_json::to_vec(&document).expect("the test document must serialize");
let gltf = gltf::Gltf::from_slice(&bytes).expect("the test document must parse");
let material = gltf
.document
.materials()
.next()
.expect("the test material must exist");
assert_eq!(normal_texture_texcoord(&material), Some(1));
}
#[test]
fn base_color_shortcut_uses_texture_id_and_transformed_uv_set() {
let document = serde_json::json!({
"asset": { "version": "2.0" },
"extensionsUsed": ["KHR_texture_transform"],
"images": [{ "uri": "unused.png" }, { "uri": "base.png" }],
"textures": [{ "source": 1 }],
"materials": [{
"pbrMetallicRoughness": {
"baseColorTexture": {
"index": 0,
"texCoord": 0,
"extensions": {
"KHR_texture_transform": { "texCoord": 1 }
}
}
}
}]
});
let bytes = serde_json::to_vec(&document).expect("the test document must serialize");
let gltf = gltf::Gltf::from_slice(&bytes).expect("the test document must parse");
let material = gltf
.document
.materials()
.next()
.expect("the test material must exist");
assert_eq!(base_color_texture(&material), (Some(0), 1));
}
#[test]
fn morphing_moves_positions_by_weighted_deltas() {
let mut primitive = RenderPrimitive::new(
0,
Transform::IDENTITY,
vec![[0.0, 0.0, 0.0]],
vec![[0.0, 0.0, 1.0]],
vec![0],
vec![[0; 4]],
vec![[0.0; 4]],
vec![MorphTarget::new(vec![[1.0, 0.0, 0.0]], None, None)],
vec![[0.0, 0.0]],
vec![[1.0, 0.0, 0.0, 1.0]],
vec![[1.0; 4]],
vec![[0.0, 0.0]],
None,
None,
PrimitiveTopology::Triangles,
vec![],
false,
None,
0,
);
primitive.set_morph_weights(&[0.5]);
let MorphedVertices { positions, .. } = primitive.morphed_vertices();
assert_eq!(positions[0], [0.5, 0.0, 0.0]);
}
#[test]
fn morphing_renormalizes_smooth_normals_with_deltas() {
let mut primitive = RenderPrimitive::new(
0,
Transform::IDENTITY,
vec![[0.0, 0.0, 0.0]],
vec![[0.0, 0.0, 1.0]],
vec![0],
vec![[0; 4]],
vec![[0.0; 4]],
vec![MorphTarget::new(
vec![[0.0, 0.0, 0.0]],
Some(vec![[0.0, 0.0, 1.0]]),
None,
)],
vec![[0.0, 0.0]],
vec![[1.0, 0.0, 0.0, 1.0]],
vec![[1.0; 4]],
vec![[0.0, 0.0]],
None,
None,
PrimitiveTopology::Triangles,
vec![],
false,
None,
0,
);
primitive.set_morph_weights(&[1.0]);
let MorphedVertices { normals, .. } = primitive.morphed_vertices();
assert_eq!(normals[0], [0.0, 0.0, 1.0]);
}
#[test]
fn morphing_recomputes_flat_normals_from_morphed_positions() {
let positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0]];
let indices = vec![0u32, 1, 2];
let mut primitive = RenderPrimitive::new(
0,
Transform::IDENTITY,
positions,
vec![[0.0, 0.0, 1.0]; 3],
indices,
vec![[0; 4]; 3],
vec![[0.0; 4]; 3],
vec![MorphTarget::new(
vec![[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, -1.0, 1.0]],
None,
None,
)],
vec![[0.0, 0.0]; 3],
vec![[1.0, 0.0, 0.0, 1.0]; 3],
vec![[1.0; 4]; 3],
vec![[0.0, 0.0]; 3],
None,
None,
PrimitiveTopology::Triangles,
vec![],
true,
None,
0,
);
primitive.set_morph_weights(&[1.0]);
let MorphedVertices { normals, .. } = primitive.morphed_vertices();
assert_eq!(
normals[0],
[0.0, -1.0, 0.0],
"raised vertex should reorient the flat normal"
);
}
}