Skip to main content

nsi_intermediate/resolve/
mod.rs

1//! Graph rewrites: turning ɴsɪ's scene-graph semantics into the flat
2//! facts a renderer wants.
3//!
4//! Both target renderers need this and neither should re-derive it.
5//! Mitsuba has no transform tree, only a `to_world` per shape; MoonRay
6//! resolves geometry to world space too. So the chain has to be
7//! composed here, once.
8
9use crate::{Edge, EdgeKind, HashSet, Node, OwnedArgument, OwnedData, Scene};
10use core::{cmp::Ordering, fmt};
11
12mod attributes;
13mod chain;
14mod instances;
15mod mesh;
16mod motion;
17mod outputs;
18mod primvar;
19mod weld;
20
21// The types are here; the walks are in the five modules above. Split
22// at 2530 lines against a stated 300-500, along the seams the code
23// already had: a chain walk, a time rule, an attribute rule, the
24// instancer, and the output chain. `mod.rs` keeps what all five need
25// so none of them has to reach sideways.
26pub use chain::WorldTransforms;
27pub use instances::Instances;
28pub use mesh::{Face, Faces};
29pub use motion::Sampled;
30pub use primvar::{Interpolation, PrimitiveVariable};
31pub use weld::{
32    NurbsSide, Weld, WeldKind, WeldProblem, WeldProblemKind, WeldSegment,
33    WeldTable, WeldUse, Welds,
34};
35
36/// A 4x4 identity, row-major.
37#[rustfmt::skip]
38pub const IDENTITY: [f64; 16] = [
39    1.0, 0.0, 0.0, 0.0,
40    0.0, 1.0, 0.0, 0.0,
41    0.0, 0.0, 1.0, 0.0,
42    0.0, 0.0, 0.0, 1.0,
43];
44
45// The names here are the naming-convention draft's, which is what a
46// `Scene` stores whichever vocabulary wrote it. See spec 012.
47
48/// The ɴsɪ attribute holding a transform node's matrix.
49const TRANSFORMATION_MATRIX: &str = "matrix";
50
51/// An `instances` node's per-instance matrices.
52const MATRICES: &str = "matrices";
53
54/// Which prototype each instance draws.
55const MODEL_INDICES: &str = "object-index";
56
57/// `mesh` topology, which only means something as a pair.
58const FACE_VERTEX_COUNTS: &str = "vertex-count";
59const HOLE_COUNTS: &str = "hole-count";
60
61/// Positions, and ɴsɪ's indirect-lookup suffix.
62const POSITIONS: &str = "P";
63const INDICES: &str = ".indices";
64
65// `outputlayer` attribute names, spelled once. The defaults they fall
66// back to live with `Scene::output_layer`, next to the specification
67// section that states them.
68const VARIABLE_NAME: &str = "variable-name";
69const VARIABLE_SOURCE: &str = "variable-source";
70const LAYER_NAME: &str = "layer-name";
71const LAYER_TYPE: &str = "layer-type";
72const SCALAR_FORMAT: &str = "scalar-format";
73const WITH_ALPHA: &str = "with-alpha";
74const DITHERING: &str = "dithering";
75const FILTER: &str = "filter.name";
76const FILTER_WIDTH: &str = "filter.width";
77const COLOR_PROFILE: &str = "color-profile";
78const SORT_KEY: &str = "sort-key";
79
80/// The instances an `instances` node skips.
81const DISABLED: &str = "disabled-index";
82
83/// Why a scene could not be resolved into flat facts.
84///
85/// Every variant is a scene ɴsɪ permits but this crate refuses to guess
86/// about. Returning a matrix or a binding anyway would be the silent
87/// failure the crate exists to prevent: it renders, with the wrong
88/// answer.
89#[derive(Debug, Clone, PartialEq)]
90#[non_exhaustive]
91pub enum ResolveError {
92    /// A node is connected to more than one parent.
93    ///
94    /// Usually through `objects`; a prototype connected to two
95    /// `instances` nodes is the same problem.
96    ///
97    /// That is ɴsɪ's lightweight instancing: the node appears once per
98    /// path, each with its own world transform. A single matrix cannot
99    /// describe it, so resolving one is refused rather than silently
100    /// answering for whichever parent was connected first.
101    MultipleParents {
102        /// The node with more than one parent.
103        handle: String,
104        /// Every parent, in connection order.
105        parents: Vec<String>,
106    },
107    /// A node carries motion-sampled placement data where a single
108    /// answer was asked for.
109    ///
110    /// Either a `transformationmatrix` on a node in the chain, or an
111    /// `instances` node's `transformationmatrices`, `modelindices` or
112    /// `disabledinstances`. Answering with the static value would hand
113    /// a motion-blurred scene back its unblurred pose, and answering
114    /// with an empty list -- which the instancer path used to do --
115    /// reads as "nothing to draw".
116    ///
117    /// Ask at a time instead:
118    /// [`Scene::world_transform_interpolated_at`],
119    /// [`Scene::placements_at`] or
120    /// [`Scene::instance_transforms_at`].
121    MotionSampledTransform {
122        /// The node whose transform is motion-sampled.
123        handle: String,
124    },
125    /// The transform chain revisits a node. ɴsɪ does not forbid a cycle;
126    /// no correct answer exists for one.
127    Cycle {
128        /// The node the walk arrived at twice.
129        handle: String,
130    },
131    /// The node is not connected to `.root`, directly or through
132    /// transforms.
133    ///
134    /// ɴsɪ: "A node can exist in an nsi context without being connected
135    /// to the root node but in that case it won't affect the render in
136    /// any way." It has no world transform and no gathered attributes,
137    /// and answering identity would put unrendered geometry at the
138    /// origin.
139    Detached {
140        /// The node that does not reach `.root`.
141        handle: String,
142    },
143    /// No node with that handle exists.
144    ///
145    /// Asking about an attribute of a node that was never created is a
146    /// caller mistake, and answering "not sampled" would read as a fact
147    /// about the scene rather than about the question.
148    UnknownHandle {
149        /// The handle that names nothing.
150        handle: String,
151    },
152    /// The node is an instancing prototype, so it has no single world
153    /// transform.
154    ///
155    /// A prototype reaches the scene through an `instances` node, and
156    /// ɴsɪ gives that node "a transformation matrix for each instance".
157    /// Answering with the instancer's own transform would put every
158    /// instance in the same, wrong place.
159    Instanced {
160        /// The `instances` node the prototype is connected to.
161        instancer: String,
162    },
163    /// An `instances` node's `transformationmatrices` is not a whole
164    /// number of 4x4 matrices.
165    MalformedInstanceMatrices {
166        /// The `instances` node.
167        instances: String,
168        /// How many values it carries.
169        values: usize,
170    },
171    /// Two prototype connections share one `index`.
172    ///
173    /// ɴsɪ: connections "must have an integer index attribute if there
174    /// are several, so the models effectively form an ordered list" --
175    /// which a duplicate does not.
176    DuplicateModelIndex {
177        /// The `instances` node.
178        instances: String,
179        /// The index used twice.
180        index: i32,
181    },
182    /// A `modelindices` entry matches no prototype connection's
183    /// `index`.
184    UnknownModelIndex {
185        /// The `instances` node.
186        instances: String,
187        /// The index that matches nothing.
188        model: i32,
189    },
190    /// [`Scene::relative_transform`] was given a node that is not on the
191    /// chain.
192    NotAnAncestor {
193        /// The node whose chain was walked.
194        handle: String,
195        /// The node that is not on it.
196        ancestor: String,
197    },
198    /// A node in the chain is motion-sampled, but has no sample at the
199    /// requested time.
200    ///
201    /// From the **exact-hit** accessors only -- [`Scene::world_transform_at`],
202    /// [`Scene::world_transform_samples`] and
203    /// [`Scene::instance_transforms`] answer where a sample exists and
204    /// refuse elsewhere, which is the right answer to "what did the
205    /// caller record".
206    ///
207    /// For "where is it mid-shutter", ask
208    /// [`Scene::world_transform_interpolated_at`],
209    /// [`Scene::placements_at`] or
210    /// [`Scene::instance_transforms_at`]. Those interpolate
211    /// element-wise, which is the renderer's own model rather than a
212    /// guess -- 3Delight's rotation blur fits component-wise far better
213    /// than slerp -- and they hold the end sample outside the sampled
214    /// range, as it does.
215    ///
216    /// The interpolating accessors still return this for a time that
217    /// names no sample at all, such as a NaN. An earlier version of
218    /// this said the crate never interpolates and that the
219    /// decomposition was the backend's; that stopped being true when
220    /// those accessors were added.
221    MissingSampleAtTime {
222        /// The node with no sample at that time.
223        handle: String,
224        /// The time that was asked for.
225        time: f64,
226        /// The times that node does have, ascending.
227        available: Vec<f64>,
228    },
229    /// A `mesh` has no `nvertices`, which ɴsɪ requires.
230    MissingFaceCounts {
231        /// The mesh.
232        handle: String,
233    },
234    /// A `<name>.indices` is not one entry per face-vertex, or points
235    /// outside the values it indexes.
236    ///
237    /// ɴsɪ says the indices say "which values of the other parameter to
238    /// use" and nothing about how many values there are, so the
239    /// indices are what must match the primitive.
240    MalformedIndices {
241        /// The primitive.
242        handle: String,
243        /// The attribute the indices belong to.
244        attribute: String,
245        /// How many indices there are.
246        indices: usize,
247        /// How many the primitive's face-vertices need.
248        face_vertices: usize,
249        /// How many values there are to index.
250        values: usize,
251    },
252    /// A primitive variable's value count matches none of the four
253    /// interpolations.
254    ///
255    /// Constant is one value, uniform is one per face, vertex is one
256    /// per vertex and face-varying is one per face-vertex. A count
257    /// that is none of those has no meaning ɴsɪ defines, and guessing
258    /// one renders -- plausibly, and wrongly, which is how a wrong
259    /// normal survives review.
260    AmbiguousInterpolation {
261        /// The primitive.
262        handle: String,
263        /// The attribute.
264        attribute: String,
265        /// How many values it carries.
266        values: usize,
267        /// How many faces the primitive has.
268        faces: usize,
269        /// How many vertices.
270        vertices: usize,
271        /// How many face-vertices.
272        face_vertices: usize,
273    },
274    /// `nholes` and `nvertices` disagree.
275    ///
276    /// ɴsɪ: with `nholes` set, the face count is the number of `nholes`
277    /// values, and each face takes `nholes + 1` values from
278    /// `nvertices` -- the outer perimeter and then one per hole. A
279    /// count that does not add up leaves the faces undefined, and a
280    /// backend that reads `nvertices` as one-count-per-face draws a
281    /// different mesh without reporting anything.
282    MalformedFaceCounts {
283        /// The mesh.
284        handle: String,
285        /// How many `nvertices` values the holes ask for.
286        expected: usize,
287        /// How many there are.
288        found: usize,
289    },
290}
291
292impl fmt::Display for ResolveError {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        match self {
295            Self::MultipleParents { handle, parents } => write!(
296                f,
297                "ɴsɪ node {handle:?} has {} parents ({}); that is \
298                 instancing, which has one world transform per path, not \
299                 one overall",
300                parents.len(),
301                parents.join(", ")
302            ),
303            Self::MotionSampledTransform { handle } => write!(
304                f,
305                "ɴsɪ node {handle:?} carries motion-sampled placement \
306                 data; the static value would be the wrong answer, so \
307                 ask at a time instead"
308            ),
309            Self::Cycle { handle } => write!(
310                f,
311                "ɴsɪ transform chain revisits node {handle:?}; a cyclic \
312                 scene has no world transform"
313            ),
314            Self::UnknownHandle { handle } => {
315                write!(f, "no ɴsɪ node is named {handle:?}")
316            }
317            Self::Detached { handle } => write!(
318                f,
319                "ɴsɪ node {handle:?} is not connected to {root:?}, so it \
320                 is not in the scene and has no world transform",
321                root = crate::ROOT
322            ),
323            Self::Instanced { instancer } => write!(
324                f,
325                "ɴsɪ node is an instancing prototype of {instancer:?}, \
326                 which carries one transform per instance; there is no \
327                 single world transform for it"
328            ),
329            Self::MalformedInstanceMatrices { instances, values } => {
330                write!(
331                    f,
332                    "ɴsɪ node {instances:?} has {values} values in \
333                     transformationmatrices, which is not a whole number \
334                     of 4x4 matrices"
335                )
336            }
337            Self::DuplicateModelIndex { instances, index } => write!(
338                f,
339                "ɴsɪ node {instances:?} has two sourcemodels connections \
340                 at index {index}, so its models are not an ordered list"
341            ),
342            Self::UnknownModelIndex { instances, model } => write!(
343                f,
344                "ɴsɪ node {instances:?} selects model index {model}, which \
345                 matches no sourcemodels connection"
346            ),
347            Self::NotAnAncestor { handle, ancestor } => write!(
348                f,
349                "ɴsɪ node {ancestor:?} is not on {handle:?}'s chain, so \
350                 there is no transform of one relative to the other"
351            ),
352            Self::MissingSampleAtTime {
353                handle,
354                time,
355                available,
356            } => write!(
357                f,
358                "ɴsɪ node {handle:?} has no transform sample at time \
359                 {time}; it has {available:?}, and this crate does not \
360                 interpolate between them"
361            ),
362            Self::MalformedIndices {
363                handle,
364                attribute,
365                indices,
366                face_vertices,
367                values,
368            } => write!(
369                f,
370                "ɴsɪ primitive {handle:?} has {indices} {attribute:?} \
371                 indices for {face_vertices} face-vertices into {values} \
372                 values; indices are read per face-vertex"
373            ),
374            Self::AmbiguousInterpolation {
375                handle,
376                attribute,
377                values,
378                faces,
379                vertices,
380                face_vertices,
381            } => write!(
382                f,
383                "ɴsɪ primitive {handle:?} has {values} {attribute:?} values, \
384                 which is neither constant (1), per face ({faces}), per \
385                 vertex ({vertices}) nor per face-vertex ({face_vertices})"
386            ),
387            Self::MissingFaceCounts { handle } => write!(
388                f,
389                "ɴsɪ mesh {handle:?} sets no \"nvertices\", which ɴsɪ \
390                 requires; its faces are undefined"
391            ),
392            Self::MalformedFaceCounts {
393                handle,
394                expected,
395                found,
396            } => write!(
397                f,
398                "ɴsɪ mesh {handle:?} has \"nholes\" asking for {expected} \
399                 \"nvertices\" values and carries {found}; with holes, each \
400                 face takes its outer perimeter plus one count per hole"
401            ),
402        }
403    }
404}
405
406impl core::error::Error for ResolveError {}
407
408/// What an ɴsɪ `attributes` node resolves to for one piece of geometry.
409#[derive(Debug, Clone, PartialEq, Eq, Hash)]
410#[non_exhaustive]
411pub struct Binding {
412    /// Every `attributes` node gathered along the path, nearest the
413    /// geometry first, then in connection order.
414    ///
415    /// The `priority` on a `geometryattributes` connection deliberately
416    /// does **not** reorder this: 3Delight ignores it, whatever the
417    /// specification says. A priority on a *shader* connection is
418    /// honoured; see [`Binding::surface_shader`] and `research.md` D12.
419    ///
420    /// ɴsɪ gathers attributes along the whole path and considers
421    /// *every* node on it -- "one attributes node can set object
422    /// visibility and another can set the surface shader" -- so this is
423    /// a list, not a winner. A backend looking for one attribute takes
424    /// the first node in this list that defines it -- correct only while
425    /// no node sets `ATTR.priority` and the attribute is not a
426    /// visibility one. [`Scene::attribute_value`] applies those two
427    /// rules and is the safe way to ask.
428    ///
429    /// When this [`Binding`] came from a [`Placement`], ask
430    /// [`Scene::attribute_value_along`] with that placement's path
431    /// instead: `attribute_value` takes a geometry, so it refuses the
432    /// multi-parent node a placement exists for.
433    ///
434    /// The handles are returned rather than their contents because what
435    /// lives on them -- visibility flags above all -- is encoded
436    /// differently by each renderer, and inventing a common shape for it
437    /// here would be guesswork.
438    pub attributes: Vec<String>,
439    /// The shader reached through `surfaceshader`, resolved across every
440    /// gathered node by the same rule, using the priority of the
441    /// `surfaceshader` connection itself.
442    ///
443    /// `None` when nothing on the path sets one.
444    pub surface_shader: Option<String>,
445    /// The `displacementshader`, resolved the same way.
446    pub displacement_shader: Option<String>,
447    /// The `volumeshader`, resolved the same way.
448    pub volume_shader: Option<String>,
449}
450
451/// ɴsɪ's ray types: the suffixes a `visibility.<ray>` attribute takes.
452///
453/// Spelled out rather than accepting any suffix, because
454/// `visibility.set.subsurface` is a *connection* to a `set` node and not
455/// a per-ray visibility int; treating it as the more specific form of
456/// `visibility` would rank a connection against a flag.
457///
458/// Public because a backend building a visibility mask needs exactly
459/// this list, and a second copy of it would drift from this one.
460pub const RAY_TYPES: [&str; 8] = [
461    "camera",
462    "diffuse",
463    "hair",
464    "reflection",
465    "refraction",
466    "shadow",
467    "specular",
468    "volume",
469];
470
471/// One placement of a geometry in the scene.
472///
473/// ɴsɪ's *lightweight* instancing: connecting a node to two transforms
474/// draws it twice, once per path. Rendered, a quad under two transforms
475/// translated `-2` and `+2` appears at both positions, and putting
476/// `visibility 1` on one parent and `visibility 0` on the other draws
477/// **one** copy -- so a path carries its own attributes as well as its
478/// own transform, and a backend emitting one instance per placement
479/// needs both together.
480#[derive(Debug, Clone, PartialEq)]
481#[non_exhaustive]
482pub struct Placement {
483    /// The nodes from the geometry to `.root`, geometry first.
484    ///
485    /// Two placements of one geometry differ here, and that is what
486    /// makes them distinguishable: the handle alone does not.
487    pub path: Vec<String>,
488    /// The world transform along this path.
489    pub transform: [f64; 16],
490    /// What binds along this path, or `None` when nothing does.
491    ///
492    /// The same shape [`Scene::geometry_binding`] returns, resolved
493    /// against this path rather than against "the" path.
494    pub binding: Option<Binding>,
495}
496
497/// The winning definition of one attribute, gathered along a path.
498///
499/// Returned by [`Scene::attribute_value`].
500#[derive(Debug, Clone, Copy, PartialEq)]
501#[non_exhaustive]
502pub struct AttributeValue<'a> {
503    /// The node the winning definition sits on.
504    ///
505    /// Usually an `attributes` node. For a shader attribute it can be
506    /// the geometry itself, which ɴsɪ ranks above every container.
507    pub node: &'a str,
508    /// The attribute that actually won, which is not always the one
509    /// asked for: in [`Scene::attribute_value`] a `visibility.<ray>`
510    /// query falls back to the less specific `visibility`, and this is
511    /// how a backend tells the two apart.
512    /// [`Scene::shader_attribute_value`] performs no such fallback, so
513    /// there it always matches the query.
514    pub name: &'a str,
515    /// The definition itself, or `None` when the winning node carries
516    /// only `<name>.priority`.
517    ///
518    /// 3Delight reads a lone `ATTR.priority` as a definition of `ATTR`
519    /// **at its ɴsɪ default**, and it wins on the strength of that
520    /// priority; [`Scene::attribute_value`] has the rendered evidence.
521    /// This crate does not carry ɴsɪ's per-attribute defaults, so it
522    /// names the winner and leaves the value to the backend: `None`
523    /// means *the default of [`AttributeValue::name`]*, never
524    /// *undefined*.
525    pub arg: Option<&'a OwnedArgument>,
526    /// The `ATTR.priority` that selected it; `0` when none is set.
527    pub priority: i32,
528}
529
530/// An attribute that two or more nodes define at the same rank, so that
531/// only the order they were connected in decides which one applies.
532///
533/// ɴsɪ ranks definitions by priority, then by proximity to the geometry,
534/// and does not say what happens when both are equal. Rendered in
535/// 3Delight 2.9.207, **the node connected first wins**, for a plain
536/// attribute and for a shader alike, and the renderer says nothing about
537/// the definitions it drops. A scene whose look depends on call order
538/// is almost never what its author meant, so this names both sides; a
539/// backend warns with its [`Display`](fmt::Display) text.
540///
541/// Returned by [`Scene::order_decided`].
542#[derive(Debug, Clone, PartialEq, Eq)]
543#[non_exhaustive]
544pub struct OrderDecided<'a> {
545    /// The geometry the attribute applies to.
546    pub geometry: &'a str,
547    /// The attribute: its name on an `attributes` node, or
548    /// `surfaceshader`, `displacementshader` or `volumeshader`.
549    pub attribute: &'a str,
550    /// The definition that applies: an `attributes` node, or for a
551    /// shader slot the shader.
552    pub winner: &'a str,
553    /// The definitions dropped only for being connected later, in
554    /// connection order.
555    pub dropped: Vec<&'a str>,
556}
557
558impl fmt::Display for OrderDecided<'_> {
559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560        write!(
561            f,
562            "ɴsɪ attribute {:?} on {:?} is defined {} times at equal \
563             priority and distance; {:?} applies because it was \
564             connected first, dropping ",
565            self.attribute,
566            self.geometry,
567            self.dropped.len() + 1,
568            self.winner,
569        )?;
570        self.dropped
571            .iter()
572            .enumerate()
573            .try_for_each(|(index, handle)| {
574                let separator = if index == 0 { "" } else { ", " };
575                write!(f, "{separator}{handle:?}")
576            })
577    }
578}
579
580/// One renderable output: a camera paired with a screen, and the AOVs
581/// written from it.
582/// `Eq` and `Hash` are absent for the reason `OwnedArgument`'s are
583/// (research D7): a layer carries `filter_width`, and a float has no
584/// total equality to derive one from.
585#[derive(Debug, Clone, PartialEq)]
586#[non_exhaustive]
587pub struct RenderOutput {
588    /// The camera the screen is connected to.
589    pub camera: String,
590    /// The screen, which is what carries resolution and oversampling.
591    pub screen: String,
592    /// AOVs in connection order; may be empty.
593    pub layers: Vec<OutputLayer>,
594}
595
596/// One instance, borrowing the matrix the scene already holds.
597///
598/// [`Scene::instance_transforms`] copies: for a set-dressing
599/// instancer with a million entries that is 136 MB of `Instance`
600/// against the 128 MB `doublematrix` array it was copied from.
601/// [`Scene::instances`] hands out these instead, which is the shape a
602/// renderer's own instancer wants -- a prototype index and a matrix it
603/// can read in place.
604#[derive(Debug, Clone, Copy, PartialEq)]
605#[non_exhaustive]
606pub struct InstanceRef<'a> {
607    /// Which prototype this instance draws, as a position in
608    /// [`Scene::instance_sources`].
609    pub source: usize,
610    /// This instance's transform, in the `instances` node's space.
611    pub transform: &'a [f64; 16],
612}
613
614/// One instance an `instances` node places.
615///
616/// ɴsɪ gives an `instances` node "a transformation matrix for each
617/// instance" and an optional `modelindices` selecting which prototype
618/// each uses. This pairs the two, so a backend building a MoonRay
619/// `InstanceGeometry` or a Mitsuba `shapegroup` reference does not have
620/// to.
621#[derive(Debug, Clone, PartialEq)]
622#[non_exhaustive]
623pub struct Instance {
624    /// Which prototype this instance draws, as a position in
625    /// [`Scene::instance_sources`].
626    ///
627    /// ɴsɪ matches `modelindices` against "the index attribute of the
628    /// model connection", not against connection order, so this is the
629    /// resolved position rather than the raw value.
630    pub source: usize,
631    /// This instance's transform, in the `instances` node's space.
632    pub transform: [f64; 16],
633}
634
635/// One AOV, resolved: what to output, how to encode it, and where it
636/// goes.
637///
638/// Every field but `handle` and `drivers` is an `outputlayer`
639/// attribute, **with the specification's default already applied** --
640/// `variablesource` "shader", `layertype` "color", `scalarformat`
641/// "uint8", `filter` "blackman-harris", `filterwidth` 3.0,
642/// `withalpha` and `dithering` off. A backend that re-derives these
643/// gets them subtly wrong: the defaults are stated once in the
644/// specification and nowhere in the scene, so a layer that sets none
645/// of them still means "a uint8 colour from a shader closure".
646#[derive(Debug, Clone, PartialEq)]
647#[non_exhaustive]
648pub struct OutputLayer {
649    /// The `outputlayer` node's handle.
650    pub handle: String,
651    /// The variable to output. `None` when the layer does not name one,
652    /// which is a scene error rather than a default.
653    pub variable_name: Option<String>,
654    /// Where the variable is read from: `"shader"`, `"attribute"` or
655    /// `"builtin"`. Defaults to `"shader"`.
656    pub variable_source: String,
657    /// The layer's name as the driver writes it -- the layer name
658    /// inside an EXR, say. `None` when unset; ɴsɪ gives no default, so
659    /// a driver picks its own.
660    pub layer_name: Option<String>,
661    /// `"scalar"`, `"color"`, `"vector"` or `"quad"`. Defaults to
662    /// `"color"`.
663    pub layer_type: String,
664    /// The quantisation: `"uint8"` through `"float"`. Defaults to
665    /// `"uint8"`, which surprises a backend expecting float AOVs.
666    pub scalar_format: String,
667    /// Whether an alpha channel is included. Defaults to `false`.
668    pub with_alpha: bool,
669    /// Whether integer scalars are dithered. Defaults to `false`.
670    pub dithering: bool,
671    /// The reconstruction filter. Defaults to `"blackman-harris"`.
672    pub filter: String,
673    /// The filter's diameter in pixels. Defaults to `3.0`, and ɴsɪ says
674    /// it is not applied for `"box"` or `"zmin"`.
675    pub filter_width: f64,
676    /// An ᴏᴄɪᴏ colour profile to apply before quantisation, if set.
677    pub color_profile: Option<String>,
678    /// The ordering key among layers on one driver, if set.
679    ///
680    /// See `drivers`: this crate applies it rather than leaving it to
681    /// the backend.
682    pub sort_key: Option<i32>,
683    /// A layer may fan out to several drivers -- a file and a display,
684    /// say.
685    ///
686    /// In connection order. ɴsɪ orders *layers* on a driver by
687    /// `sortkey`, not drivers on a layer, so this stays as connected.
688    pub drivers: Vec<String>,
689}
690
691/// Row-major 4x4 product, `a` then `b`.
692///
693/// ɴsɪ uses the RenderMan row-vector convention: a point is a row and
694/// transforms multiply on the right, so `p * a * b` applies `a` first.
695/// Composing a child with its parent is therefore `mul(child, parent)`,
696/// not the other way round.
697fn mul(a: [f64; 16], b: [f64; 16]) -> [f64; 16] {
698    let mut out = [0.0; 16];
699    for row in 0..4 {
700        for col in 0..4 {
701            let mut sum = 0.0;
702            for k in 0..4 {
703                sum += a[row * 4 + k] * b[k * 4 + col];
704            }
705            out[row * 4 + col] = sum;
706        }
707    }
708    out
709}
710
711#[cfg(test)]
712mod tests;