1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use std::collections::{BTreeSet, HashMap};
use std::convert::{TryFrom, TryInto};
use std::path::Path;
use std::sync::Arc;

use gltf::mesh::Reader;
use gltf::texture::MagFilter;
use gltf::{Buffer, Document, Node};

use crate::color::{Color, ColorFormat, Image, Interpolation, Texture};
use crate::materials::{Material, PbrMaterial};
use crate::math::{Bounds3, Hit, Mat4, Point2, Point3, Ray, Vec3, Vec4};
use crate::shapes::triangle_mesh::TriangleMesh;
use crate::shapes::{Mesh, Shape};
use crate::util::Error;

/// A [`Shape`] paired with a [`Material`].
#[derive(Clone)]
pub struct Object {
    // TODO: Arc ist pointless, cause you need to create a new shape if you want to change it's transform
    pub shape: Arc<dyn Shape>,
    pub material: Arc<dyn Material>,
}

impl Object {
    /// Create a new [`Object`].
    pub fn new(shape: Arc<dyn Shape>, material: Arc<dyn Material>) -> Self {
        Object { shape, material }
    }

    /// Propagate the transform for all children of a parent recursively.
    fn apply_transform_recursively(transform_matrices: &mut [Mat4], node: &Node) {
        node.children().for_each(|c| {
            transform_matrices[c.index()] =
                transform_matrices[node.index()] * transform_matrices[c.index()];

            Self::apply_transform_recursively(transform_matrices, &c);
        });
    }

    /// Load the index buffer of a mesh.
    ///
    /// Returns [`None`] if there is no index buffer.
    fn load_indices<'a, 's, F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>>(
        reader: &Reader<'a, 's, F>,
        node: &Node,
    ) -> Option<Vec<u32>> {
        match reader.read_indices() {
            Some(indices) => Some(indices.into_u32().collect()),
            None => {
                eprint!("ERROR: Indices not found. ");
                match node.name() {
                    Some(name) => eprintln!("Skipping '{}'", name),
                    None => eprintln!("Skipping mesh"),
                }

                None
            }
        }
    }

    /// Load the vertex buffer of a mesh.
    ///
    /// Returns [`None`] if there is no vertex buffer.
    fn load_vertices<'a, 's, F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>>(
        reader: &Reader<'a, 's, F>,
        matrix: Mat4,
        node: &Node,
    ) -> Option<Vec<Point3>> {
        let vertices_vec = match reader.read_positions() {
            Some(vertices) => vertices
                .map(|v| matrix * Point3::new(v[0] as f64, v[1] as f64, v[2] as f64))
                .collect(),
            None => {
                eprint!("ERROR: Attribute POSITION not found. ");
                match node.name() {
                    Some(name) => eprintln!("Skipping '{}'", name),
                    None => eprintln!("Skipping mesh"),
                }

                return None;
            }
        };

        Some(vertices_vec)
    }

    /// Load the normal buffer of a mesh.
    ///
    /// Returns [`None`] if there is no normal buffer.
    fn load_normals<'a, 's, F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>>(
        reader: &Reader<'a, 's, F>,
        matrix: Mat4,
        node: &Node,
    ) -> Option<Vec<Vec3>> {
        match reader.read_normals() {
            Some(normals) => Some(
                normals
                    .map(|n| {
                        (matrix * Vec3::new(n[0] as f64, n[1] as f64, n[2] as f64)).normalize()
                    })
                    .collect(),
            ),
            None => {
                eprint!("WARNING: Attribute NORMAL not found. ");
                match node.name() {
                    Some(name) => eprintln!("Generating normals for '{}'", name),
                    None => eprintln!("Generating normals"),
                }
                None
            }
        }
    }

    /// Load the tangent buffer of a mesh.
    ///
    /// Returns [`None`] if there is no tangent buffer.
    fn load_tangents<'a, 's, F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>>(
        reader: &Reader<'a, 's, F>,
        matrix: Mat4,
        node: &Node,
    ) -> Option<Vec<Vec4>> {
        match reader.read_tangents() {
            Some(tangents) => Some(
                tangents
                    .map(|t| {
                        let tangent =
                            (matrix * Vec3::new(t[0] as f64, t[1] as f64, t[2] as f64)).normalize();

                        Vec4::new(tangent.x, tangent.y, tangent.z, t[3] as f64)
                    })
                    .collect(),
            ),
            None => {
                eprint!("WARNING: Attribute TANGENT not found. ");
                match node.name() {
                    Some(name) => eprintln!("Normal maps won't be supported for '{}'", name),
                    None => eprintln!("Normal maps won't be supported"),
                }
                None
            }
        }
    }

    /// Load the UV buffer of a mesh.
    ///
    /// Returns [`None`] if there is no UV buffer.
    fn load_uvs<'a, 's, F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>>(
        reader: &Reader<'a, 's, F>,
        node: &Node,
    ) -> Option<Vec<Point2>> {
        match reader.read_tex_coords(0) {
            Some(tex_coords) => Some(
                tex_coords
                    .into_f32()
                    .map(|t| Point2::new(t[0] as f64, t[1] as f64))
                    .collect(),
            ),
            None => {
                eprint!("WARNING: Attribute TEXCOORD not found. ");
                match node.name() {
                    Some(name) => {
                        eprintln!("'{}' will only support colors, not textures", name)
                    }
                    None => eprintln!("Mesh will only support colors, not textures"),
                }
                None
            }
        }
    }

    /// Load all images from a glTF document and store them in a [`HashMap`].
    ///
    /// See [`Object::load_image`] for information when an image is [`None`].
    fn load_images(
        document: &Document,
        images: &[gltf::image::Data],
    ) -> HashMap<usize, Option<Arc<dyn Texture>>> {
        document
            .textures()
            .map(|t| {
                let index = t.source().index();
                let data = &images[index];

                (index, Self::load_image(data, &t))
            })
            .collect()
    }

    /// Load an image.
    ///
    /// If the image's [`ColorFormat`] is unsupported, [`None`] is returned.
    fn load_image(data: &gltf::image::Data, texture: &gltf::Texture) -> Option<Arc<dyn Texture>> {
        let format = match ColorFormat::try_from(data.format) {
            Ok(f) => f,
            Err(e) => {
                println!("ERROR: {}", e);

                return None;
            }
        };

        let image = Image::from_raw_with_format(
            data.width,
            data.height,
            &data.pixels,
            format,
            match texture.sampler().mag_filter() {
                None => Interpolation::Bilinear,
                Some(filter) => match filter {
                    MagFilter::Nearest => Interpolation::Closest,
                    MagFilter::Linear => Interpolation::Bilinear,
                },
            },
        );

        Some(Arc::new(image))
    }

    /// Load all materials from a glTF document and store them in a [`HashMap`].
    fn load_materials(
        document: &Document,
        images: &HashMap<usize, Option<Arc<dyn Texture>>>,
    ) -> HashMap<usize, Arc<PbrMaterial>> {
        document
            .materials()
            .filter(|m| m.index().is_some())
            .map(|m| (m.index().unwrap(), Arc::new(Self::load_material(images, m))))
            .collect()
    }

    /// Load a material.
    fn load_material(
        images: &HashMap<usize, Option<Arc<dyn Texture>>>,
        material: gltf::Material,
    ) -> PbrMaterial {
        let pbr = material.pbr_metallic_roughness();

        let base_color_factor: [f32; 3] = pbr.base_color_factor()[0..3].try_into().unwrap();
        let base_color = Color::from(base_color_factor);
        let base_color_texture = pbr
            .base_color_texture()
            .and_then(|i| images.get(&i.texture().index())?.as_ref().map(Arc::clone));

        let metallic = pbr.metallic_factor() as f64;
        let roughness = pbr.roughness_factor() as f64;

        let metallic_roughness_texture = pbr
            .metallic_roughness_texture()
            .and_then(|i| images.get(&i.texture().index())?.as_ref().map(Arc::clone));

        let transmission = material
            .transmission()
            .map(|t| t.transmission_factor())
            .unwrap_or_default() as f64;
        let ior = material.ior().unwrap_or(1.0) as f64;

        let emissive_color_factor = material.emissive_factor();
        let emissive_color = Color::from(emissive_color_factor);
        let emissive_texture = material
            .emissive_texture()
            .and_then(|i| images.get(&i.texture().index())?.as_ref().map(Arc::clone));
        let emissive_strength = material.emissive_strength().unwrap_or(1.0) as f64;

        let normal_texture = material
            .normal_texture()
            .and_then(|i| images.get(&i.texture().index())?.as_ref().map(Arc::clone));

        PbrMaterial {
            base_color,
            base_color_texture,
            metallic,
            roughness,
            metallic_roughness_texture,
            transmission,
            ior,
            emissive_color,
            emissive_texture,
            emissive_strength,
            normal_texture,
        }
    }

    /// Load all meshes from a glTF document.
    ///
    /// - If a mesh does not have indices or vertices, it will be skipped.
    /// - If a mesh does not have normals, flat shading normals will be generated.
    /// - If a mesh does not have tangents, normal mapping won't be applied.
    /// - If a mesh does not have UVs, all vertices will have `(0.0, 0.0)` as their UVs.
    ///
    /// For information about supported materials see [`PbrMaterial`].
    ///
    /// Returns an [`Error`] if the document can not be parsed.
    pub fn load_gltf<P: AsRef<Path>>(path: P) -> Result<Vec<Object>, Error> {
        let (document, buffers, images) = gltf::import(path)?;

        Self::load_gltf_document(&document, &buffers, &images)
    }

    /// Load a glTF document.
    pub(crate) fn load_gltf_document(
        document: &Document,
        buffers: &[gltf::buffer::Data],
        images: &[gltf::image::Data],
    ) -> Result<Vec<Object>, Error> {
        let mut nodes = document.nodes().collect::<Vec<Node>>();
        nodes.sort_by_key(|n| n.index());

        let nodes_indices = nodes.iter().map(|n| n.index()).collect::<BTreeSet<usize>>();

        let children_indices = nodes
            .iter()
            .flat_map(|n| n.children().map(|c| c.index()))
            .collect::<BTreeSet<usize>>();

        let mut transform_matrices = nodes
            .iter()
            .map(|n| Mat4::from(n.transform().matrix().map(|r| r.map(f64::from))).transpose())
            .collect::<Vec<Mat4>>();

        nodes_indices.difference(&children_indices).for_each(|i| {
            Self::apply_transform_recursively(&mut transform_matrices, &nodes[*i]);
        });

        let mut objects = vec![];

        let images = Self::load_images(document, images);
        let materials = Self::load_materials(document, &images);

        for node in nodes {
            if let Some(mesh) = node.mesh() {
                for primitive in mesh.primitives() {
                    let reader = primitive.reader(|buffer| Some(&buffers[buffer.index()]));

                    let matrix = transform_matrices[node.index()];

                    let indices = match Self::load_indices(&reader, &node) {
                        Some(indices) => indices,
                        None => continue,
                    };
                    let vertices = match Self::load_vertices(&reader, matrix, &node) {
                        Some(vertices) => vertices,
                        None => continue,
                    };
                    let normals = Self::load_normals(&reader, matrix, &node);
                    let tangents = Self::load_tangents(&reader, matrix, &node);
                    let uvs = Self::load_uvs(&reader, &node);

                    let triangle_mesh = TriangleMesh::new(
                        indices,
                        vertices,
                        normals.unwrap_or_default(),
                        tangents.unwrap_or_default(),
                        uvs.unwrap_or_default(),
                    );
                    let triangles = triangle_mesh.triangles().collect();

                    let material = match primitive.material().index() {
                        None => Arc::new(PbrMaterial::default()),
                        Some(i) => Arc::clone(&materials[&i]),
                    };

                    objects.push(Object::new(Arc::new(Mesh::new(triangles)), material));
                }
            }
        }

        Ok(objects)
    }
}

impl Shape for Object {
    fn intersects(&self, ray: Ray) -> Option<Hit> {
        self.shape.intersects(ray)
    }

    fn bounds(&self) -> Bounds3 {
        self.shape.bounds()
    }
}