frdt 0.3.0

Edit and inspect Resonite FrDT (.brson) documents without expanding them to JSON
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
//! Compare two documents by structure, not by bytes.
//!
//! Each document is described as entries `(path, item) -> value`, and the two
//! descriptions are matched by key. Ids drop out: a string that names an id
//! is described by what it names (`→ slot Root/0:Main`, `→ component … #2
//! Data.TargetField`, `→ asset <type> <url>`), so renumbered copies compare
//! equal while a reference that points somewhere else does not.
//!
//! - `path` is `document`, a slot path such as `Root/0:Main/2:DV` (child
//!   position and name), or `asset <type> <url>` for an asset that something
//!   references.
//! - `item` is a root field (`VersionNumber`, `FeatureFlags.X`,
//!   `TypeVersions.X`), a slot field (`Name`, `Position.0`), `slot` for the
//!   slot itself, or `#i type` and `#i <field>` for the slot's i-th component.
//! - Values are compared as written: strings, numbers, booleans, null, and the
//!   type names that type fields index. Numbers compare by value, so a double
//!   `0.0` and an int `0` are equal; other doubles compare by their exact bits.
//! - Assets that nothing references are not described.

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;

use crate::bson::{self, Element, ARRAY, BINARY, BOOL, DOCUMENT, DOUBLE, NULL, STRING};
use crate::datatree;
use crate::error::Result;
use crate::ids;
use crate::typetable;

/// One entry that differs. `left` is from the first document, `right` from
/// the second; `None` means the entry is missing on that side.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Difference {
    pub path: String,
    pub item: String,
    pub left: Option<String>,
    pub right: Option<String>,
}

/// Every difference between two decompressed documents, in the order of the
/// first document, then entries only the second has.
pub fn compare(a: &[u8], b: &[u8]) -> Result<Vec<Difference>> {
    // Both sides hash their assets the same number of rounds, so that equal
    // assets get equal names.
    let (ha, ra) = asset_hashes(a, None)?;
    let (hb, rb) = asset_hashes(b, None)?;
    let rounds = ra.max(rb);
    let ha = if ra == rounds {
        ha
    } else {
        asset_hashes(a, Some(rounds))?.0
    };
    let hb = if rb == rounds {
        hb
    } else {
        asset_hashes(b, Some(rounds))?.0
    };
    let left = describe(a, ha)?;
    let right = describe(b, hb)?;
    let right_map: HashMap<(&str, &str), &str> = right
        .iter()
        .map(|(p, i, v)| ((p.as_str(), i.as_str()), v.as_str()))
        .collect();
    let left_keys: HashSet<(&str, &str)> = left
        .iter()
        .map(|(p, i, _)| (p.as_str(), i.as_str()))
        .collect();
    let mut out = Vec::new();
    for (p, i, v) in &left {
        match right_map.get(&(p.as_str(), i.as_str())) {
            Some(r) if *r == v => {}
            other => out.push(Difference {
                path: p.clone(),
                item: i.clone(),
                left: Some(v.clone()),
                right: other.map(|r| r.to_string()),
            }),
        }
    }
    for (p, i, v) in &right {
        if !left_keys.contains(&(p.as_str(), i.as_str())) {
            out.push(Difference {
                path: p.clone(),
                item: i.clone(),
                left: None,
                right: Some(v.clone()),
            });
        }
    }
    Ok(out)
}

type Entry = (String, String, String);

/// The document as `(path, item, value)` entries.
/// `asset_names` are the hashes that name the assets (see [`asset_hashes`]).
pub fn describe(buf: &[u8], asset_names: Vec<u64>) -> Result<Vec<Entry>> {
    let types = datatree::read_types(buf)?;
    let root = datatree::root_slot_offset(buf)?;

    // Pass 1: what every defined id names.
    let mut slots: Vec<(usize, String)> = Vec::new();
    collect_slots(
        buf,
        root,
        datatree::read_string_field(buf, root, "Name")?.unwrap_or_default(),
        &mut slots,
    )?;
    let mut targets: HashMap<String, String> = HashMap::new();
    for (off, path) in &slots {
        for el in bson::elements(buf, *off)? {
            match (el.key, el.ty) {
                ("Children", _) | ("Components", _) => {}
                (k, STRING) if ids::is_id_key(k) => {
                    let s = bson::decode_string(el.value)?.to_string();
                    let at = if k == "ID" {
                        format!("slot {path}")
                    } else {
                        format!("slot {path} {k}")
                    };
                    targets.insert(s, at);
                }
                (k, DOCUMENT | ARRAY) => {
                    name_ids(buf, el.value_at, &format!("slot {path}"), k, &mut targets)?;
                }
                _ => {}
            }
        }
        for (i, c) in datatree::components_of_slot(buf, *off, &types)?
            .iter()
            .enumerate()
        {
            if let Some(data) = datatree::field(buf, c.offset, "Data")? {
                if data.ty == DOCUMENT {
                    let ctx = format!("component {path} #{i} {}", c.type_name);
                    name_ids(buf, data.value_at, &ctx, "", &mut targets)?;
                }
            }
        }
    }
    // An asset is named by its type, its URL when it has one, and a hash of
    // its values (a texture can be imported twice with other settings). Its
    // position in `Assets` does not matter, and identical copies share one
    // name.
    let mut next_hash = asset_names.into_iter();
    let mut raw_assets: Vec<(usize, String, Option<String>, u64)> = Vec::new();
    if let Some(arr) = datatree::asset_array(buf)? {
        if arr.ty == ARRAY {
            for el in bson::elements(buf, arr.value_at)?.iter() {
                if el.ty != DOCUMENT {
                    continue;
                }
                let type_name = match datatree::field(buf, el.value_at, "Type")? {
                    Some(t) if typetable::is_int(t.ty) => {
                        let ix = bson::decode_int(t.value, t.ty)?;
                        typetable::type_name(&types, ix).unwrap_or("?").to_string()
                    }
                    _ => "?".to_string(),
                };
                let url = first_url(buf, el.value_at)?;
                // `Type` is an index into this file's `Types`; the name is in
                // the description already, so only `Data` is hashed.
                let hash = next_hash.next().unwrap_or_default();
                raw_assets.push((el.value_at, type_name, url, hash));
            }
        }
    }
    let mut assets: Vec<(usize, String)> = Vec::new();
    for (off, t, url, hash) in &raw_assets {
        let ctx = match url {
            Some(u) => format!("asset {t} {u} {hash:016x}"),
            None => format!("asset {t} {hash:016x}"),
        };
        if let Some(data) = datatree::field(buf, *off, "Data")? {
            if data.ty == DOCUMENT {
                name_ids(buf, data.value_at, &ctx, "", &mut targets)?;
            }
        }
        assets.push((*off, ctx));
    }

    // Pass 2: entries.
    let mut d = Describer {
        buf,
        types: &types,
        targets: &targets,
        out: Vec::new(),
        referenced: HashSet::new(),
    };
    if let Some(el) = datatree::field(buf, 0, "VersionNumber")? {
        let v = d.scalar(&el, None)?;
        d.push("document", "VersionNumber", v);
    }
    for key in ["FeatureFlags", "TypeVersions"] {
        if let Some(el) = datatree::field(buf, 0, key)? {
            if el.ty == DOCUMENT {
                for f in bson::elements(buf, el.value_at)? {
                    let v = d.scalar(&f, None)?;
                    d.push("document", &format!("{key}.{}", f.key), v);
                }
            }
        }
    }
    for (off, path) in &slots {
        d.push(path, "slot", String::new());
        for el in bson::elements(buf, *off)? {
            match el.key {
                "Children" | "Components" => {}
                k if ids::is_id_key(k) && el.ty == STRING => {}
                _ => d.value(path, el.key, &el, None)?,
            }
        }
        for (i, c) in datatree::components_of_slot(buf, *off, &types)?
            .iter()
            .enumerate()
        {
            d.push(path, &format!("#{i} type"), c.type_name.clone());
            if let Some(data) = datatree::field(buf, c.offset, "Data")? {
                if data.ty == DOCUMENT {
                    for f in bson::elements(buf, data.value_at)? {
                        if ids::is_id_key(f.key) && f.ty == STRING {
                            continue;
                        }
                        d.value(path, &format!("#{i} {}", f.key), &f, Some(&c.type_name))?;
                    }
                }
            }
        }
    }
    // Referenced assets, described by their content.
    let mut asset_entries = Vec::new();
    let mut described: HashSet<&str> = HashSet::new();
    for (off, ctx) in &assets {
        if described.contains(ctx.as_str()) {
            continue;
        }
        if !d.referenced.iter().any(|t| {
            t == ctx
                || t.strip_prefix(ctx.as_str())
                    .is_some_and(|r| r.starts_with(' '))
        }) {
            continue;
        }
        let mut sub = Describer {
            buf,
            types: &types,
            targets: &targets,
            out: Vec::new(),
            referenced: HashSet::new(),
        };
        if let Some(data) = datatree::field(buf, *off, "Data")? {
            if data.ty == DOCUMENT {
                for f in bson::elements(buf, data.value_at)? {
                    if ids::is_id_key(f.key) && f.ty == STRING {
                        continue;
                    }
                    sub.value(ctx, f.key, &f, None)?;
                }
            }
        }
        described.insert(ctx.as_str());
        asset_entries.extend(sub.out);
    }
    d.out.extend(asset_entries);
    Ok(d.out)
}

fn collect_slots(
    buf: &[u8],
    off: usize,
    path: String,
    out: &mut Vec<(usize, String)>,
) -> Result<()> {
    let children = datatree::child_slot_offsets(buf, off)?;
    out.push((off, path.clone()));
    for (i, c) in children.into_iter().enumerate() {
        let name = datatree::read_string_field(buf, c, "Name")?.unwrap_or_default();
        collect_slots(buf, c, format!("{path}/{i}:{name}"), out)?;
    }
    Ok(())
}

/// Record what each id under the document at `off` names. `rel` is the key
/// path of that document inside `ctx`.
fn name_ids(
    buf: &[u8],
    off: usize,
    ctx: &str,
    rel: &str,
    targets: &mut HashMap<String, String>,
) -> Result<()> {
    for el in bson::elements(buf, off)? {
        let here = if rel.is_empty() {
            el.key.to_string()
        } else {
            format!("{rel}.{}", el.key)
        };
        match el.ty {
            STRING if ids::is_id_key(el.key) => {
                let s = bson::decode_string(el.value)?.to_string();
                let at = match (el.key, rel.is_empty()) {
                    ("ID", true) => ctx.to_string(),
                    ("ID", false) => format!("{ctx} {rel}"),
                    _ => format!("{ctx} {here}"),
                };
                targets.insert(s, at);
            }
            DOCUMENT | ARRAY => name_ids(buf, el.value_at, ctx, &here, targets)?,
            _ => {}
        }
    }
    Ok(())
}

/// One hash per document entry of `Assets`, in order, for naming assets.
///
/// Round 0 hashes each asset's own `Data` values (ids left out). Each further
/// round hashes them again with every id that names an asset replaced by that
/// asset's hash from the round before, so two identical-looking assets that
/// point (directly or further down a chain) at different assets get different
/// hashes. With `rounds` = `None` it stops once a round tells no more assets
/// apart than the one before (at least one round; at most one per asset) and
/// returns how many rounds that took; give the larger count of two documents
/// to hash both alike.
pub fn asset_hashes(buf: &[u8], rounds: Option<usize>) -> Result<(Vec<u64>, usize)> {
    // (ids the entry defines, its `Data` offset)
    let mut entries: Vec<(Vec<&str>, Option<usize>)> = Vec::new();
    if let Some(arr) = datatree::asset_array(buf)? {
        if arr.ty == ARRAY {
            for el in bson::elements(buf, arr.value_at)? {
                if el.ty != DOCUMENT {
                    continue;
                }
                let mut ids_here = Vec::new();
                ids::visit_defined(buf, el.value_at, &mut |id| ids_here.push(id))?;
                let data = datatree::field(buf, el.value_at, "Data")?
                    .filter(|d| d.ty == DOCUMENT)
                    .map(|d| d.value_at);
                entries.push((ids_here, data));
            }
        }
    }
    let round = |linked: &HashMap<&str, u64>| -> Result<Vec<u64>> {
        entries
            .iter()
            .map(|(_, data)| match data {
                Some(off) => content_hash(buf, *off, linked),
                None => Ok(0),
            })
            .collect()
    };
    let link = |hashes: &[u64]| -> HashMap<&str, u64> {
        let mut map = HashMap::new();
        for ((ids_here, _), h) in entries.iter().zip(hashes) {
            for id in ids_here {
                map.entry(*id).or_insert(*h);
            }
        }
        map
    };
    let distinct = |hashes: &[u64]| hashes.iter().collect::<HashSet<_>>().len();

    let mut hashes = round(&HashMap::new())?;
    let limit = rounds.unwrap_or(entries.len().max(1));
    let mut done = 0;
    while done < limit {
        let next = round(&link(&hashes))?;
        let settled = done >= 1 && distinct(&next) == distinct(&hashes);
        if rounds.is_none() && settled {
            break;
        }
        hashes = next;
        done += 1;
    }
    Ok((hashes, done))
}

/// FNV-1a over an asset's keys and values, numbers by value as in
/// [`describe`]. Ids are left out. A string that looks like an id
/// (a reference) counts as the hash `linked` gives it, or is left out.
fn content_hash(buf: &[u8], off: usize, linked: &HashMap<&str, u64>) -> Result<u64> {
    fn eat(bytes: &[u8], h: &mut u64) {
        for b in bytes {
            *h ^= u64::from(*b);
            *h = h.wrapping_mul(0x0100_0000_01b3);
        }
    }
    fn walk(buf: &[u8], off: usize, linked: &HashMap<&str, u64>, h: &mut u64) -> Result<()> {
        for el in bson::elements(buf, off)? {
            let v = match el.ty {
                STRING => {
                    let s = bson::decode_string(el.value)?;
                    if ids::is_id_key(el.key) {
                        continue;
                    }
                    if looks_like_guid(s) {
                        // An id: what it names, when that is another asset.
                        match linked.get(s) {
                            Some(other) => format!("asset {other:016x}"),
                            None => continue,
                        }
                    } else {
                        format!("{s:?}")
                    }
                }
                DOCUMENT | ARRAY => {
                    eat(el.key.as_bytes(), h);
                    eat(b"{", h);
                    walk(buf, el.value_at, linked, h)?;
                    eat(b"}", h);
                    continue;
                }
                _ => number_or_raw(&el)?,
            };
            eat(el.key.as_bytes(), h);
            eat(b"=", h);
            eat(v.as_bytes(), h);
            eat(b";", h);
        }
        Ok(())
    }
    let mut h = 0xcbf2_9ce4_8422_2325u64;
    walk(buf, off, linked, &mut h)?;
    Ok(h)
}

/// A non-string scalar as [`describe`] writes it.
fn number_or_raw(el: &Element<'_>) -> Result<String> {
    Ok(match el.ty {
        DOUBLE => {
            let f = bson::decode_f64(el.value)?;
            // An integral double reads like the same integer: 0.0 and an
            // int32 0 are one value.
            if f.fract() == 0.0
                && f.abs() < 9_007_199_254_740_992.0
                && !(f == 0.0 && f.is_sign_negative())
            {
                format!("{}", f as i64)
            } else {
                format!("{f:?}")
            }
        }
        BOOL => bson::decode_bool(el.value)?.to_string(),
        NULL => "null".to_string(),
        t if typetable::is_int(t) => bson::decode_int(el.value, t)?.to_string(),
        BINARY => {
            let mut h = 0xcbf2_9ce4_8422_2325u64;
            for b in el.value {
                h ^= u64::from(*b);
                h = h.wrapping_mul(0x0100_0000_01b3);
            }
            format!("binary {} bytes {h:016x}", el.value.len())
        }
        t => {
            let mut s = format!("bson {t:#04x} ");
            for b in el.value {
                let _ = write!(s, "{b:02x}");
            }
            s
        }
    })
}

fn first_url(buf: &[u8], off: usize) -> Result<Option<String>> {
    for el in bson::elements(buf, off)? {
        match el.ty {
            STRING => {
                let s = bson::decode_string(el.value)?;
                if s.contains("://") {
                    return Ok(Some(s.to_string()));
                }
            }
            DOCUMENT | ARRAY => {
                if let Some(u) = first_url(buf, el.value_at)? {
                    return Ok(Some(u));
                }
            }
            _ => {}
        }
    }
    Ok(None)
}

struct Describer<'a> {
    buf: &'a [u8],
    types: &'a [String],
    targets: &'a HashMap<String, String>,
    out: Vec<Entry>,
    referenced: HashSet<String>,
}

impl Describer<'_> {
    fn push(&mut self, path: &str, item: &str, value: String) {
        self.out.push((path.to_string(), item.to_string(), value));
    }

    /// Describe `el` under `item`. A `{ID, Data}` wrapper reads as its `Data`;
    /// other documents and arrays are described key by key.
    fn value(
        &mut self,
        path: &str,
        item: &str,
        el: &Element<'_>,
        component: Option<&str>,
    ) -> Result<()> {
        match el.ty {
            DOCUMENT | ARRAY => {
                let els = bson::elements(self.buf, el.value_at)?;
                let wrapper = el.ty == DOCUMENT
                    && els.iter().any(|e| e.key == "ID" && e.ty == STRING)
                    && els.iter().any(|e| e.key == "Data");
                if wrapper {
                    let data = els.iter().find(|e| e.key == "Data").copied();
                    let field = item.rsplit(' ').next().unwrap_or(item);
                    let field = field.rsplit('.').next().unwrap_or(field);
                    let type_field = component
                        .map(|c| typetable::is_type_field(c, field))
                        .unwrap_or(false);
                    if let Some(data) = data {
                        if type_field && typetable::is_int(data.ty) {
                            let ix = bson::decode_int(data.value, data.ty)?;
                            let name = typetable::type_name(self.types, ix).unwrap_or("?");
                            self.push(path, item, format!("type {name}"));
                        } else {
                            self.value(path, item, &data, component)?;
                        }
                    }
                    for other in els.iter().filter(|e| e.key != "ID" && e.key != "Data") {
                        self.value(path, &format!("{item}.{}", other.key), other, component)?;
                    }
                    return Ok(());
                }
                if els.is_empty() {
                    self.push(
                        path,
                        item,
                        if el.ty == ARRAY { "[]" } else { "{}" }.to_string(),
                    );
                }
                for e in &els {
                    if ids::is_id_key(e.key) && e.ty == STRING {
                        continue;
                    }
                    self.value(path, &format!("{item}.{}", e.key), e, component)?;
                }
                Ok(())
            }
            _ => {
                let v = self.scalar(el, component)?;
                self.push(path, item, v);
                Ok(())
            }
        }
    }

    fn scalar(&mut self, el: &Element<'_>, _component: Option<&str>) -> Result<String> {
        Ok(match el.ty {
            STRING => {
                let s = bson::decode_string(el.value)?;
                match self.targets.get(s) {
                    Some(t) => {
                        self.referenced.insert(t.clone());
                        format!("→ {t}")
                    }
                    None if looks_like_guid(s) => "→ (id not in this file)".to_string(),
                    None => format!("{s:?}"),
                }
            }
            _ => number_or_raw(el)?,
        })
    }
}

fn looks_like_guid(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() == 36
        && b.iter().enumerate().all(|(i, c)| match i {
            8 | 13 | 18 | 23 => *c == b'-',
            _ => c.is_ascii_hexdigit(),
        })
}