Skip to main content

nsi_intermediate/
edge.rs

1//! Connection classification.
2//!
3//! An ɴsɪ connection is a typed multi-relation: its meaning depends on
4//! the destination attribute. Only [`EdgeKind::SurfaceShader`] and
5//! [`EdgeKind::ShaderNetwork`] become object references in a target
6//! renderer; the rest are scene membership, transform composition,
7//! instancing, or output routing.
8//!
9//! Defaulting an unrecognised destination to a reference would be the
10//! silent failure this module exists to prevent: a misclassified
11//! connection does not fail loudly, it renders, with materials on the
12//! wrong shapes or output routed nowhere.
13//!
14//! ɴsɪ's set of destinations is **open** -- its own §4.8 connects one
15//! `attributes` node to another's `visibility` to override a value --
16//! so it cannot be enumerated. Every `<connection>` attribute the
17//! specification declares has a name here, pinned by
18//! `tests/classifier.rs`; anything else becomes [`EdgeKind::Other`],
19//! carrying its own name.
20//!
21//! Most classes are *carried*, not resolved: a backend reads them off
22//! the edge list. Only membership, attribute binding, the shader slots,
23//! instancing and the output chain are walked, so an unrecognised
24//! destination cannot become a material by accident. The cost is that a
25//! typo is now quiet rather than loud -- as it is in the renderer.
26
27use crate::{OwnedArgument, OwnedData};
28
29/// What an ɴsɪ connection means, once classified.
30#[derive(Debug, Clone, PartialEq, Eq, Hash)]
31#[non_exhaustive]
32pub enum EdgeKind {
33    /// `X -> .root "objects"`, or a transform chain link. Membership and
34    /// hierarchy share one ɴsɪ attribute; which one an edge is depends
35    /// on whether the destination is `.root`, so the recorder resolves
36    /// that when it walks the graph rather than here.
37    SceneMember,
38    /// `attributes -> geo "geometryattributes"`. The attributes node has
39    /// no counterpart in either target renderer and is dissolved at
40    /// flush time.
41    AttributeBinding,
42    /// `shader -> attributes "surfaceshader"`. Becomes the shape's
43    /// material.
44    SurfaceShader,
45    /// `shader -> attributes "displacementshader"`.
46    DisplacementShader,
47    /// `shader -> attributes "volumeshader"`.
48    VolumeShader,
49    /// `shader -> camera "lensshader"`. ɴsɪ: "a lens shader is an osl
50    /// network connected to a camera through the lensshader
51    /// connection".
52    LensShader,
53    /// `outputlayer -> outputlayer "backgroundlayer"`.
54    BackgroundLayer,
55    /// `geometry -> attributes "bounds"`.
56    Bounds,
57    /// `set -> attributes "visibility.set.subsurface"`.
58    SubsurfaceSet,
59    /// `set -> .global "exclusiveshading"`.
60    ExclusiveShading,
61    /// `set -> geometry "facesets"`. ɴsɪ's own Listing 3.2.
62    FaceSet,
63    /// A connection to some other attribute, carried but never
64    /// interpreted.
65    ///
66    /// ɴsɪ permits connecting a node to an arbitrary attribute -- the
67    /// specification's own §4.8 connects one `attributes` node to
68    /// another's `visibility` with a `"value"` argument -- so the set of
69    /// legal destinations is open and cannot be enumerated. Rejecting
70    /// what is not listed made legal scenes unrecordable; interpreting
71    /// it would be the guess this module exists to refuse. So it is
72    /// kept, with its name, and resolution ignores it.
73    Other {
74        /// The destination attribute, verbatim.
75        to_attribute: String,
76    },
77    /// `geo -> instances "sourcemodels"`.
78    InstanceSource,
79    /// `node -> set "members"`. A `set` node groups nodes so one
80    /// connection stands for many.
81    SetMember,
82    /// `set -> outputlayer "lightset"`. ɴsɪ's documented light-set
83    /// workflow connects lights to a `set`, then the set here.
84    LightSet,
85    /// `shaderattributes -> geometry|transform "shaderattributes"`.
86    ShaderAttributes,
87    /// `screen -> camera "screens"`.
88    Screen,
89    /// `outputlayer -> screen "outputlayers"`.
90    OutputLayer,
91    /// `outputdriver -> outputlayer "outputdrivers"`.
92    OutputDriver,
93    /// An attribute-to-attribute shader network edge, naming ports on
94    /// both ends.
95    ///
96    /// This maps 1:1 onto OSL's `ConnectShaders`, which is unsurprising:
97    /// ɴsɪ was designed around OSL. Renderers whose references point at
98    /// whole objects rather than attributes need an adapter here.
99    ShaderNetwork {
100        /// The output port named on the source node.
101        from_port: String,
102        /// The input port named on the destination node.
103        to_port: String,
104    },
105}
106
107/// A recorded, classified connection.
108#[derive(Debug, Clone, PartialEq)]
109#[non_exhaustive]
110pub struct Edge {
111    /// The handle the connection is made from.
112    ///
113    /// Stored rather than public, so `ustr_handles` can intern it
114    /// without that showing in any signature: read it with
115    /// [`Edge::from`].
116    pub(crate) from: crate::handle::Handle,
117    /// The handle the connection is made to. Read it with
118    /// [`Edge::to`].
119    pub(crate) to: crate::handle::Handle,
120    /// What the connection means.
121    pub kind: EdgeKind,
122    /// The arguments of the ɴsɪ `connect` call that made this edge, in
123    /// call order.
124    ///
125    /// Kept whole rather than reduced to the one argument resolution
126    /// needs, so `"strength"` -- which blocks a recursive delete -- and
127    /// `"value"` survive for a backend that wants them, and so replay
128    /// can emit what was passed.
129    pub args: Vec<OwnedArgument>,
130}
131
132impl EdgeKind {
133    /// The ɴsɪ destination attribute this class came from.
134    ///
135    /// Inverse of [`classify`] for every class but
136    /// [`EdgeKind::ShaderNetwork`], whose destination is a port name the
137    /// caller already holds. The two must change together.
138    pub fn to_attribute(&self) -> &str {
139        match self {
140            Self::SceneMember => "objects",
141            Self::AttributeBinding => "geometryattributes",
142            Self::SurfaceShader => "surfaceshader",
143            Self::DisplacementShader => "displacementshader",
144            Self::VolumeShader => "volumeshader",
145            Self::LensShader => "lensshader",
146            Self::BackgroundLayer => "backgroundlayer",
147            Self::Bounds => "bounds",
148            Self::SubsurfaceSet => "visibility.set.subsurface",
149            Self::ExclusiveShading => "exclusiveshading",
150            Self::FaceSet => "facesets",
151            Self::Other { to_attribute } => to_attribute,
152            Self::InstanceSource => "sourcemodels",
153            Self::SetMember => "members",
154            Self::LightSet => "lightset",
155            Self::ShaderAttributes => "shaderattributes",
156            Self::Screen => "screens",
157            Self::OutputLayer => "outputlayers",
158            Self::OutputDriver => "outputdrivers",
159            Self::ShaderNetwork { to_port, .. } => to_port,
160        }
161    }
162}
163
164impl Edge {
165    /// ɴsɪ's `"priority"` connection argument, or `0` when absent.
166    ///
167    /// ɴsɪ ranks a repeated attribute definition by "the highest
168    /// priority", so a larger number wins. See
169    /// [`Scene::geometry_binding`].
170    ///
171    /// [`Scene::geometry_binding`]: crate::Scene::geometry_binding
172    pub fn priority(&self) -> i32 {
173        self.integer_argument("priority")
174    }
175
176    /// ɴsɪ's `"index"` connection argument, or `0` when absent.
177    ///
178    /// ɴsɪ: connections to `sourcemodels` "must have an integer index
179    /// attribute if there are several, so the models effectively form an
180    /// ordered list", and an `instances` node's `modelindices` "is
181    /// matched to the index attribute of the model connection".
182    pub fn index(&self) -> i32 {
183        self.integer_argument("index")
184    }
185
186    /// ɴsɪ's `"strength"` connection argument, or `0` when absent.
187    ///
188    /// ɴsɪ: "a connection with a strength greater than 0 will block the
189    /// progression of a recursive `NSIDelete`."
190    pub fn strength(&self) -> i32 {
191        self.integer_argument("strength")
192    }
193
194    /// One integer connection argument, or `0` when absent.
195    fn integer_argument(&self, name: &str) -> i32 {
196        self.args
197            .iter()
198            .find(|arg| arg.name == name)
199            .and_then(|arg| match &arg.data {
200                OwnedData::I32(values) => values.first().copied(),
201                OwnedData::I64(values) => values.first().map(|v| *v as i32),
202                _ => None,
203            })
204            .unwrap_or(0)
205    }
206}
207
208/// Classify a connection by its destination attribute.
209///
210/// A *named* `from_attribute` means the source names an output port, which
211/// only happens for shader-network edges. `Some("")` is not a name:
212/// ɴsɪ documents it as equivalent to `None`, meaning the `from` node
213/// itself is connected, so it classifies by destination like any other
214/// node-level connection.
215pub fn classify(from_attribute: Option<&str>, to_attribute: &str) -> EdgeKind {
216    // A named source port is always a shader network edge, whatever the
217    // destination is called.
218    if let Some(from_port) = from_attribute.filter(|port| !port.is_empty()) {
219        return EdgeKind::ShaderNetwork {
220            from_port: from_port.to_string(),
221            to_port: to_attribute.to_string(),
222        };
223    }
224
225    match to_attribute {
226        "objects" => EdgeKind::SceneMember,
227        "geometryattributes" => EdgeKind::AttributeBinding,
228        "surfaceshader" => EdgeKind::SurfaceShader,
229        "displacementshader" => EdgeKind::DisplacementShader,
230        "volumeshader" => EdgeKind::VolumeShader,
231        "lensshader" => EdgeKind::LensShader,
232        "backgroundlayer" => EdgeKind::BackgroundLayer,
233        "bounds" => EdgeKind::Bounds,
234        "visibility.set.subsurface" => EdgeKind::SubsurfaceSet,
235        "exclusiveshading" => EdgeKind::ExclusiveShading,
236        "sourcemodels" => EdgeKind::InstanceSource,
237        "members" => EdgeKind::SetMember,
238        "lightset" => EdgeKind::LightSet,
239        "shaderattributes" => EdgeKind::ShaderAttributes,
240        "screens" => EdgeKind::Screen,
241        "outputlayers" => EdgeKind::OutputLayer,
242        "outputdrivers" => EdgeKind::OutputDriver,
243        "facesets" => EdgeKind::FaceSet,
244        // Not an error: ɴsɪ's destinations are an open set. Carried,
245        // never resolved.
246        other => EdgeKind::Other {
247            to_attribute: other.to_string(),
248        },
249    }
250}
251
252impl Edge {
253    /// The handle the connection is made from.
254    pub fn from(&self) -> &str {
255        &self.from
256    }
257
258    /// The handle the connection is made to.
259    pub fn to(&self) -> &str {
260        &self.to
261    }
262}