Skip to content

Commit

Permalink
Apply GLTF transforms
Browse files Browse the repository at this point in the history
  • Loading branch information
emilk committed Apr 7, 2022
1 parent 5f18093 commit 12ccbef
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
3 changes: 1 addition & 2 deletions examples/pbr/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ pub async fn run() {
let (mut cpu_meshes, cpu_materials) = loaded.gltf("DamagedHelmet.glb").unwrap();
let material = PhysicalMaterial::new(&context, &cpu_materials[0]).unwrap();
cpu_meshes[0].compute_tangents().unwrap();
let mut model = Model::new_with_material(&context, &cpu_meshes[0], material.clone()).unwrap();
model.set_transformation(Mat4::from_angle_x(degrees(90.0)));
let model = Model::new_with_material(&context, &cpu_meshes[0], material.clone()).unwrap();

let light =
AmbientLight::new_with_environment(&context, 1.0, Color::WHITE, skybox.texture()).unwrap();
Expand Down
31 changes: 28 additions & 3 deletions src/io/parser/gltf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl Loaded {
for scene in document.scenes() {
for node in scene.nodes() {
parse_tree(
&Mat4::identity(),
&node,
self,
&base_path,
Expand All @@ -49,13 +50,20 @@ impl Loaded {
}

fn parse_tree<'a>(
parent_transform: &Mat4,
node: &::gltf::Node,
loaded: &mut Loaded,
path: &Path,
buffers: &[::gltf::buffer::Data],
cpu_meshes: &mut Vec<CpuMesh>,
cpu_materials: &mut Vec<CpuMaterial>,
) -> ThreeDResult<()> {
let node_transform = parse_transform(node.transform());
if node_transform.determinant() == 0.0 {
return Ok(()); // glTF say that if the scale is all zeroes, the node should be ignored.
}
let transform = parent_transform * node_transform;

if let Some(mesh) = node.mesh() {
let name: String = mesh
.name()
Expand Down Expand Up @@ -199,7 +207,7 @@ fn parse_tree<'a>(
uvs
});

cpu_meshes.push(CpuMesh {
let mut cpu_mesh = CpuMesh {
name: name.clone(),
positions: Positions::F32(positions),
normals,
Expand All @@ -208,13 +216,25 @@ fn parse_tree<'a>(
colors,
uvs,
material_name: Some(material_name),
});
};
if transform != Mat4::identity() {
cpu_mesh.transform(&transform);
}
cpu_meshes.push(cpu_mesh);
}
}
}

for child in node.children() {
parse_tree(&child, loaded, path, buffers, cpu_meshes, cpu_materials)?;
parse_tree(
&transform,
&child,
loaded,
path,
buffers,
cpu_meshes,
cpu_materials,
)?;
}
Ok(())
}
Expand Down Expand Up @@ -245,3 +265,8 @@ fn parse_texture<'a>(
// TODO: Parse sampling parameters
Ok(tex)
}

fn parse_transform(transform: gltf::scene::Transform) -> Mat4 {
let [c0, c1, c2, c3] = transform.matrix();
Mat4::from_cols(c0.into(), c1.into(), c2.into(), c3.into())
}

0 comments on commit 12ccbef

Please sign in to comment.