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 /// `weld -> geometry "weld"`. The geometry's `weld.*` table declares
64 /// boundary uses in that `weld` node's namespace; see
65 /// [`Scene::weld_table`](crate::Scene::weld_table).
66 Weld,
67 /// A connection to some other attribute, carried but never
68 /// interpreted.
69 ///
70 /// ɴsɪ permits connecting a node to an arbitrary attribute -- the
71 /// specification's own §4.8 connects one `attributes` node to
72 /// another's `visibility` with a `"value"` argument -- so the set of
73 /// legal destinations is open and cannot be enumerated. Rejecting
74 /// what is not listed made legal scenes unrecordable; interpreting
75 /// it would be the guess this module exists to refuse. So it is
76 /// kept, with its name, and resolution ignores it.
77 Other {
78 /// The destination attribute, verbatim.
79 to_attribute: String,
80 },
81 /// `geo -> instances "sourcemodels"`.
82 InstanceSource,
83 /// `node -> set "members"`. A `set` node groups nodes so one
84 /// connection stands for many.
85 SetMember,
86 /// `set -> outputlayer "lightset"`. ɴsɪ's documented light-set
87 /// workflow connects lights to a `set`, then the set here.
88 LightSet,
89 /// `shaderattributes -> geometry|transform "shaderattributes"`.
90 ShaderAttributes,
91 /// `screen -> camera "screens"`.
92 Screen,
93 /// `outputlayer -> screen "outputlayers"`.
94 OutputLayer,
95 /// `outputdriver -> outputlayer "outputdrivers"`.
96 OutputDriver,
97 /// An attribute-to-attribute shader network edge, naming ports on
98 /// both ends.
99 ///
100 /// This maps 1:1 onto OSL's `ConnectShaders`, which is unsurprising:
101 /// ɴsɪ was designed around OSL. Renderers whose references point at
102 /// whole objects rather than attributes need an adapter here.
103 ShaderNetwork {
104 /// The output port named on the source node.
105 from_port: String,
106 /// The input port named on the destination node.
107 to_port: String,
108 },
109}
110
111/// A recorded, classified connection.
112#[derive(Debug, Clone, PartialEq)]
113#[non_exhaustive]
114pub struct Edge {
115 /// The handle the connection is made from.
116 ///
117 /// Stored rather than public, so `ustr_handles` can intern it
118 /// without that showing in any signature: read it with
119 /// [`Edge::from`].
120 pub(crate) from: crate::handle::Handle,
121 /// The handle the connection is made to. Read it with
122 /// [`Edge::to`].
123 pub(crate) to: crate::handle::Handle,
124 /// What the connection means.
125 pub kind: EdgeKind,
126 /// The arguments of the ɴsɪ `connect` call that made this edge, in
127 /// call order.
128 ///
129 /// Kept whole rather than reduced to the one argument resolution
130 /// needs, so `"strength"` -- which blocks a recursive delete -- and
131 /// `"value"` survive for a backend that wants them, and so replay
132 /// can emit what was passed.
133 pub args: Vec<OwnedArgument>,
134}
135
136impl EdgeKind {
137 /// The ɴsɪ destination attribute this class came from.
138 ///
139 /// Inverse of [`classify`] for every class but
140 /// [`EdgeKind::ShaderNetwork`], whose destination is a port name the
141 /// caller already holds. The two must change together.
142 pub fn to_attribute(&self) -> &str {
143 match self {
144 Self::SceneMember => "objects",
145 Self::AttributeBinding => "geometryattributes",
146 Self::SurfaceShader => "surfaceshader",
147 Self::DisplacementShader => "displacementshader",
148 Self::VolumeShader => "volumeshader",
149 Self::LensShader => "lensshader",
150 Self::BackgroundLayer => "backgroundlayer",
151 Self::Bounds => "bounds",
152 Self::SubsurfaceSet => "visibility.set.subsurface",
153 Self::ExclusiveShading => "exclusiveshading",
154 Self::FaceSet => "facesets",
155 Self::Weld => "weld",
156 Self::Other { to_attribute } => to_attribute,
157 Self::InstanceSource => "sourcemodels",
158 Self::SetMember => "members",
159 Self::LightSet => "lightset",
160 Self::ShaderAttributes => "shaderattributes",
161 Self::Screen => "screens",
162 Self::OutputLayer => "outputlayers",
163 Self::OutputDriver => "outputdrivers",
164 Self::ShaderNetwork { to_port, .. } => to_port,
165 }
166 }
167}
168
169impl Edge {
170 /// ɴsɪ's `"priority"` connection argument, or `0` when absent.
171 ///
172 /// ɴsɪ ranks a repeated attribute definition by "the highest
173 /// priority", so a larger number wins. See
174 /// [`Scene::geometry_binding`].
175 ///
176 /// [`Scene::geometry_binding`]: crate::Scene::geometry_binding
177 pub fn priority(&self) -> i32 {
178 self.integer_argument("priority")
179 }
180
181 /// ɴsɪ's `"index"` connection argument, or `0` when absent.
182 ///
183 /// ɴsɪ: connections to `sourcemodels` "must have an integer index
184 /// attribute if there are several, so the models effectively form an
185 /// ordered list", and an `instances` node's `modelindices` "is
186 /// matched to the index attribute of the model connection".
187 pub fn index(&self) -> i32 {
188 self.integer_argument("index")
189 }
190
191 /// ɴsɪ's `"strength"` connection argument, or `0` when absent.
192 ///
193 /// ɴsɪ: "a connection with a strength greater than 0 will block the
194 /// progression of a recursive `NSIDelete`."
195 pub fn strength(&self) -> i32 {
196 self.integer_argument("strength")
197 }
198
199 /// One integer connection argument, or `0` when absent.
200 fn integer_argument(&self, name: &str) -> i32 {
201 self.args
202 .iter()
203 .find(|arg| arg.name == name)
204 .and_then(|arg| match &arg.data {
205 OwnedData::I32(values) => values.first().copied(),
206 OwnedData::I64(values) => values.first().map(|v| *v as i32),
207 _ => None,
208 })
209 .unwrap_or(0)
210 }
211}
212
213/// Classify a connection by its destination attribute.
214///
215/// A *named* `from_attribute` means the source names an output port, which
216/// only happens for shader-network edges. `Some("")` is not a name:
217/// ɴsɪ documents it as equivalent to `None`, meaning the `from` node
218/// itself is connected, so it classifies by destination like any other
219/// node-level connection.
220pub fn classify(from_attribute: Option<&str>, to_attribute: &str) -> EdgeKind {
221 classify_on("", from_attribute, to_attribute)
222}
223
224/// The same, knowing the node the connection is made *to*.
225///
226/// One destination name means two things: a connection into `objects`
227/// is the models being instanced on an `instances` node -- what
228/// `sourcemodels` named before the [naming-convention draft] -- and
229/// scene membership everywhere else. Both spellings of every renamed
230/// destination classify alike, so a scene reads the same whichever
231/// vocabulary wrote it.
232///
233/// [naming-convention draft]: https://nsi.readthedocs.io/en/latest/naming-convention.html
234pub fn classify_on(
235 to_node_type: &str,
236 from_attribute: Option<&str>,
237 to_attribute: &str,
238) -> EdgeKind {
239 // A named source port is always a shader network edge, whatever the
240 // destination is called.
241 if let Some(from_port) = from_attribute.filter(|port| !port.is_empty()) {
242 return EdgeKind::ShaderNetwork {
243 from_port: from_port.to_string(),
244 to_port: to_attribute.to_string(),
245 };
246 }
247
248 // The draft's spellings classify as the shipped ones they replace,
249 // so a scene reads the same whichever vocabulary wrote it.
250 let to_attribute =
251 crate::names::legacy_attribute(to_node_type, to_attribute)
252 .unwrap_or(to_attribute);
253
254 match to_attribute {
255 // `objects` on an `instances` node was normalized to
256 // `sourcemodels` just above, the draft having renamed it there;
257 // anywhere else the word is scene membership.
258 "objects" => EdgeKind::SceneMember,
259 "geometryattributes" => EdgeKind::AttributeBinding,
260 "surfaceshader" => EdgeKind::SurfaceShader,
261 "displacementshader" => EdgeKind::DisplacementShader,
262 "volumeshader" => EdgeKind::VolumeShader,
263 "lensshader" => EdgeKind::LensShader,
264 "backgroundlayer" => EdgeKind::BackgroundLayer,
265 "bounds" => EdgeKind::Bounds,
266 "visibility.set.subsurface" => EdgeKind::SubsurfaceSet,
267 "exclusiveshading" => EdgeKind::ExclusiveShading,
268 "sourcemodels" => EdgeKind::InstanceSource,
269 "members" => EdgeKind::SetMember,
270 "lightset" => EdgeKind::LightSet,
271 "shaderattributes" => EdgeKind::ShaderAttributes,
272 "screens" => EdgeKind::Screen,
273 "outputlayers" => EdgeKind::OutputLayer,
274 "outputdrivers" => EdgeKind::OutputDriver,
275 "facesets" => EdgeKind::FaceSet,
276 "weld" => EdgeKind::Weld,
277 // Not an error: ɴsɪ's destinations are an open set. Carried,
278 // never resolved.
279 other => EdgeKind::Other {
280 to_attribute: other.to_string(),
281 },
282 }
283}
284
285impl Edge {
286 /// The handle the connection is made from.
287 pub fn from(&self) -> &str {
288 &self.from
289 }
290
291 /// The handle the connection is made to.
292 pub fn to(&self) -> &str {
293 &self.to
294 }
295}