1use 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#[derive(Debug)]
52#[non_exhaustive]
53pub enum LuaError {
54 Io(io::Error),
56 Inexpressible {
64 handle: String,
66 attribute: String,
68 type_tag: Type,
70 },
71 InexpressibleFlags {
82 handle: String,
84 attribute: String,
86 flags: i32,
88 },
89 EmptyStringArray {
96 handle: String,
98 attribute: String,
100 },
101 CreateArguments {
108 handle: String,
110 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
173pub fn write_lua<W: Write>(scene: &Scene, out: &mut W) -> Result<(), LuaError> {
180 for (handle, node) in scene.nodes() {
181 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 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
238fn write_arg<W: Write>(
240 out: &mut W,
241 handle: &str,
242 arg: &OwnedArgument,
243) -> Result<(), LuaError> {
244 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 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 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 }
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
312trait 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
341fn lua_number(value: f64) -> String {
347 if value.is_finite() {
348 let rendered = value.to_string();
349 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
364fn 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
382fn quoted_str(value: &str) -> String {
388 String::from_utf8(quoted(value.as_bytes()))
398 .expect("escaping only ASCII preserves UTF-8")
399}
400
401const 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#[derive(Debug)]
440pub struct LuaWriter<W: Write> {
441 out: Mutex<W>,
442}
443
444impl<W: Write> LuaWriter<W> {
445 pub fn new(out: W) -> Self {
447 Self {
448 out: Mutex::new(out),
449 }
450 }
451
452 pub fn into_inner(self) -> W {
454 self.out.into_inner()
455 }
456
457 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 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 "ed_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", "ed_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 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 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}