learn-wgpu icon indicating copy to clipboard operation
learn-wgpu copied to clipboard

Panic when loading .obj without normals.

Open tmff opened this issue 1 year ago • 3 comments

In load_model, it is presumed that the mesh has normal's. If a model is loaded which doesn't have them it panics with an out of bounds exception.

let vertices = (0..m.mesh.positions.len() / 3)
                .map(|i| {
                    if m.mesh.normals.is_empty(){
                        model::ModelVertex {
                            position: [
                                m.mesh.positions[i * 3],
                                m.mesh.positions[i * 3 + 1],
                                m.mesh.positions[i * 3 + 2],
                            ],
                            tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
                            normal: [0.0, 0.0, 0.0],
                        }
                    }else{
                        model::ModelVertex {
                            position: [
                                m.mesh.positions[i * 3],
                                m.mesh.positions[i * 3 + 1],
                                m.mesh.positions[i * 3 + 2],
                            ],
                            tex_coords: [m.mesh.texcoords[i * 2], 1.0 - m.mesh.texcoords[i * 2 + 1]],
                            normal: [
                                m.mesh.normals[i * 3],
                                m.mesh.normals[i * 3 + 1],
                                m.mesh.normals[i * 3 + 2],
                            ],
                        }
                    }
                })
                .collect::<Vec<_>>();

There is probably a more elegant way to do this but I am not the best with Rust.

tmff avatar Dec 24 '23 02:12 tmff

That's a perfectly fine way of doing it. There might be a way to do it with just iterators, but this is good enough. Mind making a PR?

sotrh avatar Dec 27 '23 21:12 sotrh

Yeah will do.

tmff avatar Dec 28 '23 00:12 tmff

since the vertex normals are derived from the face normals, they can be calculated from just the positions and indices.

adamgerhant avatar Feb 14 '24 23:02 adamgerhant