Skip to main content

nsi_intermediate/resolve/
primvar.rs

1//! Primitive variables: which value each face-vertex reads.
2//!
3//! ɴsɪ stores a primitive variable four ways and tells you which only
4//! implicitly. The value count decides -- one value is constant, one
5//! per face is uniform, one per vertex follows `P`, one per
6//! face-vertex is face-varying -- and the `per_face` and `per_vertex`
7//! flags exist only to break a tie. The documentation is explicit that
8//! they are "only strictly needed in rare circumstances when a
9//! geometric primitive's number of vertices matches the number of
10//! faces. The most simple case is a tetrahedral mesh which has exactly
11//! four vertices and also four faces." On top of that sits indirect
12//! lookup: an integer attribute named `<name>.indices` "is read to
13//! know which values of the other parameter to use".
14//!
15//! Every backend must implement all four rules or silently drop `st`,
16//! `N` and every user primitive variable -- and a normal read in the
17//! wrong interpolation shades plausibly and wrongly, which is worse
18//! than dropping it. So this resolves them once, here.
19//!
20//! # Indices, not values
21//!
22//! [`PrimitiveVariable::face_varying_indices`] yields the *value
23//! index* for each face-vertex rather than the value. The data is
24//! whatever ɴsɪ type the variable carries -- `st` is `f32`, an id is
25//! `i32`, a name is bytes -- and expanding to values would mean one
26//! path per type and a copy of a buffer that is already the largest
27//! thing in the scene. A backend indexes its own payload with these.
28
29use super::*;
30use nsi_ffi_wrap::nsi_sys::NSIParamFlags;
31
32/// How a primitive variable's values map onto a primitive.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum Interpolation {
35    /// One value for the whole primitive.
36    Constant,
37    /// One value per face.
38    Uniform,
39    /// One value per vertex, indexed as `P` is.
40    Vertex,
41    /// One value per face-vertex, already in face order.
42    FaceVarying,
43}
44
45/// One primitive variable, resolved against its primitive.
46#[derive(Debug, Clone)]
47pub struct PrimitiveVariable<'a> {
48    values: &'a OwnedArgument,
49    interpolation: Interpolation,
50    indices: Option<&'a [i32]>,
51    vertex_indices: Option<&'a [i32]>,
52    face_vertex_counts: Vec<usize>,
53}
54
55impl<'a> PrimitiveVariable<'a> {
56    /// The argument the values live in.
57    #[must_use]
58    pub fn values(&self) -> &'a OwnedArgument {
59        self.values
60    }
61
62    /// Which of the four classes this variable is.
63    #[must_use]
64    pub fn interpolation(&self) -> Interpolation {
65        self.interpolation
66    }
67
68    /// The variable's own `<name>.indices`, if it has one.
69    #[must_use]
70    pub fn indices(&self) -> Option<&'a [i32]> {
71        self.indices
72    }
73
74    /// How many face-vertices the primitive has.
75    #[must_use]
76    pub fn face_vertex_count(&self) -> usize {
77        self.face_vertex_counts.iter().sum()
78    }
79
80    /// The value index each face-vertex reads, in face order.
81    ///
82    /// This is the one order every backend wants and none of them
83    /// should have to derive: whatever the storage, the result is
84    /// `face_vertex_count()` indices into [`PrimitiveVariable::values`].
85    pub fn face_varying_indices(&self) -> impl Iterator<Item = usize> + '_ {
86        let mut face_vertex = 0usize;
87        self.face_vertex_counts
88            .iter()
89            .enumerate()
90            .flat_map(move |(face, count)| {
91                let start = face_vertex;
92                face_vertex += count;
93                (0..*count).map(move |corner| (face, start + corner))
94            })
95            .map(move |(face, position)| match self.interpolation {
96                Interpolation::Constant => 0,
97                Interpolation::Uniform => face,
98                Interpolation::FaceVarying => self
99                    .indices
100                    .map_or(position, |indices| indices[position] as usize),
101                // A per-vertex variable is indexed the way `P` is: by
102                // the mesh's own `P.indices` where there is one, and
103                // otherwise face-vertex order, since an unindexed mesh
104                // lists its vertices in exactly that order.
105                Interpolation::Vertex => self.indices.map_or_else(
106                    || {
107                        self.vertex_indices.map_or(position, |vertices| {
108                            vertices[position] as usize
109                        })
110                    },
111                    |indices| indices[position] as usize,
112                ),
113            })
114    }
115}
116
117impl Scene {
118    /// Resolve one primitive variable on a `mesh`.
119    ///
120    /// # Errors
121    ///
122    /// [`ResolveError::MissingFaceCounts`] and
123    /// [`ResolveError::MalformedFaceCounts`] from [`Scene::faces`],
124    /// [`ResolveError::MalformedIndices`] when a `<name>.indices` is
125    /// not one entry per face-vertex or points outside the values, and
126    /// [`ResolveError::AmbiguousInterpolation`] when the value count
127    /// matches none of the four classes. Refusing is deliberate: a
128    /// guessed interpolation renders, which is how it survives review.
129    pub fn primitive_variable(
130        &self,
131        handle: &str,
132        name: &str,
133    ) -> Result<Option<PrimitiveVariable<'_>>, ResolveError> {
134        let Some(node) = self.node(handle) else {
135            return Ok(None);
136        };
137        let Some(values) = node.effective(name) else {
138            return Ok(None);
139        };
140
141        let face_vertex_counts: Vec<usize> =
142            self.faces(handle)?.map(|face| face.vertices()).collect();
143        let face_vertices: usize = face_vertex_counts.iter().sum();
144        let faces = face_vertex_counts.len();
145        let points = node
146            .effective(POSITIONS)
147            .map_or(0, OwnedArgument::element_count);
148        let vertex_indices = node
149            .effective(&format!("{POSITIONS}{INDICES}"))
150            .and_then(OwnedArgument::as_i32s);
151
152        let count = values.element_count();
153        let indices = node
154            .effective(&format!("{name}{INDICES}"))
155            .and_then(OwnedArgument::as_i32s);
156
157        // Indirect lookup first: ɴsɪ says the indices say which values
158        // to use, and says nothing about how many values there are.
159        if let Some(indices) = indices
160            && (indices.len() != face_vertices
161                || indices.iter().any(|index| *index as usize >= count))
162        {
163            return Err(ResolveError::MalformedIndices {
164                handle: handle.to_string(),
165                attribute: name.to_string(),
166                indices: indices.len(),
167                face_vertices,
168                values: count,
169            });
170        }
171
172        let flags = NSIParamFlags::from_bits_truncate(values.flags);
173        // A flag only decides where the count is genuinely ambiguous;
174        // it never overrides a count that cannot mean what it claims.
175        let per_face = flags.contains(NSIParamFlags::PerFace) && count == faces;
176        let per_vertex =
177            flags.contains(NSIParamFlags::PerVertex) && count == points;
178
179        // The case the flags exist for: with as many faces as vertices
180        // -- the documentation's tetrahedron -- the count says nothing
181        // and an unflagged variable means two different things. Choosing
182        // one renders, so this refuses instead.
183        if count == faces
184            && count == points
185            && count != face_vertices
186            && !per_face
187            && !per_vertex
188        {
189            return Err(ResolveError::AmbiguousInterpolation {
190                handle: handle.to_string(),
191                attribute: name.to_string(),
192                values: count,
193                faces,
194                vertices: points,
195                face_vertices,
196            });
197        }
198
199        let interpolation = if indices.is_some() {
200            Interpolation::FaceVarying
201        } else if per_face
202            || (!per_vertex && count == faces && count != face_vertices)
203        {
204            Interpolation::Uniform
205        } else if !per_vertex && count == face_vertices {
206            Interpolation::FaceVarying
207        } else if count == points && points != 0 {
208            Interpolation::Vertex
209        } else if count == 1 {
210            Interpolation::Constant
211        } else {
212            return Err(ResolveError::AmbiguousInterpolation {
213                handle: handle.to_string(),
214                attribute: name.to_string(),
215                values: count,
216                faces,
217                vertices: points,
218                face_vertices,
219            });
220        };
221
222        Ok(Some(PrimitiveVariable {
223            values,
224            interpolation,
225            indices,
226            vertex_indices,
227            face_vertex_counts,
228        }))
229    }
230}