Skip to main content

hapi_rs/
pdg.rs

1use crate::Result;
2use crate::ffi;
3use crate::ffi::{
4    PDGEventInfo, PDGWorkItemInfo, PDGWorkItemOutputFile,
5    raw::{PdgEventType, PdgState},
6};
7use crate::node::{HoudiniNode, NodeHandle};
8use std::fmt::Formatter;
9use std::ops::ControlFlow;
10
11/// Represents a single work item.
12pub struct PDGWorkItem<'node> {
13    pub id: WorkItemId,
14    pub context_id: i32,
15    pub node: &'node HoudiniNode,
16}
17
18#[derive(Debug, Copy, Clone)]
19#[repr(transparent)]
20pub struct WorkItemId(pub(crate) i32);
21
22impl std::fmt::Debug for PDGWorkItem<'_> {
23    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
24        f.debug_struct("PDGWorkItem")
25            .field("id", &self.id)
26            .field("context", &self.context_id)
27            .finish()
28    }
29}
30
31impl From<WorkItemId> for i32 {
32    fn from(value: WorkItemId) -> Self {
33        value.0
34    }
35}
36
37impl From<TopNode> for NodeHandle {
38    fn from(value: TopNode) -> Self {
39        value.node.handle
40    }
41}
42
43impl<'session> PDGWorkItem<'session> {
44    pub fn get_info(&self) -> Result<PDGWorkItemInfo> {
45        ffi::get_workitem_info(&self.node.session, self.context_id, self.id.0).map(PDGWorkItemInfo)
46    }
47    /// Retrieve the results of work, if the work item has any.
48    pub fn get_results(&self) -> Result<Vec<PDGWorkItemOutputFile<'session>>> {
49        match self.get_info()?.output_file_count() {
50            0 => Ok(Vec::new()),
51            count => {
52                let results = ffi::get_workitem_result(
53                    &self.node.session,
54                    self.node.handle,
55                    self.id.0,
56                    count,
57                )?;
58                let results = results
59                    .into_iter()
60                    .map(|inner| PDGWorkItemOutputFile(inner, (&self.node.session).into()))
61                    .collect();
62
63                Ok(results)
64            }
65        }
66    }
67
68    pub fn set_int_attribute(&self, attrib_name: &str, value: &[i32]) -> Result<()> {
69        let attrib_name = std::ffi::CString::new(attrib_name)?;
70        ffi::set_workitem_int_attribute(
71            &self.node.session,
72            self.node.handle,
73            self.id.0,
74            &attrib_name,
75            value,
76        )
77    }
78    pub fn get_int_attribute(&self, attr_name: &str) -> Result<Vec<i32>> {
79        let attr_name = std::ffi::CString::new(attr_name)?;
80        let attr_size = ffi::get_workitem_attribute_size(
81            &self.node.session,
82            self.node.handle,
83            self.id.0,
84            &attr_name,
85        )?;
86        let mut buffer = vec![0; attr_size as usize];
87        ffi::get_workitem_int_attribute(
88            &self.node.session,
89            self.node.handle,
90            self.id.0,
91            &attr_name,
92            &mut buffer,
93        )?;
94        Ok(buffer)
95    }
96
97    pub fn set_float_attribute(&self, attrib_name: &str, value: &[f32]) -> Result<()> {
98        let attrib_name = std::ffi::CString::new(attrib_name)?;
99        ffi::set_workitem_float_attribute(
100            &self.node.session,
101            self.node.handle,
102            self.id.0,
103            &attrib_name,
104            value,
105        )
106    }
107
108    pub fn get_float_attribute(&self, attr_name: &str) -> Result<Vec<f32>> {
109        let attr_name = std::ffi::CString::new(attr_name)?;
110        let attr_size = ffi::get_workitem_attribute_size(
111            &self.node.session,
112            self.node.handle,
113            self.id.0,
114            &attr_name,
115        )?;
116        let mut buffer = Vec::new();
117        buffer.resize(attr_size as usize, 0.0);
118        ffi::get_workitem_float_attribute(
119            &self.node.session,
120            self.node.handle,
121            self.id.0,
122            &attr_name,
123            &mut buffer,
124        )?;
125        Ok(buffer)
126    }
127}
128
129#[derive(Debug, Clone)]
130/// A wrapper for [`HoudiniNode`] with methods for cooking PDG.
131pub struct TopNode {
132    pub node: HoudiniNode,
133}
134
135/// A convenient wrapper for a single event generated by PDG.
136#[derive(Debug, Copy, Clone)]
137pub struct CookStep {
138    pub event: PDGEventInfo,
139    pub graph_id: i32,
140    pub graph_name: i32,
141}
142
143// Helper to create a vec of events. No Default impl for it.
144fn create_events() -> Vec<ffi::raw::HAPI_PDG_EventInfo> {
145    const NUM: usize = 32;
146    vec![
147        ffi::raw::HAPI_PDG_EventInfo {
148            nodeId: -1,
149            workItemId: -1,
150            dependencyId: -1,
151            currentState: -1,
152            lastState: -1,
153            eventType: -1,
154            msgSH: -1,
155        };
156        NUM
157    ]
158}
159
160impl TopNode {
161    /// Start cooking a TOP node asynchronously.
162    /// For each generated event, a user closure will be called with a [`CookStep`] argument.
163    /// If `sleep` is provided, the function will sleep for the duration before checking for new events.
164    ///
165    /// The closure returns [`Result<ControlFlow<bool>>`] which is handled like this:
166    ///
167    /// If its an `Err(_)` - bubble up the error.
168    /// If it's [`ControlFlow::Break`] then the `bool` is either to cancel the cooking
169    /// or just break the loop and return.
170    /// In case of [`ControlFlow::Continue`] run until completion.
171    ///
172    /// See the `pdg_cook` example in the `/examples` folder.
173    pub fn cook_async<F>(
174        &self,
175        all_outputs: bool,
176        sleep: Option<std::time::Duration>,
177        mut func: F,
178    ) -> Result<()>
179    where
180        F: FnMut(CookStep) -> Result<ControlFlow<bool>>,
181    {
182        let session = &self.node.session;
183        log::debug!("Start cooking PDG node: {}", self.node.path()?);
184        debug_assert!(session.is_valid());
185        ffi::cook_pdg(session, self.node.handle, false, false, all_outputs)?;
186        let mut events = create_events();
187        'main: loop {
188            std::thread::sleep(sleep.unwrap_or_default());
189            let (graph_ids, graph_names) = ffi::get_pdg_contexts(session)?;
190            debug_assert_eq!(graph_ids.len(), graph_names.len());
191            for (graph_id, graph_name) in graph_ids.into_iter().zip(graph_names) {
192                for event in ffi::get_pdg_events(session, graph_id, &mut events)? {
193                    let event = PDGEventInfo(*event);
194                    match event.event_type() {
195                        PdgEventType::EventCookComplete => break 'main,
196                        _ => {
197                            match func(CookStep {
198                                event,
199                                graph_id,
200                                graph_name,
201                            }) {
202                                Err(e) => return Err(e),
203                                Ok(ControlFlow::Continue(())) => {}
204                                Ok(ControlFlow::Break(stop_cooking)) => {
205                                    if stop_cooking {
206                                        // TODO: Should we call this for all graph ids?
207                                        ffi::cancel_pdg_cook(session, graph_id)?;
208                                    }
209                                    break 'main;
210                                }
211                            }
212                        }
213                    }
214                }
215            }
216        }
217        Ok(())
218    }
219
220    /// Trigger PDG cooking and wait for completion.
221    /// If `all_outputs` is true and this TOP node is of topnet type, cook all network outptus.
222    /// Results can then be retrieved from workitems with `get_all_workitems()`
223    pub fn cook_pdg_blocking(&self, all_outputs: bool) -> Result<()> {
224        ffi::cook_pdg(
225            &self.node.session,
226            self.node.handle,
227            false,
228            true,
229            all_outputs,
230        )
231    }
232
233    pub fn generate_static_items(&self, all_outputs: bool) -> Result<()> {
234        ffi::cook_pdg(
235            &self.node.session,
236            self.node.handle,
237            true,
238            true,
239            all_outputs,
240        )
241    }
242
243    /// Get the graph(context) id of this node in PDG.
244    pub fn get_context_id(&self) -> Result<i32> {
245        ffi::get_pdg_context_id(&self.node.session, self.node.handle)
246    }
247
248    /// Cancel cooking.
249    pub fn cancel_cooking(&self) -> Result<()> {
250        log::debug!("Cancel PDG cooking {}", self.node.path()?);
251        let context = self.get_context_id()?;
252        ffi::cancel_pdg_cook(&self.node.session, context)
253    }
254
255    /// Pause cooking process
256    pub fn pause_cooking(&self) -> Result<()> {
257        log::debug!("Pause PDG cooking {}", self.node.path()?);
258        let context = self.get_context_id()?;
259        ffi::pause_pdg_cook(&self.node.session, context)
260    }
261
262    /// Dirty the node, forcing the work items to regenerate.
263    pub fn dirty_node(&self, clean_results: bool) -> Result<()> {
264        log::debug!("Set PDG node dirty {}", self.node.path()?);
265        ffi::dirty_pdg_node(&self.node.session, self.node.handle, clean_results)
266    }
267
268    /// Which this node current [`PdgState`]
269    pub fn get_current_state(&self, context_id: Option<i32>) -> Result<PdgState> {
270        let context = match context_id {
271            Some(c) => c,
272            None => self.get_context_id()?,
273        };
274        ffi::get_pdg_state(&self.node.session, context)
275    }
276
277    /// Get the work item by id and graph(context) id.
278    pub fn get_workitem(&self, workitem_id: WorkItemId) -> Result<PDGWorkItem<'_>> {
279        let context_id = self.get_context_id()?;
280        ffi::get_workitem_info(&self.node.session, context_id, workitem_id.0).map(|_| PDGWorkItem {
281            id: workitem_id,
282            context_id,
283            node: &self.node,
284        })
285    }
286
287    pub fn get_all_workitems(&self) -> Result<Vec<PDGWorkItem<'_>>> {
288        let context_id = self.get_context_id()?;
289        ffi::get_pdg_workitems(&self.node.session, self.node.handle).map(|vec| {
290            vec.into_iter()
291                .map(|id| PDGWorkItem {
292                    id: WorkItemId(id),
293                    context_id,
294                    node: &self.node,
295                })
296                .collect()
297        })
298    }
299
300    pub fn create_workitem(
301        &self,
302        name: &str,
303        index: i32,
304        context_id: Option<i32>,
305    ) -> Result<PDGWorkItem<'_>> {
306        let name = std::ffi::CString::new(name)?;
307        let context_id = match context_id {
308            Some(c) => c,
309            None => self.get_context_id()?,
310        };
311        let id = ffi::create_pdg_workitem(&self.node.session, self.node.handle, &name, index)?;
312        Ok(PDGWorkItem {
313            id: WorkItemId(id),
314            context_id,
315            node: &self.node,
316        })
317    }
318
319    pub fn commit_workitems(&self) -> Result<()> {
320        ffi::commit_pdg_workitems(&self.node.session, self.node.handle)
321    }
322}