use crate::Error;
use core::num::NonZeroUsize;
use mlua::{Lua, Table, Value, Variadic};
use nsi_ffi_wrap::{
Arg, ArgData, StringSlice,
argument::{
Color3F32Slice, IntegerI32Slice, Matrix4F32Slice, Matrix4F64Slice,
Normal3F32Slice, Point3F32Slice, Point4F32Slice, RealF32Slice,
Vector3F32Slice,
},
};
use nsi_trait::{Action, Nsi, Type};
use std::cell::RefCell;
#[derive(Clone)]
struct Param {
name: String,
type_tag: Type,
array_length: Option<NonZeroUsize>,
f32s: Vec<f32>,
f64s: Vec<f64>,
i32s: Vec<i32>,
i64s: Vec<i64>,
strings: Vec<Vec<u8>>,
}
pub fn run_lua<N>(source: &[u8], sink: &N) -> Result<(), Error<N::Error>>
where
N: Nsi,
for<'call> N: Nsi<Arg<'call> = nsi_ffi_wrap::Arg<'call, 'static>>,
{
let lua = Lua::new();
let failure: RefCell<Option<N::Error>> = RefCell::new(None);
let outcome = lua.scope(|scope| {
let nsi = lua.create_table()?;
for (name, tag) in [
("TypeFloat", Type::RealF32),
("TypeInteger", Type::IntegerI32),
("TypeString", Type::String),
("TypeColor", Type::Color3F32),
("TypePoint", Type::Point3F32),
("TypeVector", Type::Vector3F32),
("TypeNormal", Type::Normal3F32),
("TypeMatrix", Type::Matrix4F32),
("TypeDoubleMatrix", Type::Matrix4F64),
("TypeHPoint", Type::Point4F32),
] {
nsi.set(name, tag as i32)?;
}
macro_rules! record {
($body:expr) => {
scope.create_function_mut($body)?
};
}
nsi.set(
"Create",
record!(|_, (handle, node_type): (String, String)| {
keep(&failure, sink.create(&handle, &node_type, None))
}),
)?;
nsi.set(
"Delete",
record!(|_, (handle, rest): (String, Variadic<Value>)| {
let params = params_of(rest)?;
with_args(¶ms, |args| {
keep(&failure, sink.delete(&handle, Some(args)))
})
}),
)?;
nsi.set(
"DeleteAttribute",
record!(|_, (handle, name): (String, String)| {
keep(&failure, sink.delete_attribute(&handle, &name))
}),
)?;
nsi.set(
"SetAttribute",
record!(|_, (handle, rest): (String, Variadic<Value>)| {
let params = params_of(rest)?;
with_args(¶ms, |args| {
keep(&failure, sink.set_attribute(&handle, args))
})
}),
)?;
nsi.set(
"SetAttributeAtTime",
record!(
|_, (handle, time, rest): (String, f64, Variadic<Value>)| {
let params = params_of(rest)?;
with_args(¶ms, |args| {
keep(
&failure,
sink.set_attribute_at_time(&handle, time, args),
)
})
}
),
)?;
nsi.set(
"Connect",
record!(|_,
(from, from_attribute, to, to_attribute, rest): (
String,
String,
String,
String,
Variadic<Value>,
)| {
let params = params_of(rest)?;
let port =
Some(from_attribute.as_str()).filter(|p| !p.is_empty());
with_args(¶ms, |args| {
keep(
&failure,
sink.connect(
&from,
port,
&to,
&to_attribute,
Some(args),
),
)
})
}),
)?;
nsi.set(
"Disconnect",
record!(|_,
(from, from_attribute, to, to_attribute): (
String,
String,
String,
String,
)| {
let port =
Some(from_attribute.as_str()).filter(|p| !p.is_empty());
keep(&failure, sink.disconnect(&from, port, &to, &to_attribute))
}),
)?;
nsi.set(
"Evaluate",
record!(|_, rest: Variadic<Value>| {
let params = params_of(rest)?;
with_args(¶ms, |args| keep(&failure, sink.evaluate(args)))
}),
)?;
nsi.set(
"RenderControl",
record!(|_, rest: Variadic<Value>| {
let params = params_of(rest)?;
let action = params
.iter()
.find(|p| p.name == "action" && p.type_tag == Type::String)
.and_then(|p| p.strings.first())
.and_then(|name| action_of(name))
.ok_or_else(|| {
mlua::Error::runtime(
"nsi.RenderControl needs a known action",
)
})?;
let rest: Vec<&Param> =
params.iter().filter(|p| p.name != "action").collect();
let owned: Vec<Param> = rest.into_iter().cloned().collect();
with_args(&owned, |args| {
keep(&failure, sink.render_control(action, Some(args)))
})
}),
)?;
lua.globals().set("nsi", nsi)?;
lua.load(source).exec()
});
if let Some(error) = failure.into_inner() {
return Err(Error::Sink(error));
}
outcome.map_err(|error| Error::Lua(error.to_string()))
}
fn keep<E>(
slot: &RefCell<Option<E>>,
result: Result<(), E>,
) -> mlua::Result<()> {
match result {
Ok(()) => Ok(()),
Err(error) => {
let mut slot = slot.borrow_mut();
if slot.is_none() {
*slot = Some(error);
}
Err(mlua::Error::runtime("the ɴsɪ sink refused a call"))
}
}
}
fn params_of(rest: Variadic<Value>) -> mlua::Result<Vec<Param>> {
let mut tables: Vec<Table> = Vec::new();
for value in rest {
let Value::Table(table) = value else {
return Err(mlua::Error::runtime(
"an ɴsɪ parameter must be a table",
));
};
if table.contains_key("name")? {
tables.push(table);
} else {
for entry in table.sequence_values::<Table>() {
tables.push(entry?);
}
}
}
tables.into_iter().map(param_of).collect()
}
fn param_of(table: Table) -> mlua::Result<Param> {
let name: String = table.get("name")?;
let array_length: Option<usize> = table.get("arraylength")?;
let declared: Option<i32> = table.get("type")?;
let data: Value = table.get("data")?;
let mut param = Param {
name,
type_tag: Type::Invalid,
array_length: array_length.and_then(NonZeroUsize::new),
f32s: Vec::new(),
f64s: Vec::new(),
i32s: Vec::new(),
i64s: Vec::new(),
strings: Vec::new(),
};
let type_tag = match declared {
Some(value) => tag_of(value)?,
None => match &data {
Value::Integer(_) => Type::IntegerI32,
Value::Number(_) => Type::RealF32,
Value::String(_) => Type::String,
_ => {
return Err(mlua::Error::runtime(
"an ɴsɪ parameter with table data needs a type",
));
}
},
};
param.type_tag = type_tag;
let values: Vec<Value> = match data {
Value::Table(table) => table
.sequence_values::<Value>()
.collect::<mlua::Result<_>>()?,
scalar => vec![scalar],
};
for value in values {
match type_tag {
Type::String => {
let text = value
.as_string()
.ok_or_else(|| mlua::Error::runtime("expected a string"))?
.as_bytes()
.to_vec();
if text.contains(&0) {
return Err(mlua::Error::runtime(
"an ɴsɪ string cannot contain an interior NUL",
));
}
param.strings.push(text);
}
Type::IntegerI32 => {
param.i32s.push(i32::try_from(integer(&value)?).map_err(
|_| mlua::Error::runtime("an ɴsɪ int does not fit 32 bits"),
)?)
}
Type::IntegerI64 => param.i64s.push(integer(&value)?),
Type::RealF64 | Type::Matrix4F64 => {
param.f64s.push(number(&value)?)
}
_ => param.f32s.push(number(&value)? as f32),
}
}
let width = match type_tag {
Type::Color3F32
| Type::Point3F32
| Type::Vector3F32
| Type::Normal3F32 => 3,
Type::Point4F32 => 4,
Type::Matrix4F32 | Type::Matrix4F64 => 16,
_ => 1,
};
let count = match type_tag {
Type::RealF64 | Type::Matrix4F64 => param.f64s.len(),
Type::IntegerI32 => param.i32s.len(),
Type::IntegerI64 => param.i64s.len(),
Type::String => param.strings.len(),
_ => param.f32s.len(),
};
if width > 1 && !count.is_multiple_of(width) {
return Err(mlua::Error::runtime(
"an ɴsɪ tuple parameter needs a whole number of elements",
));
}
let stride = width * param.array_length.map_or(1, NonZeroUsize::get);
if stride > 1 && !count.is_multiple_of(stride) {
return Err(mlua::Error::runtime(
"an ɴsɪ parameter's data must divide by its arraylength",
));
}
Ok(param)
}
fn number(value: &Value) -> mlua::Result<f64> {
match value {
Value::Integer(integer) => Ok(*integer as f64),
Value::Number(number) => Ok(*number),
_ => Err(mlua::Error::runtime("expected a number")),
}
}
fn integer(value: &Value) -> mlua::Result<i64> {
match value {
Value::Integer(integer) => Ok(*integer),
Value::Number(number) => Ok(*number as i64),
_ => Err(mlua::Error::runtime("expected a number")),
}
}
fn action_of(name: &[u8]) -> Option<Action> {
Some(match name {
b"start" => Action::Start,
b"stop" => Action::Stop,
b"suspend" => Action::Suspend,
b"resume" => Action::Resume,
b"wait" => Action::Wait,
b"synchronize" => Action::Synchronize,
_ => return None,
})
}
fn tag_of(value: i32) -> mlua::Result<Type> {
Ok(match value {
1 => Type::RealF32,
2 => Type::IntegerI32,
3 => Type::String,
4 => Type::Color3F32,
5 => Type::Point3F32,
6 => Type::Vector3F32,
7 => Type::Normal3F32,
8 => Type::Matrix4F32,
0x18 => Type::Matrix4F64,
10 => Type::Point4F32,
_ => return Err(mlua::Error::runtime("unknown ɴsɪ type")),
})
}
fn with_args<T>(
params: &[Param],
apply: impl FnOnce(&[Arg<'_, 'static>]) -> T,
) -> T {
let triples: Vec<Vec<[f32; 3]>> = params
.iter()
.map(|p| p.f32s.as_chunks::<3>().0.to_vec())
.collect();
let quads: Vec<Vec<[f32; 4]>> = params
.iter()
.map(|p| p.f32s.as_chunks::<4>().0.to_vec())
.collect();
let matrices_f32: Vec<Vec<[f32; 16]>> = params
.iter()
.map(|p| p.f32s.as_chunks::<16>().0.to_vec())
.collect();
let matrices_f64: Vec<Vec<[f64; 16]>> = params
.iter()
.map(|p| p.f64s.as_chunks::<16>().0.to_vec())
.collect();
let borrowed: Vec<Vec<&[u8]>> = params
.iter()
.map(|p| p.strings.iter().map(Vec::as_slice).collect())
.collect();
let args: Vec<Arg<'_, 'static>> = params
.iter()
.enumerate()
.map(|(index, p)| {
let data = match p.type_tag {
Type::RealF32 => ArgData::from(RealF32Slice::new(&p.f32s)),
Type::IntegerI32 => {
ArgData::from(IntegerI32Slice::new(&p.i32s))
}
Type::String => {
ArgData::from(StringSlice::new(&borrowed[index]))
}
Type::Color3F32 => {
ArgData::from(Color3F32Slice::new(&triples[index]))
}
Type::Point3F32 => {
ArgData::from(Point3F32Slice::new(&triples[index]))
}
Type::Vector3F32 => {
ArgData::from(Vector3F32Slice::new(&triples[index]))
}
Type::Normal3F32 => {
ArgData::from(Normal3F32Slice::new(&triples[index]))
}
Type::Matrix4F32 => {
ArgData::from(Matrix4F32Slice::new(&matrices_f32[index]))
}
Type::Matrix4F64 => {
ArgData::from(Matrix4F64Slice::new(&matrices_f64[index]))
}
Type::Point4F32 => {
ArgData::from(Point4F32Slice::new(&quads[index]))
}
Type::RealF64
| Type::IntegerI64
| Type::Reference
| Type::Invalid => {
unreachable!("no Lua spelling yields {:?}", p.type_tag)
}
};
let arg = Arg::new(&p.name, data);
match p.array_length {
Some(length) => arg.array_len(length),
None => arg,
}
})
.collect();
apply(&args)
}