frdt 0.2.4

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
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! Wiki-shaped documents for the v1 tests.
//!
//! Field nesting is the Resonite wiki's: `Components` is `{ID, Data: [component]}`,
//! `Children` is an array of slots, and a reference is `{ID, Data}`.

use crate::bson::DocBuf;
use crate::container;

pub const AVATAR_ROOT: &str = "[FrooxEngine]FrooxEngine.AvatarRoot";
pub const HEAD_MARKER: &str = "[FrooxEngine]FrooxEngine.HeadMarker";
pub const SPINNER: &str = "[FrooxEngine]FrooxEngine.Spinner";
pub const VALUE_VAR: &str = "[FrooxEngine]FrooxEngine.DynamicValueVariable<float>";
pub const REF_VAR: &str = "[FrooxEngine]FrooxEngine.DynamicReferenceVariable<Slot>";
pub const VAR_SPACE: &str = "[FrooxEngine]FrooxEngine.DynamicVariableSpace";
pub const VALUE_FLOAT3: &str = "[FrooxEngine]FrooxEngine.DynamicValueVariable<float3>";

pub const ID_AV_ROOT: &str = "av-root";
pub const ID_AV_HEAD: &str = "av-head";
pub const ID_HAT_ROOT: &str = "hat-root";
pub const ID_HAT_CHILD: &str = "hat-child";
pub const ID_REF: &str = "ref-1";
pub const ID_ASSET: &str = "asset-1";

pub fn asset_payload() -> Vec<u8> {
    vec![0xAB; 64]
}

pub fn avatar_bson() -> Vec<u8> {
    let head = slot(ID_AV_HEAD, "Head", ID_AV_ROOT, &[], &[], (1.0, 1.0, 1.0));
    let root = slot(ID_AV_ROOT, "Root", "", &[], &[head], (1.0, 1.0, 1.0));
    document(
        1,
        &[("ColorManagement", true)],
        &[AVATAR_ROOT, HEAD_MARKER],
        &[(AVATAR_ROOT, 1)],
        &root,
        &[],
    )
}

pub fn hat_bson() -> Vec<u8> {
    let mut data = DocBuf::new();
    data.doc("Link", &world_ref(ID_REF, ID_HAT_CHILD));
    data.string("Label", "not-an-id");
    let comp = component(0, &data.finish());
    let bobble = slot(
        ID_HAT_CHILD,
        "Bobble",
        ID_HAT_ROOT,
        &[],
        &[],
        (1.0, 1.0, 1.0),
    );
    let root = slot(ID_HAT_ROOT, "Hat", "", &[comp], &[bobble], (1.0, 1.0, 1.0));
    let mut asset = DocBuf::new();
    asset.string("ID", ID_ASSET);
    asset.int32("Type", 0);
    asset.binary("Payload", 0, &asset_payload());
    asset.string("Note", "keep-me");
    document(
        1,
        &[("ColorManagement", false), ("ProtoFlux", true)],
        &[SPINNER],
        &[(SPINNER, 3), (AVATAR_ROOT, 9)],
        &root,
        &[asset.finish()],
    )
}

/// Avatar that already lists `Spinner`, so a graft must reuse that index.
pub fn avatar_with_spinner_bson() -> Vec<u8> {
    let head = slot(ID_AV_HEAD, "Head", ID_AV_ROOT, &[], &[], (1.0, 1.0, 1.0));
    let root = slot(ID_AV_ROOT, "Root", "", &[], &[head], (1.0, 1.0, 1.0));
    document(
        1,
        &[("ColorManagement", true)],
        &[AVATAR_ROOT, SPINNER],
        &[(AVATAR_ROOT, 1), (SPINNER, 4)],
        &root,
        &[],
    )
}

pub fn counts_bson() -> Vec<u8> {
    let grand = slot(
        "grand",
        "Grand",
        "child-a",
        &[component(0, &DocBuf::new().finish())],
        &[],
        (1.0, 1.0, 1.0),
    );
    let child_a = slot("child-a", "ChildA", "root", &[], &[grand], (1.0, 1.0, 1.0));
    let child_b = slot("child-b", "ChildB", "root", &[], &[], (1.0, 1.0, 1.0));
    let root = slot(
        "root",
        "Root",
        "",
        &[
            component(0, &DocBuf::new().finish()),
            component(0, &DocBuf::new().finish()),
        ],
        &[child_a, child_b],
        (1.0, 1.0, 1.0),
    );
    let mut doc = DocBuf::new();
    doc.int32("VersionNumber", 1);
    doc.array("Types", &crate::bson::array_of_strings(&[HEAD_MARKER]));
    doc.doc("Object", &root);
    doc.array("Asset", &crate::bson::array_of_docs(&[]));
    // A large field the streaming walk must discard rather than store.
    doc.binary("Padding", 0, &vec![0x11; 64 * 1024]);
    doc.finish()
}

pub fn dynvar_bson() -> Vec<u8> {
    let mut raw = DocBuf::new();
    raw.string("VariableName", "User/Color");
    raw.double("Value", f64::INFINITY);
    let mut wrapped_ref = DocBuf::new();
    wrapped_ref.doc("VariableName", &sync_string("wrap-name", "User/Slot"));
    wrapped_ref.doc("Reference", &sync_string("wrap-ref", ID_AV_ROOT));
    let mut space = DocBuf::new();
    space.string("SpaceName", "User");
    let mut ignored = DocBuf::new();
    ignored.string("VariableName", "should-not-appear");
    ignored.string("Value", "x");
    let mut wrapped_float = DocBuf::new();
    wrapped_float.string("VariableName", "User/Scale");
    let mut sync_float = DocBuf::new();
    sync_float.string("ID", "wrap-float");
    sync_float.doc("Data", &float3_doc(2.0, 3.0, 4.0));
    wrapped_float.doc("Value", &sync_float.finish());

    let comps = [
        component(0, &raw.finish()),
        component(1, &wrapped_ref.finish()),
        component(2, &space.finish()),
        component(3, &ignored.finish()),
        component(4, &wrapped_float.finish()),
    ];
    let root = slot("dyn-root", "Root", "", &comps, &[], (1.0, 1.0, 1.0));
    document(
        1,
        &[],
        &[VALUE_VAR, REF_VAR, VAR_SPACE, SPINNER, VALUE_FLOAT3],
        &[],
        &root,
        &[],
    )
}

/// Two children share one slot id. `append` must not collapse their handle keys.
pub fn duplicate_child_ids_bson() -> Vec<u8> {
    let a = slot("dup", "A", "root", &[], &[], (1.0, 1.0, 1.0));
    let b = slot("dup", "B", "root", &[], &[], (1.0, 1.0, 1.0));
    let root = slot("root", "Root", "", &[], &[a, b], (1.0, 1.0, 1.0));
    document(1, &[], &[AVATAR_ROOT], &[], &root, &[])
}

pub fn nonfinite_bson() -> Vec<u8> {
    let root = slot(
        "nf-root",
        "Root",
        "",
        &[],
        &[],
        (f64::INFINITY, f64::NEG_INFINITY, f64::NAN),
    );
    document(1, &[], &[AVATAR_ROOT], &[], &root, &[])
}

pub fn avatar_brson() -> Vec<u8> {
    wrap(&avatar_bson())
}
pub fn hat_brson() -> Vec<u8> {
    wrap(&hat_bson())
}
pub fn avatar_with_spinner_brson() -> Vec<u8> {
    wrap(&avatar_with_spinner_bson())
}
pub fn counts_brson() -> Vec<u8> {
    wrap(&counts_bson())
}
pub fn dynvar_brson() -> Vec<u8> {
    wrap(&dynvar_bson())
}
pub fn nonfinite_brson() -> Vec<u8> {
    wrap(&nonfinite_bson())
}
pub fn duplicate_child_ids_brson() -> Vec<u8> {
    wrap(&duplicate_child_ids_bson())
}

fn wrap(bson: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    container::write_brson(bson, &mut out, 5).expect("fixture compress");
    out
}

fn document(
    version: i32,
    flags: &[(&str, bool)],
    types: &[&str],
    versions: &[(&str, i32)],
    object: &[u8],
    assets: &[Vec<u8>],
) -> Vec<u8> {
    let mut flags_doc = DocBuf::new();
    for (name, value) in flags {
        flags_doc.bool(name, *value);
    }
    let mut versions_doc = DocBuf::new();
    for (name, value) in versions {
        versions_doc.int32(name, *value);
    }
    let mut doc = DocBuf::new();
    doc.int32("VersionNumber", version);
    doc.doc("FeatureFlags", &flags_doc.finish());
    doc.array("Types", &crate::bson::array_of_strings(types));
    doc.doc("TypeVersions", &versions_doc.finish());
    doc.doc("Object", object);
    doc.array("Asset", &crate::bson::array_of_docs(assets));
    doc.finish()
}

fn slot(
    id: &str,
    name: &str,
    parent: &str,
    components: &[Vec<u8>],
    children: &[Vec<u8>],
    scale: (f64, f64, f64),
) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.string("ID", id);
    doc.doc(
        "Components",
        &unique_ptr(&format!("{id}-comps"), components),
    );
    doc.string("ParentReference", parent);
    doc.array("Children", &crate::bson::array_of_docs(children));
    doc.string("Name", name);
    doc.string("Tag", "");
    doc.doc("Position", &float3_doc(0.0, 0.0, 0.0));
    doc.doc("Rotation", &floatq_doc(0.0, 0.0, 0.0, 1.0));
    doc.doc("Scale", &float3_doc(scale.0, scale.1, scale.2));
    doc.int64("OrderOffset", 0);
    doc.finish()
}

fn component(type_index: i32, data: &[u8]) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.int32("Type", type_index);
    doc.doc("Data", data);
    doc.finish()
}

fn unique_ptr(id: &str, items: &[Vec<u8>]) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.string("ID", id);
    doc.array("Data", &crate::bson::array_of_docs(items));
    doc.finish()
}

fn world_ref(id: &str, target: &str) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.string("ID", id);
    doc.string("Data", target);
    doc.finish()
}

fn sync_string(id: &str, value: &str) -> Vec<u8> {
    world_ref(id, value)
}

fn float3_doc(x: f64, y: f64, z: f64) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.double("x", x);
    doc.double("y", y);
    doc.double("z", z);
    doc.finish()
}

fn floatq_doc(x: f64, y: f64, z: f64, w: f64) -> Vec<u8> {
    let mut doc = DocBuf::new();
    doc.double("x", x);
    doc.double("y", y);
    doc.double("z", z);
    doc.double("w", w);
    doc.finish()
}

// ---------------------------------------------------------------------------
// A MirageX unit in the layout Resonite writes: `{ID, Data}` fields,
// `Persistent-ID` on slots, `persistent-ID` on components, double arrays for
// `float3` / `floatQ`, and `Assets` whose id sits in `Data.ID`.
//
// ```text
// Pkg/Unit                    DynamicVariableSpace
// ├─ DV                       DynamicReferenceVariable<Slot> Static.Ref -> Ref
// └─ Ref                      DynamicVariableSpace
//    ├─ Main                  MeshRenderer, Button, GizmoLink, ReferenceField
//    │  └─ Content            ProtoFlux node with InputType
//    ├─ Extra                 ValueField<string>
//    ├─ DV/Static             Static.Root, Static.Main, Static.ChildrenParent
//    └─ DV/Props              DynamicField<string> Props.Label -> Extra's Value
// Assets: mesh (used), material (used, -> texture), texture, unused
// ```

pub const UNIT_SPACE: &str = "[FrooxEngine]FrooxEngine.DynamicVariableSpace";
pub const UNIT_REF_VAR: &str =
    "[FrooxEngine]FrooxEngine.DynamicReferenceVariable<[FrooxEngine]FrooxEngine.Slot>";
pub const UNIT_RENDERER: &str = "[FrooxEngine]FrooxEngine.MeshRenderer";
pub const UNIT_BUTTON: &str = "[FrooxEngine]FrooxEngine.UIX.Button";
pub const UNIT_GIZMO_LINK: &str = "[FrooxEngine]FrooxEngine.GizmoLink";
pub const UNIT_SLOT_GIZMO: &str = "[FrooxEngine]FrooxEngine.SlotGizmo";
pub const UNIT_REF_FIELD: &str =
    "[FrooxEngine]FrooxEngine.ReferenceField<[FrooxEngine]FrooxEngine.IField>";
pub const UNIT_NODE: &str =
    "[ProtoFluxBindings]FrooxEngine.ProtoFlux.Runtimes.Execution.Nodes.Casts.ObjectCast";
pub const UNIT_NODE_INPUT: &str = "[FrooxEngine]FrooxEngine.IWorldElement";
pub const UNIT_VALUE_FIELD: &str = "[FrooxEngine]FrooxEngine.ValueField<string>";
pub const UNIT_DYN_FIELD: &str = "[FrooxEngine]FrooxEngine.DynamicField<string>";
pub const UNIT_MESH: &str = "[FrooxEngine]FrooxEngine.StaticMesh";
pub const UNIT_MATERIAL: &str = "[FrooxEngine]FrooxEngine.PBS_Metallic";
pub const UNIT_TEXTURE: &str = "[FrooxEngine]FrooxEngine.StaticTexture2D";
pub const UNIT_UNUSED_ASSET: &str = "[FrooxEngine]FrooxEngine.StaticAudioClip";
pub const UNIT_NEVER_USED: &str = "[FrooxEngine]FrooxEngine.NeverUsed";

pub const U_ROOT: &str = "00000001-0000-0000-0000-000000000000";
pub const U_DV: &str = "00000002-0000-0000-0000-000000000000";
pub const U_REF: &str = "00000003-0000-0000-0000-000000000000";
pub const U_MAIN: &str = "00000004-0000-0000-0000-000000000000";
pub const U_CONTENT: &str = "00000005-0000-0000-0000-000000000000";
pub const U_EXTRA: &str = "00000006-0000-0000-0000-000000000000";
pub const U_DV_STATIC: &str = "00000007-0000-0000-0000-000000000000";
pub const U_DV_PROPS: &str = "00000008-0000-0000-0000-000000000000";
/// Component on `Content` that `Main`'s button calls.
pub const U_NODE_COMP: &str = "00000100-0000-0000-0000-000000000000";
/// `Value` field of the component on `Extra`.
pub const U_EXTRA_VALUE: &str = "00000101-0000-0000-0000-000000000000";
pub const U_ASSET_MESH: &str = "00000200-0000-0000-0000-000000000000";
pub const U_ASSET_MATERIAL: &str = "00000201-0000-0000-0000-000000000000";
pub const U_ASSET_TEXTURE: &str = "00000202-0000-0000-0000-000000000000";
pub const U_ASSET_UNUSED: &str = "00000203-0000-0000-0000-000000000000";
pub const U_MESH_URL: &str =
    "@resdb:///1111111111111111111111111111111111111111111111111111111111111111.meshx";
pub const U_TEXTURE_URL: &str =
    "@resdb:///2222222222222222222222222222222222222222222222222222222222222222.webp";
pub const U_UNUSED_URL: &str =
    "@resdb:///3333333333333333333333333333333333333333333333333333333333333333.brson";

pub const UNIT_TYPES: [&str; 15] = [
    UNIT_SPACE,
    UNIT_REF_VAR,
    UNIT_NEVER_USED,
    UNIT_RENDERER,
    UNIT_BUTTON,
    UNIT_GIZMO_LINK,
    UNIT_SLOT_GIZMO,
    UNIT_REF_FIELD,
    UNIT_NODE,
    UNIT_NODE_INPUT,
    UNIT_VALUE_FIELD,
    UNIT_DYN_FIELD,
    UNIT_MESH,
    UNIT_MATERIAL,
    UNIT_TEXTURE,
];

fn unit_type(name: &str) -> i64 {
    if name == UNIT_UNUSED_ASSET {
        return UNIT_TYPES.len() as i64;
    }
    UNIT_TYPES
        .iter()
        .position(|t| *t == name)
        .expect("unit type") as i64
}

/// Counter-based ids for fields, so every id in the fixture is distinct.
struct Ids(u32);

impl Ids {
    fn next(&mut self) -> String {
        self.0 += 1;
        format!("{:08x}-0000-0000-0000-00000000ffff", self.0)
    }
}

fn wrapped(ids: &mut Ids, data: impl FnOnce(&mut DocBuf)) -> Vec<u8> {
    let mut d = DocBuf::new();
    d.string("ID", &ids.next());
    data(&mut d);
    d.finish()
}

fn wrapped_str(ids: &mut Ids, value: &str) -> Vec<u8> {
    wrapped(ids, |d| {
        d.string("Data", value);
    })
}

fn doubles(values: &[f64]) -> Vec<u8> {
    let mut body = Vec::new();
    for (i, v) in values.iter().enumerate() {
        crate::bson::push_element(
            &mut body,
            crate::bson::DOUBLE,
            &i.to_string(),
            &v.to_le_bytes(),
        );
    }
    crate::bson::finish_doc(&body).unwrap()
}

fn rcomp(
    ids: &mut Ids,
    type_name: &str,
    id: Option<&str>,
    fields: Vec<(&str, Vec<u8>)>,
) -> Vec<u8> {
    let mut data = DocBuf::new();
    data.string("ID", &id.map(str::to_string).unwrap_or_else(|| ids.next()));
    data.string("persistent-ID", &ids.next());
    data.doc(
        "UpdateOrder",
        &wrapped(ids, |d| {
            d.int32("Data", 0);
        }),
    );
    data.doc(
        "Enabled",
        &wrapped(ids, |d| {
            d.bool("Data", true);
        }),
    );
    for (key, value) in fields {
        data.doc(key, &value);
    }
    let mut c = DocBuf::new();
    c.int64("Type", unit_type(type_name));
    c.doc("Data", &data.finish());
    c.finish()
}

fn rslot(
    ids: &mut Ids,
    id: &str,
    name: &str,
    parent: &str,
    comps: &[Vec<u8>],
    children: &[Vec<u8>],
) -> Vec<u8> {
    let mut s = DocBuf::new();
    s.string("ID", id);
    let mut ptr = DocBuf::new();
    ptr.string("ID", &ids.next());
    ptr.array("Data", &crate::bson::array_of_docs(comps));
    s.doc("Components", &ptr.finish());
    s.doc("Name", &wrapped_str(ids, name));
    s.doc(
        "Tag",
        &wrapped(ids, |d| {
            d.null("Data");
        }),
    );
    s.doc(
        "Active",
        &wrapped(ids, |d| {
            d.bool("Data", true);
        }),
    );
    s.string("Persistent-ID", &ids.next());
    s.doc(
        "Position",
        &wrapped(ids, |d| {
            d.array("Data", &doubles(&[0.0, 1.5, 0.0]));
        }),
    );
    s.doc(
        "Rotation",
        &wrapped(ids, |d| {
            d.array("Data", &doubles(&[0.0, 0.0, 0.0, 1.0]));
        }),
    );
    s.doc(
        "Scale",
        &wrapped(ids, |d| {
            d.array("Data", &doubles(&[1.0, 1.0, 1.0]));
        }),
    );
    s.doc(
        "OrderOffset",
        &wrapped(ids, |d| {
            d.int64("Data", 0);
        }),
    );
    s.string("ParentReference", parent);
    s.array("Children", &crate::bson::array_of_docs(children));
    s.finish()
}

fn ref_var(ids: &mut Ids, name: &str, target: &str) -> Vec<u8> {
    let name_field = wrapped_str(ids, name);
    let reference = wrapped_str(ids, target);
    let override_field = wrapped(ids, |d| {
        d.bool("Data", false);
    });
    rcomp(
        ids,
        UNIT_REF_VAR,
        None,
        vec![
            ("VariableName", name_field),
            ("Reference", reference),
            ("OverrideOnLink", override_field),
        ],
    )
}

fn space(ids: &mut Ids) -> Vec<u8> {
    let name = wrapped(ids, |d| {
        d.null("Data");
    });
    rcomp(ids, UNIT_SPACE, None, vec![("SpaceName", name)])
}

fn asset(ids: &mut Ids, type_name: &str, id: &str, fields: Vec<(&str, Vec<u8>)>) -> Vec<u8> {
    let mut data = DocBuf::new();
    data.string("ID", id);
    data.doc(
        "persistent",
        &wrapped(ids, |d| {
            d.bool("Data", true);
        }),
    );
    for (key, value) in fields {
        data.doc(key, &value);
    }
    let mut a = DocBuf::new();
    a.int64("Type", unit_type(type_name));
    a.doc("Data", &data.finish());
    a.finish()
}

pub fn unit_bson() -> Vec<u8> {
    unit_bson_with_renderer_version(3)
}

/// The same unit, with a different `TypeVersions` entry for `MeshRenderer`.
pub fn unit_bson_with_renderer_version(renderer_version: i64) -> Vec<u8> {
    let mut ids = Ids(0);

    let node = {
        let input = wrapped(&mut ids, |d| {
            d.int64("Data", unit_type(UNIT_NODE_INPUT));
        });
        rcomp(
            &mut ids,
            UNIT_NODE,
            Some(U_NODE_COMP),
            vec![("InputType", input)],
        )
    };
    let content = rslot(&mut ids, U_CONTENT, "Content", U_MAIN, &[node], &[]);

    let renderer = {
        let mesh = wrapped_str(&mut ids, U_ASSET_MESH);
        let materials = {
            let item = wrapped_str(&mut ids, U_ASSET_MATERIAL);
            wrapped(&mut ids, |d| {
                d.array("Data", &crate::bson::array_of_docs(&[item]));
            })
        };
        rcomp(
            &mut ids,
            UNIT_RENDERER,
            None,
            vec![("Mesh", mesh), ("Materials", materials)],
        )
    };
    let button = {
        let mut target = DocBuf::new();
        target.string("Target", U_NODE_COMP);
        target.string("Method", "OnPress");
        let target = target.finish();
        let pressed = wrapped(&mut ids, |d| {
            d.doc("Data", &target);
        });
        rcomp(&mut ids, UNIT_BUTTON, None, vec![("Pressed", pressed)])
    };
    let gizmo = {
        let worker = wrapped_str(&mut ids, U_MAIN);
        let gizmo = wrapped(&mut ids, |d| {
            d.null("Data");
        });
        let ty = wrapped(&mut ids, |d| {
            d.int32("Data", unit_type(UNIT_SLOT_GIZMO) as i32);
        });
        rcomp(
            &mut ids,
            UNIT_GIZMO_LINK,
            None,
            vec![("_worker", worker), ("_gizmo", gizmo), ("_type", ty)],
        )
    };
    let cross = {
        let to_extra = wrapped_str(&mut ids, U_EXTRA_VALUE);
        let to_outside = wrapped_str(&mut ids, U_DV);
        rcomp(
            &mut ids,
            UNIT_REF_FIELD,
            None,
            vec![("Reference", to_extra), ("Outside", to_outside)],
        )
    };
    let main = rslot(
        &mut ids,
        U_MAIN,
        "Main",
        U_REF,
        &[renderer, button, gizmo, cross],
        &[content],
    );

    let extra = {
        // A field whose id is fixed, so `DV/Props` and `Main` can name it.
        let mut v = DocBuf::new();
        v.string("ID", U_EXTRA_VALUE);
        v.string("Data", "hello");
        let comp = rcomp(
            &mut ids,
            UNIT_VALUE_FIELD,
            None,
            vec![("Value", v.finish())],
        );
        rslot(&mut ids, U_EXTRA, "Extra", U_REF, &[comp], &[])
    };

    let dv_static = {
        let root = ref_var(&mut ids, "Static.Root", U_REF);
        let main = ref_var(&mut ids, "Static.Main", U_MAIN);
        let parent = ref_var(&mut ids, "Static.ChildrenParent", U_CONTENT);
        rslot(
            &mut ids,
            U_DV_STATIC,
            "DV/Static",
            U_REF,
            &[root, main, parent],
            &[],
        )
    };
    let dv_props = {
        let name = wrapped_str(&mut ids, "Props.Label");
        let target = wrapped_str(&mut ids, U_EXTRA_VALUE);
        let comp = rcomp(
            &mut ids,
            UNIT_DYN_FIELD,
            None,
            vec![("VariableName", name), ("TargetField", target)],
        );
        rslot(&mut ids, U_DV_PROPS, "DV/Props", U_REF, &[comp], &[])
    };
    let ref_space = space(&mut ids);
    let r = rslot(
        &mut ids,
        U_REF,
        "Ref",
        U_ROOT,
        &[ref_space],
        &[main, extra, dv_static, dv_props],
    );
    let dv = {
        let static_ref = ref_var(&mut ids, "Static.Ref", U_REF);
        rslot(&mut ids, U_DV, "DV", U_ROOT, &[static_ref], &[])
    };
    let root_space = space(&mut ids);
    let root = rslot(
        &mut ids,
        U_ROOT,
        "Pkg/Unit",
        "00000000-0000-0000-0000-00000000dead",
        &[root_space],
        &[dv, r],
    );

    let assets = {
        let url = wrapped_str(&mut ids, U_MESH_URL);
        let mesh = asset(&mut ids, UNIT_MESH, U_ASSET_MESH, vec![("URL", url)]);
        let tex = wrapped_str(&mut ids, U_ASSET_TEXTURE);
        let material = asset(
            &mut ids,
            UNIT_MATERIAL,
            U_ASSET_MATERIAL,
            vec![("AlbedoTexture", tex)],
        );
        let url = wrapped_str(&mut ids, U_TEXTURE_URL);
        let texture = asset(&mut ids, UNIT_TEXTURE, U_ASSET_TEXTURE, vec![("URL", url)]);
        let url = wrapped_str(&mut ids, U_UNUSED_URL);
        let unused = asset(
            &mut ids,
            UNIT_UNUSED_ASSET,
            U_ASSET_UNUSED,
            vec![("URL", url)],
        );
        // Unused first, so a copy that kept positions would be visible.
        vec![unused, mesh, material, texture]
    };

    let mut flags = DocBuf::new();
    flags.int64("ColorManagement", 0);
    flags.int64("ProtoFlux", 0);
    let mut versions = DocBuf::new();
    versions.int64(UNIT_RENDERER, renderer_version);
    versions.int64(UNIT_NEVER_USED, 7);
    versions.int64(UNIT_MATERIAL, 2);
    let mut types: Vec<&str> = UNIT_TYPES.to_vec();
    types.push(UNIT_UNUSED_ASSET);

    let mut doc = DocBuf::new();
    doc.string("VersionNumber", "2024.9.16.1105");
    doc.doc("FeatureFlags", &flags.finish());
    doc.array("Types", &crate::bson::array_of_strings(&types));
    doc.doc("TypeVersions", &versions.finish());
    doc.doc("Object", &root);
    doc.array("Assets", &crate::bson::array_of_docs(&assets));
    doc.finish()
}

pub fn unit_brson() -> Vec<u8> {
    wrap(&unit_bson())
}

pub fn unit_brson_with_renderer_version(renderer_version: i64) -> Vec<u8> {
    wrap(&unit_bson_with_renderer_version(renderer_version))
}

/// A slot's own BSON document. Test helper.
pub fn slot_bson(slot: &crate::SlotHandle) -> crate::Result<Vec<u8>> {
    slot.raw()
}

/// Each `Assets` entry as its own BSON document. Test helper.
pub fn asset_bsons(doc: &crate::Document) -> crate::Result<Vec<Vec<u8>>> {
    doc.asset_raw()
}

/// `doc` written as `.brson` with root field `key` replaced by an element of
/// BSON type `ty` and raw value `value` (added when missing). For tests of
/// root fields that `Document` would not write.
pub fn with_root_field(doc: &crate::Document, key: &str, ty: u8, value: &[u8]) -> Vec<u8> {
    let mut bson = doc.bson_bytes().expect("bson");
    let mut element = Vec::new();
    crate::bson::push_element(&mut element, ty, key, value);
    let (start, end) = match crate::datatree::field(&bson, 0, key).expect("root") {
        Some(el) => (el.start, el.start + el.raw.len()),
        None => {
            let end = crate::bson::doc_end(&bson, 0).expect("root end") - 1;
            (end, end)
        }
    };
    crate::bson::splice(&mut bson, start, end, &element, &[0]).expect("splice");
    crate::bson::validate(&bson).expect("valid");
    wrap(&bson)
}

/// A BSON document of `(key, type, raw value)` elements, for
/// [`with_root_field`].
pub fn raw_doc(elements: &[(&str, u8, Vec<u8>)]) -> Vec<u8> {
    let mut body = Vec::new();
    for (key, ty, value) in elements {
        crate::bson::push_element(&mut body, *ty, key, value);
    }
    crate::bson::finish_doc(&body).expect("doc")
}