openusd 0.8.0

Rust native USD library
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! The shared machinery behind stage-tier property authoring: where a spec
//! comes from when the edit target holds none, which fields the generic
//! metadata calls may not touch, and the closures that edit a typed spec.
//!
//! Creating or editing a property on the edit target follows C++
//! `UsdStage::_CreatePropertySpecForEditing` in two phases. The read phase,
//! [`plan_property_spec`], runs before any transaction and is the only place
//! composition is consulted: it resolves an [`EnsurePlan`] in C++ precedence
//! order — the edit target's own spec, the schema declaration, the strongest
//! authored spec of any kind, then the caller's fallback. The write phase,
//! [`apply_plan`], runs inside the single transaction and only rechecks the
//! local spec and stamps the resolved declaration. Splitting them keeps
//! composed queries out of the transaction closure, which holds the layer
//! graph mutably, and lets a caller stamp the spec and perform its own
//! mutation as one atomic edit. Holding the read phase of several
//! properties open before the write is what a [`StageEdit`] does, so a
//! batch of them commits together.

use std::cell::RefCell;
use std::fmt;
use std::sync::Arc;

use crate::{pcp, sdf, tf};

use super::attribute::AttributeAuthoringPlan;
use super::{
    Attribute, AttributeBuilder, EditTarget, Prim, PrimTypeInfo, Relationship, RelationshipBuilder, SpecSite, Stage,
    StageAuthoringError,
};

/// The properties queued for one stage transaction.
///
/// What [`Stage::edit`] hands its closure. The authoring entry points here
/// mirror the stage's own — [`prim`](Self::prim) for a prim to author on, and
/// the property builders for a path — but the builders they hand out queue
/// their property instead of committing it, so where a builder came from is
/// what puts it in the transaction. The queue is stamped and written when the
/// closure returns, as one edit of the target layer; any error — from the
/// closure, from a plan, from a [`sdf::LayerSink`] veto — leaves every property
/// unchanged.
///
/// Reads inside the closure see the stage as it stands, not what the batch has
/// queued: a queued property reaches the stage only when the batch commits.
///
/// The batch is tied to the edit target it opened on. Each queued property
/// resolved its spec path, its value and its sample time against that target,
/// so moving the target while the batch is open would write them somewhere
/// else; the batch reports
/// [`StageAuthoringError::EditTargetMoved`] rather than commit them through a
/// target they were not planned for.
pub struct StageEdit {
    stage: Stage,
    /// The edit target every queued property was planned against.
    target: EditTarget,
    queued: RefCell<Vec<PlannedProperty>>,
}

impl fmt::Debug for StageEdit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StageEdit").field("queued", &self.queued).finish()
    }
}

impl StageEdit {
    pub(super) fn new(stage: &Stage) -> Self {
        StageEdit {
            stage: stage.clone(),
            target: stage.edit_target(),
            queued: RefCell::new(Vec::new()),
        }
    }

    /// A prim to author on inside the transaction: [`Stage::prim`], whose
    /// property builders queue rather than commit.
    pub fn prim(&self, path: impl sdf::IntoPath) -> Result<PrimEdit<'_>, sdf::PathParseError> {
        Ok(PrimEdit {
            batch: self,
            prim: self.stage.prim(path)?,
        })
    }

    /// An attribute at a property path, queued rather than committed:
    /// [`Stage::attribute_builder`] inside the transaction.
    pub fn attribute_builder(
        &self,
        path: impl sdf::IntoPath,
        type_name: impl Into<sdf::ValueTypeName>,
    ) -> AttributeBuilder<'_> {
        self.stage.attribute_builder(path, type_name).in_batch(self)
    }

    /// A relationship at a property path, queued rather than committed:
    /// [`Stage::relationship_builder`] inside the transaction.
    pub fn relationship_builder(&self, path: impl sdf::IntoPath) -> RelationshipBuilder<'_> {
        self.stage.relationship_builder(path).in_batch(self)
    }

    /// Queues several properties as one: all of what `f` builds joins the
    /// transaction, or none of it does.
    ///
    /// `f` receives a batch of its own, on the edit target this one planned
    /// against. When `f` succeeds its properties move into this batch
    /// together, and when it fails they are dropped, so an operation made of
    /// several properties leaves no part of itself queued behind an error the
    /// caller goes on from. A property this batch already holds is
    /// [`StageAuthoringError::DuplicateProperty`], and none of the group
    /// joins.
    ///
    /// Nothing is written until the outermost batch commits, and reads inside
    /// `f` see the stage as it stands.
    pub fn group<T, E>(&self, f: impl FnOnce(&StageEdit) -> Result<T, E>) -> Result<T, E>
    where
        E: From<StageAuthoringError>,
    {
        let group = StageEdit {
            stage: self.stage.clone(),
            target: self.target.clone(),
            queued: RefCell::new(Vec::new()),
        };
        let value = f(&group)?;
        self.absorb(group.queued.into_inner())?;
        Ok(value)
    }

    /// Queues `properties` together, or none of them where the batch already
    /// holds one of their paths.
    fn absorb(&self, properties: Vec<PlannedProperty>) -> Result<(), StageAuthoringError> {
        let mut queued = self.queued.borrow_mut();
        let repeated = properties
            .iter()
            .find(|property| queued.iter().any(|other| other.path == property.path));
        if let Some(repeated) = repeated {
            return Err(StageAuthoringError::DuplicateProperty {
                path: repeated.path.clone(),
            });
        }
        queued.extend(properties);
        Ok(())
    }

    /// Queues an already-planned property, and hands back where it will be
    /// authored for the builder to make its handle from.
    ///
    /// Returns [`StageAuthoringError::DuplicateProperty`] where the batch
    /// already holds that path — two plans for one property each resolve
    /// against a stage the other has not changed yet, so neither accounts for
    /// what the other declares.
    pub(super) fn queue(&self, planned: PlannedProperty) -> Result<(Stage, sdf::Path), StageAuthoringError> {
        let mut queued = self.queued.borrow_mut();
        if queued.iter().any(|other| other.path == planned.path) {
            return Err(StageAuthoringError::DuplicateProperty { path: planned.path });
        }
        let site = (planned.stage.clone(), planned.path.clone());
        queued.push(planned);
        Ok(site)
    }

    /// That the stage still has the edit target the batch planned against,
    /// checked before a builder plans against it and again before the queue is
    /// written.
    ///
    /// A property's spec path, its value and its sample time are all resolved
    /// through the target that was current when it was queued, so a target the
    /// batch did not plan for would put the write somewhere else.
    pub(super) fn holds_target(&self) -> Result<(), StageAuthoringError> {
        match self.stage.holds_edit_target(&self.target) {
            true => Ok(()),
            false => Err(StageAuthoringError::EditTargetMoved),
        }
    }

    /// Stamps and writes every queued property as one transaction.
    pub(super) fn commit(self) -> Result<(), StageAuthoringError> {
        if self.queued.borrow().is_empty() {
            return Ok(());
        }
        self.holds_target()?;

        let (paths, writes): (Vec<sdf::Path>, Vec<PropertyWrite>) = self
            .queued
            .into_inner()
            .into_iter()
            .map(|property| (property.path, property.write))
            .unzip();
        self.stage
            .with_target_layer_at_each(&paths, move |layer, spec_paths| {
                for (write, spec_path) in writes.into_iter().zip(spec_paths) {
                    write.apply(layer.data_mut(), &spec_path)?;
                }
                Ok(())
            })
            .map(|_| ())
    }
}

/// A prim to author on inside a [`StageEdit`]'s transaction.
///
/// The transaction-bound counterpart of [`Prim`]: the same property builders,
/// each queued into the batch rather than committed on its own. Reads go
/// through [`prim`](Self::prim), and see the stage as it stands rather than
/// what the batch has queued.
#[derive(Debug)]
pub struct PrimEdit<'a> {
    batch: &'a StageEdit,
    prim: Prim,
}

impl<'a> PrimEdit<'a> {
    /// The prim itself, for reading it.
    ///
    /// It is an ordinary [`Prim`], so its own authoring methods author on their
    /// own: only the builders below queue into the transaction.
    pub fn prim(&self) -> &Prim {
        &self.prim
    }

    /// An attribute on the prim, queued rather than committed:
    /// [`Prim::attribute_builder`] inside the transaction.
    pub fn attribute_builder(
        &self,
        name: impl Into<tf::Token>,
        type_name: impl Into<sdf::ValueTypeName>,
    ) -> AttributeBuilder<'a> {
        self.prim.attribute_builder(name, type_name).in_batch(self.batch)
    }

    /// A relationship on the prim, queued rather than committed:
    /// [`Prim::relationship_builder`] inside the transaction.
    pub fn relationship_builder(&self, name: impl Into<tf::Token>) -> RelationshipBuilder<'a> {
        self.prim.relationship_builder(name).in_batch(self.batch)
    }

    /// Queues several of the prim's properties as one: [`StageEdit::group`],
    /// with `f` handed this prim inside the group.
    pub fn group<T, E>(&self, f: impl FnOnce(&PrimEdit<'_>) -> Result<T, E>) -> Result<T, E>
    where
        E: From<StageAuthoringError>,
    {
        self.batch.group(|batch| {
            f(&PrimEdit {
                batch,
                prim: self.prim.clone(),
            })
        })
    }
}

/// A property resolved against composed state, waiting for the transaction
/// that writes it.
///
/// What a builder produces: the composed reads the write depends on are already
/// done, so applying it needs nothing but the edit target's layer. That is what
/// lets several properties share one transaction: the read phase a single
/// property's write already runs first, held open long enough to collect more
/// of them.
#[derive(Debug)]
pub(super) struct PlannedProperty {
    stage: Stage,
    path: sdf::Path,
    write: PropertyWrite,
}

/// The write phase of one property, run against the edit target's own spec path
/// for it: all a [`PlannedProperty`] has left to do once the transaction opens.
#[derive(Debug)]
pub(super) enum PropertyWrite {
    /// An attribute declared, with the value opinion and the metadata fields
    /// planned for it.
    Attribute {
        value: AttributeWrite,
        metadata: Vec<(&'static str, sdf::Value)>,
    },
    /// A relationship declared, and its targets replaced where the caller gave
    /// some.
    Relationship {
        ensure: EnsurePlan,
        targets: Option<Vec<sdf::Path>>,
    },
}

/// What an attribute's write does to its value.
#[derive(Debug)]
pub(super) enum AttributeWrite {
    /// Declares the attribute, and leaves it at whatever value it has.
    Declare(EnsurePlan),
    /// Gives it the value planned for it.
    Set(Box<AttributeAuthoringPlan>),
    /// Blocks every weaker value opinion.
    Block(Box<AttributeAuthoringPlan>),
}

impl PlannedProperty {
    pub(super) fn new(stage: Stage, path: sdf::Path, write: PropertyWrite) -> Self {
        PlannedProperty { stage, path, write }
    }

    /// Writes the property on its own, as one transaction, and hands back where
    /// it was authored for the caller to build its handle from.
    pub(super) fn commit(self) -> Result<(Stage, sdf::Path), StageAuthoringError> {
        let PlannedProperty { stage, path, write } = self;
        stage.with_target_layer_at(&path, move |layer, spec_path| write.apply(layer.data_mut(), &spec_path))?;
        Ok((stage, path))
    }
}

impl PropertyWrite {
    fn apply(self, data: &mut dyn sdf::AbstractData, path: &sdf::Path) -> Result<(), StageAuthoringError> {
        match self {
            Self::Attribute { value, metadata } => {
                match value {
                    AttributeWrite::Declare(ensure) => apply_plan(data, path, Attribute::KIND, &ensure)?,
                    AttributeWrite::Set(plan) => plan.write(data, path)?,
                    AttributeWrite::Block(plan) => plan.block(data, path)?,
                }
                if metadata.is_empty() {
                    return Ok(());
                }
                edit_spec(data, path.clone(), Attribute::KIND, Attribute::view, |spec| {
                    for (key, value) in metadata {
                        spec.set(key, value);
                    }
                    Ok(())
                })
            }
            Self::Relationship { ensure, targets } => {
                apply_plan(data, path, Relationship::KIND, &ensure)?;
                let Some(targets) = targets else {
                    return Ok(());
                };
                edit_spec(data, path.clone(), Relationship::KIND, Relationship::view, |spec| {
                    Ok(spec.set_target_paths(targets)?)
                })
            }
        }
    }
}

/// A property kind, as the authoring operations below work on it: what its
/// specs are, and how one is opened for editing.
///
/// Implemented on the stage-tier handles, so an operation names the thing being
/// authored: `author::<Attribute>`.
pub(super) trait PropertySpecKind {
    /// What a spec of this kind answers to, for the checks that a path holds
    /// the kind the caller meant.
    const KIND: sdf::SpecType;

    /// A mutable view of one, borrowed from the layer that holds it.
    type View<'a>;

    /// Opens the spec at `path`, or `None` where the layer holds none.
    fn view(data: &mut dyn sdf::AbstractData, path: sdf::Path) -> Option<Self::View<'_>>;
}

impl PropertySpecKind for Attribute {
    const KIND: sdf::SpecType = sdf::SpecType::Attribute;

    type View<'a> = sdf::AttributeSpecMut<'a>;

    fn view(data: &mut dyn sdf::AbstractData, path: sdf::Path) -> Option<Self::View<'_>> {
        sdf::AttributeSpecMut::get(data, path)
    }
}

impl PropertySpecKind for Relationship {
    const KIND: sdf::SpecType = sdf::SpecType::Relationship;

    type View<'a> = sdf::RelationshipSpecMut<'a>;

    fn view(data: &mut dyn sdf::AbstractData, path: sdf::Path) -> Option<Self::View<'_>> {
        sdf::RelationshipSpecMut::get(data, path)
    }
}

/// Stamps the spec `path` needs on the edit target and runs `edit` on it, as
/// one transaction.
///
/// The phase order lives here: the read that resolves where the spec comes
/// from, then the transaction that stamps it and mutates it. A caller supplies
/// the mutation alone, typed to the spec its kind opens.
pub(super) fn author<P: PropertySpecKind>(
    stage: &Stage,
    path: &sdf::Path,
    edit: impl FnOnce(&mut P::View<'_>) -> Result<(), StageAuthoringError>,
) -> Result<(), StageAuthoringError> {
    let plan = plan_property_spec(stage, path, P::KIND, None)?;
    stage
        .with_target_layer_at(path, |layer, spec_path| {
            apply_plan(layer.data_mut(), &spec_path, P::KIND, &plan)?;
            edit_spec(layer.data_mut(), spec_path, P::KIND, P::view, edit)
        })
        .map(|_| ())
}

/// Runs `edit` on the spec `path` already has on the edit target, and does
/// nothing where it has none. A property of a prim the stage does not hold is
/// [`PrimNotValid`](StageAuthoringError::PrimNotValid).
///
/// The path every clear takes. Removing an opinion never stamps a spec to
/// remove it from, so a layer that says nothing about the property goes on
/// saying nothing — which is what parts this from [`author`], and why the two
/// are separate operations rather than one asked to skip a phase.
pub(super) fn edit_existing<P: PropertySpecKind>(
    stage: &Stage,
    path: &sdf::Path,
    edit: impl FnOnce(&mut P::View<'_>) -> Result<(), StageAuthoringError>,
) -> Result<(), StageAuthoringError> {
    stage.require_included(path)?;
    stage
        .with_target_layer_at(path, |layer, spec_path| {
            edit_existing_spec(layer.data_mut(), spec_path, P::KIND, P::view, edit)
        })
        .map(|_| ())
}

/// What a property spec stamped on the edit target declares: the fields C++
/// `_StampNewPropertySpec` copies from the declaration it found.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum PropertyDeclaration {
    Attribute {
        type_name: sdf::ValueTypeName,
        variability: sdf::Variability,
        custom: bool,
    },
    Relationship {
        variability: sdf::Variability,
        custom: bool,
    },
}

impl PropertyDeclaration {
    pub fn kind(&self) -> sdf::SpecType {
        match self {
            Self::Attribute { .. } => sdf::SpecType::Attribute,
            Self::Relationship { .. } => sdf::SpecType::Relationship,
        }
    }
}

/// The read phase's answer for a property about to be authored.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum EnsurePlan {
    /// The edit target already holds a spec of the wanted kind, which is left
    /// as it is.
    Existing,
    /// The edit target holds no spec; this declaration is stamped first.
    Stamp(PropertyDeclaration),
}

impl EnsurePlan {
    /// The value type this plan would declare an attribute with, or `None`
    /// when it stamps nothing — a target that already holds the spec says
    /// nothing about the type — or stamps a relationship.
    pub fn attribute_type(&self) -> Option<&sdf::ValueTypeName> {
        match self {
            Self::Stamp(PropertyDeclaration::Attribute { type_name, .. }) => Some(type_name),
            // A target that already holds the spec says nothing about its
            // type, and a relationship plan never reaches a value write.
            Self::Existing | Self::Stamp(PropertyDeclaration::Relationship { .. }) => None,
        }
    }
}

/// The read phase of authoring the property at `path` as a `kind` spec.
///
/// A property of a prim the stage does not hold — outside the population mask
/// or below an inactive prim — is
/// [`PrimNotValid`](StageAuthoringError::PrimNotValid), as C++ holds no
/// `UsdPrim` there to author through.
///
/// Otherwise, in C++ precedence order: a spec of that kind already on the edit target is
/// [`EnsurePlan::Existing`]; otherwise the schema declaration, then the
/// strongest authored spec of any kind, supplies the declaration to stamp; only
/// when nothing declares the property does `fallback` apply (`None` for an
/// edit, the supplied declaration for a creation). A declaration of the other
/// kind found at any of those sources is
/// [`SpecKindMismatch`](StageAuthoringError::SpecKindMismatch), never skipped
/// in favour of a weaker one. A declaration taken from a layer is read with
/// the fallible readers, so a malformed strongest spec is an error; the
/// fallback is checked only when it is stamped.
pub(super) fn plan_property_spec(
    stage: &Stage,
    path: &sdf::Path,
    kind: sdf::SpecType,
    fallback: Option<PropertyDeclaration>,
) -> Result<EnsurePlan, StageAuthoringError> {
    stage.require_included(path)?;
    if let Some(found) = stage.local_spec_type(path)? {
        return if found == kind {
            Ok(EnsurePlan::Existing)
        } else {
            Err(kind_mismatch(path, kind, found))
        };
    }
    let Some((info, name)) = schema_definition(stage, path)? else {
        return Err(sdf::AuthoringError::InvalidPath {
            path: path.clone(),
            reason: "property authoring needs a property path",
        }
        .into());
    };

    if let Some(property) = info.prim_definition().property(&name) {
        let found = property.spec_type();
        if found != kind {
            return Err(kind_mismatch(path, kind, found));
        }
        let declaration = if kind == sdf::SpecType::Attribute {
            PropertyDeclaration::Attribute {
                type_name: property
                    .type_name_token()
                    .map(sdf::ValueTypeName::from)
                    .ok_or(sdf::ValueTypeError::Empty)?,
                variability: property.variability(),
                custom: false,
            }
        } else {
            PropertyDeclaration::Relationship {
                variability: property.variability(),
                custom: false,
            }
        };
        return Ok(EnsurePlan::Stamp(declaration));
    }

    let strongest = stage
        .masked_opinions(path, |graph, cache| cache.property_stack(graph, path, None))?
        .into_iter()
        .next();
    if let Some(site) = strongest {
        let declaration = declaration_at(stage, &site, kind)?;
        if declaration.kind() != kind {
            return Err(kind_mismatch(path, kind, declaration.kind()));
        }
        return Ok(EnsurePlan::Stamp(declaration));
    }

    fallback.map(EnsurePlan::Stamp).ok_or_else(|| missing_spec(path, kind))
}

/// The write phase: inside the transaction, recheck the edit target's spec
/// at `path` and stamp the plan's declaration when it holds none.
pub(super) fn apply_plan(
    data: &mut dyn sdf::AbstractData,
    path: &sdf::Path,
    kind: sdf::SpecType,
    plan: &EnsurePlan,
) -> Result<(), StageAuthoringError> {
    match data.spec_type(path) {
        Some(found) if found == kind => Ok(()),
        Some(found) => Err(kind_mismatch(path, kind, found)),
        None => match plan {
            EnsurePlan::Existing => Err(missing_spec(path, kind)),
            EnsurePlan::Stamp(declaration) => stamp(data, path, declaration),
        },
    }
}

/// The schema of the prim the property at `path` hangs off, with the
/// property's own name: the pair every schema-declaration lookup starts from
/// (C++ `UsdStage::_GetSchemaProperty`). `None` when `path` is not a property
/// path.
pub(super) fn schema_definition(
    stage: &Stage,
    path: &sdf::Path,
) -> Result<Option<(Arc<PrimTypeInfo>, tf::Token)>, pcp::QueryError> {
    let Some((prim, name)) = path.split_property() else {
        return Ok(None);
    };
    Ok(Some((stage.prim_type_info_composed(prim)?, tf::Token::from(name))))
}

/// The field `key` the declaring schema gives the property at `path`, or
/// `None` where no schema declares the property or the field (C++
/// `UsdStage::_GetSchemaAttribute` and its relationship counterpart).
///
/// Everything a schema states about a property — its type, its variability,
/// its display metadata — lives on the same declaration, whether or not any
/// layer authors a spec, so this is what a property's generic metadata read
/// falls back to where nothing authors the field.
pub(super) fn schema_property_field(
    stage: &Stage,
    path: &sdf::Path,
    key: &str,
) -> Result<Option<sdf::Value>, pcp::QueryError> {
    let Some((info, name)) = schema_definition(stage, path)? else {
        return Ok(None);
    };
    Ok(info
        .prim_definition()
        .property(&name)
        .and_then(|property| property.field(key).cloned()))
}

/// Run `f` on the `kind` spec at `path` on the edit-target layer, or return
/// [`sdf::AuthoringError::InvalidPath`] when no such spec exists. `get` is the
/// spec view's constructor (e.g. `sdf::PrimSpecMut::get`). The shared body of
/// the `usd`-tier authoring closures.
pub(super) fn edit_spec<'a, S>(
    data: &'a mut dyn sdf::AbstractData,
    path: sdf::Path,
    kind: sdf::SpecType,
    get: impl FnOnce(&'a mut dyn sdf::AbstractData, sdf::Path) -> Option<S>,
    f: impl FnOnce(&mut S) -> Result<(), StageAuthoringError>,
) -> Result<(), StageAuthoringError> {
    match get(data, path.clone()) {
        Some(mut spec) => f(&mut spec),
        None => Err(missing_spec(&path, kind)),
    }
}

/// The non-creating counterpart of [`edit_spec`]: run `f` on the `kind` spec
/// at `path` when the edit-target layer holds one, do nothing when it holds
/// none, and report a spec of the other kind. The clear operations use it, so
/// removing an opinion never stamps a spec to remove it from.
pub(super) fn edit_existing_spec<'a, S>(
    data: &'a mut dyn sdf::AbstractData,
    path: sdf::Path,
    kind: sdf::SpecType,
    get: impl FnOnce(&'a mut dyn sdf::AbstractData, sdf::Path) -> Option<S>,
    f: impl FnOnce(&mut S) -> Result<(), StageAuthoringError>,
) -> Result<(), StageAuthoringError> {
    match data.spec_type(&path) {
        None => Ok(()),
        Some(found) if found == kind => {
            let mut spec = get(data, path).expect("the kind was checked");
            f(&mut spec)
        }
        Some(found) => Err(kind_mismatch(&path, kind, found)),
    }
}

/// Rejects `key` when a `kind` spec authors it only through a dedicated,
/// validated setter, so the generic metadata calls cannot bypass the
/// invariants those setters keep. This is this crate's authoring
/// restriction, not a fact about the field: C++ `_IsPrivateFieldKey` is a
/// read-side classifier of value, arc and clip fields that does not police
/// `SetMetadata`, and a state only the raw field reaches — a whole-field
/// `timeSamples` block, an empty sample map — is authored on the layer
/// through [`sdf::Layer::edit`].
// TODO: the reserved fields belong in a per-spec-type field definition, the
// counterpart of C++ `SdfSchema::SpecDefinition`, which would also own the
// required-field knowledge `usda::parser::KNOWN_PROPS` keeps. Until then a
// prim's `typeName`, `active`, `hidden`, `kind` and `instanceable` have
// dedicated setters but stay reachable here, since gating them needs the
// matching clear operations first; `spline` joins the attribute list once
// splines are authored.
pub(super) fn check_reserved(kind: sdf::SpecType, key: &'static str) -> Result<(), StageAuthoringError> {
    let reserved: &[sdf::FieldKey] = match kind {
        sdf::SpecType::Attribute => &[
            sdf::FieldKey::Default,
            sdf::FieldKey::TimeSamples,
            sdf::FieldKey::TypeName,
            sdf::FieldKey::ConnectionPaths,
            sdf::FieldKey::Variability,
            sdf::FieldKey::Custom,
        ],
        sdf::SpecType::Relationship => &[
            sdf::FieldKey::TargetPaths,
            sdf::FieldKey::Variability,
            sdf::FieldKey::Custom,
        ],
        _ => &[],
    };
    if reserved.iter().any(|field| field.as_str() == key) {
        return Err(StageAuthoringError::ReservedField { field: key });
    }
    Ok(())
}

/// The declaration the spec at `site` carries, read from that layer with the
/// fallible readers; `wanted` names the kind being authored for the error
/// when the site holds none.
fn declaration_at(
    stage: &Stage,
    site: &SpecSite,
    wanted: sdf::SpecType,
) -> Result<PropertyDeclaration, StageAuthoringError> {
    let layer = stage
        .layer(&site.layer)
        .ok_or_else(|| StageAuthoringError::LayerNotFound {
            layer: site.layer.clone(),
        })?;
    declaration_of(layer.data(), &site.path, wanted)
}

/// The declaration a layer's property spec at `path` carries. An attribute
/// without a `typeName` is [`sdf::ValueTypeError::Empty`], a field holding
/// the wrong variant [`sdf::SpecError::FieldType`], and a decode failure a
/// [`sdf::DataError`]: a malformed declaration is never silently repaired.
fn declaration_of(
    data: &dyn sdf::AbstractData,
    path: &sdf::Path,
    wanted: sdf::SpecType,
) -> Result<PropertyDeclaration, StageAuthoringError> {
    match data.spec_type(path) {
        Some(sdf::SpecType::Attribute) => {
            let spec = sdf::AttributeSpecRef::get(data, path.clone()).expect("the kind was checked");
            Ok(PropertyDeclaration::Attribute {
                type_name: spec.declared_type()?.ok_or(sdf::ValueTypeError::Empty)?,
                variability: spec
                    .typed_field(sdf::FieldKey::Variability, "Variability")?
                    .unwrap_or_default(),
                custom: spec.typed_field(sdf::FieldKey::Custom, "Bool")?.unwrap_or(false),
            })
        }
        Some(sdf::SpecType::Relationship) => {
            let spec = sdf::RelationshipSpecRef::get(data, path.clone()).expect("the kind was checked");
            Ok(PropertyDeclaration::Relationship {
                variability: spec
                    .typed_field(sdf::FieldKey::Variability, "Variability")?
                    .unwrap_or_default(),
                custom: spec.typed_field(sdf::FieldKey::Custom, "Bool")?.unwrap_or(false),
            })
        }
        Some(found) => Err(kind_mismatch(path, wanted, found)),
        None => Err(missing_spec(path, wanted)),
    }
}

fn stamp(
    data: &mut dyn sdf::AbstractData,
    path: &sdf::Path,
    declaration: &PropertyDeclaration,
) -> Result<(), StageAuthoringError> {
    match declaration {
        PropertyDeclaration::Attribute {
            type_name,
            variability,
            custom,
        } => {
            sdf::AttributeSpec::new(data, path.clone(), type_name.clone(), *variability, *custom)?;
        }
        PropertyDeclaration::Relationship { variability, custom } => {
            sdf::RelationshipSpec::new(data, path.clone(), *variability, *custom)?;
        }
    }
    Ok(())
}

fn kind_mismatch(path: &sdf::Path, expected: sdf::SpecType, found: sdf::SpecType) -> StageAuthoringError {
    StageAuthoringError::SpecKindMismatch {
        path: path.clone(),
        expected,
        found,
    }
}

/// The error for a `kind` spec the edit target was expected to hold at
/// `path` and does not.
pub(super) fn missing_spec(path: &sdf::Path, kind: sdf::SpecType) -> StageAuthoringError {
    let reason = match kind {
        sdf::SpecType::Prim => "no prim spec at path on the edit target layer",
        sdf::SpecType::Attribute => "no attribute spec at path on the edit target layer",
        sdf::SpecType::Relationship => "no relationship spec at path on the edit target layer",
        _ => "no spec at path on the edit target layer",
    };
    sdf::AuthoringError::InvalidPath {
        path: path.clone(),
        reason,
    }
    .into()
}

#[cfg(test)]
mod tests {
    use crate::Result;
    use crate::sdf;
    use crate::usd::{EditTarget, Stage, StageAuthoringError, TimeCode};

    fn stage() -> Result<Stage> {
        Stage::builder().in_memory("anon.usda")
    }

    /// An edit target on the same layer that maps `/World` into a variant, so
    /// a property planned against the stage's own target would land elsewhere
    /// through this one.
    fn variant_target(stage: &Stage) -> Result<EditTarget, sdf::PathParseError> {
        let root = stage.edit_target().layer_identifier().to_string();
        EditTarget::for_local_direct_variant(root, "/World{set=sel}")
    }

    /// Attributes and relationships share the one batch, and the closure's own
    /// value comes back once they commit.
    #[test]
    fn batch_authors_together() -> Result<()> {
        let stage = stage()?;
        stage.define_prim("/World")?;
        let (height, proxy) = stage.edit(|edit| {
            let world = edit.prim("/World")?;
            let height = world.attribute_builder("height", "double").set(2.0).build()?;
            let proxy = world
                .relationship_builder("proxy")
                .custom(false)
                .set_targets(["/World"])
                .build()?;
            Ok::<_, StageAuthoringError>((height, proxy))
        })?;

        assert_eq!(height.get::<f64>()?, Some(2.0));
        assert_eq!(proxy.targets()?, vec![sdf::Path::new("/World")?]);
        assert!(!proxy.is_custom()?);
        Ok(())
    }

    /// A property path reaches the batch without naming its prim first.
    #[test]
    fn batch_takes_property_paths() -> Result<()> {
        let stage = stage()?;
        stage.define_prim("/World")?;
        let height = stage.edit(|edit| edit.attribute_builder("/World.height", "double").set(2.0).build())?;

        assert_eq!(height.get::<f64>()?, Some(2.0));
        Ok(())
    }

    /// Where a builder came from is what puts it in the transaction: one taken
    /// from the prim itself commits on its own, batch or no batch.
    #[test]
    fn prim_builder_commits_now() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let failed = stage.edit(|edit| {
            prim.attribute_builder("height", "double").set(2.0).build()?;
            edit.prim("/World")?
                .attribute_builder("radius", "double")
                .set(1.0)
                .build()?;
            Err::<(), _>(StageAuthoringError::OutsideEditTarget {
                path: sdf::Path::new("/World.radius")?,
            })
        });

        assert!(failed.is_err());
        // The queued property is rolled back with the batch; the one that
        // committed on its own is already on the stage.
        assert!(prim.attribute("height").is_defined()?);
        assert!(!prim.attribute("radius").is_defined()?);
        Ok(())
    }

    /// A closure that gives up leaves the stage as it was, however much it
    /// queued first.
    #[test]
    fn batch_error_authors_none() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let failed = stage.edit(|edit| {
            edit.prim("/World")?
                .attribute_builder("height", "double")
                .set(2.0)
                .build()?;
            Err::<(), _>(StageAuthoringError::OutsideEditTarget {
                path: sdf::Path::new("/World.height")?,
            })
        });

        assert!(matches!(failed, Err(StageAuthoringError::OutsideEditTarget { .. })));
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// Two plans for one property would each resolve against a stage the other
    /// has not changed, so the batch refuses the second.
    #[test]
    fn duplicate_property_rejected() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let failed = stage.edit(|edit| {
            let world = edit.prim("/World")?;
            world.attribute_builder("height", "double").set(2.0).build()?;
            world.attribute_builder("height", "double").set(3.0).build()
        });

        assert!(matches!(failed, Err(StageAuthoringError::DuplicateProperty { .. })));
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// A queued property was planned against one edit target — its spec path,
    /// its value and its sample time all mapped through that target — so the
    /// batch refuses to write it through another.
    #[test]
    fn target_move_rejected() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let variant = variant_target(&stage)?;

        let failed = stage.edit(|edit| {
            edit.prim("/World")?
                .attribute_builder("height", "double")
                .set_at(2.0, TimeCode::new(15.0))
                .build()?;
            stage.set_edit_target(variant.clone())?;
            Ok(())
        });

        assert!(matches!(failed, Err(StageAuthoringError::EditTargetMoved)));
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// The same move caught as it happens, rather than at the commit that
    /// would have written through the wrong target.
    #[test]
    fn target_move_rejects_queue() -> Result<()> {
        let stage = stage()?;
        stage.define_prim("/World")?;
        let variant = variant_target(&stage)?;

        let failed = stage.edit(|edit| {
            stage.set_edit_target(variant.clone())?;
            edit.prim("/World")?
                .attribute_builder("height", "double")
                .set(2.0)
                .build()
        });

        assert!(matches!(failed, Err(StageAuthoringError::EditTargetMoved)));
        Ok(())
    }

    /// A caller's own error, as a layer above the stage would carry one.
    #[derive(Debug)]
    enum CallerError {
        Refused,
        Stage(StageAuthoringError),
    }

    impl From<StageAuthoringError> for CallerError {
        fn from(error: StageAuthoringError) -> Self {
            Self::Stage(error)
        }
    }

    /// The closure's own error comes back as it was, and nothing it queued is
    /// written.
    #[test]
    fn edit_carries_caller_error() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let failed = stage.edit(|edit| {
            edit.prim("/World")
                .map_err(StageAuthoringError::from)?
                .attribute_builder("height", "double")
                .set(2.0)
                .build()?;
            Err::<(), _>(CallerError::Refused)
        });

        assert!(matches!(failed, Err(CallerError::Refused)));
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// A failure at the commit reaches the caller in the caller's error type.
    #[test]
    fn commit_error_converts() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        let variant = variant_target(&stage)?;
        let failed = stage.edit(|edit| {
            edit.attribute_builder("/World.height", "double").set(2.0).build()?;
            stage.set_edit_target(variant.clone())?;
            Ok::<_, CallerError>(())
        });

        assert!(matches!(
            failed,
            Err(CallerError::Stage(StageAuthoringError::EditTargetMoved))
        ));
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// A group's properties join the batch they were grouped in, and commit
    /// with it.
    #[test]
    fn group_joins_batch() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        stage.edit(|edit| {
            let world = edit.prim("/World")?;
            world.attribute_builder("radius", "double").set(1.0).build()?;
            world.group(|group| {
                group.attribute_builder("height", "double").set(2.0).build()?;
                group.attribute_builder("width", "double").set(3.0).build()?;
                Ok::<_, StageAuthoringError>(())
            })?;
            assert!(!prim.attribute("height").is_defined()?, "nothing is written yet");
            Ok::<_, crate::Error>(())
        })?;

        for (name, value) in [("radius", 1.0), ("height", 2.0), ("width", 3.0)] {
            assert_eq!(prim.attribute(name).get::<f64>()?, Some(value), "{name}");
        }
        Ok(())
    }

    /// A group that fails queues none of its properties, so a caller that
    /// goes on from the error commits only what it queued itself.
    #[test]
    fn group_error_queues_nothing() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        stage.edit(|edit| {
            let world = edit.prim("/World")?;
            world.attribute_builder("radius", "double").set(1.0).build()?;
            let failed = world.group(|group| {
                group.attribute_builder("height", "double").set(2.0).build()?;
                Err::<(), _>(CallerError::Refused)
            });
            assert!(matches!(failed, Err(CallerError::Refused)));
            Ok::<_, StageAuthoringError>(())
        })?;

        assert!(prim.attribute("radius").is_defined()?);
        assert!(!prim.attribute("height").is_defined()?);
        Ok(())
    }

    /// A group naming a property the batch already holds joins it with none
    /// of its properties, the ones that did not collide included.
    #[test]
    fn group_duplicate_absorbs_nothing() -> Result<()> {
        let stage = stage()?;
        let prim = stage.define_prim("/World")?;
        stage.edit(|edit| {
            let world = edit.prim("/World")?;
            world.attribute_builder("height", "double").set(2.0).build()?;
            let failed = world.group(|group| {
                group.attribute_builder("width", "double").set(3.0).build()?;
                group.attribute_builder("height", "double").set(4.0).build()?;
                Ok::<_, StageAuthoringError>(())
            });
            assert!(matches!(failed, Err(StageAuthoringError::DuplicateProperty { .. })));
            Ok::<_, StageAuthoringError>(())
        })?;

        assert_eq!(prim.attribute("height").get::<f64>()?, Some(2.0));
        assert!(!prim.attribute("width").is_defined()?);
        Ok(())
    }

    /// A group plans against the target its batch opened on, so a target
    /// moved under it is refused there as well.
    #[test]
    fn group_shares_target() -> Result<()> {
        let stage = stage()?;
        stage.define_prim("/World")?;
        let variant = variant_target(&stage)?;
        let failed = stage.edit(|edit| {
            edit.group(|group| {
                stage.set_edit_target(variant.clone())?;
                group.attribute_builder("/World.height", "double").set(2.0).build()
            })
        });

        assert!(matches!(failed, Err(StageAuthoringError::EditTargetMoved)));
        Ok(())
    }

    /// An empty batch is a no-op that still hands back the closure's value.
    #[test]
    fn empty_batch_authors_nothing() -> Result<()> {
        let stage = stage()?;
        assert_eq!(stage.edit(|_| Ok::<_, StageAuthoringError>(7))?, 7);
        Ok(())
    }
}