use std::path::PathBuf;
use std::sync::Arc;
use crate::cameras::PerspectiveCamera;
use crate::core::{Mesh, Object3D};
use crate::lights::{AmbientLight, DirectionalLight, HemisphereLight};
use crate::materials::{Material, StandardMaterial};
use crate::math::{Color, Vector3};
use crate::openscad::{scad, ScadPart, Solid};
use crate::scene::Scene;
enum Source {
Text(String),
File(PathBuf),
Builder(Arc<dyn Fn(f64) -> Solid + Send + Sync>),
}
pub use crate::openscad::frame::ScadFrame;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScadEasing {
#[default]
Linear,
EaseIn,
EaseOut,
EaseInOut,
Sine,
}
impl ScadEasing {
pub fn apply(self, p: f64) -> f64 {
let p = p.clamp(0.0, 1.0);
match self {
ScadEasing::Linear => p,
ScadEasing::EaseIn => p * p,
ScadEasing::EaseOut => 1.0 - (1.0 - p) * (1.0 - p),
ScadEasing::EaseInOut => {
if p < 0.5 {
2.0 * p * p
} else {
1.0 - 2.0 * (1.0 - p) * (1.0 - p)
}
}
ScadEasing::Sine => (1.0 - (p * std::f64::consts::TAU).cos()) * 0.5,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScadKernel {
#[default]
Exact,
Float,
}
#[derive(Clone, Debug)]
pub struct ScadProgress {
pub done: usize,
pub total: usize,
pub message: String,
}
type ProgressFn = Box<dyn FnMut(&ScadProgress) + Send>;
fn progress_tick(done: usize, total: usize) -> ScadProgress {
let pct = (done * 100).checked_div(total).unwrap_or(100);
ScadProgress {
done,
total,
message: format!("Evaluating {done}/{total} ({pct}%)"),
}
}
pub struct ScadAnimation {
source: Source,
frames: usize,
fps: u32,
kernel: ScadKernel,
#[allow(clippy::type_complexity)]
vars: Vec<(String, Arc<dyn Fn(f64) -> f64 + Send + Sync>)>,
looping: bool,
constants: Vec<(String, f64)>,
speed: f64,
target_seconds: Option<f64>,
ping_pong: bool,
easing: ScadEasing,
concurrency: Option<usize>,
on_progress: Option<ProgressFn>,
}
impl std::fmt::Debug for ScadAnimation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScadAnimation")
.field(
"source",
&match &self.source {
Source::Text(_) => "text",
Source::File(p) => return f.write_fmt(format_args!("ScadAnimation({p:?})")),
Source::Builder(_) => "builder",
},
)
.field("frames", &self.frames)
.field("fps", &self.fps)
.field("kernel", &self.kernel)
.finish()
}
}
impl ScadAnimation {
fn with_source(source: Source) -> Self {
Self {
source,
frames: 60,
fps: 30,
kernel: ScadKernel::default(),
vars: Vec::new(),
looping: true,
constants: Vec::new(),
speed: 1.0,
target_seconds: None,
ping_pong: false,
easing: ScadEasing::Linear,
concurrency: None,
on_progress: None,
}
}
pub fn from_source(src: impl Into<String>) -> Self {
Self::with_source(Source::Text(src.into()))
}
pub fn from_file(path: impl Into<PathBuf>) -> Self {
Self::with_source(Source::File(path.into()))
}
pub fn from_fn(f: impl Fn(f64) -> Solid + Send + Sync + 'static) -> Self {
Self::with_source(Source::Builder(Arc::new(f)))
}
pub fn frames(mut self, frames: usize) -> Self {
self.frames = frames.max(1);
self
}
pub fn fps(mut self, fps: u32) -> Self {
self.fps = fps.max(1);
self
}
pub fn kernel(mut self, kernel: ScadKernel) -> Self {
self.kernel = kernel;
self
}
pub fn var(
mut self,
name: impl Into<String>,
value: impl Fn(f64) -> f64 + Send + Sync + 'static,
) -> Self {
self.vars.push((name.into(), Arc::new(value)));
self
}
pub fn constant(mut self, name: impl Into<String>, value: f64) -> Self {
self.constants.push((name.into(), value));
self
}
pub fn looping(mut self, looping: bool) -> Self {
self.looping = looping;
self
}
pub fn speed(mut self, multiplier: f64) -> Self {
self.speed = if multiplier.is_finite() && multiplier > 0.0 {
multiplier
} else {
1.0
};
self
}
pub fn seconds(mut self, seconds: f64) -> Self {
self.target_seconds = (seconds.is_finite() && seconds > 0.0).then_some(seconds);
self
}
pub fn ping_pong(mut self, ping_pong: bool) -> Self {
self.ping_pong = ping_pong;
self
}
pub fn easing(mut self, easing: ScadEasing) -> Self {
self.easing = easing;
self
}
pub fn quality(mut self, quality: ScadQuality) -> Self {
self.kernel = quality.kernel();
self.constants.retain(|(n, _)| n != "$fa" && n != "$fs");
if let Some((fa, fs)) = quality.facets() {
self.constants.push(("$fa".into(), fa));
self.constants.push(("$fs".into(), fs));
}
self
}
pub fn on_progress(mut self, cb: impl FnMut(&ScadProgress) + Send + 'static) -> Self {
self.on_progress = Some(Box::new(cb));
self
}
pub fn concurrency(mut self, frames_at_once: usize) -> Self {
self.concurrency = Some(frames_at_once.max(1));
self
}
pub fn frame_count(&self) -> usize {
self.frames
}
pub fn frame_rate(&self) -> u32 {
let base = match self.target_seconds {
Some(seconds) => self.frames as f64 / seconds,
None => self.fps as f64,
};
(base * self.speed).round().clamp(1.0, u32::MAX as f64) as u32
}
pub fn duration(&self) -> f64 {
self.frames as f64 / self.frame_rate() as f64
}
pub fn t_at(&self, index: usize) -> f64 {
self.eval().t_at(index)
}
pub fn is_animated(&self) -> bool {
let text = match &self.source {
Source::Builder(_) => return true,
Source::Text(s) => std::borrow::Cow::Borrowed(s.as_str()),
Source::File(p) => match std::fs::read_to_string(p) {
Ok(s) => std::borrow::Cow::Owned(s),
Err(_) => return true,
},
};
if mentions_any(&text, &self.var_names()) {
return true;
}
text.contains("include") || text.contains("use <")
}
fn var_names(&self) -> Vec<String> {
let mut names = vec!["$t".to_string()];
names.extend(self.vars.iter().map(|(n, _)| n.clone()));
names
}
fn resolved_concurrency(&self) -> usize {
self.concurrency.unwrap_or_else(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
})
}
fn eval(&self) -> Eval<'_> {
Eval {
source: &self.source,
vars: &self.vars,
constants: &self.constants,
kernel: self.kernel,
frames: self.frames,
looping: self.looping,
ping_pong: self.ping_pong,
easing: self.easing,
}
}
pub fn frame(&self, index: usize) -> Result<ScadFrame, String> {
self.eval().frame(index)
}
pub fn viewport_at(&self, t: f64) -> scad::Viewport {
self.eval().viewport_at(t)
}
pub fn evaluate(&mut self) -> Result<Vec<ScadFrame>, String> {
let total = self.frames;
if !self.is_animated() {
let eval = self.eval();
let parts = Arc::new(eval.parts_at(eval.t_at(0))?);
let frames: Vec<ScadFrame> = (0..total)
.map(|index| {
let t = eval.t_at(index);
ScadFrame {
index,
t,
parts: parts.clone(),
viewport: eval.viewport_at(t),
}
})
.collect();
self.report(total, total);
return Ok(frames);
}
self.evaluate_all_frames()
}
fn evaluate_all_frames(&mut self) -> Result<Vec<ScadFrame>, String> {
let total = self.frames;
let workers = self.resolved_concurrency().min(total).max(1);
let mut progress = self.on_progress.take();
let outcome = evaluate_frames(self.eval(), total, workers, &mut progress);
self.on_progress = progress;
outcome
}
fn report(&mut self, done: usize, total: usize) {
if let Some(cb) = self.on_progress.as_mut() {
cb(&progress_tick(done, total));
}
}
}
struct Eval<'a> {
source: &'a Source,
#[allow(clippy::type_complexity)]
vars: &'a [(String, Arc<dyn Fn(f64) -> f64 + Send + Sync>)],
constants: &'a [(String, f64)],
kernel: ScadKernel,
frames: usize,
looping: bool,
ping_pong: bool,
easing: ScadEasing,
}
impl Eval<'_> {
fn t_at(&self, index: usize) -> f64 {
let index = index.min(self.frames.saturating_sub(1));
let p = if self.looping {
index as f64 / self.frames as f64
} else if self.frames <= 1 {
0.0
} else {
index as f64 / (self.frames - 1) as f64
};
let p = if self.ping_pong {
1.0 - (2.0 * p - 1.0).abs()
} else {
p
};
self.easing.apply(p)
}
fn seeds(&self, t: f64) -> Vec<(String, f64)> {
let mut seeds = vec![("$t".to_string(), t)];
seeds.extend(self.constants.iter().cloned());
seeds.extend(self.vars.iter().map(|(n, f)| (n.clone(), f(t))));
seeds
}
fn viewport_at(&self, t: f64) -> scad::Viewport {
match self.source {
Source::Text(s) => scad::scad_viewport(s, t),
Source::File(p) => scad::scad_viewport_file(p, t),
Source::Builder(_) => scad::Viewport::default(),
}
}
fn parts_at(&self, t: f64) -> Result<Vec<ScadPart>, String> {
let solid = match self.source {
Source::Builder(f) => f(t),
Source::Text(src) => {
let seeds = self.seeds(t);
let refs: Vec<(&str, f64)> = seeds.iter().map(|(k, v)| (k.as_str(), *v)).collect();
scad::parse_scad_with(src, &refs)?
}
Source::File(path) => {
let seeds = self.seeds(t);
let refs: Vec<(&str, f64)> = seeds.iter().map(|(k, v)| (k.as_str(), *v)).collect();
scad::parse_scad_file_with(path, &refs)?
}
};
Ok(match self.kernel {
ScadKernel::Exact => solid.parts(),
ScadKernel::Float => {
let parts = solid.clone().parts_float();
if parts.is_empty() {
solid.parts()
} else {
parts
}
}
})
}
fn frame(&self, index: usize) -> Result<ScadFrame, String> {
let t = self.t_at(index);
Ok(ScadFrame {
index,
t,
parts: Arc::new(self.parts_at(t)?),
viewport: self.viewport_at(t),
})
}
}
fn evaluate_frames(
eval: Eval<'_>,
total: usize,
workers: usize,
progress: &mut Option<ProgressFn>,
) -> Result<Vec<ScadFrame>, String> {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut report = |done: usize| {
if let Some(cb) = progress.as_mut() {
cb(&progress_tick(done, total));
}
};
if workers <= 1 {
let mut out = Vec::with_capacity(total);
for index in 0..total {
out.push(eval.frame(index)?);
report(index + 1);
}
return Ok(out);
}
let next = AtomicUsize::new(0);
let (tx, rx) = std::sync::mpsc::channel::<(usize, Result<ScadFrame, String>)>();
let mut slots: Vec<Option<Result<ScadFrame, String>>> = (0..total).map(|_| None).collect();
std::thread::scope(|scope| {
for _ in 0..workers {
let tx = tx.clone();
let next = &next;
let eval = &eval;
scope.spawn(move || loop {
let index = next.fetch_add(1, Ordering::Relaxed);
if index >= total {
return;
}
if tx.send((index, eval.frame(index))).is_err() {
return;
}
});
}
drop(tx);
let mut done = 0usize;
while let Ok((index, result)) = rx.recv() {
slots[index] = Some(result);
done += 1;
report(done);
}
});
slots
.into_iter()
.map(|slot| slot.unwrap_or_else(|| Err("frame was never evaluated".into())))
.collect()
}
fn mentions_any(text: &str, names: &[String]) -> bool {
names.iter().any(|name| mentions(text, name))
}
fn mentions(text: &str, name: &str) -> bool {
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut from = 0;
while let Some(hit) = text[from..].find(name) {
let at = from + hit;
let before_ok = text[..at].chars().next_back().is_none_or(|c| !is_ident(c));
let after_ok = text[at + name.len()..]
.chars()
.next()
.is_none_or(|c| !is_ident(c));
if before_ok && after_ok {
return true;
}
from = at + name.len().max(1);
}
false
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScadCamera {
Auto { yaw: f32, pitch: f32, zoom: f32 },
Turntable {
pitch: f32,
turns: f32,
zoom: f32,
start_yaw: f32,
},
Viewport,
Fixed {
eye: [f32; 3],
target: [f32; 3],
fov: f32,
},
}
impl Default for ScadCamera {
fn default() -> Self {
Self::auto()
}
}
impl ScadCamera {
pub fn auto() -> Self {
ScadCamera::Auto {
yaw: 35.0,
pitch: 25.0,
zoom: 1.0,
}
}
pub fn turntable() -> Self {
ScadCamera::Turntable {
pitch: 25.0,
turns: 1.0,
zoom: 1.0,
start_yaw: 35.0,
}
}
pub fn zoomed(self, zoom: f32) -> Self {
match self {
ScadCamera::Auto { yaw, pitch, .. } => ScadCamera::Auto { yaw, pitch, zoom },
ScadCamera::Turntable {
pitch,
turns,
start_yaw,
..
} => ScadCamera::Turntable {
pitch,
turns,
zoom,
start_yaw,
},
other => other,
}
}
pub fn is_animated(self) -> bool {
matches!(self, ScadCamera::Turntable { .. } | ScadCamera::Viewport)
}
}
fn place_camera(
camera: ScadCamera,
frame: &ScadFrame,
fit: ([f32; 3], [f32; 3]),
aspect: f32,
) -> PerspectiveCamera {
let up = Vector3::new(0.0, 0.0, 1.0);
let center = Vector3::new(
(fit.0[0] + fit.1[0]) * 0.5,
(fit.0[1] + fit.1[1]) * 0.5,
(fit.0[2] + fit.1[2]) * 0.5,
);
let corners = box_corners(fit);
let radius = corners
.iter()
.map(|c| (*c - center).length())
.fold(0.0f32, f32::max)
.max(1e-3);
let default_fov = 45.0f32;
let (eye, target, fov) = match camera {
ScadCamera::Fixed { eye, target, fov } => (
Vector3::new(eye[0], eye[1], eye[2]),
Vector3::new(target[0], target[1], target[2]),
fov,
),
ScadCamera::Viewport if frame.viewport.explicit => {
let vp = frame.viewport;
let target = Vector3::new(vp.target[0], vp.target[1], vp.target[2]);
(
orbit_eye_from_vpr(vp.rotation, vp.distance, target),
target,
vp.fov,
)
}
ScadCamera::Viewport => {
let (yaw, pitch, zoom) = (35.0, 25.0, 1.0);
let dir = orbit_direction(yaw, pitch);
let d = fit_distance(&corners, center, dir, up, default_fov, aspect) * zoom;
(center + dir * d, center, default_fov)
}
ScadCamera::Auto { yaw, pitch, zoom } => {
let dir = orbit_direction(yaw, pitch);
let d = fit_distance(&corners, center, dir, up, default_fov, aspect) * zoom.max(0.01);
(center + dir * d, center, default_fov)
}
ScadCamera::Turntable {
pitch,
turns,
zoom,
start_yaw,
} => {
let yaw = start_yaw + 360.0 * turns * frame.t as f32;
let dir = orbit_direction(yaw, pitch);
let d = orbit_fit_distance(&corners, center, pitch, up, default_fov, aspect)
* zoom.max(0.01);
(center + dir * d, center, default_fov)
}
};
let span = (eye - target).length().max(1e-3);
let near = ((span - radius) * 0.5).max(span * 0.002).max(1e-4);
let far = span + radius * 4.0;
let mut cam = PerspectiveCamera::new(fov, aspect, near, far);
cam.up = up;
cam.position = eye;
cam.look_at(target);
cam
}
fn box_corners(bounds: ([f32; 3], [f32; 3])) -> [Vector3; 8] {
let (min, max) = bounds;
std::array::from_fn(|i| {
Vector3::new(
if i & 1 == 0 { min[0] } else { max[0] },
if i & 2 == 0 { min[1] } else { max[1] },
if i & 4 == 0 { min[2] } else { max[2] },
)
})
}
fn orbit_direction(yaw_deg: f32, pitch_deg: f32) -> Vector3 {
let yaw = yaw_deg.to_radians();
let pitch = pitch_deg.to_radians().clamp(-1.5533, 1.5533);
Vector3::new(
pitch.cos() * yaw.sin(),
-pitch.cos() * yaw.cos(),
pitch.sin(),
)
.normalize()
}
fn fit_distance(
corners: &[Vector3; 8],
center: Vector3,
dir_to_eye: Vector3,
up: Vector3,
fov_deg: f32,
aspect: f32,
) -> f32 {
let forward = dir_to_eye * -1.0;
let right = forward.cross(up).normalize();
let cam_up = right.cross(forward).normalize();
let tan_v = (fov_deg.to_radians() * 0.5).tan().max(1e-4);
let tan_h = (tan_v * aspect.max(0.05)).max(1e-4);
let mut distance = 0.0f32;
for corner in corners {
let v = *corner - center;
let along = v.dot(forward);
let x = v.dot(right).abs();
let y = v.dot(cam_up).abs();
distance = distance.max(x / tan_h - along).max(y / tan_v - along);
}
(distance.max(1e-3)) * 1.06
}
fn orbit_fit_distance(
corners: &[Vector3; 8],
center: Vector3,
pitch: f32,
up: Vector3,
fov_deg: f32,
aspect: f32,
) -> f32 {
(0..72)
.map(|i| {
let dir = orbit_direction(i as f32 * 5.0, pitch);
fit_distance(corners, center, dir, up, fov_deg, aspect)
})
.fold(0.0f32, f32::max)
.max(1e-3)
}
fn orbit_eye_from_vpr(rotation: [f32; 3], distance: f32, target: Vector3) -> Vector3 {
let (rx, rz) = (rotation[0].to_radians(), rotation[2].to_radians());
let (sx, cx) = rx.sin_cos();
let (sz, cz) = rz.sin_cos();
let v = Vector3::new(0.0, -distance, 0.0);
let after_x = Vector3::new(v.x, v.y * cx - v.z * sx, v.y * sx + v.z * cx);
let after_z = Vector3::new(
after_x.x * cz - after_x.y * sz,
after_x.x * sz + after_x.y * cz,
after_x.z,
);
target - after_z
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScadMaterial {
pub color: [f32; 4],
pub metalness: f32,
pub roughness: f32,
}
impl Default for ScadMaterial {
fn default() -> Self {
Self {
color: [0.96, 0.76, 0.20, 1.0],
metalness: 0.05,
roughness: 0.45,
}
}
}
impl ScadMaterial {
pub fn color(mut self, rgba: [f32; 4]) -> Self {
self.color = rgba;
self
}
pub fn metalness(mut self, metalness: f32) -> Self {
self.metalness = metalness.clamp(0.0, 1.0);
self
}
pub fn roughness(mut self, roughness: f32) -> Self {
self.roughness = roughness.clamp(0.0, 1.0);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ScadPalette {
pub name: String,
pub background: [f32; 4],
pub default_part: [f32; 4],
pub cycle: Vec<[f32; 4]>,
pub sky: [f32; 3],
pub ground: [f32; 3],
}
fn palette(name: &str, background: u32, parts: &[u32], sky: u32, ground: u32) -> ScadPalette {
let rgba = |hex: u32| {
[
((hex >> 16) & 0xFF) as f32 / 255.0,
((hex >> 8) & 0xFF) as f32 / 255.0,
(hex & 0xFF) as f32 / 255.0,
1.0,
]
};
let rgb = |hex: u32| {
let c = rgba(hex);
[c[0], c[1], c[2]]
};
ScadPalette {
name: name.to_string(),
background: rgba(background),
default_part: rgba(parts.first().copied().unwrap_or(0xF9D72C)),
cycle: parts.iter().map(|h| rgba(*h)).collect(),
sky: rgb(sky),
ground: rgb(ground),
}
}
impl Default for ScadPalette {
fn default() -> Self {
Self::studio()
}
}
impl ScadPalette {
pub fn all() -> Vec<ScadPalette> {
vec![
Self::studio(),
Self::cornfield(),
Self::metallic(),
Self::sunset(),
Self::midnight(),
Self::blueprint(),
Self::nature(),
Self::monochrome(),
]
}
pub fn by_name(name: &str) -> Option<ScadPalette> {
let wanted = name.trim().to_ascii_lowercase();
Self::all().into_iter().find(|p| p.name == wanted)
}
pub fn studio() -> Self {
palette(
"studio",
0x12141B,
&[0xC8CDD6, 0x7FA6C9, 0xD9A05B, 0x8FBF7F, 0xC98F9E, 0x9C8FBF],
0xB9C6DA,
0x2A2E38,
)
}
pub fn cornfield() -> Self {
palette(
"cornfield",
0xFFFFE5,
&[0xF9D72C, 0xC5A800, 0xE8C33A, 0xA8912B, 0xFFE97F, 0x8F7B1E],
0xFFF6D8,
0x6B6046,
)
}
pub fn metallic() -> Self {
palette(
"metallic",
0xAAAAFF,
&[0xDDDDFF, 0x9FA8B8, 0xC0C6D0, 0x7C8796, 0xE6E9F0, 0x5E6875],
0xDDE4FF,
0x3C4250,
)
}
pub fn sunset() -> Self {
palette(
"sunset",
0x2B1B2E,
&[0xFF9E4A, 0xE5603D, 0xFFD08A, 0xB8425A, 0xF7C948, 0x7A3B5C],
0xFFD2A8,
0x40202E,
)
}
pub fn midnight() -> Self {
palette(
"midnight",
0x05060A,
&[0x4FC3F7, 0xFFB74D, 0x81C784, 0xE57373, 0xBA68C8, 0xFFF176],
0x8FB4D9,
0x0A0F1A,
)
}
pub fn blueprint() -> Self {
palette(
"blueprint",
0x0D3B66,
&[0xE8F1F8, 0xA9C8E8, 0x6FA3D2, 0xCFE2F3, 0x4A7FB5, 0x8FB8DC],
0xDCEBFA,
0x0A2C50,
)
}
pub fn nature() -> Self {
palette(
"nature",
0x1A2418,
&[0x8FBF6F, 0xC9A96A, 0x5F8F4F, 0xE0D5A8, 0x3F6B3A, 0xA88B5A],
0xD8E8C8,
0x2A2418,
)
}
pub fn monochrome() -> Self {
palette(
"monochrome",
0x101010,
&[0xF0F0F0, 0xBDBDBD, 0x8A8A8A, 0x5C5C5C, 0xD6D6D6, 0x757575],
0xFFFFFF,
0x1A1A1A,
)
}
pub fn from_hex(name: &str, background: u32, parts: &[u32]) -> Self {
palette(name, background, parts, 0xC8D2E0, 0x24282F)
}
pub fn lit_by(mut self, sky: [f32; 3], ground: [f32; 3]) -> Self {
self.sky = sky;
self.ground = ground;
self
}
pub fn colors(mut self, cycle: Vec<[f32; 4]>) -> Self {
if let Some(first) = cycle.first() {
self.default_part = *first;
}
self.cycle = cycle;
self
}
pub fn background(mut self, rgba: [f32; 4]) -> Self {
self.background = rgba;
self
}
pub fn color_at(&self, index: usize) -> [f32; 4] {
if self.cycle.is_empty() {
self.default_part
} else {
self.cycle[index % self.cycle.len()]
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScadColoring {
#[default]
Model,
ModelThenPalette,
Palette,
Uniform,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScadQuality {
Draft,
#[default]
Balanced,
Fine,
}
impl ScadQuality {
pub fn supersample(self) -> u32 {
match self {
ScadQuality::Draft => 1,
ScadQuality::Balanced => 2,
ScadQuality::Fine => 3,
}
}
pub fn kernel(self) -> ScadKernel {
match self {
ScadQuality::Draft => ScadKernel::Float,
_ => ScadKernel::Exact,
}
}
pub fn facets(self) -> Option<(f64, f64)> {
match self {
ScadQuality::Draft => Some((24.0, 4.0)),
ScadQuality::Balanced => None,
ScadQuality::Fine => Some((6.0, 0.8)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ScadLight {
Ambient { color: [f32; 3], intensity: f32 },
Hemisphere {
sky: [f32; 3],
ground: [f32; 3],
intensity: f32,
},
Directional {
color: [f32; 3],
intensity: f32,
direction: [f32; 3],
},
Key {
color: [f32; 3],
intensity: f32,
azimuth: f32,
elevation: f32,
},
Point {
color: [f32; 3],
intensity: f32,
position: [f32; 3],
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ScadRig {
#[default]
Studio,
Sun,
Flat,
Custom,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ScadLighting {
pub rig: ScadRig,
pub intensity: f32,
pub ambient: f32,
pub hemisphere: Option<([f32; 3], [f32; 3])>,
pub warmth: f32,
pub key_angles: [f32; 2],
pub shadows: bool,
pub extra: Vec<ScadLight>,
}
impl Default for ScadLighting {
fn default() -> Self {
Self::studio()
}
}
impl ScadLighting {
pub fn studio() -> Self {
Self {
rig: ScadRig::Studio,
intensity: 1.0,
ambient: 0.35,
hemisphere: None,
warmth: 0.35,
key_angles: [35.0, 30.0],
shadows: true,
extra: Vec::new(),
}
}
pub fn sun(azimuth: f32, elevation: f32) -> Self {
Self {
rig: ScadRig::Sun,
intensity: 1.0,
ambient: 0.32,
hemisphere: None,
warmth: 0.5,
key_angles: [azimuth, elevation],
shadows: true,
extra: Vec::new(),
}
}
pub fn flat() -> Self {
Self {
rig: ScadRig::Flat,
intensity: 1.0,
ambient: 0.82,
hemisphere: None,
warmth: 0.0,
key_angles: [20.0, 20.0],
shadows: false,
extra: Vec::new(),
}
}
pub fn custom(lights: Vec<ScadLight>) -> Self {
Self {
rig: ScadRig::Custom,
intensity: 1.0,
ambient: 0.0,
hemisphere: None,
warmth: 0.0,
key_angles: [0.0, 0.0],
shadows: false,
extra: lights,
}
}
pub fn intensity(mut self, intensity: f32) -> Self {
self.intensity = intensity.max(0.0);
self
}
pub fn ambient(mut self, ambient: f32) -> Self {
self.ambient = ambient.max(0.0);
self
}
pub fn hemisphere(mut self, sky: [f32; 3], ground: [f32; 3]) -> Self {
self.hemisphere = Some((sky, ground));
self
}
pub fn warmth(mut self, warmth: f32) -> Self {
self.warmth = warmth.clamp(0.0, 1.0);
self
}
pub fn key_angles(mut self, azimuth: f32, elevation: f32) -> Self {
self.key_angles = [azimuth, elevation];
self
}
pub fn shadows(mut self, shadows: bool) -> Self {
self.shadows = shadows;
self
}
pub fn add_light(mut self, light: ScadLight) -> Self {
self.extra.push(light);
self
}
fn tints(&self) -> ([f32; 3], [f32; 3]) {
let w = self.warmth.clamp(0.0, 1.0);
let key = [1.0, 1.0 - 0.06 * w, 1.0 - 0.16 * w];
let fill = [1.0 - 0.14 * w, 1.0 - 0.06 * w, 1.0];
(key, fill)
}
}
pub struct ScadRender {
width: u32,
height: u32,
supersample: u32,
background: [f32; 4],
camera: ScadCamera,
material: ScadMaterial,
palette: ScadPalette,
coloring: ScadColoring,
lighting: ScadLighting,
fit_per_frame: bool,
}
impl ScadRender {
pub fn new(width: u32, height: u32) -> Self {
Self {
width: width.max(1),
height: height.max(1),
supersample: 1,
background: [0.07, 0.08, 0.11, 1.0],
camera: ScadCamera::default(),
material: ScadMaterial::default(),
palette: ScadPalette::default(),
coloring: ScadColoring::default(),
lighting: ScadLighting::default(),
fit_per_frame: false,
}
}
pub fn supersample(mut self, factor: u32) -> Self {
self.supersample = factor.clamp(1, 4);
self
}
pub fn background(mut self, rgba: [f32; 4]) -> Self {
self.background = rgba;
self
}
pub fn camera(mut self, camera: ScadCamera) -> Self {
self.camera = camera;
self
}
pub fn material(mut self, material: ScadMaterial) -> Self {
self.material = material;
self
}
pub fn palette(mut self, palette: ScadPalette) -> Self {
self.background = palette.background;
self.palette = palette;
self
}
pub fn palette_named(self, name: &str) -> Self {
match ScadPalette::by_name(name) {
Some(p) => self.palette(p),
None => self,
}
}
pub fn coloring(mut self, coloring: ScadColoring) -> Self {
self.coloring = coloring;
self
}
pub fn part_colors(mut self, colors: Vec<[f32; 4]>) -> Self {
self.palette = self.palette.clone().colors(colors);
self.coloring = ScadColoring::Palette;
self
}
pub fn lighting(mut self, lighting: ScadLighting) -> Self {
self.lighting = lighting;
self
}
pub fn lighting_ref(&self) -> &ScadLighting {
&self.lighting
}
pub fn quality(mut self, quality: ScadQuality) -> Self {
self.supersample = quality.supersample();
self
}
pub fn palette_ref(&self) -> &ScadPalette {
&self.palette
}
pub fn coloring_mode(&self) -> ScadColoring {
self.coloring
}
pub fn fit_per_frame(mut self, per_frame: bool) -> Self {
self.fit_per_frame = per_frame;
self
}
pub fn size(&self) -> (u32, u32) {
(self.width, self.height)
}
pub fn build_scene(&self, frame: &ScadFrame, camera: &PerspectiveCamera) -> Scene {
let mut scene = Scene::new();
let lin = crate::utils::srgb::srgb_to_linear_f32;
scene.background = Color::new(
lin(self.background[0]),
lin(self.background[1]),
lin(self.background[2]),
);
scene.background_alpha = self.background[3];
let shadows = self.add_lights(&mut scene, frame, camera);
for (index, part) in frame.parts.iter().enumerate() {
let rgba = self.color_for(part, index);
let mut material = StandardMaterial::new(Color::new(rgba[0], rgba[1], rgba[2]));
material.metalness = self.material.metalness;
material.roughness = self.material.roughness;
let transparent = rgba[3] < 0.999;
if transparent {
material.opacity = rgba[3];
material.side = 2; }
let mut object = Object3D::mesh(Mesh::new(
part.geometry.clone(),
Material::Standard(material),
));
object.cast_shadow = shadows && !transparent;
object.receive_shadow = shadows;
scene.add(object);
}
scene
}
fn add_lights(&self, scene: &mut Scene, frame: &ScadFrame, camera: &PerspectiveCamera) -> bool {
let light = &self.lighting;
let gain = light.intensity;
let (key_tint, fill_tint) = light.tints();
let (sky, ground) = light
.hemisphere
.unwrap_or((self.palette.sky, self.palette.ground));
let world_up = Vector3::new(0.0, 0.0, 1.0);
let forward = (camera.target - camera.position).normalize();
let right = forward.cross(world_up);
let right = if right.length() < 1e-4 {
Vector3::new(1.0, 0.0, 0.0)
} else {
right.normalize()
};
let up = right.cross(forward).normalize();
let toward_view_light = |azimuth: f32, elevation: f32| {
let (az, el) = (azimuth.to_radians(), elevation.to_radians());
(right * (az.sin() * el.cos()) + up * el.sin() - forward * (az.cos() * el.cos()))
.normalize()
};
let mut hemi = Object3D::light(HemisphereLight::new(
Color::new(sky[0], sky[1], sky[2]),
Color::new(ground[0], ground[1], ground[2]),
light.ambient * gain,
));
hemi.quaternion =
crate::math::Quaternion::from_euler_xyz(std::f32::consts::FRAC_PI_2, 0.0, 0.0);
let shadow_settings = light
.shadows
.then(|| frame.bounds().map(shadow_settings_for))
.flatten();
let shadows = shadow_settings.is_some();
let key_light = |toward: Vector3, tint: [f32; 3], strength: f32| {
let mut key = directional(tint, strength, toward);
if let Some(settings) = shadow_settings {
key.cast_shadow = true;
key.shadow = settings;
}
key
};
match light.rig {
ScadRig::Studio => {
scene.add(hemi);
let [az, el] = light.key_angles;
scene.add_light(key_light(toward_view_light(az, el), key_tint, 1.52 * gain));
scene.add_light(directional(
fill_tint,
0.44 * gain,
toward_view_light(-(az + 25.0), el * 0.2),
));
scene.add_light(directional(
[0.90, 0.94, 1.0],
0.68 * gain,
toward_view_light(180.0 - az * 0.5, el + 20.0),
));
}
ScadRig::Sun => {
scene.add(hemi);
let [az, el] = light.key_angles;
scene.add_light(key_light(orbit_direction(az, el), key_tint, 1.68 * gain));
scene.add_light(directional(
fill_tint,
0.32 * gain,
orbit_direction(az + 150.0, 12.0),
));
}
ScadRig::Flat => {
scene.add(hemi);
scene.add_light(directional(
[1.0, 1.0, 1.0],
1.05 * gain,
toward_view_light(12.0, 14.0),
));
}
ScadRig::Custom => {}
}
for extra in &light.extra {
match *extra {
ScadLight::Ambient { color, intensity } => {
scene.add_light(AmbientLight::new(
Color::new(color[0], color[1], color[2]),
intensity * gain,
));
}
ScadLight::Hemisphere {
sky,
ground,
intensity,
} => {
let mut object = Object3D::light(HemisphereLight::new(
Color::new(sky[0], sky[1], sky[2]),
Color::new(ground[0], ground[1], ground[2]),
intensity * gain,
));
object.quaternion = crate::math::Quaternion::from_euler_xyz(
std::f32::consts::FRAC_PI_2,
0.0,
0.0,
);
scene.add(object);
}
ScadLight::Directional {
color,
intensity,
direction,
} => {
let d = Vector3::new(direction[0], direction[1], direction[2]);
if d.length() > 1e-6 {
scene.add_light(directional(color, intensity * gain, d.normalize() * -1.0));
}
}
ScadLight::Key {
color,
intensity,
azimuth,
elevation,
} => {
scene.add_light(directional(
color,
intensity * gain,
toward_view_light(azimuth, elevation),
));
}
ScadLight::Point {
color,
intensity,
position,
} => {
let mut object = Object3D::light(crate::lights::PointLight::new(
Color::new(color[0], color[1], color[2]),
intensity * gain,
));
object.position = Vector3::new(position[0], position[1], position[2]);
scene.add(object);
}
}
}
shadows
}
pub fn color_for(&self, part: &ScadPart, index: usize) -> [f32; 4] {
match self.coloring {
ScadColoring::Model => part.rgba_or(self.material.color),
ScadColoring::ModelThenPalette => {
part.color.unwrap_or_else(|| self.palette.color_at(index))
}
ScadColoring::Palette => self.palette.color_at(index),
ScadColoring::Uniform => self.material.color,
}
}
pub fn build_camera(&self, frame: &ScadFrame, fit: ([f32; 3], [f32; 3])) -> PerspectiveCamera {
place_camera(
self.camera,
frame,
fit,
self.width as f32 / self.height as f32,
)
}
}
#[cfg(feature = "render")]
impl ScadRender {
pub fn render_frames(&self, animation: &mut ScadAnimation) -> Result<Vec<Vec<u8>>, String> {
self.render_evaluated(&animation.evaluate()?)
}
pub fn render_evaluated(&self, frames: &[ScadFrame]) -> Result<Vec<Vec<u8>>, String> {
let mut renderer = self.headless()?;
let fit = animation_bounds(frames);
let mut out = Vec::with_capacity(frames.len());
for frame in frames {
out.push(self.render_one(&mut renderer, frame, fit));
}
Ok(out)
}
pub fn render_frame(&self, animation: &ScadAnimation, index: usize) -> Result<Vec<u8>, String> {
let frame = animation.frame(index)?;
let fit = frame.bounds().unwrap_or(([-1.0; 3], [1.0; 3]));
let mut renderer = self.headless()?;
Ok(self.render_one(&mut renderer, &frame, fit))
}
pub fn render_png(
&self,
animation: &ScadAnimation,
index: usize,
path: impl AsRef<std::path::Path>,
) -> Result<(), String> {
let rgba = self.render_frame(animation, index)?;
let bytes = crate::utils::png::encode_png(self.width, self.height, &rgba);
std::fs::write(path.as_ref(), bytes)
.map_err(|e| format!("cannot write {}: {e}", path.as_ref().display()))
}
pub fn export_png_sequence(
&self,
animation: &mut ScadAnimation,
dir: impl AsRef<std::path::Path>,
prefix: &str,
) -> Result<Vec<std::path::PathBuf>, String> {
let dir = dir.as_ref();
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
let frames = self.render_frames(animation)?;
let mut paths = Vec::with_capacity(frames.len());
for (i, rgba) in frames.iter().enumerate() {
let path = dir.join(format!("{prefix}{i:04}.png"));
let bytes = crate::utils::png::encode_png(self.width, self.height, rgba);
std::fs::write(&path, bytes)
.map_err(|e| format!("cannot write {}: {e}", path.display()))?;
paths.push(path);
}
Ok(paths)
}
fn headless(&self) -> Result<crate::renderer::HeadlessRenderer, String> {
crate::renderer::HeadlessRenderer::builder()
.size(self.width, self.height)
.supersample(self.supersample)
.color_format(wgpu::TextureFormat::Rgba8Unorm)
.high_resolution(true)
.build()
}
fn render_one(
&self,
renderer: &mut crate::renderer::HeadlessRenderer,
frame: &ScadFrame,
animation_fit: ([f32; 3], [f32; 3]),
) -> Vec<u8> {
let fit = if self.fit_per_frame {
frame.bounds().unwrap_or(animation_fit)
} else {
animation_fit
};
let camera = self.build_camera(frame, fit);
let mut scene = self.build_scene(frame, &camera);
let rgba = renderer.render_to_rgba_resolved(&mut scene, &camera);
renderer.renderer().clear_geometry_cache();
rgba
}
}
fn shadow_settings_for(bounds: ([f32; 3], [f32; 3])) -> crate::lights::ShadowSettings {
let reach = box_corners(bounds)
.iter()
.map(|c| c.length())
.fold(0.0f32, f32::max)
.max(1e-3);
crate::lights::ShadowSettings {
map_size: 2048,
radius: 1.0,
bias: (reach * 3.0e-4).max(1e-5),
normal_bias: (reach * 4.0e-3).max(1e-4),
camera_size: reach * 1.15,
camera_near: (reach * 0.7).max(1e-3),
camera_far: reach * 2.8,
..Default::default()
}
}
fn directional(color: [f32; 3], intensity: f32, toward: Vector3) -> DirectionalLight {
DirectionalLight::new(Color::new(color[0], color[1], color[2]), intensity)
.with_direction(toward * -1.0)
}
pub fn animation_bounds(frames: &[ScadFrame]) -> ([f32; 3], [f32; 3]) {
let mut lo = [f32::MAX; 3];
let mut hi = [f32::MIN; 3];
let mut any = false;
for frame in frames {
if let Some((min, max)) = frame.bounds() {
any = true;
for i in 0..3 {
lo[i] = lo[i].min(min[i]);
hi[i] = hi[i].max(max[i]);
}
}
}
if any {
(lo, hi)
} else {
([-1.0; 3], [1.0; 3])
}
}