nsi-core 0.8.0

Nodal Scene Interface for (offline) 3D renderers – ɴsɪ.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
//! An ɴsɪ context.

// Needed for the example dode to build.
extern crate self as nsi;
use crate::{argument::*, *};
use null_terminated_str::NullTerminatedStr;
use rclite::Arc;
#[allow(unused_imports)]
use std::{
    ffi::{c_char, CStr, CString},
    marker::PhantomData,
    ops::Drop,
    os::raw::{c_int, c_void},
};
use ustr::Ustr;

/// The actual context and a marker to hold on to callbacks
/// (closures)/references passed via [`set_attribute()`] or the like.
///
/// We wrap this in an [`Arc`] in [`Context`] to make sure drop() is only
/// called when the last clone ceases existing.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
struct InnerContext<'a> {
    context: NSIContext,
    // _marker needs to be invariant in 'a.
    // See "Making a struct outlive a parameter given to a method of
    // that struct": https://stackoverflow.com/questions/62374326/
    _marker: PhantomData<*mut &'a ()>,
}

unsafe impl<'a> Send for InnerContext<'a> {}
unsafe impl<'a> Sync for InnerContext<'a> {}

impl<'a> Drop for InnerContext<'a> {
    #[inline]
    fn drop(&mut self) {
        NSI_API.NSIEnd(self.context);
    }
}

/// # An ɴꜱɪ Context.
///
/// A `Context` is used to describe a scene to the renderer and request images
/// to be rendered from it.
///
/// ## Safety
/// A `Context` may be used in multiple threads at once.
///
/// ## Lifetime
/// A `Context` can be used without worrying about its lifetime until you want
/// to store it somewhere, e.g. in a struct.
///
/// The reason `Context` has an explicit lifetime is so that it can take
/// [`Reference`]s and [`Callback`]s (closures). These must be valid until the
/// context is dropped and this guarantee requires explicit lifetimes. When you
/// use a context directly this is not an issue but when you want to reference
/// it somewhere the same rules as with all references apply.
///
/// ## Further Reading
/// See the [ɴꜱɪ documentation on context
/// handling](https://nsi.readthedocs.io/en/latest/c-api.html#context-handling).
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Context<'a>(Arc<InnerContext<'a>>);

unsafe impl<'a> Send for Context<'a> {}
unsafe impl<'a> Sync for Context<'a> {}

impl<'a> From<Context<'a>> for NSIContext {
    #[inline]
    fn from(context: Context<'a>) -> Self {
        context.0.context
    }
}

impl<'a> From<NSIContext> for Context<'a> {
    #[inline]
    fn from(context: NSIContext) -> Self {
        Self(Arc::new(InnerContext {
            context,
            _marker: PhantomData,
        }))
    }
}

impl<'a> Context<'a> {
    /// Creates an ɴsɪ context.
    ///
    /// Contexts may be used in multiple threads at once.
    ///
    /// # Examples
    ///
    /// ```
    /// # use nsi_core as nsi;
    /// // Create rendering context that dumps to stdout.
    /// let ctx =
    ///     nsi::Context::new(Some(&[nsi::string!("streamfilename", "stdout")]))
    ///         .expect("Could not create ɴsɪ context.");
    /// ```
    /// # Error
    /// If this method fails for some reason, it returns [`None`].
    #[inline]
    pub fn new(args: Option<&ArgSlice<'_, 'a>>) -> Option<Self> {
        let (_, _, mut args_out) = get_c_param_vec(args);

        let fn_pointer: nsi_sys::NSIErrorHandler = Some(
            error_handler
                as extern "C" fn(*mut c_void, c_int, c_int, *const c_char),
        );

        if let Some(args) = args {
            if let Some(arg) = args
                .iter()
                .find(|arg| Ustr::from("errorhandler") == arg.name)
            {
                args_out.push(nsi_sys::NSIParam {
                    name: Ustr::from("errorhandler").as_char_ptr(),
                    data: &fn_pointer as *const _ as _,
                    type_: NSIType::Pointer as _,
                    arraylength: 0,
                    count: 1,
                    flags: 0,
                });
                args_out.push(nsi_sys::NSIParam {
                    name: Ustr::from("errorhandlerdata").as_char_ptr(),
                    data: &arg.data.as_c_ptr() as *const _ as _,
                    type_: NSIType::Pointer as _,
                    arraylength: 1,
                    count: 1,
                    flags: 0,
                });
            }
        }

        let context = NSI_API.NSIBegin(args_out.len() as _, args_out.as_ptr());

        if 0 == context {
            None
        } else {
            Some(Self(Arc::new(InnerContext {
                context,
                _marker: PhantomData,
            })))
        }
    }

    /// Creates a new node.
    ///
    /// # Arguments
    ///
    /// * `handle` -- A node handle. This string will uniquely identify the node
    ///   in the scene.
    ///
    ///   If the supplied handle matches an existing node, the function does
    /// nothing if all other parameters match the call which created that
    /// node. Otherwise, it emits an error. Note that handles need only be
    /// unique within a given [`Context`]. It is ok to reuse the same
    /// handle inside different [`Context`]s.
    ///
    /// * `node_type` -- The type of node to create. The crate has `&str`
    ///   constants for all [`node`]s that are in the official NSI
    ///   specification. As this parameter is just a string you can instance
    ///   other node types that a particular implementation may provide and
    ///   which are not part of the official specification.
    ///
    /// * `args` -- A [`slice`](std::slice) of optional [`Arg`] arguments.
    ///   *There are no optional arguments defined as of now*.
    ///
    /// ```
    /// # use nsi_core as nsi;
    /// // Create a context to send the scene to.
    /// let ctx = nsi::Context::new(None).unwrap();
    ///
    /// // Create an infinte plane.
    /// ctx.create("ground", nsi::PLANE, None);
    /// ```
    #[inline]
    pub fn create(
        &self,
        handle: &str,
        node_type: &str,
        args: Option<&ArgSlice<'_, 'a>>,
    ) {
        let handle = HandleString::from(handle);
        let node_type = Ustr::from(node_type);
        let (args_len, args_ptr, _args_out) = get_c_param_vec(args);

        NSI_API.NSICreate(
            self.0.context,
            handle.as_char_ptr(),
            node_type.as_char_ptr(),
            args_len,
            args_ptr,
        );
    }

    /// This function deletes a node from the scene. All connections to and from
    /// the node are also deleted.
    ///
    /// Note that it is not possible to delete the `.root` or the `.global`
    /// node.
    ///
    /// # Arguments
    ///
    /// * `handle` -- A handle to a node previously created with
    ///   [`create()`](Context::create()).
    ///
    /// * `args` -- A [`slice`](std::slice) of optional [`Arg`] arguments.
    ///
    /// # Optional Arguments
    ///
    /// * `"recursive"` ([`Integer`]) -- Specifies whether deletion is
    ///   recursive. By default, only the specified node is deleted. If a value
    ///   of `1` is given, then nodes which connect to the specified node are
    ///   recursively removed. Unless they meet one of the following conditions:
    ///   * They also have connections which do not eventually lead to the
    ///     specified node.
    ///   * Their connection to the node to be deleted was created with a
    ///     `strength` greater than `0`.
    ///
    ///   This allows, for example, deletion of an entire shader network in a
    ///   single call.
    #[inline]
    pub fn delete(&self, handle: &str, args: Option<&ArgSlice<'_, 'a>>) {
        let handle = HandleString::from(handle);
        let (args_len, args_ptr, _args_out) = get_c_param_vec(args);

        NSI_API.NSIDelete(
            self.0.context,
            handle.as_char_ptr(),
            args_len,
            args_ptr,
        );
    }

    /// This functions sets attributes on a previously node.
    /// All optional arguments of the function become attributes of
    /// the node.
    ///
    /// On a [`shader`](`node::SHADER`), this function is used to set the
    /// implicitly defined shader arguments.
    ///
    /// Setting an attribute using this function replaces any value
    /// previously set by [`set_attribute()`](Context::set_attribute()) or
    /// [`set_attribute_at_time()`](Context::set_attribute_at_time()).
    ///
    /// To reset an attribute to its default value, use
    /// [`delete_attribute()`](Context::delete_attribute()).
    ///
    /// # Arguments
    ///
    /// * `handle` -- A handle to a node previously created with
    ///   [`create()`](Context::create()).
    ///
    /// * `args` -- A [`slice`](std::slice) of optional [`Arg`] arguments.
    #[inline]
    pub fn set_attribute(&self, handle: &str, args: &ArgSlice<'_, 'a>) {
        let handle = HandleString::from(handle);
        let (args_len, args_ptr, _args_out) = get_c_param_vec(Some(args));

        NSI_API.NSISetAttribute(
            self.0.context,
            handle.as_char_ptr(),
            args_len,
            args_ptr,
        );
    }

    /// This function sets time-varying attributes (i.e. motion blurred).
    ///
    /// The `time` argument specifies at which time the attribute is being
    /// defined.
    ///
    /// It is not required to set time-varying attributes in any
    /// particular order. In most uses, attributes that are motion blurred must
    /// have the same specification throughout the time range.
    ///
    /// A notable  exception is the `P` attribute on [`particles`
    /// node](`node::PARTICLES`) which can be of different size for each
    /// time step because of appearing or disappearing particles. Setting an
    /// attribute using this function replaces any value previously set by
    /// [`set_attribute()`](Context::set_attribute()).
    ///
    /// # Arguments
    ///
    /// * `handle` -- A handle to a node previously created with
    ///   [`create()`](Context::create()).
    ///
    /// * `time` -- The time at which to set the value.
    ///
    /// * `args` -- A [`slice`](std::slice) of optional [`Arg`] arguments.
    #[inline]
    pub fn set_attribute_at_time(
        &self,
        handle: &str,
        time: f64,
        args: &ArgSlice<'_, 'a>,
    ) {
        let handle = HandleString::from(handle);
        let (args_len, args_ptr, _args_out) = get_c_param_vec(Some(args));

        NSI_API.NSISetAttributeAtTime(
            self.0.context,
            handle.as_char_ptr(),
            time,
            args_len,
            args_ptr,
        );
    }

    /// This function deletes any attribute with a name which matches
    /// the `name` argument on the specified object. There is no way to
    /// delete an attribute only for a specific time value.
    ///
    /// Deleting an attribute resets it to its default value.
    ///
    /// For example, after deleting the `transformationmatrix` attribute
    /// on a [`transform` node](`node::TRANSFORM`), the transform will be an
    /// identity. Deleting a previously set attribute on a [`shader`
    /// node](`node::SHADER`) will default to whatever is declared inside
    /// the shader.
    ///
    /// # Arguments
    ///
    /// * `handle` -- A handle to a node previously created with
    ///   [`create()`](Context::create()).
    ///
    /// * `name` -- The name of the attribute to be deleted/reset.
    #[inline]
    pub fn delete_attribute(&self, handle: &str, name: &str) {
        let handle = HandleString::from(handle);
        let name = Ustr::from(name);

        NSI_API.NSIDeleteAttribute(
            self.0.context,
            handle.as_char_ptr(),
            name.as_char_ptr(),
        );
    }

    /// Create a connection between two elements.
    ///
    /// It is not an error to create a connection which already exists
    /// or to remove a connection which does not exist but the nodes
    /// on which the connection is performed must exist.
    ///
    /// # Arguments
    ///
    /// * `from` -- The handle of the node from which the connection is made.
    ///
    /// * `from_attr` -- The name of the attribute from which the connection is
    ///   made. If this is an empty string then the connection is made from the
    ///   node instead of from a specific attribute of the node.
    ///
    ///   If this is `None` the node itself will be connected.
    ///
    /// * `to` -- The handle of the node to which the connection is made.
    ///
    /// * `to_attr` -- The name of the attribute to which the connection is
    ///   made. If this is an empty string then the connection is made to the
    ///   node instead of to a specific attribute of the node.
    ///
    /// # Optional Arguments
    ///
    /// * `"value"` -- This can be used to change the value of a node's
    ///   attribute in some contexts. Refer to guidelines on inter-object
    ///   visibility for more information about the utility of this parameter.
    ///
    /// * `"priority"` ([`Integer`]) -- When connecting attribute nodes,
    ///   indicates in which order the nodes should be considered when
    ///   evaluating the value of an attribute.
    ///
    /// * `"strength"` ([`Integer`]) -- A connection with a `strength` greater
    ///   than `0` will *block* the progression of a recursive
    ///   [`delete()`](Context::delete()).
    #[inline]
    pub fn connect(
        &self,
        from: &str,
        from_attr: Option<&str>,
        to: &str,
        to_attr: &str,
        args: Option<&ArgSlice<'_, 'a>>,
    ) {
        let from = HandleString::from(from);
        let from_attr = Ustr::from(from_attr.unwrap_or(""));
        let to = HandleString::from(to);
        let to_attr = Ustr::from(to_attr);
        let (args_len, args_ptr, _args_out) = get_c_param_vec(args);

        NSI_API.NSIConnect(
            self.0.context,
            from.as_char_ptr(),
            from_attr.as_char_ptr(),
            to.as_char_ptr(),
            to_attr.as_char_ptr(),
            args_len,
            args_ptr,
        );
    }

    /// This function removes a connection between two elements.
    ///
    /// The handle for either node may be the special value
    /// [`.all`](crate::node::ALL). This will remove all connections which
    /// match the other three arguments.
    ///
    /// # Examples
    ///
    /// ```
    /// # use nsi_core as nsi;
    /// # // Create a rendering context.
    /// # let ctx = nsi::Context::new(None).unwrap();
    /// // Disconnect everything from the scene's root.
    /// ctx.disconnect(nsi::ALL, None, ".root", "");
    /// ```
    #[inline]
    pub fn disconnect(
        &self,
        from: &str,
        from_attr: Option<&str>,
        to: &str,
        to_attr: &str,
    ) {
        let from = HandleString::from(from);
        let from_attr = Ustr::from(from_attr.unwrap_or(""));
        let to = HandleString::from(to);
        let to_attr = Ustr::from(to_attr);

        NSI_API.NSIDisconnect(
            self.0.context,
            from.as_char_ptr(),
            from_attr.as_char_ptr(),
            to.as_char_ptr(),
            to_attr.as_char_ptr(),
        );
    }

    /// This function includes a block of interface calls from an external
    /// source into the current scene. It blends together the concepts of a
    /// file include, commonly known as an *archive*, with that of
    /// procedural include which is traditionally a compiled executable. Both
    /// are the same idea expressed in a different language.
    ///
    /// Note that for delayed procedural evaluation you should use a
    /// `Procedural` node.
    ///
    /// The ɴꜱɪ adds a third option which sits in-between — [Lua
    /// scripts](https://nsi.readthedocs.io/en/latest/lua-api.html). They are more powerful than a
    /// simple included file yet they are also easier to generate as they do not
    /// require compilation.
    ///
    /// For example, it is realistic to export a whole new script for every
    /// frame of an animation. It could also be done for every character in
    /// a frame. This gives great flexibility in how components of a scene
    /// are put together.
    ///
    /// The ability to load ɴꜱɪ commands from memory is also provided.
    ///
    /// # Optional Arguments
    ///
    /// * `"type"` ([`String`]) – The type of file which will generate the
    ///   interface calls. This can be one of:
    ///   * `"apistream"` – Read in an ɴꜱɪ stream. This requires either
    ///     `"filename"` or `"buffer"`/`"size"` arguments to be specified too.
    ///
    ///   * `"lua"` – Execute a Lua script, either from file or inline. See also
    ///     [how to evaluate a Lua script](https://nsi.readthedocs.io/en/latest/lua-api.html#luaapi-evaluation).
    ///
    ///   * `"dynamiclibrary"` – Execute native compiled code in a loadable library. See
    ///     [dynamic library procedurals](https://nsi.readthedocs.io/en/latest/procedurals.html#section-procedurals)
    ///     for an implementation example in C.
    ///
    /// * `"filename"` ([`String`]) – The name of the file which contains the
    ///   interface calls to include.
    ///
    /// * `"script"` ([`String`]) – A valid Lua script to execute when `"type"`
    ///   is set to `"lua"`.
    ///
    /// * `"buffer"` ([`String`]) – A memory block that contain ɴꜱɪ commands to
    ///   execute.
    ///
    /// * `"backgroundload"` ([`Integer`]) – If this is nonzero, the object may
    ///   be loaded in a separate thread, at some later time. This requires that
    ///   further interface calls not directly reference objects defined in the
    ///   included file. The only guarantee is that the file will be loaded
    ///   before rendering begins.
    #[inline]
    pub fn evaluate(&self, args: &ArgSlice<'_, 'a>) {
        let (args_len, args_ptr, _args_out) = get_c_param_vec(Some(args));

        NSI_API.NSIEvaluate(self.0.context, args_len, args_ptr);
    }

    /// This function is the only control function of the API.
    ///
    /// It is responsible of starting, suspending and stopping the render. It
    /// also allows for synchronizing the render with interactive calls that
    /// might have been issued.
    ///
    /// Note that this call will block if [`Action::Wait`] is selected.
    ///
    /// # Arguments
    ///
    /// * `action` -- Specifies the render [`Action`] to be performed on the
    ///   scene.
    ///
    /// # Optional Arguments
    ///
    /// * `"progressive"` ([`Integer`]) -- If set to `1`, render the image in a
    ///   progressive fashion.
    ///
    /// * `"interactive"` ([`Integer`]) -- If set to `1`, the renderer will
    ///   accept commands to edit scene’s state while rendering. The difference
    ///   with a normal render is that the render task will not exit even if
    ///   rendering is finished. Interactive renders are by definition
    ///   progressive.
    ///
    /// * `"callback"` ([`FnStatus`]) -- A closure that will be called be when
    ///   the status of the render changes.
    ///
    ///   # Example
    ///
    ///   ```
    ///   # use nsi_core as nsi;
    ///   # let ctx = nsi::Context::new(None).unwrap();
    ///   let status_callback = nsi::StatusCallback::new(
    ///       |_ctx: &nsi::Context, status: nsi::RenderStatus| {
    ///           println!("Status: {:?}", status);
    ///         },
    ///      );
    ///
    ///   /// The renderer will abort because we didn't define an output driver.
    ///   /// So our status_callback() above will receive RenderStatus::Aborted.
    ///   ctx.render_control(
    ///       nsi::Action::Start,
    ///       Some(&[
    ///           nsi::integer!("interactive", true as _),
    ///           nsi::callback!("callback", status_callback),
    ///       ]),
    ///   );
    ///
    ///   // Block until the renderer is really done.
    ///   ctx.render_control(nsi::Action::Wait, None);
    ///   ```
    #[inline]
    pub fn render_control(
        &self,
        action: Action,
        args: Option<&ArgSlice<'_, 'a>>,
    ) {
        let (_, _, mut args_out) = get_c_param_vec(args);

        let fn_pointer: nsi_sys::NSIRenderStopped =
            Some(render_status as extern "C" fn(*mut c_void, c_int, c_int));

        args_out.push(nsi_sys::NSIParam {
            name: Ustr::from("action").as_char_ptr(),
            data: &Ustr::from(match action {
                Action::Start => "start",
                Action::Wait => "wait",
                Action::Synchronize => "synchronize",
                Action::Suspend => "suspend",
                Action::Resume => "resume",
                Action::Stop => "stop",
            })
            .as_char_ptr() as *const _ as _,
            type_: NSIType::String as _,
            arraylength: 0,
            count: 1,
            flags: 0,
        });

        if let Some(args) = args {
            if let Some(arg) =
                args.iter().find(|arg| Ustr::from("callback") == arg.name)
            {
                args_out.push(nsi_sys::NSIParam {
                    name: Ustr::from("stoppedcallback").as_char_ptr(),
                    data: &fn_pointer as *const _ as _,
                    type_: NSIType::Pointer as _,
                    arraylength: 0,
                    count: 1,
                    flags: 0,
                });
                args_out.push(nsi_sys::NSIParam {
                    name: Ustr::from("stoppedcallbackdata").as_char_ptr(),
                    data: &arg.data.as_c_ptr() as *const _ as _,
                    type_: NSIType::Pointer as _,
                    arraylength: 1,
                    count: 1,
                    flags: 0,
                });
            }
        }

        NSI_API.NSIRenderControl(
            self.0.context,
            args_out.len() as _,
            args_out.as_ptr(),
        );
    }
}

/// The render action to perform when calling
/// [`render_control()`](Context::render_control()).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Action {
    /// Starts rendering the scene in the provided context. The render starts
    /// in parallel -- this does not block.
    Start,
    /// Wait for a render to finish. This blocks.
    Wait,
    /// For an interactive render, apply all the buffered calls to scene's
    /// state.
    Synchronize,
    /// Suspends render. Does not block.
    Suspend,
    /// Resumes a previously suspended render. Does not block.
    Resume,
    /// Stops rendering in the provided context without destroying the scene.
    /// Does not block.
    Stop,
}

/// The status of a *interactive* render session.
#[repr(i32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, num_enum::FromPrimitive)]
pub enum RenderStatus {
    #[num_enum(default)]
    Completed = nsi_sys::NSIStoppingStatus::RenderCompleted as _,
    Aborted = nsi_sys::NSIStoppingStatus::RenderAborted as _,
    Synchronized = nsi_sys::NSIStoppingStatus::RenderSynchronized as _,
    Restarted = nsi_sys::NSIStoppingStatus::RenderRestarted as _,
}

/// A closure which is called to inform about the status of an ongoing render.
///
/// It is passed to ɴsɪ via [`render_control()`](Context::render_control())’s
/// `"callback"` argument.
///
/// # Examples
///
/// ```
/// # use nsi_core as nsi;
/// # let ctx = nsi::Context::new(None).unwrap();
/// let status_callback = nsi::context::StatusCallback::new(
///     |_: &nsi::context::Context, status: nsi::context::RenderStatus| {
///         println!("Status: {:?}", status);
///     },
/// );
///
/// ctx.render_control(
///     nsi::Action::Start,
///     Some(&[nsi::callback!("callback", status_callback)]),
/// );
/// ```
pub trait FnStatus<'a>: Fn(
    // The [`Context`] for which this closure was called.
    &Context,
    // Status of interactive render session.
    RenderStatus,
)
+ 'a {}

#[doc(hidden)]
impl<
        'a,
        T: Fn(&Context, RenderStatus)
            + 'a
            + for<'r, 's> Fn(&'r context::Context<'s>, RenderStatus),
    > FnStatus<'a> for T
{
}

// FIXME once trait aliases are in stable.
/*
trait FnStatus<'a> = FnMut(
    // Status of interactive render session.
    status: RenderStatus
    )
    + 'a
*/

/// Wrapper to pass a [`FnStatus`] closure to a [`Context`].
pub struct StatusCallback<'a>(Box<Box<dyn FnStatus<'a>>>);

unsafe impl Send for StatusCallback<'static> {}
unsafe impl Sync for StatusCallback<'static> {}

impl<'a> StatusCallback<'a> {
    pub fn new<F>(fn_status: F) -> Self
    where
        F: FnStatus<'a>,
    {
        StatusCallback(Box::new(Box::new(fn_status)))
    }
}

impl CallbackPtr for StatusCallback<'_> {
    #[doc(hidden)]
    fn to_ptr(self) -> *const core::ffi::c_void {
        Box::into_raw(self.0) as *const _ as _
    }
}

// Trampoline function for the FnStatus callback.
#[no_mangle]
pub(crate) extern "C" fn render_status(
    payload: *mut c_void,
    context: nsi_sys::NSIContext,
    status: c_int,
) {
    if !payload.is_null() {
        let fn_status =
            unsafe { Box::from_raw(payload as *mut Box<dyn FnStatus>) };
        let ctx = Context(Arc::new(InnerContext {
            context,
            _marker: PhantomData,
        }));

        fn_status(&ctx, status.into());

        // We must not call drop() on this context.
        // This is safe as Context doesn't allocate and this one is on the stack
        // anyway.
        std::mem::forget(ctx);
    }
}

/// A closure which is called to inform about the errors during scene defintion
/// or a render.
///
/// It is passed to ɴsɪ via [`new()`](Context::new())’s `"errorhandler"`
/// argument.
///
/// # Examples
///
/// ```
/// # use nsi_core as nsi;
/// use log::{debug, error, info, trace, warn, Level};
///
/// let error_handler = nsi::ErrorCallback::new(
///     |level: Level, message_id: i32, message: &str| match level {
///         Level::Error => error!("[{}] {}", message_id, message),
///         Level::Warn => warn!("[{}] {}", message_id, message),
///         Level::Info => info!("[{}] {}", message_id, message),
///         Level::Debug => debug!("[{}] {}", message_id, message),
///         Level::Trace => trace!("[{}] {}", message_id, message),
///     },
/// );
///
/// let ctx = nsi::Context::new(Some(&[nsi::callback!(
///     "errorhander",
///     error_handler
/// )]))
/// .unwrap();
///
/// // Do something with ctx ...
/// ```
pub trait FnError<'a>: Fn(
    // The error level.
    log::Level,
    // The message id.
    i32,
    // The message.
    &str,
)
+ 'a {}

#[doc(hidden)]
impl<
        'a,
        T: Fn(log::Level, i32, &str) + 'a + for<'r> Fn(log::Level, i32, &'r str),
    > FnError<'a> for T
{
}

/// Wrapper to pass a [`FnError`] closure to a [`Context`].
pub struct ErrorCallback<'a>(Box<Box<dyn FnError<'a>>>);

unsafe impl Send for ErrorCallback<'static> {}
unsafe impl Sync for ErrorCallback<'static> {}

impl<'a> ErrorCallback<'a> {
    pub fn new<F>(fn_error: F) -> Self
    where
        F: FnError<'a>,
    {
        ErrorCallback(Box::new(Box::new(fn_error)))
    }
}

impl CallbackPtr for ErrorCallback<'_> {
    #[doc(hidden)]
    fn to_ptr(self) -> *const core::ffi::c_void {
        Box::into_raw(self.0) as *const _ as _
    }
}

// Trampoline function for the FnError callback.
#[no_mangle]
pub(crate) extern "C" fn error_handler(
    payload: *mut c_void,
    level: c_int,
    code: c_int,
    message: *const c_char,
) {
    if !payload.is_null() {
        let fn_error =
            unsafe { Box::from_raw(payload as *mut Box<dyn FnError>) };

        let message = unsafe {
            NullTerminatedStr::from_cstr_unchecked(CStr::from_ptr(message as _))
        };

        let level = match NSIErrorLevel::from(level) {
            NSIErrorLevel::Message => log::Level::Trace,
            NSIErrorLevel::Info => log::Level::Info,
            NSIErrorLevel::Warning => log::Level::Warn,
            NSIErrorLevel::Error => log::Level::Error,
        };

        fn_error(level, code as _, message.as_ref());
    }
}