Skip to main content

hapi_rs/
geometry.rs

1//! Access to geometry data, attributes, and geometry file I/O.
2//!
3//! Attribute lookup and creation methods take a HAPI part id once and return a
4//! typed handle bound to that part, owner, and name. The handle's data methods
5//! operate on that identity and do not take another part id. Because
6//! HAPI part ids may be reordered by cooking, reacquire attribute handles after
7//! a cook that can change the geometry's part layout.
8
9use crate::attribute::{
10    AnyAttribute, Attribute, AttributeShape, DictionaryAttribute, Fixed, Jagged, NumericPrimitive,
11    StringAttribute,
12};
13use crate::errors::Result;
14pub use crate::ffi::{
15    AttributeInfo, BoxInfo, CameraInfo, CookOptions, CurveInfo, GeoInfo, InputCurveInfo, PartInfo,
16    SphereInfo, Transform, VolumeInfo, VolumeTileInfo, VolumeVisualInfo, enums::*,
17};
18use crate::material::Material;
19use crate::node::{HoudiniNode, NodeHandle};
20use crate::stringhandle::StringArray;
21use crate::utils::uzize_to_i32;
22use crate::volume::{Tile, VolumeBounds, VolumeStorage};
23use std::ffi::{CStr, CString};
24
25#[derive(Debug, Clone)]
26/// Represents a SOP node with methods for manipulating geometry.
27pub struct Geometry {
28    pub node: HoudiniNode,
29    pub(crate) info: GeoInfo,
30}
31
32/// In-memory geometry format
33#[derive(Debug, Copy, Clone)]
34pub enum GeoFormat {
35    Geo,
36    Bgeo,
37    Obj,
38}
39
40#[derive(Debug)]
41/// Face materials
42pub enum Materials {
43    /// Material was assigned at object level or all faces on geometry share the same material
44    Single(Material),
45    /// Materials assigned per-face
46    Multiple(Vec<Material>),
47}
48
49impl GeoFormat {
50    const fn as_cstr(self) -> &'static CStr {
51        unsafe {
52            CStr::from_bytes_with_nul_unchecked(match self {
53                GeoFormat::Geo => b".geo\0",
54                GeoFormat::Bgeo => b".bgeo\0",
55                GeoFormat::Obj => b".obj\0",
56            })
57        }
58    }
59}
60
61/// Common geometry attribute names
62#[derive(Debug)]
63pub enum AttributeName {
64    Cd,
65    P,
66    N,
67    Uv,
68    TangentU,
69    TangentV,
70    Scale,
71    Name,
72    User(CString),
73}
74
75impl TryFrom<&str> for AttributeName {
76    type Error = std::ffi::NulError;
77
78    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
79        CString::new(value).map(AttributeName::User)
80    }
81}
82
83impl TryFrom<String> for AttributeName {
84    type Error = std::ffi::NulError;
85
86    fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
87        CString::new(value).map(AttributeName::User)
88    }
89}
90
91impl From<&CStr> for AttributeName {
92    fn from(value: &CStr) -> Self {
93        AttributeName::User(value.to_owned())
94    }
95}
96
97impl From<AttributeName> for CString {
98    fn from(name: AttributeName) -> Self {
99        macro_rules! cstr {
100            ($attr:expr) => {
101                unsafe { CStr::from_bytes_with_nul_unchecked($attr).to_owned() }
102            };
103        }
104        match name {
105            AttributeName::Cd => cstr!(crate::raw::HAPI_ATTRIB_COLOR),
106            AttributeName::P => cstr!(crate::raw::HAPI_ATTRIB_POSITION),
107            AttributeName::N => cstr!(crate::raw::HAPI_ATTRIB_NORMAL),
108            AttributeName::Uv => cstr!(crate::raw::HAPI_ATTRIB_UV),
109            AttributeName::TangentU => cstr!(crate::raw::HAPI_ATTRIB_TANGENT),
110            AttributeName::TangentV => cstr!(crate::raw::HAPI_ATTRIB_TANGENT2),
111            AttributeName::Scale => cstr!(crate::raw::HAPI_ATTRIB_SCALE),
112            AttributeName::Name => cstr!(crate::raw::HAPI_ATTRIB_NAME),
113            AttributeName::User(val) => val,
114        }
115    }
116}
117
118impl Geometry {
119    /// Get geometry partition info by index.
120    pub fn part_info(&self, part_id: i32) -> Result<PartInfo> {
121        self.assert_node_cooked()?;
122        crate::ffi::get_part_info(&self.node, part_id).map(PartInfo)
123    }
124
125    pub fn volume_info(&self, part_id: i32) -> Result<VolumeInfo> {
126        self.assert_node_cooked()?;
127        crate::ffi::get_volume_info(&self.node, part_id).map(VolumeInfo)
128    }
129
130    pub fn set_volume_info(&self, part_id: i32, info: &VolumeInfo) -> Result<()> {
131        crate::ffi::set_volume_info(&self.node, part_id, &info.0)
132    }
133
134    #[inline]
135    #[allow(unused_must_use)]
136    fn assert_node_cooked(&self) -> Result<()> {
137        debug_assert!(
138            crate::ffi::get_node_info(self.node.handle, &self.node.session)?.totalCookCount > 0,
139            "Node not cooked"
140        );
141        Ok(())
142    }
143
144    pub fn volume_bounds(&self, part_id: i32) -> Result<VolumeBounds> {
145        self.assert_node_cooked()?;
146        crate::ffi::get_volume_bounds(&self.node, part_id)
147    }
148    pub fn get_volume_visual_info(&self, part_id: i32) -> Result<VolumeVisualInfo> {
149        crate::ffi::get_volume_visual_info(&self.node, part_id).map(VolumeVisualInfo)
150    }
151
152    /// Get information about Node's geometry.
153    /// Note: The node must be cooked before calling this method.
154    pub fn geo_info(&self) -> Result<GeoInfo> {
155        self.assert_node_cooked()?;
156        GeoInfo::from_node(&self.node)
157    }
158
159    pub fn set_part_info(&self, info: &PartInfo) -> Result<()> {
160        debug_assert!(self.node.is_valid()?);
161        crate::ffi::set_part_info(&self.node, info)
162    }
163
164    pub fn box_info(&self, part_id: i32) -> Result<BoxInfo> {
165        self.assert_node_cooked()?;
166        crate::ffi::get_box_info(self.node.handle, &self.node.session, part_id).map(BoxInfo)
167    }
168
169    pub fn sphere_info(&self, part_id: i32) -> Result<SphereInfo> {
170        self.assert_node_cooked()?;
171        crate::ffi::get_sphere_info(self.node.handle, &self.node.session, part_id).map(SphereInfo)
172    }
173
174    pub fn camera_info(&self, part_id: i32) -> Result<CameraInfo> {
175        self.assert_node_cooked()?;
176        crate::ffi::get_camera_info(self.node.handle, &self.node.session, part_id).map(CameraInfo)
177    }
178
179    pub fn camera_transform(&self, part_id: i32) -> Result<Transform> {
180        self.assert_node_cooked()?;
181        crate::ffi::get_camera_transform(self.node.handle, &self.node.session, part_id)
182            .map(Transform)
183    }
184
185    pub fn set_curve_info(&self, part_id: i32, info: &CurveInfo) -> Result<()> {
186        debug_assert!(self.node.is_valid()?);
187        crate::ffi::set_curve_info(&self.node, part_id, info)
188    }
189
190    pub fn set_input_curve_info(&self, part_id: i32, info: &InputCurveInfo) -> Result<()> {
191        debug_assert!(self.node.is_valid()?);
192        crate::ffi::set_input_curve_info(&self.node, part_id, info)
193    }
194
195    pub fn get_input_curve_info(&self, part_id: i32) -> Result<InputCurveInfo> {
196        debug_assert!(self.node.is_valid()?);
197        crate::ffi::get_input_curve_info(&self.node, part_id).map(InputCurveInfo)
198    }
199
200    pub fn set_input_curve_positions(&self, part_id: i32, positions: &[f32]) -> Result<()> {
201        crate::ffi::set_input_curve_positions(
202            &self.node,
203            part_id,
204            positions,
205            0,
206            uzize_to_i32(positions.len()),
207        )
208    }
209
210    pub fn set_input_curve_transform(
211        &self,
212        part_id: i32,
213        positions: &[f32],
214        rotation: &[f32],
215        scale: &[f32],
216    ) -> Result<()> {
217        crate::ffi::set_input_curve_transform(&self.node, part_id, positions, rotation, scale)
218    }
219
220    pub fn set_curve_counts(&self, part_id: i32, count: &[i32]) -> Result<()> {
221        debug_assert!(self.node.is_valid()?);
222        crate::ffi::set_curve_counts(&self.node, part_id, count)
223    }
224
225    pub fn set_curve_knots(&self, part_id: i32, knots: &[f32]) -> Result<()> {
226        debug_assert!(self.node.is_valid()?);
227        crate::ffi::set_curve_knots(&self.node, part_id, knots)
228    }
229
230    pub fn set_vertex_list(&self, part_id: i32, list: impl AsRef<[i32]>) -> Result<()> {
231        debug_assert!(self.node.is_valid()?);
232        crate::ffi::set_geo_vertex_list(&self.node, part_id, list.as_ref())
233    }
234
235    pub fn set_face_counts(&self, part_id: i32, list: impl AsRef<[i32]>) -> Result<()> {
236        debug_assert!(self.node.is_valid()?);
237        crate::ffi::set_geo_face_counts(&self.node, part_id, list.as_ref())
238    }
239
240    pub fn update(&mut self) -> Result<()> {
241        self.info = self.geo_info()?;
242        Ok(())
243    }
244
245    pub fn curve_info(&self, part_id: i32) -> Result<CurveInfo> {
246        self.assert_node_cooked()?;
247        crate::ffi::get_curve_info(&self.node, part_id).map(CurveInfo)
248    }
249
250    /// Retrieve the number of vertices for each curve in the part.
251    pub fn curve_counts(&self, part_id: i32, start: i32, length: i32) -> Result<Vec<i32>> {
252        self.assert_node_cooked()?;
253        crate::ffi::get_curve_counts(&self.node, part_id, start, length)
254    }
255
256    /// Retrieve the orders for each curve in the part if the curve has varying order.
257    pub fn curve_orders(&self, part_id: i32, start: i32, length: i32) -> Result<Vec<i32>> {
258        self.assert_node_cooked()?;
259        crate::ffi::get_curve_orders(&self.node, part_id, start, length)
260    }
261
262    /// Retrieve the knots of the curves in this part.
263    pub fn curve_knots(&self, part_id: i32, start: i32, length: i32) -> Result<Vec<f32>> {
264        self.assert_node_cooked()?;
265        crate::ffi::get_curve_knots(&self.node, part_id, start, length)
266    }
267
268    /// Get array containing the vertex-point associations where the
269    /// ith element in the array is the point index the ith vertex
270    /// associates with.
271    pub fn vertex_list(&self, part: &PartInfo) -> Result<Vec<i32>> {
272        self.assert_node_cooked()?;
273        crate::ffi::get_geo_vertex_list(
274            &self.node.session,
275            self.node.handle,
276            part.part_id(),
277            0,
278            part.vertex_count(),
279        )
280    }
281
282    pub fn partitions(&self) -> Result<Vec<PartInfo>> {
283        self.assert_node_cooked()?;
284        (0..self.geo_info()?.part_count())
285            .map(|part| self.part_info(part))
286            .collect()
287    }
288
289    pub fn get_face_counts(&self, part: &PartInfo) -> Result<Vec<i32>> {
290        self.assert_node_cooked()?;
291        crate::ffi::get_face_counts(
292            &self.node.session,
293            self.node.handle,
294            part.part_id(),
295            0,
296            part.face_count(),
297        )
298    }
299
300    /// Return material nodes applied to geometry.
301    pub fn get_materials(&self, part: &PartInfo) -> Result<Option<Materials>> {
302        self.assert_node_cooked()?;
303        let (all_the_same, mats) = crate::ffi::get_material_node_ids_on_faces(
304            &self.node.session,
305            self.node.handle,
306            part.face_count(),
307            part.part_id(),
308        )?;
309        if all_the_same {
310            if mats[0] == -1 {
311                Ok(None)
312            } else {
313                let mat_node = NodeHandle(mats[0]);
314                let info = crate::ffi::get_material_info(&self.node.session, mat_node)?;
315                Ok(Some(Materials::Single(Material {
316                    session: self.node.session.clone(),
317                    info,
318                })))
319            }
320        } else {
321            let session = self.node.session.clone();
322            let mats = mats
323                .into_iter()
324                .map(|id| {
325                    crate::ffi::get_material_info(&session, NodeHandle(id)).map(|info| Material {
326                        session: session.clone(),
327                        info,
328                    })
329                })
330                .collect::<Result<Vec<_>>>();
331            mats.map(|vec| Some(Materials::Multiple(vec)))
332        }
333    }
334
335    /// Get geometry group names by type.
336    pub fn get_group_names(&self, group_type: GroupType) -> Result<StringArray> {
337        self.assert_node_cooked()?;
338        let count = match group_type {
339            GroupType::Point => self.info.point_group_count(),
340            GroupType::Prim => self.info.primitive_group_count(),
341            GroupType::Edge => self.info.edge_group_count(),
342            _ => unreachable!("Impossible GroupType value"),
343        };
344        crate::ffi::get_group_names(&self.node, group_type, count)
345    }
346
347    pub fn get_edge_count_of_edge_group(&self, group: &str, part_id: i32) -> Result<i32> {
348        self.assert_node_cooked()?;
349        let group = CString::new(group)?;
350        crate::ffi::get_edge_count_of_edge_group(
351            &self.node.session,
352            self.node.handle,
353            &group,
354            part_id,
355        )
356    }
357    /// Get num geometry elements by type (points, prims, vertices).
358    pub fn get_element_count_by_owner(
359        &self,
360        part: &PartInfo,
361        owner: AttributeOwner,
362    ) -> Result<i32> {
363        Ok(crate::ffi::get_element_count_by_attribute_owner(
364            part, owner,
365        ))
366    }
367
368    /// Get number of attributes by type.
369    pub fn get_attribute_count_by_owner(
370        &self,
371        part: &PartInfo,
372        owner: AttributeOwner,
373    ) -> Result<i32> {
374        Ok(crate::ffi::get_attribute_count_by_owner(part, owner))
375    }
376
377    pub fn get_attribute_names(
378        &self,
379        owner: AttributeOwner,
380        part: &PartInfo,
381    ) -> Result<StringArray> {
382        self.assert_node_cooked()?;
383        let counts = part.attribute_counts();
384        let count = match owner {
385            AttributeOwner::Invalid | AttributeOwner::Max => {
386                return Err(crate::HapiError::Internal(format!(
387                    "Invalid AttributeOwner: {owner:?}"
388                )));
389            }
390            AttributeOwner::Vertex => counts[0],
391            AttributeOwner::Point => counts[1],
392            AttributeOwner::Prim => counts[2],
393            AttributeOwner::Detail => counts[3],
394        };
395        crate::ffi::get_attribute_names(&self.node, part.part_id(), count, owner)
396    }
397
398    /// Retrieve information about a geometry attribute.
399    pub fn get_attribute_info(
400        &self,
401        part_id: i32,
402        owner: AttributeOwner,
403        name: impl TryInto<AttributeName, Error = impl Into<crate::HapiError>>,
404    ) -> Result<AttributeInfo> {
405        let name: AttributeName = name.try_into().map_err(Into::into)?;
406        let name: CString = name.into();
407        AttributeInfo::new(&self.node, part_id, owner, &name)
408    }
409
410    /// Gets an attribute by part, owner, and name without assuming its storage.
411    ///
412    /// Returns `Ok(None)` when the attribute does not exist. Otherwise the
413    /// returned [`AnyAttribute`] variant contains a typed handle bound to the
414    /// requested part. Invalid or unsupported HAPI storage is reported as an
415    /// error.
416    pub fn get_attribute<T>(
417        &self,
418        part_id: i32,
419        owner: AttributeOwner,
420        name: T,
421    ) -> Result<Option<AnyAttribute>>
422    where
423        T: TryInto<AttributeName>,
424        T::Error: Into<crate::HapiError>,
425    {
426        self.assert_node_cooked()?;
427        let name: AttributeName = name.try_into().map_err(Into::into)?;
428        let name: CString = name.into();
429        let info = AttributeInfo::new(&self.node, part_id, owner, &name)?;
430        let storage = info.storage();
431        if !info.exists() {
432            return Ok(None);
433        }
434        let node = self.node.clone();
435        let attr = match storage {
436            s @ (StorageType::Invalid | StorageType::Max) => {
437                return Err(crate::HapiError::Internal(format!(
438                    "Invalid attribute storage {name:?}: {s:?}"
439                )));
440            }
441            StorageType::Int => AnyAttribute::Int(Attribute::new(name, info, node, part_id)),
442            StorageType::Int64 => AnyAttribute::Int64(Attribute::new(name, info, node, part_id)),
443            StorageType::Float => AnyAttribute::Float(Attribute::new(name, info, node, part_id)),
444            StorageType::Float64 => {
445                AnyAttribute::Float64(Attribute::new(name, info, node, part_id))
446            }
447            StorageType::String => {
448                AnyAttribute::String(StringAttribute::new(name, info, node, part_id))
449            }
450            StorageType::Uint8 => AnyAttribute::Uint8(Attribute::new(name, info, node, part_id)),
451            StorageType::Int8 => AnyAttribute::Int8(Attribute::new(name, info, node, part_id)),
452            StorageType::Int16 => AnyAttribute::Int16(Attribute::new(name, info, node, part_id)),
453            StorageType::IntArray => {
454                AnyAttribute::IntArray(Attribute::new(name, info, node, part_id))
455            }
456            StorageType::Int64Array => {
457                AnyAttribute::Int64Array(Attribute::new(name, info, node, part_id))
458            }
459            StorageType::FloatArray => {
460                AnyAttribute::FloatArray(Attribute::new(name, info, node, part_id))
461            }
462            StorageType::Float64Array => {
463                AnyAttribute::Float64Array(Attribute::new(name, info, node, part_id))
464            }
465            StorageType::StringArray => {
466                AnyAttribute::StringArray(StringAttribute::new(name, info, node, part_id))
467            }
468            StorageType::Uint8Array => {
469                AnyAttribute::Uint8Array(Attribute::new(name, info, node, part_id))
470            }
471            StorageType::Int8Array => {
472                AnyAttribute::Int8Array(Attribute::new(name, info, node, part_id))
473            }
474            StorageType::Int16Array => {
475                AnyAttribute::Int16Array(Attribute::new(name, info, node, part_id))
476            }
477            StorageType::Dictionary => {
478                AnyAttribute::Dictionary(DictionaryAttribute::new(name, info, node, part_id))
479            }
480            StorageType::DictionaryArray => {
481                AnyAttribute::DictionaryArray(DictionaryAttribute::new(name, info, node, part_id))
482            }
483        };
484        Ok(Some(attr))
485    }
486
487    /// Finds an attribute by name without assuming its owner.
488    ///
489    /// Returns an error instead of choosing arbitrarily when the name exists
490    /// on more than one concrete owner.
491    pub fn find_attribute<T>(&self, part_id: i32, name: T) -> Result<Option<AnyAttribute>>
492    where
493        T: TryInto<AttributeName>,
494        T::Error: Into<crate::HapiError>,
495    {
496        let name: CString = name.try_into().map_err(Into::into)?.into();
497        let mut found: Option<AnyAttribute> = None;
498        for owner in [
499            AttributeOwner::Vertex,
500            AttributeOwner::Point,
501            AttributeOwner::Prim,
502            AttributeOwner::Detail,
503        ] {
504            let Some(attribute) = self.get_attribute(part_id, owner, name.as_c_str())? else {
505                continue;
506            };
507            if let Some(existing) = &found {
508                return Err(crate::HapiError::Internal(format!(
509                    "attribute {name:?} is ambiguous on part {part_id}: it exists for owners {:?} and {:?}",
510                    existing.owner(),
511                    owner
512                )));
513            }
514            found = Some(attribute);
515        }
516        Ok(found)
517    }
518
519    /// Gets a numeric attribute when its primitive type and shape match `T` and `S`.
520    ///
521    /// Returns `Ok(None)` when the attribute does not exist and an error when
522    /// it exists with different storage. The returned handle is bound to
523    /// `part_id`; whole-attribute and fixed-range operations use cached metadata.
524    pub fn get_numeric_attribute<T: NumericPrimitive, S: AttributeShape>(
525        &self,
526        part_id: i32,
527        owner: AttributeOwner,
528        name: impl TryInto<AttributeName, Error = impl Into<crate::HapiError>>,
529    ) -> Result<Option<Attribute<T, S>>> {
530        let name: CString = name.try_into().map_err(Into::into)?.into();
531        let info = AttributeInfo::new(&self.node, part_id, owner, &name)?;
532        if !info.exists() {
533            return Ok(None);
534        }
535        let expected = S::storage::<T>();
536        if info.storage() != expected {
537            return Err(crate::HapiError::Internal(format!(
538                "attribute {name:?} has storage {:?}, expected {expected:?}",
539                info.storage()
540            )));
541        }
542        Ok(Some(Attribute::new(name, info, self.node.clone(), part_id)))
543    }
544
545    /// Gets a string attribute with the requested fixed or jagged shape.
546    ///
547    /// Returns `Ok(None)` when the attribute does not exist and an error when
548    /// its storage does not match `S`.
549    pub fn get_string_attribute<S: AttributeShape>(
550        &self,
551        part_id: i32,
552        owner: AttributeOwner,
553        name: impl TryInto<AttributeName, Error = impl Into<crate::HapiError>>,
554    ) -> Result<Option<StringAttribute<S>>> {
555        let name: CString = name.try_into().map_err(Into::into)?.into();
556        let info = AttributeInfo::new(&self.node, part_id, owner, &name)?;
557        if !info.exists() {
558            return Ok(None);
559        }
560        let expected = if std::any::TypeId::of::<S>() == std::any::TypeId::of::<Fixed>() {
561            StorageType::String
562        } else {
563            StorageType::StringArray
564        };
565        if info.storage() != expected {
566            return Err(crate::HapiError::Internal(format!(
567                "attribute {name:?} has storage {:?}, expected {expected:?}",
568                info.storage()
569            )));
570        }
571        Ok(Some(StringAttribute::new(
572            name,
573            info,
574            self.node.clone(),
575            part_id,
576        )))
577    }
578
579    /// Gets a dictionary attribute with the requested fixed or jagged shape.
580    ///
581    /// Returns `Ok(None)` when the attribute does not exist and an error when
582    /// its storage does not match `S`.
583    pub fn get_dictionary_attribute<S: AttributeShape>(
584        &self,
585        part_id: i32,
586        owner: AttributeOwner,
587        name: impl TryInto<AttributeName, Error = impl Into<crate::HapiError>>,
588    ) -> Result<Option<DictionaryAttribute<S>>> {
589        let name: CString = name.try_into().map_err(Into::into)?.into();
590        let info = AttributeInfo::new(&self.node, part_id, owner, &name)?;
591        if !info.exists() {
592            return Ok(None);
593        }
594        let expected = if std::any::TypeId::of::<S>() == std::any::TypeId::of::<Fixed>() {
595            StorageType::Dictionary
596        } else {
597            StorageType::DictionaryArray
598        };
599        if info.storage() != expected {
600            return Err(crate::HapiError::Internal(format!(
601                "attribute {name:?} has storage {:?}, expected {expected:?}",
602                info.storage()
603            )));
604        }
605        Ok(Some(DictionaryAttribute::new(
606            name,
607            info,
608            self.node.clone(),
609            part_id,
610        )))
611    }
612
613    /// Adds a numeric attribute whose storage is derived from `T` and `S`.
614    ///
615    /// The `storage` field supplied in `info` is ignored and replaced. The
616    /// tuple size must be positive. The returned handle is bound to `part_id`.
617    pub fn add_numeric_attribute<T: NumericPrimitive, S: AttributeShape>(
618        &self,
619        name: &str,
620        part_id: i32,
621        info: AttributeInfo,
622    ) -> Result<Attribute<T, S>> {
623        if info.tuple_size() <= 0 {
624            return Err(crate::HapiError::Internal(format!(
625                "attribute {name:?} tuple_size must be > 0"
626            )));
627        }
628        let mut info = info;
629        info.set_storage(S::storage::<T>());
630        log::debug!("Adding numeric geometry attriubute: {name}");
631        let name = CString::new(name)?;
632        crate::ffi::add_attribute(&self.node, part_id, &name, &info.0)?;
633        Ok(Attribute::<T, S>::new(
634            name,
635            info,
636            self.node.clone(),
637            part_id,
638        ))
639    }
640
641    /// Adds a fixed-tuple string attribute.
642    ///
643    /// `info` must specify [`StorageType::String`] and a positive tuple size.
644    pub fn add_string_attribute(
645        &self,
646        name: &str,
647        part_id: i32,
648        info: AttributeInfo,
649    ) -> Result<StringAttribute<Fixed>> {
650        if info.storage() != StorageType::String || info.tuple_size() <= 0 {
651            return Err(crate::HapiError::Internal(format!(
652                "string attribute {name:?} requires String storage and a positive tuple size"
653            )));
654        }
655        log::debug!("Adding string geometry attriubute: {name}");
656        let name = CString::new(name)?;
657        crate::ffi::add_attribute(&self.node, part_id, &name, &info.0)?;
658        Ok(StringAttribute::new(name, info, self.node.clone(), part_id))
659    }
660
661    /// Adds a jagged string array attribute.
662    ///
663    /// `info` must specify [`StorageType::StringArray`] and a positive tuple size.
664    pub fn add_string_array_attribute(
665        &self,
666        name: &str,
667        part_id: i32,
668        info: AttributeInfo,
669    ) -> Result<StringAttribute<Jagged>> {
670        if info.storage() != StorageType::StringArray || info.tuple_size() <= 0 {
671            return Err(crate::HapiError::Internal(format!(
672                "jagged string attribute {name:?} requires StringArray storage and a positive tuple size"
673            )));
674        }
675        log::debug!("Adding string array geometry attriubute: {name}");
676        let name = CString::new(name)?;
677        crate::ffi::add_attribute(&self.node, part_id, &name, &info.0)?;
678        Ok(StringAttribute::new(name, info, self.node.clone(), part_id))
679    }
680
681    /// Adds a fixed-tuple JSON dictionary attribute.
682    ///
683    /// `info` must specify [`StorageType::Dictionary`] and a positive tuple size.
684    pub fn add_dictionary_attribute(
685        &self,
686        name: &str,
687        part_id: i32,
688        info: AttributeInfo,
689    ) -> Result<DictionaryAttribute<Fixed>> {
690        if info.storage() != StorageType::Dictionary || info.tuple_size() <= 0 {
691            return Err(crate::HapiError::Internal(format!(
692                "dictionary attribute {name:?} requires Dictionary storage and a positive tuple size"
693            )));
694        }
695        log::debug!("Adding dictionary geometry attriubute: {name}");
696        let name = CString::new(name)?;
697        crate::ffi::add_attribute(&self.node, part_id, &name, &info.0)?;
698        Ok(DictionaryAttribute::new(
699            name,
700            info,
701            self.node.clone(),
702            part_id,
703        ))
704    }
705
706    /// Adds a jagged JSON dictionary array attribute.
707    ///
708    /// `info` must specify [`StorageType::DictionaryArray`] and a positive tuple size.
709    pub fn add_dictionary_array_attribute(
710        &self,
711        name: &str,
712        part_id: i32,
713        info: AttributeInfo,
714    ) -> Result<DictionaryAttribute<Jagged>> {
715        if info.storage() != StorageType::DictionaryArray || info.tuple_size() <= 0 {
716            return Err(crate::HapiError::Internal(format!(
717                "jagged dictionary attribute {name:?} requires DictionaryArray storage and a positive tuple size"
718            )));
719        }
720        log::debug!("Adding dictionary array geometry attriubute: {name}");
721        let name = CString::new(name)?;
722        crate::ffi::add_attribute(&self.node, part_id, &name, &info.0)?;
723        Ok(DictionaryAttribute::new(
724            name,
725            info,
726            self.node.clone(),
727            part_id,
728        ))
729    }
730
731    /// Create a new geometry group.
732    pub fn add_group(
733        &self,
734        part_id: i32,
735        group_type: GroupType,
736        group_name: &str,
737        membership: Option<&[i32]>,
738    ) -> Result<()> {
739        debug_assert!(self.node.is_valid()?);
740        let group_name = CString::new(group_name)?;
741        crate::ffi::add_group(
742            &self.node.session,
743            self.node.handle,
744            part_id,
745            group_type,
746            &group_name,
747        )?;
748        match membership {
749            None => Ok(()),
750            Some(array) => crate::ffi::set_group_membership(
751                &self.node.session,
752                self.node.handle,
753                part_id,
754                group_type,
755                &group_name,
756                array,
757            ),
758        }
759    }
760
761    /// Delete a geometry group.
762    pub fn delete_group(
763        &self,
764        part_id: i32,
765        group_type: GroupType,
766        group_name: &str,
767    ) -> Result<()> {
768        debug_assert!(self.node.is_valid()?);
769        let group_name = CString::new(group_name)?;
770        crate::ffi::delete_group(
771            &self.node.session,
772            self.node.handle,
773            part_id,
774            group_type,
775            &group_name,
776        )
777    }
778
779    /// Set element membership for a group.
780    pub fn set_group_membership(
781        &self,
782        part_id: i32,
783        group_type: GroupType,
784        group_name: &str,
785        array: &[i32],
786    ) -> Result<()> {
787        debug_assert!(self.node.is_valid()?);
788        let group_name = CString::new(group_name)?;
789        crate::ffi::set_group_membership(
790            &self.node.session,
791            self.node.handle,
792            part_id,
793            group_type,
794            &group_name,
795            array,
796        )
797    }
798
799    /// Get element membership for a group.
800    pub fn get_group_membership(
801        &self,
802        part: &PartInfo,
803        group_type: GroupType,
804        group_name: &str,
805    ) -> Result<Vec<i32>> {
806        self.assert_node_cooked()?;
807        let group_name = CString::new(group_name)?;
808        crate::ffi::get_group_membership(
809            &self.node.session,
810            self.node.handle,
811            part.part_id(),
812            group_type,
813            &group_name,
814            part.element_count_by_group(group_type),
815        )
816    }
817
818    /// Number of geometry groups by type.
819    pub fn group_count_by_type(&self, group_type: GroupType) -> Result<i32> {
820        self.assert_node_cooked()?;
821        Ok(crate::ffi::get_group_count_by_type(&self.info, group_type))
822    }
823
824    pub fn get_instanced_part_ids(&self, part: &PartInfo) -> Result<Vec<i32>> {
825        self.assert_node_cooked()?;
826        crate::ffi::get_instanced_part_ids(
827            &self.node.session,
828            self.node.handle,
829            part.part_id(),
830            part.instanced_part_count(),
831        )
832    }
833
834    /// Get group membership for a packed instance part.
835    /// This functions allows you to get the group membership for a specific packed primitive part.
836    pub fn get_group_membership_on_packed_instance_part(
837        &self,
838        part: &PartInfo,
839        group_type: GroupType,
840        group_name: &CStr,
841    ) -> Result<(bool, Vec<i32>)> {
842        crate::ffi::get_group_membership_on_packed_instance_part(
843            &self.node, part, group_type, group_name,
844        )
845    }
846
847    pub fn get_group_count_on_packed_instance(&self, part: &PartInfo) -> Result<(i32, i32)> {
848        self.assert_node_cooked()?;
849        crate::ffi::get_group_count_on_instance_part(
850            &self.node.session,
851            self.node.handle,
852            part.part_id(),
853        )
854    }
855
856    pub fn get_instance_part_groups_names(
857        &self,
858        group: GroupType,
859        part_id: i32,
860    ) -> Result<StringArray> {
861        self.assert_node_cooked()?;
862        crate::ffi::get_group_names_on_instance_part(
863            &self.node.session,
864            self.node.handle,
865            part_id,
866            group,
867        )
868    }
869
870    pub fn get_instance_part_transforms(
871        &self,
872        part: &PartInfo,
873        order: RSTOrder,
874    ) -> Result<Vec<Transform>> {
875        self.assert_node_cooked()?;
876        crate::ffi::get_instanced_part_transforms(
877            &self.node.session,
878            self.node.handle,
879            part.part_id(),
880            order,
881            part.instance_count(),
882        )
883        .map(|vec| vec.into_iter().map(Transform).collect())
884    }
885
886    /// Save geometry to a file.
887    pub fn save_to_file(&self, filepath: &str) -> Result<()> {
888        self.assert_node_cooked()?;
889        let path = CString::new(filepath)?;
890        crate::ffi::save_geo_to_file(&self.node, &path)
891    }
892
893    /// Load geometry from a file.
894    pub fn load_from_file(&self, filepath: &str) -> Result<()> {
895        debug_assert!(self.node.is_valid()?);
896        let path = CString::new(filepath)?;
897        crate::ffi::load_geo_from_file(&self.node, &path)
898    }
899
900    /// Commits accumulated geometry edits to the node.
901    ///
902    /// Topology and attribute setters never commit implicitly. Batch related
903    /// edits and call this once before cooking or consuming an input node.
904    /// Reacquire or refresh attribute handles after a later cook that may
905    /// change their cached metadata or part layout.
906    pub fn commit(&self) -> Result<()> {
907        debug_assert!(self.node.is_valid()?);
908        log::debug!("Commiting geometry changes");
909        crate::ffi::commit_geo(&self.node)
910    }
911
912    /// Revert last geometry edits
913    pub fn revert(&self) -> Result<()> {
914        debug_assert!(self.node.is_valid()?);
915        crate::ffi::revert_geo(&self.node)
916    }
917
918    /// Serialize node's geometry to bytes.
919    pub fn save_to_memory(&self, format: GeoFormat) -> Result<Vec<i8>> {
920        self.assert_node_cooked()?;
921        crate::ffi::save_geo_to_memory(&self.node.session, self.node.handle, format.as_cstr())
922    }
923
924    /// Load geometry from a given buffer into this node.
925    pub fn load_from_memory(&self, data: &[i8], format: GeoFormat) -> Result<()> {
926        crate::ffi::load_geo_from_memory(
927            &self.node.session,
928            self.node.handle,
929            data,
930            format.as_cstr(),
931        )
932    }
933
934    pub fn read_volume_tile<T: VolumeStorage>(
935        &self,
936        part: i32,
937        fill: T,
938        tile: &VolumeTileInfo,
939        values: &mut [T],
940    ) -> Result<()> {
941        self.assert_node_cooked()?;
942        T::read_tile(&self.node, part, fill, values, &tile.0)
943    }
944
945    pub fn write_volume_tile<T: VolumeStorage>(
946        &self,
947        part: i32,
948        tile: &VolumeTileInfo,
949        values: &[T],
950    ) -> Result<()> {
951        self.assert_node_cooked()?;
952        T::write_tile(&self.node, part, values, &tile.0)
953    }
954
955    pub fn read_volume_voxel<T: VolumeStorage>(
956        &self,
957        part: i32,
958        x_index: i32,
959        y_index: i32,
960        z_index: i32,
961        values: &mut [T],
962    ) -> Result<()> {
963        self.assert_node_cooked()?;
964        T::read_voxel(&self.node, part, x_index, y_index, z_index, values)
965    }
966
967    pub fn write_volume_voxel<T: VolumeStorage>(
968        &self,
969        part: i32,
970        x_index: i32,
971        y_index: i32,
972        z_index: i32,
973        values: &[T],
974    ) -> Result<()> {
975        self.assert_node_cooked()?;
976        T::write_voxel(&self.node, part, x_index, y_index, z_index, values)
977    }
978
979    /// Iterate over volume tiles and apply a function to each tile.
980    pub fn foreach_volume_tile(
981        &self,
982        part: i32,
983        info: &VolumeInfo,
984        callback: impl Fn(Tile),
985    ) -> Result<()> {
986        self.assert_node_cooked()?;
987        let tile_size = (info.tile_size().pow(3) * info.tuple_size()) as usize;
988        crate::volume::iterate_tiles(&self.node, part, tile_size, callback)
989    }
990
991    pub fn get_heightfield_data(&self, part_id: i32, volume_info: &VolumeInfo) -> Result<Vec<f32>> {
992        self.assert_node_cooked()?;
993        let length = volume_info.x_length() * volume_info.y_length();
994        crate::ffi::get_heightfield_data(&self.node, part_id, length)
995    }
996
997    pub fn set_heightfield_data(&self, part_id: i32, name: &str, data: &[f32]) -> Result<()> {
998        crate::ffi::set_heightfield_data(&self.node, part_id, &CString::new(name)?, data)
999    }
1000
1001    pub fn create_heightfield_input(
1002        &self,
1003        parent: impl Into<Option<NodeHandle>>,
1004        volume_name: &str,
1005        x_size: i32,
1006        y_size: i32,
1007        voxel_size: f32,
1008        sampling: HeightFieldSampling,
1009    ) -> Result<HeightfieldNodes> {
1010        let name = CString::new(volume_name)?;
1011        let (heightfield, height, mask, merge) = crate::ffi::create_heightfield_input(
1012            &self.node,
1013            parent.into(),
1014            &name,
1015            x_size,
1016            y_size,
1017            voxel_size,
1018            sampling,
1019        )?;
1020        Ok(HeightfieldNodes {
1021            heightfield: NodeHandle(heightfield).to_node(&self.node.session)?,
1022            height: NodeHandle(height).to_node(&self.node.session)?,
1023            mask: NodeHandle(mask).to_node(&self.node.session)?,
1024            merge: NodeHandle(merge).to_node(&self.node.session)?,
1025        })
1026    }
1027
1028    pub fn create_heightfield_input_volume(
1029        &self,
1030        parent: impl Into<Option<NodeHandle>>,
1031        volume_name: &str,
1032        x_size: i32,
1033        y_size: i32,
1034        voxel_size: f32,
1035    ) -> Result<HoudiniNode> {
1036        let name = CString::new(volume_name)?;
1037        let handle = crate::ffi::create_heightfield_input_volume(
1038            &self.node,
1039            parent.into(),
1040            &name,
1041            x_size,
1042            y_size,
1043            voxel_size,
1044        )?;
1045        handle.to_node(&self.node.session)
1046    }
1047}
1048
1049/// Holds `HoudiniNode` handles to a heightfield SOP
1050/// Used with [`Geometry::create_heightfield_input`]
1051pub struct HeightfieldNodes {
1052    pub heightfield: HoudiniNode,
1053    pub height: HoudiniNode,
1054    pub mask: HoudiniNode,
1055    pub merge: HoudiniNode,
1056}
1057
1058impl PartInfo {
1059    #[must_use]
1060    pub fn element_count_by_group(&self, group_type: GroupType) -> i32 {
1061        crate::ffi::get_element_count_by_group(self, group_type)
1062    }
1063}
1064
1065/// Geometry extension trait with some useful utilities
1066pub mod extra {
1067    use super::{
1068        Attribute, AttributeInfo, AttributeName, AttributeOwner, CString, Fixed, Geometry,
1069        PartInfo, Result, StorageType, uzize_to_i32,
1070    };
1071    pub trait GeometryExtension {
1072        fn create_position_attribute(&self, part: &PartInfo) -> Result<Attribute<f32, Fixed>>;
1073        fn create_point_color_attribute(&self, part: &PartInfo) -> Result<Attribute<f32, Fixed>>;
1074        fn get_color_attribute(
1075            &self,
1076            part: &PartInfo,
1077            owner: AttributeOwner,
1078        ) -> Result<Option<Attribute<f32, Fixed>>>;
1079        fn get_normal_attribute(
1080            &self,
1081            part: &PartInfo,
1082            owner: AttributeOwner,
1083        ) -> Result<Option<Attribute<f32, Fixed>>>;
1084        fn get_position_attribute(&self, part: &PartInfo) -> Result<Option<Attribute<f32, Fixed>>>;
1085    }
1086
1087    impl GeometryExtension for Geometry {
1088        fn create_position_attribute(&self, part: &PartInfo) -> Result<Attribute<f32, Fixed>> {
1089            create_point_tuple_attribute::<3>(self, part, AttributeName::P)
1090        }
1091
1092        fn create_point_color_attribute(&self, part: &PartInfo) -> Result<Attribute<f32, Fixed>> {
1093            create_point_tuple_attribute::<3>(self, part, AttributeName::Cd)
1094        }
1095
1096        fn get_color_attribute(
1097            &self,
1098            part: &PartInfo,
1099            owner: AttributeOwner,
1100        ) -> Result<Option<Attribute<f32, Fixed>>> {
1101            debug_assert!(matches!(
1102                owner,
1103                AttributeOwner::Point | AttributeOwner::Vertex
1104            ));
1105            get_tuple3_attribute(self, part, AttributeName::Cd, owner)
1106        }
1107        fn get_normal_attribute(
1108            &self,
1109            part: &PartInfo,
1110            owner: AttributeOwner,
1111        ) -> Result<Option<Attribute<f32, Fixed>>> {
1112            debug_assert!(matches!(
1113                owner,
1114                AttributeOwner::Point | AttributeOwner::Vertex
1115            ));
1116            get_tuple3_attribute(self, part, AttributeName::N, owner)
1117        }
1118        fn get_position_attribute(&self, part: &PartInfo) -> Result<Option<Attribute<f32, Fixed>>> {
1119            get_tuple3_attribute(self, part, AttributeName::P, AttributeOwner::Point)
1120        }
1121    }
1122
1123    #[inline]
1124    fn create_point_tuple_attribute<const N: usize>(
1125        geo: &Geometry,
1126        part: &PartInfo,
1127        name: AttributeName,
1128    ) -> Result<Attribute<f32, Fixed>> {
1129        log::debug!("Creating point attriute {name:?}");
1130        let name: CString = name.into();
1131        let attr_info = AttributeInfo::default()
1132            .with_count(part.point_count())
1133            .with_tuple_size(uzize_to_i32(N))
1134            .with_owner(AttributeOwner::Point)
1135            .with_storage(StorageType::Float);
1136        crate::ffi::add_attribute(&geo.node, part.part_id(), &name, &attr_info.0)
1137            .map(|()| Attribute::new(name, attr_info, geo.node.clone(), part.part_id()))
1138    }
1139
1140    #[inline]
1141    fn get_tuple3_attribute(
1142        geo: &Geometry,
1143        part: &PartInfo,
1144        name: AttributeName,
1145        owner: AttributeOwner,
1146    ) -> Result<Option<Attribute<f32, Fixed>>> {
1147        let name: CString = name.into();
1148        AttributeInfo::new(&geo.node, part.part_id(), owner, &name).map(|info| {
1149            info.exists()
1150                .then(|| Attribute::new(name, info, geo.node.clone(), part.part_id()))
1151        })
1152    }
1153}