pak 0.7.1

An easy-to-use data pak format for games.
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use {
    super::{
        Asset, Canonicalize, Euler, Rotation, Writer, file_key, is_toml, material::MaterialAsset,
        mesh::MeshAsset, parent,
    },
    crate::{
        SceneId,
        scene::{DataData, GeometryData, ReferenceData, Scene},
    },
    anyhow::Context,
    glam::{EulerRot, Quat, Vec3, vec3},
    log::info,
    ordered_float::OrderedFloat,
    parking_lot::Mutex,
    serde::{
        Deserialize, Deserializer,
        de::{Error, MapAccess, Visitor, value::MapAccessDeserializer},
    },
    std::{
        collections::BTreeMap,
        fmt::Formatter,
        marker::PhantomData,
        mem::size_of,
        path::{Path, PathBuf},
        sync::Arc,
    },
    tokio::runtime::Runtime,
};

/// A reference to an asset or source file.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum AssetRef<T> {
    /// A `T` asset specified inline.
    Asset(T),

    /// A `T` asset file or `T` source file.
    Path(PathBuf),
}

impl<'de, T> AssetRef<T>
where
    T: Deserialize<'de>,
{
    /// Deserialize from any of absent or:
    ///
    /// src of file.gltf:
    /// .. = "file.gltf"
    ///
    /// src of file.toml which must be a `T` asset:
    /// .. = "file.toml"
    ///
    /// src of a `T` asset:
    /// .. = { src = "file.gltf" }
    fn de<D>(deserializer: D) -> Result<Option<Self>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct AssetRefVisitor<T>(PhantomData<T>);

        impl<'de, T> Visitor<'de> for AssetRefVisitor<T>
        where
            T: Deserialize<'de>,
        {
            type Value = Option<AssetRef<T>>;

            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
                formatter.write_str("path string or asset")
            }

            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let asset = Deserialize::deserialize(MapAccessDeserializer::new(map))?;

                Ok(Some(AssetRef::Asset(asset)))
            }

            fn visit_str<E>(self, str: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Some(AssetRef::Path(PathBuf::from(str))))
            }
        }

        deserializer.deserialize_any(AssetRefVisitor(PhantomData))
    }
}

impl<'de, T> Deserialize<'de> for AssetRef<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        AssetRef::<T>::de(deserializer).transpose().unwrap()
    }
}

impl<T> Canonicalize for AssetRef<T>
where
    T: Canonicalize,
{
    fn canonicalize(&mut self, project_dir: impl AsRef<Path>, src_dir: impl AsRef<Path>) {
        match self {
            Self::Asset(asset) => asset.canonicalize(project_dir, src_dir),
            Self::Path(src) => *src = Self::canonicalize_project_path(project_dir, src_dir, &src),
        }
    }
}

/// Holds a description of indexed triangle geometries.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
pub struct Geometry {
    id: Option<String>,

    // Values
    euler: Option<Euler>,
    indices: Box<[u32]>,
    rotation: Option<Rotation>,
    translation: Option<[OrderedFloat<f32>; 3]>,
    vertices: Box<[OrderedFloat<f32>]>,

    // Tables must follow values
    tags: Option<Box<[String]>>,
    data: Option<BTreeMap<String, Data>>,
}

impl Geometry {
    /// An arbitrary collection of program-specific strings.
    #[allow(unused)]
    pub fn data(&self) -> impl Iterator<Item = (&String, &Data)> {
        self.data
            .as_ref()
            .map(|data| data.iter())
            .unwrap_or_default()
    }

    /// Euler ordering of the mesh orientation.
    pub fn euler(&self) -> EulerRot {
        match self.euler.unwrap_or(Euler::XYZ) {
            Euler::XYZ => EulerRot::XYZ,
            Euler::XZY => EulerRot::XZY,
            Euler::YXZ => EulerRot::YXZ,
            Euler::YZX => EulerRot::YZX,
            Euler::ZXY => EulerRot::ZXY,
            Euler::ZYX => EulerRot::ZYX,
        }
    }

    /// Main identifier of a geometry, not required to be unique.
    pub fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }

    /// Orientation of a geometry.
    pub fn rotation(&self) -> Quat {
        match self.rotation {
            Some(Rotation::Euler(rotation)) => Quat::from_euler(
                self.euler(),
                rotation[0].0.to_radians(),
                rotation[1].0.to_radians(),
                rotation[2].0.to_radians(),
            ),
            Some(Rotation::Quaternion(rotation)) => {
                Quat::from_array([rotation[0].0, rotation[1].0, rotation[2].0, rotation[3].0])
            }
            None => Quat::IDENTITY,
        }
    }

    /// An arbitrary collection of program-specific strings.
    pub fn tags(&self) -> &[String] {
        self.tags.as_deref().unwrap_or_default()
    }

    /// Translation of a geometry.
    pub fn translation(&self) -> Vec3 {
        self.translation
            .map(|translation| vec3(translation[0].0, translation[1].0, translation[2].0))
            .unwrap_or(Vec3::ZERO)
    }
}

/// Holds a description of scene entities and tagged data.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
pub struct SceneAsset {
    #[serde(rename = "geometry")]
    geometries: Option<Box<[Geometry]>>,

    #[serde(rename = "ref")]
    references: Option<Box<[Reference]>>,
}

impl SceneAsset {
    /// Reads and processes scene source files into an existing `.pak` file buffer.
    pub fn bake(
        &self,
        rt: &Runtime,
        writer: &Arc<Mutex<Writer>>,
        project_dir: impl AsRef<Path>,
        path: impl AsRef<Path>,
    ) -> anyhow::Result<SceneId> {
        // Early-out if we have already baked this scene
        let asset = self.clone().into();
        if let Some(h) = writer.lock().ctx.get(&asset) {
            return Ok(h.as_scene().unwrap());
        }

        let key = file_key(&project_dir, &path);

        info!("Baking scene: {}", key);

        let src_dir = parent(&path);

        let geometries = self
            .geometries()
            .iter()
            .map(|geometry| {
                let data = geometry
                    .data()
                    .map(|(key, value)| (key.clone(), value.clone().into()))
                    .collect();

                // all tags must be lower case (no localized text!)
                let mut tags = vec![];
                for tag in geometry.tags() {
                    let baked = tag.as_str().trim().to_lowercase();
                    if let Err(idx) = tags.binary_search(&baked) {
                        tags.insert(idx, baked);
                    }
                }

                let mut vertices = Vec::with_capacity(geometry.vertices.len() * size_of::<f32>());
                geometry
                    .vertices
                    .iter()
                    .map(|vertex| vertex.0.to_ne_bytes())
                    .for_each(|vertex| vertices.extend_from_slice(&vertex));

                GeometryData {
                    data,
                    id: geometry.id().map(|id| id.to_owned()),
                    indices: geometry.indices.to_vec(),
                    vertices,
                    rotation: geometry.rotation().into(),
                    tags,
                    translation: geometry.translation().into(),
                }
            })
            .collect::<Box<_>>();

        let references = self
            .refs()
            .iter()
            .map(|reference| {
                // all tags must be lower case (no localized text!)
                let mut tags = vec![];
                for tag in reference.tags() {
                    let baked = tag.as_str().trim().to_lowercase();
                    if let Err(idx) = tags.binary_search(&baked) {
                        tags.insert(idx, baked);
                    }
                }

                let data = reference
                    .data()
                    .map(|(key, value)| (key.clone(), value.clone().into()))
                    .collect();

                let materials = reference
                    .materials()
                    .iter()
                    .map(|material| match material {
                        AssetRef::Asset(material) => {
                            // Material asset specified inline
                            let material = material.clone();
                            (None, material)
                        }
                        AssetRef::Path(src) => {
                            if is_toml(src) {
                                // Asset file reference
                                let mut material = Asset::read(src)
                                    .context("Reading material asset")
                                    .expect("Unable to read material asset")
                                    .into_material()
                                    .expect("Not a material");
                                let src_dir = parent(src);
                                material.canonicalize(&project_dir, &src_dir);
                                (Some(src), material)
                            } else {
                                // Material color file reference
                                (None, MaterialAsset::new(src))
                            }
                        }
                    })
                    .map(|(src, mut material)| {
                        material
                            .bake(rt, writer, &project_dir, &src_dir, src)
                            .expect("material")
                    })
                    .collect();

                let mesh = reference
                    .mesh()
                    .map(|mesh| match mesh {
                        AssetRef::Asset(mesh) => {
                            // Mesh asset specified inline
                            let mesh = mesh.clone();
                            (None, mesh)
                        }
                        AssetRef::Path(src) => {
                            if is_toml(src) {
                                // Asset file reference
                                let mut mesh = Asset::read(src)
                                    .context("Reading mesh asset")
                                    .expect("Unable to read mesh asset")
                                    .into_mesh()
                                    .expect("Not a mesh");
                                let src_dir = parent(src);
                                mesh.canonicalize(&project_dir, &src_dir);
                                (Some(src), mesh)
                            } else {
                                // Mesh file reference
                                (None, MeshAsset::new(src))
                            }
                        }
                    })
                    .map(|(src, mesh)| mesh.bake(writer, &project_dir, src).expect("bake mesh"));

                ReferenceData {
                    data,
                    id: reference.id().map(str::to_owned),
                    materials,
                    mesh,
                    rotation: reference.rotation().into(),
                    tags,
                    translation: reference.translation().into(),
                }
            })
            .collect::<Box<_>>();

        let scene = Scene::new(geometries, references);

        let mut writer = writer.lock();
        if let Some(h) = writer.ctx.get(&asset) {
            return Ok(h.as_scene().unwrap());
        }

        let id = writer.push_scene(scene, key);
        writer.ctx.insert(asset, id.into());

        Ok(id)
    }

    /// Individual geometries within a scene.
    #[allow(unused)]
    pub fn geometries(&self) -> &[Geometry] {
        self.geometries.as_deref().unwrap_or_default()
    }

    /// Individual references within a scene.
    #[allow(unused)]
    pub fn refs(&self) -> &[Reference] {
        self.references.as_deref().unwrap_or_default()
    }
}

impl Canonicalize for SceneAsset {
    fn canonicalize(&mut self, project_dir: impl AsRef<Path>, src_dir: impl AsRef<Path>) {
        self.references
            .as_deref_mut()
            .unwrap_or_default()
            .iter_mut()
            .for_each(|reference| reference.canonicalize(&project_dir, &src_dir));
    }
}

/// Holds a description of one scene reference.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
pub struct Reference {
    id: Option<String>,

    // Values
    euler: Option<Euler>,
    materials: Option<Vec<AssetRef<MaterialAsset>>>,
    #[serde(default, deserialize_with = "AssetRef::<MeshAsset>::de")]
    mesh: Option<AssetRef<MeshAsset>>,
    rotation: Option<Rotation>,
    translation: Option<[OrderedFloat<f32>; 3]>,

    // Tables must follow values
    data: Option<BTreeMap<String, Data>>,
    tags: Option<Vec<String>>,
}

impl Reference {
    /// An arbitrary collection of program-specific strings.
    #[allow(unused)]
    pub fn data(&self) -> impl Iterator<Item = (&String, &Data)> {
        self.data
            .as_ref()
            .map(|data| data.iter())
            .unwrap_or_default()
    }

    /// Euler ordering of the mesh orientation.
    pub fn euler(&self) -> EulerRot {
        match self.euler.unwrap_or(Euler::XYZ) {
            Euler::XYZ => EulerRot::XYZ,
            Euler::XZY => EulerRot::XZY,
            Euler::YXZ => EulerRot::YXZ,
            Euler::YZX => EulerRot::YZX,
            Euler::ZXY => EulerRot::ZXY,
            Euler::ZYX => EulerRot::ZYX,
        }
    }

    /// Main identifier of a reference, not required to be unique.
    #[allow(unused)]
    pub fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }

    /// Optional direct reference to a mesh asset file.
    ///
    /// If specified, the mesh asset does not need to be referenced in any content file. If the
    /// mesh is referenced in a content file it will not be duplicated or cause any problems.
    ///
    /// May either be a `Mesh` asset specified inline or a mesh source file. Mesh source files
    /// may be either `.toml` `Mesh` asset files or direct references to `.glb`/`.gltf` files.
    pub fn mesh(&self) -> Option<&AssetRef<MeshAsset>> {
        self.mesh.as_ref()
    }

    /// Optional direct reference to a material asset files.
    ///
    /// If specified, the material assets do not need to be referenced in any content file. If the
    /// material is referenced in a content file it will not be duplicated or cause any problems.
    pub fn materials(&self) -> &[AssetRef<MaterialAsset>] {
        self.materials.as_deref().unwrap_or_default()
    }

    /// Any 3D orientation or orientation-like data.
    #[allow(unused)]
    pub fn rotation(&self) -> Quat {
        match self.rotation {
            Some(Rotation::Euler(rotation)) => Quat::from_euler(
                self.euler(),
                rotation[0].0.to_radians(),
                rotation[1].0.to_radians(),
                rotation[2].0.to_radians(),
            ),
            Some(Rotation::Quaternion(rotation)) => {
                Quat::from_array([rotation[0].0, rotation[1].0, rotation[2].0, rotation[3].0])
            }
            None => Quat::IDENTITY,
        }
    }

    /// An arbitrary collection of program-specific strings.
    #[allow(unused)]
    pub fn tags(&self) -> &[String] {
        self.tags.as_deref().unwrap_or_default()
    }

    /// Any 3D position or position-like data.
    #[allow(unused)]
    pub fn translation(&self) -> Vec3 {
        self.translation
            .map(|translation| vec3(translation[0].0, translation[1].0, translation[2].0))
            .unwrap_or(Vec3::ZERO)
    }
}

impl Canonicalize for Reference {
    fn canonicalize(&mut self, project_dir: impl AsRef<Path>, src_dir: impl AsRef<Path>) {
        if let Some(materials) = self.materials.as_mut() {
            for material in materials {
                material.canonicalize(&project_dir, &src_dir);
            }
        }

        if let Some(mesh) = self.mesh.as_mut() {
            mesh.canonicalize(&project_dir, &src_dir);
        }
    }
}

/// Encapsulates any scene data.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum Data {
    Array(Vec<Data>),
    Bool(bool),
    Float(OrderedFloat<f32>),
    Number(i32),
    String(String),
}

impl<'de> Data {
    fn de<D>(deserializer: D) -> Result<Option<Self>, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct DataVisitor;

        impl<'de> Visitor<'de> for DataVisitor {
            type Value = Option<Data>;

            fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
                formatter.write_str("bool, number, string, or array of any")
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Some(Data::Bool(v)))
            }

            fn visit_char<E>(self, v: char) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_string(v.to_string())
            }

            fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_f64(v as _)
            }

            fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(Some(Data::Float(OrderedFloat(v as _))))
            }

            fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_i64(v as _)
            }

            fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_i64(v as _)
            }

            fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_i64(v as _)
            }

            fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                if v >= i32::MIN as i64 && v <= i32::MAX as i64 {
                    Ok(Some(Data::Number(v as _)))
                } else {
                    Err(Error::invalid_type(
                        serde::de::Unexpected::Signed(v),
                        &"an i32",
                    ))
                }
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                let mut res = vec![];

                while let Some(item) = seq.next_element()? {
                    res.push(item);
                }

                Ok(Some(Data::Array(res)))
            }

            fn visit_str<E>(self, str: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                self.visit_string(str.to_string())
            }

            fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
            where
                E: Error,
            {
                Ok(Some(Data::String(v)))
            }

            fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_u64(v as _)
            }

            fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_u64(v as _)
            }

            fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
            where
                E: Error,
            {
                self.visit_u64(v as _)
            }

            fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                if v <= i32::MAX as u64 {
                    Ok(Some(Data::Number(v as _)))
                } else {
                    Err(Error::invalid_type(
                        serde::de::Unexpected::Unsigned(v),
                        &"an i32",
                    ))
                }
            }
        }

        deserializer.deserialize_any(DataVisitor)
    }
}

impl<'de> Deserialize<'de> for Data {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Data::de(deserializer).transpose().unwrap()
    }
}

impl From<Data> for DataData {
    fn from(value: Data) -> Self {
        match value {
            Data::Array(values) => DataData::Array(values.into_iter().map(Into::into).collect()),
            Data::Bool(value) => DataData::Bool(value),
            Data::Float(OrderedFloat(value)) => DataData::Float(value),
            Data::Number(value) => DataData::Number(value),
            Data::String(value) => DataData::String(value),
        }
    }
}