Skip to main content

nsi_intermediate/
lua.rs

1//! Lua script emission.
2//!
3//! ɴsɪ has three front ends -- the C API, the stream, and a Lua script
4//! -- and this writes the third. The scene comes out as the calls that
5//! would rebuild it:
6//!
7//! ```lua
8//! nsi.Create("cam", "perspectivecamera")
9//! nsi.SetAttribute("cam", {name="fov", data={45}, type=nsi.TypeFloat})
10//! nsi.Connect("cam", "", ".root", "objects")
11//! ```
12//!
13//! # What Lua cannot say
14//!
15//! ɴsɪ's Lua binding is narrower than its C API, in three ways that all
16//! lose data silently, so each is refused instead:
17//!
18//! - **Types.** There is no `nsi.TypeDouble`, no `nsi.TypeInt64` and no
19//!   pointer type. Those names are `nil`, and a parameter table whose
20//!   `type` is `nil` is a runtime error in the renderer; passing the
21//!   value untyped instead makes a double a `float`, and a 64-bit
22//!   integer comes back as a different number entirely.
23//! - **Flags.** A parameter table has `name`, `data`, `type` and
24//!   `arraylength`, and nothing else. `per_vertex`, `per_face` and
25//!   `linear_interpolation` cannot be said, and a per-vertex normal
26//!   emitted without its flag rebuilds a different surface.
27//! - **Empty string arrays.** Setting one from Lua aborts 3Delight with
28//!   a heap error rather than reporting a problem.
29//!
30//! A wrong answer that renders is worse than a loud one, so
31//! [`write_lua`] fails rather than emitting any of them.
32//!
33//! `doublematrix` is the exception among the wide types --
34//! `nsi.TypeDoubleMatrix` exists -- so a transform survives.
35//!
36//! # Grouping
37//!
38//! One attribute per `nsi.SetAttribute` call, matching
39//! [`crate::write_stream`]. Lua would allow all of a node's attributes
40//! in one call, but then the two emitters would disagree about
41//! statement boundaries and could not be compared against one another.
42
43use crate::{OwnedArgument, OwnedData, Scene};
44use core::{error::Error, fmt};
45use nsi_ffi_wrap::{Arg, nsi_sys::NSIParamFlags};
46use nsi_trait::{Action, Nsi, Type};
47use parking_lot::Mutex;
48use std::io::{self, Write};
49
50/// Why a scene could not be written as a Lua script.
51#[derive(Debug)]
52#[non_exhaustive]
53pub enum LuaError {
54    /// Writing failed.
55    Io(io::Error),
56    /// ɴsɪ's Lua binding has no name for this attribute's type.
57    ///
58    /// `f64` and `i64` arguments have no Lua spelling: `nsi.TypeDouble`
59    /// and `nsi.TypeInt64` are `nil`, and passing a *typed* parameter
60    /// whose type is `nil` is a runtime error in the renderer, while
61    /// passing the value untyped silently makes a double a `float` and
62    /// a large integer a different number.
63    Inexpressible {
64        /// The node carrying the attribute.
65        handle: String,
66        /// The attribute name.
67        attribute: String,
68        /// The ɴsɪ type that has no Lua spelling.
69        type_tag: Type,
70    },
71    /// The argument carries ɴsɪ flags that its Lua binding cannot
72    /// express.
73    ///
74    /// A Lua parameter table has `name`, `data`, `type` and
75    /// `arraylength` -- and nothing for `per_vertex`, `per_face` or
76    /// `linear_interpolation`. Emitting the argument without them
77    /// rebuilds a *different surface*: a per-vertex normal becomes a
78    /// per-varying one, which on a subdivision mesh is a different
79    /// shape. Verified against 3Delight: every spelling of a flag key
80    /// is ignored.
81    InexpressibleFlags {
82        /// The node carrying the attribute.
83        handle: String,
84        /// The attribute name.
85        attribute: String,
86        /// The flags that have no Lua spelling.
87        flags: i32,
88    },
89    /// An empty string array.
90    ///
91    /// `{name="x", data={}, type=nsi.TypeString}` aborts 3Delight with
92    /// a heap error rather than reporting a problem, so emitting one
93    /// hands a consumer a script that kills the renderer. Empty numeric
94    /// arrays are fine.
95    EmptyStringArray {
96        /// The node carrying the attribute.
97        handle: String,
98        /// The attribute name.
99        attribute: String,
100    },
101    /// A `Create` carrying parameters.
102    ///
103    /// ɴsɪ's Lua `nsi.Create` takes a handle and a node type and
104    /// nothing else, while `NSICreate` and the stream both take
105    /// optional parameters and 3Delight writes them. Emitting the
106    /// create without them would drop whatever they said.
107    CreateArguments {
108        /// The node being created.
109        handle: String,
110        /// The type it was created with.
111        node_type: String,
112    },
113}
114
115impl fmt::Display for LuaError {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Self::Io(error) => error.fmt(f),
119            Self::CreateArguments { handle, node_type } => write!(
120                f,
121                "`nsi.Create` takes no parameters, so creating {handle:?} \
122                 as {node_type:?} with them cannot be written as Lua",
123            ),
124            Self::Inexpressible {
125                handle,
126                attribute,
127                type_tag,
128            } => write!(
129                f,
130                "ɴsɪ attribute {attribute:?} on node {handle:?} has type \
131                 {type_tag:?}, which ɴsɪ's Lua binding cannot express; \
132                 emitting it untyped would change its value"
133            ),
134            Self::InexpressibleFlags {
135                handle,
136                attribute,
137                flags,
138            } => write!(
139                f,
140                "ɴsɪ attribute {attribute:?} on node {handle:?} carries \
141                 flags {flags:#x}, which a Lua parameter table cannot \
142                 express; emitting it without them would rebuild a \
143                 different surface"
144            ),
145            Self::EmptyStringArray { handle, attribute } => write!(
146                f,
147                "ɴsɪ attribute {attribute:?} on node {handle:?} is an \
148                 empty string array, which aborts the renderer when a \
149                 Lua script sets one"
150            ),
151        }
152    }
153}
154
155impl Error for LuaError {
156    fn source(&self) -> Option<&(dyn Error + 'static)> {
157        match self {
158            Self::Io(error) => Some(error),
159            Self::Inexpressible { .. }
160            | Self::InexpressibleFlags { .. }
161            | Self::EmptyStringArray { .. }
162            | Self::CreateArguments { .. } => None,
163        }
164    }
165}
166
167impl From<io::Error> for LuaError {
168    fn from(error: io::Error) -> Self {
169        Self::Io(error)
170    }
171}
172
173/// Write `scene` as a Lua script.
174///
175/// # Errors
176///
177/// [`LuaError::Inexpressible`] for an attribute whose ɴsɪ type has no
178/// Lua spelling, and [`LuaError::Io`] for a write failure.
179pub fn write_lua<W: Write>(scene: &Scene, out: &mut W) -> Result<(), LuaError> {
180    for (handle, node) in scene.nodes() {
181        // The reserved handles need no `create`, exactly as in a stream.
182        if !crate::is_reserved(handle) {
183            writeln!(
184                out,
185                "nsi.Create({}, {})",
186                quoted_str(handle),
187                quoted_str(&node.node_type)
188            )?;
189        }
190
191        for arg in node.attribute_table().values() {
192            write!(out, "nsi.SetAttribute({}, ", quoted_str(handle))?;
193            write_arg(out, handle, arg)?;
194            writeln!(out, ")")?;
195        }
196
197        // In call order, as `write_stream` explains.
198        for (_, calls) in node.samples() {
199            for (time, arg) in calls {
200                write!(
201                    out,
202                    "nsi.SetAttributeAtTime({}, {}, ",
203                    quoted_str(handle),
204                    lua_number(*time)
205                )?;
206                write_arg(out, handle, arg)?;
207                writeln!(out, ")")?;
208            }
209        }
210    }
211
212    for edge in scene.edges() {
213        let (from_port, to_port) = match &edge.kind {
214            crate::EdgeKind::ShaderNetwork { from_port, to_port } => {
215                (from_port.as_str(), to_port.as_str())
216            }
217            other => ("", other.to_attribute()),
218        };
219
220        write!(
221            out,
222            "nsi.Connect({}, {}, {}, {}",
223            quoted_str(&edge.from),
224            quoted_str(from_port),
225            quoted_str(&edge.to),
226            quoted_str(to_port)
227        )?;
228        for arg in &edge.args {
229            write!(out, ", ")?;
230            write_arg(out, &edge.from, arg)?;
231        }
232        writeln!(out, ")")?;
233    }
234
235    Ok(())
236}
237
238/// One parameter table: `{name=..., data=..., type=...}`.
239fn write_arg<W: Write>(
240    out: &mut W,
241    handle: &str,
242    arg: &OwnedArgument,
243) -> Result<(), LuaError> {
244    // A Lua parameter table has room for `name`, `data`, `type` and
245    // `arraylength` -- and nothing else. Dropping a flag silently
246    // rebuilds a different surface.
247    let inexpressible = NSIParamFlags::PerFace.bits()
248        | NSIParamFlags::PerVertex.bits()
249        | NSIParamFlags::InterpolateLinear.bits();
250    if arg.flags & inexpressible != 0 {
251        return Err(LuaError::InexpressibleFlags {
252            handle: handle.to_string(),
253            attribute: arg.name.clone(),
254            flags: arg.flags,
255        });
256    }
257
258    // An empty string array aborts the renderer outright.
259    if matches!(&arg.data, OwnedData::String(values) if values.is_empty()) {
260        return Err(LuaError::EmptyStringArray {
261            handle: handle.to_string(),
262            attribute: arg.name.clone(),
263        });
264    }
265
266    let type_name =
267        lua_type_name(arg.type_tag).ok_or_else(|| LuaError::Inexpressible {
268            handle: handle.to_string(),
269            attribute: arg.name.clone(),
270            type_tag: arg.type_tag,
271        })?;
272
273    write!(out, "{{name={}", quoted_str(&arg.name))?;
274    if arg.flags & NSIParamFlags::IsArray.bits() != 0 {
275        write!(out, ", arraylength={}", arg.array_length)?;
276    }
277
278    // A typed parameter's data must be a table even when it holds one
279    // value: the renderer reads a bare number as an empty array and
280    // writes `"name" "float" 0 [ ]`.
281    write!(out, ", data={{")?;
282    match &arg.data {
283        OwnedData::F32(values) => write_numbers(out, values)?,
284        OwnedData::F64(values) => write_numbers(out, values)?,
285        OwnedData::I32(values) => write_numbers(out, values)?,
286        OwnedData::I64(values) => write_numbers(out, values)?,
287        OwnedData::String(values) => {
288            for (index, value) in values.iter().enumerate() {
289                if index > 0 {
290                    out.write_all(b", ")?;
291                }
292                out.write_all(&self::quoted(value))?;
293            }
294        }
295        OwnedData::Reference(_) => {
296            // Unreachable: `lua_type_name` rejected it above.
297        }
298    }
299    write!(out, "}}, type=nsi.{type_name}}}")?;
300
301    Ok(())
302}
303
304fn write_numbers<W: Write, T: LuaNumber>(
305    out: &mut W,
306    values: &[T],
307) -> io::Result<()> {
308    let rendered: Vec<String> = values.iter().map(LuaNumber::to_lua).collect();
309    write!(out, "{}", rendered.join(", "))
310}
311
312/// A value Lua writes as a number literal.
313trait LuaNumber {
314    fn to_lua(&self) -> String;
315}
316
317impl LuaNumber for f32 {
318    fn to_lua(&self) -> String {
319        lua_number(f64::from(*self))
320    }
321}
322
323impl LuaNumber for f64 {
324    fn to_lua(&self) -> String {
325        lua_number(*self)
326    }
327}
328
329impl LuaNumber for i32 {
330    fn to_lua(&self) -> String {
331        self.to_string()
332    }
333}
334
335impl LuaNumber for i64 {
336    fn to_lua(&self) -> String {
337        self.to_string()
338    }
339}
340
341/// A Lua number literal.
342///
343/// Lua numbers are doubles, so this uses Rust's shortest round-tripping
344/// form rather than the stream's `%.17g`: the consumer is a Lua parser,
345/// not 3Delight's stream reader.
346fn lua_number(value: f64) -> String {
347    if value.is_finite() {
348        let rendered = value.to_string();
349        // Lua needs a decimal point to read a float as a float.
350        if rendered.contains(['.', 'e', 'E']) {
351            rendered
352        } else {
353            format!("{rendered}.0")
354        }
355    } else if value.is_nan() {
356        "0/0".to_string()
357    } else if value.is_sign_negative() {
358        "-math.huge".to_string()
359    } else {
360        "math.huge".to_string()
361    }
362}
363
364/// One Lua string literal, escaped.
365fn quoted(value: &[u8]) -> Vec<u8> {
366    let mut out = Vec::with_capacity(value.len() + 2);
367    out.push(b'"');
368    for &byte in value {
369        match byte {
370            b'"' => out.extend_from_slice(b"\\\""),
371            b'\\' => out.extend_from_slice(b"\\\\"),
372            b'\n' => out.extend_from_slice(b"\\n"),
373            b'\r' => out.extend_from_slice(b"\\r"),
374            b'\t' => out.extend_from_slice(b"\\t"),
375            _ => out.push(byte),
376        }
377    }
378    out.push(b'"');
379    out
380}
381
382/// [`quoted`] for an identifier, which the scene stores as text.
383///
384/// Escaping only ever substitutes ASCII sequences and copies every other
385/// byte through, so UTF-8 in gives UTF-8 out. The fallback is
386/// unreachable rather than a repair.
387fn quoted_str(value: &str) -> String {
388    // Unreachable, and stated rather than repaired: `quoted` substitutes
389    // only for `"`, `\`, `\n`, `\t` and bytes below `0x20`, all ASCII,
390    // and in valid UTF-8 an ASCII byte is always a whole code point --
391    // lead and continuation bytes are `0x80` and above. So every
392    // multi-byte sequence is copied through contiguously and unchanged.
393    // Falling back to a lossy conversion here would quietly rewrite an
394    // identifier, which is the one thing this crate refuses to do.
395    // SAFETY: `quoted` only ever inserts ASCII escapes and copies
396    // every other byte through unchanged, so a UTF-8 input stays UTF-8.
397    String::from_utf8(quoted(value.as_bytes()))
398        .expect("escaping only ASCII preserves UTF-8")
399}
400
401/// The `nsi.Type*` name for an ɴsɪ type, where Lua has one.
402///
403/// `None` for the three ɴsɪ types with no Lua spelling. Verified against
404/// 3Delight 2.9.207: naming `nsi.TypeDouble` or `nsi.TypeInt64` is a
405/// parse error in the renderer.
406const fn lua_type_name(type_tag: Type) -> Option<&'static str> {
407    match type_tag {
408        Type::F32 => Some("TypeFloat"),
409        Type::I32 => Some("TypeInteger"),
410        Type::String => Some("TypeString"),
411        Type::Color => Some("TypeColor"),
412        Type::Point => Some("TypePoint"),
413        Type::Vector => Some("TypeVector"),
414        Type::Normal => Some("TypeNormal"),
415        Type::MatrixF32 => Some("TypeMatrix"),
416        Type::MatrixF64 => Some("TypeDoubleMatrix"),
417        Type::F64 | Type::I64 | Type::Reference | Type::Invalid => None,
418    }
419}
420
421/// An [`Nsi`] sink that writes each call straight to a Lua script.
422///
423/// The Lua twin of [`crate::StreamWriter`], and the writing half of a
424/// filter whose output is a script rather than a stream. Every
425/// restriction [`write_lua`] documents applies here and for the same
426/// reason: the binding is narrower than the C API, so a call it cannot
427/// say is refused rather than emitted as something else.
428///
429/// ```
430/// # use nsi_intermediate::LuaWriter;
431/// # use nsi_trait::Nsi;
432/// let writer = LuaWriter::new(Vec::new());
433/// writer.create("cam", "perspectivecamera", None).unwrap();
434/// assert_eq!(
435///     String::from_utf8(writer.into_inner()).unwrap(),
436///     "nsi.Create(\"cam\", \"perspectivecamera\")\n",
437/// );
438/// ```
439#[derive(Debug)]
440pub struct LuaWriter<W: Write> {
441    out: Mutex<W>,
442}
443
444impl<W: Write> LuaWriter<W> {
445    /// A writer emitting into `out`.
446    pub fn new(out: W) -> Self {
447        Self {
448            out: Mutex::new(out),
449        }
450    }
451
452    /// The `out` this was built with.
453    pub fn into_inner(self) -> W {
454        self.out.into_inner()
455    }
456
457    /// `nsi.Name(head, {arg}, {arg}, ...)`.
458    fn statement(
459        &self,
460        call: &str,
461        head: &str,
462        handle: &str,
463        args: &[Arg<'_, '_>],
464    ) -> Result<(), LuaError> {
465        let mut out = self.out.lock();
466        write!(out, "nsi.{call}({head}")?;
467        for arg in args {
468            write!(out, ", ")?;
469            write_arg(&mut *out, handle, &OwnedArgument::from_param(arg))?;
470        }
471        writeln!(out, ")")?;
472        Ok(())
473    }
474}
475
476impl<W: Write + Send> Nsi for LuaWriter<W> {
477    type Arg<'call> = Arg<'call, 'static>;
478    type Error = LuaError;
479
480    /// # Errors
481    ///
482    /// [`LuaError::CreateArguments`] when the create carries
483    /// parameters: `nsi.Create` has nowhere to put them.
484    fn create(
485        &self,
486        handle: &str,
487        node_type: &str,
488        args: Option<&[Self::Arg<'_>]>,
489    ) -> Result<(), Self::Error> {
490        if !args.unwrap_or_default().is_empty() {
491            return Err(LuaError::CreateArguments {
492                handle: handle.to_string(),
493                node_type: node_type.to_string(),
494            });
495        }
496        self.statement(
497            "Create",
498            &format!("{}, {}", quoted_str(handle), quoted_str(node_type)),
499            handle,
500            &[],
501        )
502    }
503
504    fn delete(
505        &self,
506        handle: &str,
507        args: Option<&[Self::Arg<'_>]>,
508    ) -> Result<(), Self::Error> {
509        self.statement(
510            "Delete",
511            &quoted_str(handle),
512            handle,
513            args.unwrap_or_default(),
514        )
515    }
516
517    fn set_attribute(
518        &self,
519        handle: &str,
520        args: &[Self::Arg<'_>],
521    ) -> Result<(), Self::Error> {
522        self.statement("SetAttribute", &quoted_str(handle), handle, args)
523    }
524
525    fn set_attribute_at_time(
526        &self,
527        handle: &str,
528        time: f64,
529        args: &[Self::Arg<'_>],
530    ) -> Result<(), Self::Error> {
531        self.statement(
532            "SetAttributeAtTime",
533            &format!("{}, {}", quoted_str(handle), lua_number(time)),
534            handle,
535            args,
536        )
537    }
538
539    fn delete_attribute(
540        &self,
541        handle: &str,
542        name: &str,
543    ) -> Result<(), Self::Error> {
544        self.statement(
545            "DeleteAttribute",
546            &format!("{}, {}", quoted_str(handle), quoted_str(name)),
547            handle,
548            &[],
549        )
550    }
551
552    fn connect(
553        &self,
554        from: &str,
555        from_attribute: Option<&str>,
556        to: &str,
557        to_attribute: &str,
558        args: Option<&[Self::Arg<'_>]>,
559    ) -> Result<(), Self::Error> {
560        self.statement(
561            "Connect",
562            &format!(
563                "{}, {}, {}, {}",
564                quoted_str(from),
565                // An unnamed source port is the empty string, as in a
566                // stream.
567                quoted_str(from_attribute.unwrap_or_default()),
568                quoted_str(to),
569                quoted_str(to_attribute)
570            ),
571            from,
572            args.unwrap_or_default(),
573        )
574    }
575
576    fn disconnect(
577        &self,
578        from: &str,
579        from_attribute: Option<&str>,
580        to: &str,
581        to_attribute: &str,
582    ) -> Result<(), Self::Error> {
583        self.statement(
584            "Disconnect",
585            &format!(
586                "{}, {}, {}, {}",
587                quoted_str(from),
588                quoted_str(from_attribute.unwrap_or_default()),
589                quoted_str(to),
590                quoted_str(to_attribute)
591            ),
592            from,
593            &[],
594        )
595    }
596
597    fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
598        let mut out = self.out.lock();
599        write!(out, "nsi.Evaluate(")?;
600        for (index, arg) in args.iter().enumerate() {
601            if index > 0 {
602                write!(out, ", ")?;
603            }
604            write_arg(&mut *out, "Evaluate", &OwnedArgument::from_param(arg))?;
605        }
606        writeln!(out, ")")?;
607        Ok(())
608    }
609
610    /// The action is written as the `"action"` parameter ɴsɪ's Lua
611    /// binding reads, and one that arrived in `args` is dropped --
612    /// [`crate::StreamWriter::render_control`] says why.
613    fn render_control(
614        &self,
615        action: Action,
616        args: Option<&[Self::Arg<'_>]>,
617    ) -> Result<(), Self::Error> {
618        let mut out = self.out.lock();
619        write!(out, "nsi.RenderControl(")?;
620        write_arg(
621            &mut *out,
622            "RenderControl",
623            &OwnedArgument::new(
624                "action",
625                Type::String,
626                1,
627                0,
628                OwnedData::String(vec![action.as_str().as_bytes().to_vec()]),
629            ),
630        )?;
631        for arg in args.unwrap_or_default() {
632            let owned = OwnedArgument::from_param(arg);
633            if owned.name == "action" {
634                continue;
635            }
636            write!(out, ", ")?;
637            write_arg(&mut *out, "RenderControl", &owned)?;
638        }
639        writeln!(out, ")")?;
640        Ok(())
641    }
642}