use crate::{EdgeKind, OwnedArgument, OwnedData, Scene};
use core::fmt;
use nsi_ffi_wrap::{Arg, nsi_sys::NSIParamFlags};
use nsi_trait::{Action, Nsi, Type};
use parking_lot::Mutex;
use std::io::{self, Write};
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'\t' => out.extend_from_slice(b"\\t"),
control if control < 0x20 => {
out.extend_from_slice(format!("\\{control:03o}").as_bytes());
}
_ => 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")
}
fn format_f64(value: f64) -> String {
const SIGNIFICANT: i32 = 17;
if value == 0.0 {
if value.is_sign_negative() {
"-0".to_string()
} else {
"0".to_string()
}
} else if !value.is_finite() {
if value.is_nan() {
"nan".to_string()
} else if value.is_sign_negative() {
"-inf".to_string()
} else {
"inf".to_string()
}
} else {
let scientific = format!("{:.*e}", (SIGNIFICANT - 1) as usize, value);
let (mantissa, exponent) =
scientific.split_once('e').expect("Rust always writes one");
let exponent: i32 = exponent.parse().expect("an integer exponent");
if !(-4..SIGNIFICANT).contains(&exponent) {
format!(
"{}e{}{:02}",
trim_zeros(mantissa),
if exponent < 0 { '-' } else { '+' },
exponent.abs()
)
} else {
let decimals = (SIGNIFICANT - 1 - exponent) as usize;
trim_zeros(&format!("{value:.decimals$}"))
}
}
}
fn format_f32(value: f32) -> String {
if value.is_finite() {
let decimal = format!("{value}");
let exponent = format!("{value:e}");
if exponent.len() < decimal.len() {
exponent
} else {
decimal
}
} else if value.is_nan() {
"nan".to_string()
} else if value.is_sign_negative() {
"-inf".to_string()
} else {
"inf".to_string()
}
}
fn trim_zeros(value: &str) -> String {
if value.contains('.') {
value
.trim_end_matches('0')
.trim_end_matches('.')
.to_string()
} else {
value.to_string()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Compression {
#[default]
None,
#[cfg(feature = "gzip")]
Gzip,
#[cfg(feature = "zstd")]
Zstd,
}
impl Compression {
pub const fn extension(self) -> &'static str {
match self {
Self::None => "",
#[cfg(feature = "gzip")]
Self::Gzip => ".gz",
#[cfg(feature = "zstd")]
Self::Zstd => ".zst",
}
}
}
pub fn write_stream_with<W: Write>(
scene: &Scene,
mut out: W,
compression: Compression,
) -> io::Result<()> {
match compression {
Compression::None => {
write_stream(scene, &mut out)?;
out.flush()
}
#[cfg(feature = "gzip")]
Compression::Gzip => {
let mut encoder = flate2::write::GzEncoder::new(
out,
flate2::Compression::default(),
);
write_stream(scene, &mut encoder)?;
encoder.finish()?.flush()
}
#[cfg(feature = "zstd")]
Compression::Zstd => {
let mut encoder = zstd::stream::write::Encoder::new(out, 0)?;
write_stream(scene, &mut encoder)?;
encoder.finish()?.flush()
}
}
}
pub fn write_stream<W: Write>(scene: &Scene, out: &mut W) -> io::Result<()> {
for args in scene.evaluations() {
write!(out, "Evaluate")?;
for arg in args {
write_arg(out, arg)?;
}
writeln!(out)?;
}
for (handle, node) in scene.nodes() {
if !crate::is_reserved(handle) {
writeln!(
out,
"Create {} {}",
quoted_str(handle),
quoted_str(&node.node_type)
)?;
}
for arg in node.attribute_table().values() {
writeln!(out, "SetAttribute {}", quoted_str(handle))?;
write_arg(out, arg)?;
}
for (_, calls) in node.samples() {
for (time, arg) in calls {
writeln!(
out,
"SetAttributeAtTime {} {}",
quoted_str(handle),
format_f64(*time)
)?;
write_arg(out, arg)?;
}
}
}
for edge in scene.edges() {
let (from_port, to_port) = match &edge.kind {
EdgeKind::ShaderNetwork { from_port, to_port } => {
(from_port.as_str(), to_port.as_str())
}
other => ("", other.to_attribute()),
};
writeln!(
out,
"Connect {} {} {} {}",
quoted_str(&edge.from),
quoted_str(from_port),
quoted_str(&edge.to),
quoted_str(to_port)
)?;
for arg in &edge.args {
write_arg(out, arg)?;
}
}
Ok(())
}
fn write_arg<W: Write>(out: &mut W, arg: &OwnedArgument) -> io::Result<()> {
if matches!(arg.data, OwnedData::Reference(_)) {
return Ok(());
}
write!(
out,
" {} {} {} ",
quoted_str(&arg.name),
quoted_str(&type_name(arg)),
element_count(arg)
)?;
let scalars = scalar_count(arg);
if scalars == 0 {
return writeln!(out, "[ ]");
}
if scalars != 1 {
write!(out, "[ ")?;
}
match &arg.data {
OwnedData::F32(v) => {
let formatted: Vec<String> =
v.iter().copied().map(format_f32).collect();
write!(out, "{}", formatted.join(" "))?;
}
OwnedData::F64(v) => {
let formatted: Vec<String> =
v.iter().copied().map(format_f64).collect();
write!(out, "{}", formatted.join(" "))?;
}
OwnedData::I32(v) => write_scalars(out, v)?,
OwnedData::I64(v) => write_scalars(out, v)?,
OwnedData::String(v) => {
for (index, value) in v.iter().enumerate() {
if index > 0 {
out.write_all(b" ")?;
}
out.write_all("ed(value))?;
}
}
OwnedData::Reference(_) => {}
}
if scalars != 1 {
write!(out, " ]")?;
}
writeln!(out)
}
fn write_scalars<W: Write, T: fmt::Display>(
out: &mut W,
values: &[T],
) -> io::Result<()> {
let joined: Vec<String> = values.iter().map(ToString::to_string).collect();
write!(out, "{}", joined.join(" "))
}
fn scalar_count(arg: &OwnedArgument) -> usize {
match &arg.data {
OwnedData::F32(v) => v.len(),
OwnedData::F64(v) => v.len(),
OwnedData::I32(v) => v.len(),
OwnedData::I64(v) => v.len(),
OwnedData::String(v) => v.len(),
OwnedData::Reference(v) => v.len(),
}
}
fn element_count(arg: &OwnedArgument) -> usize {
let per = components_per_element(arg.type_tag);
scalar_count(arg) / per / arg.array_length.max(1)
}
const fn components_per_element(type_tag: Type) -> usize {
match type_tag {
Type::Color | Type::Point | Type::Vector | Type::Normal => 3,
Type::MatrixF32 | Type::MatrixF64 => 16,
_ => 1,
}
}
fn type_name(arg: &OwnedArgument) -> String {
let base = base_type_name(arg.type_tag);
let sized = if arg.flags & NSIParamFlags::IsArray.bits() != 0 {
format!("{base}[{}]", arg.array_length)
} else {
base.to_string()
};
let flags = flag_prefix(arg.flags);
if flags.is_empty() {
sized
} else {
format!("{flags} {sized}")
}
}
fn flag_prefix(flags: i32) -> String {
[
(NSIParamFlags::PerFace, 'f'),
(NSIParamFlags::PerVertex, 'v'),
(NSIParamFlags::InterpolateLinear, 'l'),
]
.iter()
.filter(|(flag, _)| flags & flag.bits() != 0)
.map(|(_, letter)| *letter)
.collect()
}
const fn base_type_name(type_tag: Type) -> &'static str {
match type_tag {
Type::F32 => "float",
Type::F64 => "double",
Type::I32 => "int",
Type::I64 => "int64",
Type::String => "string",
Type::Color => "color",
Type::Point => "point",
Type::Vector => "vector",
Type::Normal => "normal",
Type::MatrixF32 => "matrix",
Type::MatrixF64 => "doublematrix",
Type::Reference => "pointer",
Type::Invalid => "invalid",
}
}
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub struct StreamWriter<W: Write> {
out: Mutex<W>,
}
impl<W: Write> StreamWriter<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,
head: &str,
args: &[Arg<'_, '_>],
skip: Option<&str>,
) -> io::Result<()> {
let mut out = self.out.lock();
writeln!(out, "{head}")?;
for arg in args {
let owned = OwnedArgument::from_param(arg);
if skip == Some(owned.name.as_str()) {
continue;
}
write_arg(&mut *out, &owned)?;
}
Ok(())
}
}
impl<W: Write + Send> Nsi for StreamWriter<W> {
type Arg<'call> = Arg<'call, 'static>;
type Error = io::Error;
fn create(
&self,
handle: &str,
node_type: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
&format!("Create {} {}", quoted_str(handle), quoted_str(node_type)),
args.unwrap_or_default(),
None,
)
}
fn delete(
&self,
handle: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
&format!("Delete {}", quoted_str(handle)),
args.unwrap_or_default(),
None,
)
}
fn set_attribute(
&self,
handle: &str,
args: &[Self::Arg<'_>],
) -> Result<(), Self::Error> {
self.statement(
&format!("SetAttribute {}", quoted_str(handle)),
args,
None,
)
}
fn set_attribute_at_time(
&self,
handle: &str,
time: f64,
args: &[Self::Arg<'_>],
) -> Result<(), Self::Error> {
self.statement(
&format!(
"SetAttributeAtTime {} {}",
quoted_str(handle),
format_f64(time)
),
args,
None,
)
}
fn delete_attribute(
&self,
handle: &str,
name: &str,
) -> Result<(), Self::Error> {
self.statement(
&format!(
"DeleteAttribute {} {}",
quoted_str(handle),
quoted_str(name)
),
&[],
None,
)
}
fn connect(
&self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
&format!(
"Connect {} {} {} {}",
quoted_str(from),
quoted_str(from_attribute.unwrap_or_default()),
quoted_str(to),
quoted_str(to_attribute)
),
args.unwrap_or_default(),
None,
)
}
fn disconnect(
&self,
from: &str,
from_attribute: Option<&str>,
to: &str,
to_attribute: &str,
) -> Result<(), Self::Error> {
self.statement(
&format!(
"Disconnect {} {} {} {}",
quoted_str(from),
quoted_str(from_attribute.unwrap_or_default()),
quoted_str(to),
quoted_str(to_attribute)
),
&[],
None,
)
}
fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
self.statement("Evaluate", args, None)
}
fn render_control(
&self,
action: Action,
args: Option<&[Self::Arg<'_>]>,
) -> Result<(), Self::Error> {
self.statement(
"RenderControl",
args.unwrap_or_default(),
Some("action"),
)?;
let mut out = self.out.lock();
writeln!(
out,
" {} {} 1 {}",
quoted_str("action"),
quoted_str("string"),
quoted_str(action.as_str())
)
}
}