File size: 3,608 Bytes
12f41e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Ownership of asset callbacks across USD subtree replacement.

This module uses USD only; standalone asset scripts need no benchmark runtime.
The benchmark retires owners before deleting a subtree. USD notices also make
callbacks harmless when an editor removes the subtree directly.
"""

from collections.abc import Callable
from weakref import WeakSet

from pxr import Sdf, Tf, Usd


_owners = WeakSet()


class SceneOwner:
    """A lease on one original prim, never a lookup of its replacement."""

    def __init__(self, prim: Usd.Prim, retire: Callable[[], None]) -> None:
        if not prim or not prim.IsValid():
            raise ValueError("Cannot own callbacks for an invalid USD prim")
        self.prim = prim
        self.stage = prim.GetStage()
        self.path = prim.GetPath()
        self.generation = 0
        self.closed = False
        self._retire = retire
        self._context = None
        self._stage_subscription = None
        self._notice = Tf.Notice.Register(
            Usd.Notice.ObjectsChanged, self._objects_changed, self.stage
        )
        try:
            import omni.usd
        except ModuleNotFoundError as error:
            if error.name not in {"omni", "omni.usd"}:
                self._notice.Revoke()
                raise
        else:
            try:
                context = omni.usd.get_context()
                if context.get_stage() == self.stage:
                    self._context = context
                    self._stage_subscription = context.get_stage_event_stream().create_subscription_to_pop(
                        self._stage_changed
                    )
            except BaseException:
                self._notice.Revoke()
                self._stage_subscription = None
                raise
        _owners.add(self)

    @property
    def stage_active(self) -> bool:
        return self._context is None or self._context.get_stage() == self.stage

    @property
    def valid(self) -> bool:
        """Whether rollback may still touch the original object."""
        return (
            bool(self.prim)
            and self.prim.IsValid()
            and self.stage_active
        )

    @property
    def current(self) -> bool:
        return not self.closed and self.valid

    def _objects_changed(self, notice, sender):
        if not self.valid:
            self.close()

    def _stage_changed(self, event):
        if not self.valid:
            self.close()

    def close(self) -> None:
        """Invalidate queued work before releasing subscriptions; run once."""
        if self.closed:
            return
        self.closed = True
        self.generation += 1
        notice, self._notice = self._notice, None
        if notice is not None:
            notice.Revoke()
        self._stage_subscription = None
        retire, self._retire = self._retire, None
        _owners.discard(self)
        retire()


def retire_scope(stage: Usd.Stage, root_path: str | Sdf.Path) -> None:
    """Synchronously retire all owners before removing their original USD root.

    Continue releasing other owners if one cleanup fails, then fail the scene
    switch rather than deleting a subtree whose cleanup did not complete.
    """
    root = Sdf.Path(root_path)
    failures = []
    for owner in list(_owners):
        if owner.stage == stage and owner.path.HasPrefix(root):
            try:
                owner.close()
            except Exception as error:
                failures.append(f"{owner.path}: {error}")
    if failures:
        raise RuntimeError("Asset callback cleanup failed: " + "; ".join(failures))