frdt 0.2.2

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
//! Field-name view of a DataTree BSON document.
//!
//! Layout follows the Resonite wiki: `Components` is `UniquePtr(Array(IComponent))`,
//! `Children` is `Array(Slot)`, and a `WorldElementRef` is a document `{ID, Data}`.
//! Readers look up fields by name and skip the rest, so a later real file only
//! has to change this module when a name or a wrapper differs.

use crate::bson::{self, Element, ARRAY, DOCUMENT, STRING};
use crate::error::{Error, Result};
use crate::value::{Float3, FloatQ, Value};

pub const TYPE_VALUE_VAR: &str = "DynamicValueVariable";
pub const TYPE_REF_VAR: &str = "DynamicReferenceVariable";
pub const TYPE_VAR_SPACE: &str = "DynamicVariableSpace";

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotLoc {
    /// Identity that stays with this slot when its BSON `ID` changes.
    /// Not stored in the work file; assigned when the index is built.
    pub key: u64,
    pub offset: usize,
    pub end: usize,
    pub id: String,
    pub parent_ref: Option<String>,
    pub name: String,
    /// Offset of the `Children` array document, when present.
    pub children_array: Option<usize>,
    /// Length-prefix offsets of this slot and every document or array around it,
    /// innermost last. Used to patch sizes after an edit inside the slot.
    pub container_lengths: Vec<usize>,
}

#[derive(Debug, Clone)]
pub struct ComponentView {
    pub offset: usize,
    pub type_index: i64,
    pub type_name: String,
    /// Target ids stored in `WorldElementRef.Data` under this component.
    pub references: Vec<String>,
}

pub fn field<'a>(buf: &'a [u8], doc_off: usize, name: &str) -> Result<Option<Element<'a>>> {
    Ok(bson::elements(buf, doc_off)?
        .into_iter()
        .find(|e| e.key == name))
}

pub fn root_slot_offset(buf: &[u8]) -> Result<usize> {
    let object =
        field(buf, 0, "Object")?.ok_or_else(|| Error::Invalid("root has no Object".into()))?;
    if object.ty != DOCUMENT {
        return Err(Error::Invalid("Object is not a document".into()));
    }
    Ok(object.value_at)
}

pub fn read_types(buf: &[u8]) -> Result<Vec<String>> {
    let Some(types) = field(buf, 0, "Types")? else {
        return Ok(Vec::new());
    };
    if types.ty != ARRAY {
        return Err(Error::Invalid("Types is not an array".into()));
    }
    let mut out = Vec::new();
    for el in bson::elements(buf, types.value_at)? {
        if el.ty != STRING {
            return Err(Error::Invalid("Types entry is not a string".into()));
        }
        out.push(bson::decode_string(el.value)?.to_string());
    }
    Ok(out)
}

pub fn read_string_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<String>> {
    let Some(el) = field(buf, doc_off, name)? else {
        return Ok(None);
    };
    read_string_value(buf, &el, name)
}

fn read_string_value(buf: &[u8], el: &Element<'_>, name: &str) -> Result<Option<String>> {
    if let Some(data) = sync_data(buf, el)? {
        return read_string_value(buf, &data, name);
    }
    match el.ty {
        STRING => Ok(Some(bson::decode_string(el.value)?.to_string())),
        bson::NULL => Ok(None),
        _ => Err(Error::Invalid(format!("{name} is not a string"))),
    }
}

/// `Sync<T>` and `UniquePtr<T>` are `{ID, Data}`. A plain value has no `ID`.
fn sync_data<'a>(buf: &'a [u8], el: &Element<'a>) -> Result<Option<Element<'a>>> {
    if el.ty != DOCUMENT {
        return Ok(None);
    }
    let els = bson::elements(buf, el.value_at)?;
    if !els.iter().any(|e| e.key == "ID") {
        return Ok(None);
    }
    Ok(els.into_iter().find(|e| e.key == "Data"))
}

pub fn read_slot(buf: &[u8], offset: usize, container_lengths: Vec<usize>) -> Result<SlotLoc> {
    let end = bson::doc_end(buf, offset)?;
    let id = read_string_field(buf, offset, "ID")?.unwrap_or_default();
    let parent_ref = read_string_field(buf, offset, "ParentReference")?;
    let name = read_string_field(buf, offset, "Name")?.unwrap_or_default();
    let children_array = match field(buf, offset, "Children")? {
        Some(el) if el.ty == ARRAY => Some(el.value_at),
        Some(_) => return Err(Error::Invalid("Children is not an array".into())),
        None => None,
    };
    Ok(SlotLoc {
        key: 0,
        offset,
        end,
        id,
        parent_ref,
        name,
        children_array,
        container_lengths,
    })
}

pub fn child_slot_offsets(buf: &[u8], slot_off: usize) -> Result<Vec<usize>> {
    let Some(children) = field(buf, slot_off, "Children")? else {
        return Ok(Vec::new());
    };
    if children.ty != ARRAY {
        return Err(Error::Invalid("Children is not an array".into()));
    }
    let mut out = Vec::new();
    for el in bson::elements(buf, children.value_at)? {
        if el.ty != DOCUMENT {
            return Err(Error::Invalid(
                "Children entry is not a slot document".into(),
            ));
        }
        out.push(el.value_at);
    }
    Ok(out)
}

/// Depth-first slots. `outer` holds length offsets of documents that contain this slot.
pub fn walk_slots(
    buf: &[u8],
    slot_off: usize,
    outer: &[usize],
    out: &mut Vec<SlotLoc>,
) -> Result<()> {
    let mut chain = outer.to_vec();
    chain.push(slot_off);
    let slot = read_slot(buf, slot_off, chain.clone())?;
    let children_array = slot.children_array;
    out.push(slot);
    if let Some(arr) = children_array {
        let mut child_outer = chain;
        child_outer.push(arr);
        for child in child_slot_offsets(buf, slot_off)? {
            walk_slots(buf, child, &child_outer, out)?;
        }
    }
    Ok(())
}

pub fn all_slots(buf: &[u8]) -> Result<Vec<SlotLoc>> {
    let root = root_slot_offset(buf)?;
    let mut out = Vec::new();
    // The root document at offset 0 contains Object.
    walk_slots(buf, root, &[0], &mut out)?;
    Ok(out)
}

pub fn find_slot_by_id(buf: &[u8], id: &str) -> Result<Option<SlotLoc>> {
    Ok(all_slots(buf)?.into_iter().find(|s| s.id == id))
}

pub fn components_of_slot(
    buf: &[u8],
    slot_off: usize,
    types: &[String],
) -> Result<Vec<ComponentView>> {
    let Some(comps) = field(buf, slot_off, "Components")? else {
        return Ok(Vec::new());
    };
    if comps.ty != DOCUMENT {
        return Err(Error::Invalid(
            "Components is not a UniquePtr document".into(),
        ));
    }
    let Some(data) = field(buf, comps.value_at, "Data")? else {
        return Ok(Vec::new());
    };
    if data.ty != ARRAY {
        return Err(Error::Invalid("Components.Data is not an array".into()));
    }
    let mut out = Vec::new();
    for el in bson::elements(buf, data.value_at)? {
        if el.ty != DOCUMENT {
            return Err(Error::Invalid("component is not a document".into()));
        }
        let type_index = match field(buf, el.value_at, "Type")? {
            Some(t) => bson::decode_int(t.value, t.ty)?,
            None => return Err(Error::Invalid("component has no Type".into())),
        };
        let type_name = types
            .get(usize::try_from(type_index).unwrap_or(usize::MAX))
            .cloned()
            .unwrap_or_default();
        let mut references = Vec::new();
        if let Some(body) = field(buf, el.value_at, "Data")? {
            if body.ty == DOCUMENT || body.ty == ARRAY {
                collect_ref_targets(buf, body.value_at, &mut references)?;
            }
        }
        out.push(ComponentView {
            offset: el.value_at,
            type_index,
            type_name,
            references,
        });
    }
    Ok(out)
}

fn collect_ref_targets(buf: &[u8], doc_off: usize, out: &mut Vec<String>) -> Result<()> {
    let elems = bson::elements(buf, doc_off)?;
    let has_id = elems.iter().any(|e| e.key == "ID");
    if has_id {
        if let Some(data) = elems.iter().find(|e| e.key == "Data") {
            if data.ty == STRING {
                out.push(bson::decode_string(data.value)?.to_string());
            }
        }
    }
    for el in &elems {
        if el.ty == DOCUMENT || el.ty == ARRAY {
            collect_ref_targets(buf, el.value_at, out)?;
        }
    }
    Ok(())
}

pub fn collect_ids(buf: &[u8], doc_off: usize, out: &mut Vec<String>) -> Result<()> {
    for el in bson::elements(buf, doc_off)? {
        if el.key == "ID" && el.ty == STRING {
            out.push(bson::decode_string(el.value)?.to_string());
        }
        if el.ty == DOCUMENT || el.ty == ARRAY {
            collect_ids(buf, el.value_at, out)?;
        }
    }
    Ok(())
}

pub fn document_ids(buf: &[u8]) -> Result<Vec<String>> {
    let mut out = Vec::new();
    collect_ids(buf, 0, &mut out)?;
    Ok(out)
}

pub fn read_slot_value(buf: &[u8], slot_off: usize, name: &str) -> Result<Value> {
    let el = field(buf, slot_off, name)?.ok_or_else(|| Error::FieldNotFound(name.to_string()))?;
    decode_slot_value(buf, &el)
}

/// Like [`decode_slot_value`], but a null value (wrapped or not) is `None`.
pub fn decode_optional_value(buf: &[u8], el: &Element<'_>) -> Result<Option<Value>> {
    if let Some(data) = sync_data(buf, el)? {
        return decode_optional_value(buf, &data);
    }
    if el.ty == bson::NULL {
        return Ok(None);
    }
    decode_slot_value(buf, el).map(Some)
}

pub fn decode_slot_value(buf: &[u8], el: &Element<'_>) -> Result<Value> {
    if let Some(data) = sync_data(buf, el)? {
        return decode_slot_value(buf, &data);
    }
    match el.ty {
        bson::DOUBLE => Ok(Value::F64(bson::decode_f64(el.value)?)),
        bson::INT64 => Ok(Value::I64(bson::decode_i64(el.value)?)),
        bson::INT32 => Ok(Value::I64(i64::from(bson::decode_i32(el.value)?))),
        bson::BOOL => Ok(Value::Bool(bson::decode_bool(el.value)?)),
        STRING => Ok(Value::String(bson::decode_string(el.value)?.to_string())),
        DOCUMENT => {
            if let Ok(q) = bson::decode_floatq(el.value) {
                return Ok(Value::FloatQ(q));
            }
            if let Ok(v) = bson::decode_float3(el.value) {
                return Ok(Value::Float3(v));
            }
            Err(Error::Invalid(format!(
                "cannot read field {} as a value",
                el.key
            )))
        }
        ARRAY => decode_float_array(buf, el.value_at)
            .ok_or_else(|| Error::Invalid(format!("cannot read field {} as a value", el.key))),
        _ => Err(Error::Invalid(format!(
            "cannot read field {} as a value",
            el.key
        ))),
    }
}

/// Real files store `float3` and `floatQ` as a BSON array of doubles.
fn decode_float_array(buf: &[u8], array_off: usize) -> Option<Value> {
    let els = bson::elements(buf, array_off).ok()?;
    let mut nums = Vec::with_capacity(els.len());
    for el in els {
        if el.ty != bson::DOUBLE {
            return None;
        }
        nums.push(bson::decode_f64(el.value).ok()?);
    }
    match nums.as_slice() {
        [x, y, z] => Some(Value::Float3(Float3 {
            x: *x,
            y: *y,
            z: *z,
        })),
        [x, y, z, w] => Some(Value::FloatQ(FloatQ {
            x: *x,
            y: *y,
            z: *z,
            w: *w,
        })),
        _ => None,
    }
}

pub fn read_number_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<i64>> {
    let Some(el) = field(buf, doc_off, name)? else {
        return Ok(None);
    };
    Ok(Some(bson::decode_int(el.value, el.ty)?))
}

pub fn read_bool_field(buf: &[u8], doc_off: usize, name: &str) -> Result<Option<bool>> {
    let Some(el) = field(buf, doc_off, name)? else {
        return Ok(None);
    };
    match el.ty {
        bson::BOOL => Ok(Some(bson::decode_bool(el.value)?)),
        bson::INT32 | bson::INT64 => Ok(Some(bson::decode_int(el.value, el.ty)? != 0)),
        _ => Err(Error::Invalid(format!("{name} is not a bool"))),
    }
}

pub fn asset_views(buf: &[u8]) -> Result<Vec<(String, Option<i64>)>> {
    let Some(asset) = asset_array(buf)? else {
        return Ok(Vec::new());
    };
    if asset.ty != ARRAY {
        return Err(Error::Invalid("Assets is not an array".into()));
    }
    let mut out = Vec::new();
    for el in bson::elements(buf, asset.value_at)? {
        if el.ty != DOCUMENT {
            return Err(Error::Invalid("Assets entry is not a document".into()));
        }
        let id = asset_id(buf, el.value_at)?;
        let type_index = match field(buf, el.value_at, "Type")? {
            Some(t) => Some(bson::decode_int(t.value, t.ty)?),
            None => None,
        };
        out.push((id, type_index));
    }
    Ok(out)
}

/// Synthetic fixtures use `Asset`. Resonite writes `Assets`.
pub fn asset_array(buf: &[u8]) -> Result<Option<Element<'_>>> {
    if let Some(assets) = field(buf, 0, "Assets")? {
        return Ok(Some(assets));
    }
    field(buf, 0, "Asset")
}

pub fn asset_id(buf: &[u8], doc_off: usize) -> Result<String> {
    if let Some(id) = read_string_field(buf, doc_off, "ID")? {
        if !id.is_empty() {
            return Ok(id);
        }
    }
    let Some(data) = field(buf, doc_off, "Data")? else {
        return Ok(String::new());
    };
    if data.ty != DOCUMENT {
        return Ok(String::new());
    }
    Ok(read_string_field(buf, data.value_at, "ID")?.unwrap_or_default())
}

pub fn is_dyn_type(type_name: &str) -> Option<DynKind> {
    if type_name.contains(TYPE_VALUE_VAR) {
        Some(DynKind::Value)
    } else if type_name.contains(TYPE_REF_VAR) {
        Some(DynKind::Reference)
    } else if type_name.contains(TYPE_VAR_SPACE) {
        Some(DynKind::Space)
    } else {
        None
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DynKind {
    Value,
    Reference,
    Space,
}

/// Interpret a small document as float3, floatQ, or the `Data` of a `{ID, Data}` wrapper.
pub fn interpret_dyn_fields(fields: &[(String, crate::value::DynValue)]) -> crate::value::DynValue {
    use crate::value::DynValue;
    let has_id = fields.iter().any(|(k, _)| k == "ID");
    if has_id {
        if let Some((_, data)) = fields.iter().find(|(k, _)| k == "Data") {
            return data.clone();
        }
    }
    let num = |name: &str| -> Option<f64> {
        fields
            .iter()
            .find(|(k, _)| k == name)
            .and_then(|(_, v)| v.as_f64())
    };
    if let (Some(x), Some(y), Some(z), Some(w)) = (num("x"), num("y"), num("z"), num("w")) {
        return DynValue::FloatQ(FloatQ { x, y, z, w });
    }
    if let (Some(x), Some(y), Some(z)) = (num("x"), num("y"), num("z")) {
        return DynValue::Float3(Float3 { x, y, z });
    }
    DynValue::Null
}