use crate::{OwnedArgument, OwnedData, Scene};
use core::{error::Error, fmt};
use nsi_ffi_wrap::{Arg, nsi_sys::NSIParamFlags};
use nsi_trait::{Action, Nsi, Type};
use parking_lot::Mutex;
use std::io::{self, Write};
#[derive(Debug)]
#[non_exhaustive]
pub enum LuaError {
Io(io::Error),
Inexpressible {
handle: String,
attribute: String,
type_tag: Type,
},
InexpressibleFlags {
handle: String,
attribute: String,
flags: i32,
},
EmptyStringArray {
handle: String,
attribute: String,
},
CreateArguments {
handle: String,
node_type: String,
},
}
impl fmt::Display for LuaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => error.fmt(f),
Self::CreateArguments { handle, node_type } => write!(
f,
"`nsi.Create` takes no parameters, so creating {handle:?} \
as {node_type:?} with them cannot be written as Lua",
),
Self::Inexpressible {
handle,
attribute,
type_tag,
} => write!(
f,
"ɴsɪ attribute {attribute:?} on node {handle:?} has type \
{type_tag:?}, which ɴsɪ's Lua binding cannot express; \
emitting it untyped would change its value"
),
Self::InexpressibleFlags {
handle,
attribute,
flags,
} => write!(
f,
"ɴsɪ attribute {attribute:?} on node {handle:?} carries \
flags {flags:#x}, which a Lua parameter table cannot \
express; emitting it without them would rebuild a \
different surface"
),
Self::EmptyStringArray { handle, attribute } => write!(
f,
"ɴsɪ attribute {attribute:?} on node {handle:?} is an \
empty string array, which aborts the renderer when a \
Lua script sets one"
),
}
}
}
impl Error for LuaError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Inexpressible { .. }
| Self::InexpressibleFlags { .. }
| Self::EmptyStringArray { .. }
| Self::CreateArguments { .. } => None,
}
}
}
impl From<io::Error> for LuaError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
pub fn write_lua<W: Write>(scene: &Scene, out: &mut W) -> Result<(), LuaError> {
for (handle, node) in scene.nodes() {
if !crate::is_reserved(handle) {
writeln!(
out,
"nsi.Create({}, {})",
quoted_str(handle),
quoted_str(&node.node_type)
)?;
}
for arg in node.attribute_table().values() {
write!(out, "nsi.SetAttribute({}, ", quoted_str(handle))?;
write_arg(out, handle, arg)?;
writeln!(out, ")")?;
}
for (_, calls) in node.samples() {
for (time, arg) in calls {
write!(
out,
"nsi.SetAttributeAtTime({}, {}, ",
quoted_str(handle),
lua_number(*time)
)?;
write_arg(out, handle, arg)?;
writeln!(out, ")")?;
}
}
}
for edge in scene.edges() {
let (from_port, to_port) = match &edge.kind {
crate::EdgeKind::ShaderNetwork { from_port, to_port } => {
(from_port.as_str(), to_port.as_str())
}
other => ("", other.to_attribute()),
};
write!(
out,
"nsi.Connect({}, {}, {}, {}",
quoted_str(&edge.from),
quoted_str(from_port),
quoted_str(&edge.to),
quoted_str(to_port)
)?;
for arg in &edge.args {
write!(out, ", ")?;
write_arg(out, &edge.from, arg)?;
}
writeln!(out, ")")?;
}
Ok(())
}
fn write_arg<W: Write>(
out: &mut W,
handle: &str,
arg: &OwnedArgument,
) -> Result<(), LuaError> {
let inexpressible = NSIParamFlags::PerFace.bits()
| NSIParamFlags::PerVertex.bits()
| NSIParamFlags::InterpolateLinear.bits();
if arg.flags & inexpressible != 0 {
return Err(LuaError::InexpressibleFlags {
handle: handle.to_string(),
attribute: arg.name.clone(),
flags: arg.flags,
});
}
if matches!(&arg.data, OwnedData::String(values) if values.is_empty()) {
return Err(LuaError::EmptyStringArray {
handle: handle.to_string(),
attribute: arg.name.clone(),
});
}
let type_name =
lua_type_name(arg.type_tag).ok_or_else(|| LuaError::Inexpressible {
handle: handle.to_string(),
attribute: arg.name.clone(),
type_tag: arg.type_tag,
})?;
write!(out, "{{name={}", quoted_str(&arg.name))?;
if arg.flags & NSIParamFlags::IsArray.bits() != 0 {
write!(out, ", arraylength={}", arg.array_length)?;
}
write!(out, ", data={{")?;
match &arg.data {
OwnedData::F32(values) => write_numbers(out, values)?,
OwnedData::F64(values) => write_numbers(out, values)?,
OwnedData::I32(values) => write_numbers(out, values)?,
OwnedData::I64(values) => write_numbers(out, values)?,
OwnedData::String(values) => {
for (index, value) in values.iter().enumerate() {
if index > 0 {
out.write_all(b", ")?;
}
out.write_all(&self::quoted(value))?;
}
}
OwnedData::Reference(_) => {
}
}
write!(out, "}}, type=nsi.{type_name}}}")?;
Ok(())
}
fn write_numbers<W: Write, T: LuaNumber>(
out: &mut W,
values: &[T],
) -> io::Result<()> {
let rendered: Vec<String> = values.iter().map(LuaNumber::to_lua).collect();
write!(out, "{}", rendered.join(", "))
}
trait LuaNumber {
fn to_lua(&self) -> String;
}
impl LuaNumber for f32 {
fn to_lua(&self) -> String {
lua_number(f64::from(*self))
}
}
impl LuaNumber for f64 {
fn to_lua(&self) -> String {
lua_number(*self)
}
}
impl LuaNumber for i32 {
fn to_lua(&self) -> String {
self.to_string()
}
}
impl LuaNumber for i64 {
fn to_lua(&self) -> String {
self.to_string()
}
}
fn lua_number(value: f64) -> String {
if value.is_finite() {
let rendered = value.to_string();
if rendered.contains(['.', 'e', 'E']) {
rendered
} else {
format!("{rendered}.0")
}
} else if value.is_nan() {
"0/0".to_string()
} else if value.is_sign_negative() {
"-math.huge".to_string()
} else {
"math.huge".to_string()
}
}
fn quoted(value: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(value.len() + 2);
out.push(b'"');
for &byte in value {
match byte {
b'"' => out.extend_from_slice(b"\\\""),
b'\\' => out.extend_from_slice(b"\\\\"),
b'\n' => out.extend_from_slice(b"\\n"),
b'\r' => out.extend_from_slice(b"\\r"),
b'\t' => out.extend_from_slice(b"\\t"),
_ => out.push(byte),
}
}
out.push(b'"');
out
}
fn quoted_str(value: &str) -> String {
String::from_utf8(quoted(value.as_bytes()))
.expect("escaping only ASCII preserves UTF-8")
}
const fn lua_type_name(type_tag: Type) -> Option<&'static str> {
match type_tag {
Type::F32 => Some("TypeFloat"),
Type::I32 => Some("TypeInteger"),
Type::String => Some("TypeString"),
Type::Color => Some("TypeColor"),
Type::Point => Some("TypePoint"),
Type::Vector => Some("TypeVector"),
Type::Normal => Some("TypeNormal"),
Type::MatrixF32 => Some("TypeMatrix"),
Type::MatrixF64 => Some("TypeDoubleMatrix"),
Type::F64 | Type::I64 | Type::Reference | Type::Invalid => None,
}
}
#[derive(Debug)]
pub struct LuaWriter<W: Write> {
out: Mutex<W>,
}
impl<W: Write> LuaWriter<W> {
pub fn new(out: W) -> Self {
Self {
out: Mutex::new(out),
}
}
pub fn into_inner(self) -> W {
self.out.into_inner()
}
fn statement(
&self,
call: &str,
head: &str,
handle: &str,
args: &[Arg<'_, '_>],
) -> Result<(), LuaError> {
let mut out = self.out.lock();
write!(out, "nsi.{call}({head}")?;
for arg in args {
write!(out, ", ")?;
write_arg(&mut *out, handle, &OwnedArgument::from_param(arg))?;
}
writeln!(out, ")")?;
Ok(())
}
}
impl<W: Write + Send> Nsi for LuaWriter<W> {
type Arg<'call> = Arg<'call, 'static>;
type Error = LuaError;
fn create(
&self,
handle: &str,
node_type: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
if !args.unwrap_or_default().is_empty() {
return Err(LuaError::CreateArguments {
handle: handle.to_string(),
node_type: node_type.to_string(),
});
}
self.statement(
"Create",
&format!("{}, {}", quoted_str(handle), quoted_str(node_type)),
handle,
&[],
)
}
fn delete(
&self,
handle: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
"Delete",
"ed_str(handle),
handle,
args.unwrap_or_default(),
)
}
fn set_attribute(
&self,
handle: &str,
args: &[Self::Arg<'_>],
) -> Result<(), Self::Error> {
self.statement("SetAttribute", "ed_str(handle), handle, args)
}
fn set_attribute_at_time(
&self,
handle: &str,
time: f64,
args: &[Self::Arg<'_>],
) -> Result<(), Self::Error> {
self.statement(
"SetAttributeAtTime",
&format!("{}, {}", quoted_str(handle), lua_number(time)),
handle,
args,
)
}
fn delete_attribute(
&self,
handle: &str,
name: &str,
) -> Result<(), Self::Error> {
self.statement(
"DeleteAttribute",
&format!("{}, {}", quoted_str(handle), quoted_str(name)),
handle,
&[],
)
}
fn connect(
&self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
"Connect",
&format!(
"{}, {}, {}, {}",
quoted_str(from),
quoted_str(from_attribute.unwrap_or_default()),
quoted_str(to),
quoted_str(to_attribute)
),
from,
args.unwrap_or_default(),
)
}
fn disconnect(
&self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
) -> Result<(), Self::Error> {
self.statement(
"Disconnect",
&format!(
"{}, {}, {}, {}",
quoted_str(from),
quoted_str(from_attribute.unwrap_or_default()),
quoted_str(to),
quoted_str(to_attribute)
),
from,
&[],
)
}
fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
let mut out = self.out.lock();
write!(out, "nsi.Evaluate(")?;
for (index, arg) in args.iter().enumerate() {
if index > 0 {
write!(out, ", ")?;
}
write_arg(&mut *out, "Evaluate", &OwnedArgument::from_param(arg))?;
}
writeln!(out, ")")?;
Ok(())
}
fn render_control(
&self,
action: Action,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
let mut out = self.out.lock();
write!(out, "nsi.RenderControl(")?;
write_arg(
&mut *out,
"RenderControl",
&OwnedArgument::new(
"action",
Type::String,
1,
0,
OwnedData::String(vec![action.as_str().as_bytes().to_vec()]),
),
)?;
for arg in args.unwrap_or_default() {
let owned = OwnedArgument::from_param(arg);
if owned.name == "action" {
continue;
}
write!(out, ", ")?;
write_arg(&mut *out, "RenderControl", &owned)?;
}
writeln!(out, ")")?;
Ok(())
}
}