From 96ad0d956c7aa4372dc2bb438c4be72a346c83cb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:07:51 -0500 Subject: [PATCH 001/471] feat(scene): reserve document places for shots, variants and animation Shots, material variants and model sets, the configurator, measurements and the animation each get an empty block in the document, left out of the file when empty so existing projects save byte for byte, so they can be written side by side. Ran cargo clippy on fsh-scene with -D warnings. --- native/crates/fsh-scene/src/animation/mod.rs | 22 ++++++++++++++++ native/crates/fsh-scene/src/animation/rigs.rs | 15 +++++++++++ native/crates/fsh-scene/src/configurator.rs | 16 ++++++++++++ native/crates/fsh-scene/src/document.rs | 25 +++++++++++++++++++ native/crates/fsh-scene/src/lib.rs | 5 ++++ native/crates/fsh-scene/src/measure.rs | 15 +++++++++++ native/crates/fsh-scene/src/shots.rs | 15 +++++++++++ native/crates/fsh-scene/src/variants.rs | 15 +++++++++++ 8 files changed, 128 insertions(+) create mode 100644 native/crates/fsh-scene/src/animation/mod.rs create mode 100644 native/crates/fsh-scene/src/animation/rigs.rs create mode 100644 native/crates/fsh-scene/src/configurator.rs create mode 100644 native/crates/fsh-scene/src/measure.rs create mode 100644 native/crates/fsh-scene/src/shots.rs create mode 100644 native/crates/fsh-scene/src/variants.rs diff --git a/native/crates/fsh-scene/src/animation/mod.rs b/native/crates/fsh-scene/src/animation/mod.rs new file mode 100644 index 00000000..8a940886 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/mod.rs @@ -0,0 +1,22 @@ +//! Keyed animation: the timeline, tracks of keys on transforms, cameras, materials and lights, and rigs such as +//! turntables and camera paths, evaluated into the document at a time. + +pub mod rigs; + +use serde::{Deserialize, Serialize}; + +/// The document's animation. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Animation { + /// Generated motion (turntables, camera paths), applied after the keyed tracks. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub rigs: Vec, +} + +impl Animation { + /// True when nothing is stored, so the block is left out of the file. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs new file mode 100644 index 00000000..6b000cf0 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -0,0 +1,15 @@ +//! Rigs: motion made from a few settings instead of keys (turntables, camera paths). + +use serde::{Deserialize, Serialize}; + +use crate::document::DocumentData; + +/// One rig. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Rig {} + +/// Applies every rig at `time` seconds to the document data, after the keyed tracks. +pub fn apply(rigs: &[Rig], d: &mut DocumentData, time: f32) { + let _ = (rigs, d, time); +} diff --git a/native/crates/fsh-scene/src/configurator.rs b/native/crates/fsh-scene/src/configurator.rs new file mode 100644 index 00000000..416d43ad --- /dev/null +++ b/native/crates/fsh-scene/src/configurator.rs @@ -0,0 +1,16 @@ +//! The configurator: options a customer chooses between, each choice naming variants, model sets or shots, and the +//! rules that keep combinations valid. + +use serde::{Deserialize, Serialize}; + +/// The document's configurator. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Configurator {} + +impl Configurator { + /// True when nothing is stored, so the block is left out of the file. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} diff --git a/native/crates/fsh-scene/src/document.rs b/native/crates/fsh-scene/src/document.rs index 0faa1ad1..e760f861 100644 --- a/native/crates/fsh-scene/src/document.rs +++ b/native/crates/fsh-scene/src/document.rs @@ -1,5 +1,10 @@ +use crate::animation::Animation; +use crate::configurator::Configurator; use crate::error::{Result, SceneError}; use crate::material::{Material, TextureRef}; +use crate::measure::Measurements; +use crate::shots::Shots; +use crate::variants::Variants; use crate::mesh::Mesh; use crate::node::{Node, NodeKind}; use crate::ser; @@ -52,6 +57,21 @@ pub struct DocumentData { pub image_style: ImageStyle, /// Output settings. pub render: RenderSettings, + /// Shots (left out of the file when empty). + #[serde(skip_serializing_if = "Shots::is_empty")] + pub shots: Shots, + /// Material variants and model sets (left out of the file when empty). + #[serde(skip_serializing_if = "Variants::is_empty")] + pub variants: Variants, + /// Configurator options and rules (left out of the file when empty). + #[serde(skip_serializing_if = "Configurator::is_empty")] + pub configurator: Configurator, + /// Measurements (left out of the file when empty). + #[serde(skip_serializing_if = "Measurements::is_empty")] + pub measurements: Measurements, + /// Keyed animation and rigs (left out of the file when empty). + #[serde(skip_serializing_if = "Animation::is_empty")] + pub animation: Animation, } impl Default for DocumentData { @@ -72,6 +92,11 @@ impl Default for DocumentData { ground: Ground::default(), image_style: ImageStyle::default(), render: RenderSettings::default(), + shots: Shots::default(), + variants: Variants::default(), + configurator: Configurator::default(), + measurements: Measurements::default(), + animation: Animation::default(), } } } diff --git a/native/crates/fsh-scene/src/lib.rs b/native/crates/fsh-scene/src/lib.rs index 2361d2ad..283764d5 100644 --- a/native/crates/fsh-scene/src/lib.rs +++ b/native/crates/fsh-scene/src/lib.rs @@ -1,9 +1,11 @@ //! FormShot document layer: nodes, shared meshes, materials, cameras and settings; the closed command enum with //! undo and redo; selection; and `flatten()` into an immutable render snapshot. +pub mod animation; mod catalogue; mod command; mod compile; +pub mod configurator; mod denoise_settings; mod document; mod editor; @@ -13,6 +15,7 @@ mod history; mod labels; pub mod lighting; mod material; +pub mod measure; mod mesh; mod node; mod preview; @@ -20,10 +23,12 @@ pub mod primitives; pub mod ser; mod selection; mod settings; +pub mod shots; mod slots; mod snapshot; mod tx; mod types; +pub mod variants; pub use catalogue::{catalogue, catalogue_json, CommandInfo}; pub use command::{ diff --git a/native/crates/fsh-scene/src/measure.rs b/native/crates/fsh-scene/src/measure.rs new file mode 100644 index 00000000..9103adba --- /dev/null +++ b/native/crates/fsh-scene/src/measure.rs @@ -0,0 +1,15 @@ +//! Measurements: distances, dimensions and angles placed on the model and kept in the document. + +use serde::{Deserialize, Serialize}; + +/// The document's measurements. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Measurements {} + +impl Measurements { + /// True when nothing is stored, so the block is left out of the file. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} diff --git a/native/crates/fsh-scene/src/shots.rs b/native/crates/fsh-scene/src/shots.rs new file mode 100644 index 00000000..c6785ae9 --- /dev/null +++ b/native/crates/fsh-scene/src/shots.rs @@ -0,0 +1,15 @@ +//! Shots: named views of the scene (camera, look, lighting, visibility and output) kept in the document. + +use serde::{Deserialize, Serialize}; + +/// The document's shots. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Shots {} + +impl Shots { + /// True when nothing is stored, so the block is left out of the file. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} diff --git a/native/crates/fsh-scene/src/variants.rs b/native/crates/fsh-scene/src/variants.rs new file mode 100644 index 00000000..f61297ed --- /dev/null +++ b/native/crates/fsh-scene/src/variants.rs @@ -0,0 +1,15 @@ +//! Material variants and model sets: alternative looks and alternative parts of one product, kept in the document. + +use serde::{Deserialize, Serialize}; + +/// The document's material variants and model sets. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Variants {} + +impl Variants { + /// True when nothing is stored, so the block is left out of the file. + pub fn is_empty(&self) -> bool { + *self == Self::default() + } +} From 1d50d2970922dc94a2198bf29d86e5bc314e4921 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:10:43 -0500 Subject: [PATCH 002/471] feat(scene): reserve render settings for motion blur and transport Render settings gain a motion blur block and a transport block holding spectral rendering and caustics, each empty, defaulted and left out of the file when default, with their checks already called from the render settings check. Ran cargo clippy on the workspace with -D warnings. --- native/crates/fsh-scene/src/lib.rs | 4 ++ native/crates/fsh-scene/src/motion.rs | 23 +++++++++++ native/crates/fsh-scene/src/settings.rs | 12 ++++++ .../fsh-scene/src/transport/caustics.rs | 20 ++++++++++ native/crates/fsh-scene/src/transport/mod.rs | 38 +++++++++++++++++++ .../fsh-scene/src/transport/spectral.rs | 20 ++++++++++ 6 files changed, 117 insertions(+) create mode 100644 native/crates/fsh-scene/src/motion.rs create mode 100644 native/crates/fsh-scene/src/transport/caustics.rs create mode 100644 native/crates/fsh-scene/src/transport/mod.rs create mode 100644 native/crates/fsh-scene/src/transport/spectral.rs diff --git a/native/crates/fsh-scene/src/lib.rs b/native/crates/fsh-scene/src/lib.rs index 283764d5..4f024cda 100644 --- a/native/crates/fsh-scene/src/lib.rs +++ b/native/crates/fsh-scene/src/lib.rs @@ -17,6 +17,7 @@ pub mod lighting; mod material; pub mod measure; mod mesh; +mod motion; mod node; mod preview; pub mod primitives; @@ -26,6 +27,7 @@ mod settings; pub mod shots; mod slots; mod snapshot; +pub mod transport; mod tx; mod types; pub mod variants; @@ -53,6 +55,8 @@ pub use labels::{validate_labels, Label, MaterialLabelAdd, MaterialLabelMove, Ma pub use material::{Material, SurfaceParams, TextureRef, TextureRole, MATERIAL_FIELDS}; pub use slots::{validate_projection, Channel, CoordSpace, MapProjection, MaterialInput, TextureSlot, UvTransform}; pub use mesh::Mesh; +pub use motion::MotionBlur; +pub use transport::{Caustics, Spectral, Transport}; pub use node::{ CapMode, Cutaway, CutawayShape, Light, LightColour, LightShape, Node, NodeKind, PowerUnit, RayVisibility, Trs, }; diff --git a/native/crates/fsh-scene/src/motion.rs b/native/crates/fsh-scene/src/motion.rs new file mode 100644 index 00000000..4aa7695c --- /dev/null +++ b/native/crates/fsh-scene/src/motion.rs @@ -0,0 +1,23 @@ +//! Motion blur: how long the shutter stays open while parts, lights and the camera move. + +use serde::{Deserialize, Serialize}; + +use crate::error::Result; + +/// Motion blur settings of a render. Every field is defaulted, and the block is left out of the document when it +/// equals the default. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MotionBlur {} + +impl MotionBlur { + /// True when every field has its default value. + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// Checks every value. + pub fn validate(&self) -> Result<()> { + Ok(()) + } +} diff --git a/native/crates/fsh-scene/src/settings.rs b/native/crates/fsh-scene/src/settings.rs index 12461324..46086a9e 100644 --- a/native/crates/fsh-scene/src/settings.rs +++ b/native/crates/fsh-scene/src/settings.rs @@ -1,7 +1,9 @@ use crate::denoise_settings::DenoiseSettings; use crate::error::{finite, non_negative, positive, range, Result, SceneError}; use crate::lighting::{validate_pins, Backplate, BackgroundImage, Dome, EnvPin}; +use crate::motion::MotionBlur; use crate::ser; +use crate::transport::Transport; use fsh_core::{Rgb, TextureKey, Vec3}; use serde::{Deserialize, Serialize}; @@ -1133,6 +1135,12 @@ pub struct RenderSettings { /// Length of the ambient occlusion rays in metres, above 0 and at most 1000. Default 1. #[serde(skip_serializing_if = "default_ao")] pub ao_distance: f32, + /// Motion blur (left out of the JSON when default). + #[serde(skip_serializing_if = "MotionBlur::is_default")] + pub motion_blur: MotionBlur, + /// Spectral rendering and caustics (left out of the JSON when default). + #[serde(skip_serializing_if = "Transport::is_default")] + pub transport: Transport, } impl Default for RenderSettings { @@ -1147,6 +1155,8 @@ impl Default for RenderSettings { denoising: DenoiseSettings::default(), passes: Passes::NONE, ao_distance: DEFAULT_AO_DISTANCE, + motion_blur: MotionBlur::default(), + transport: Transport::default(), } } } @@ -1167,6 +1177,8 @@ impl RenderSettings { chk("render.max_bounces", self.max_bounces, 1, 256)?; positive("render.ao_distance", self.ao_distance)?; range("render.ao_distance", self.ao_distance, 0.0, 1000.0)?; + self.motion_blur.validate()?; + self.transport.validate()?; self.denoising.validate() } diff --git a/native/crates/fsh-scene/src/transport/caustics.rs b/native/crates/fsh-scene/src/transport/caustics.rs new file mode 100644 index 00000000..7f195669 --- /dev/null +++ b/native/crates/fsh-scene/src/transport/caustics.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; + +use crate::error::Result; + +/// Caustics settings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Caustics {} + +impl Caustics { + /// True when every field has its default value. + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// Checks every value. + pub fn validate(&self) -> Result<()> { + Ok(()) + } +} diff --git a/native/crates/fsh-scene/src/transport/mod.rs b/native/crates/fsh-scene/src/transport/mod.rs new file mode 100644 index 00000000..eec6f403 --- /dev/null +++ b/native/crates/fsh-scene/src/transport/mod.rs @@ -0,0 +1,38 @@ +//! Light transport options of a render that are not tied to one material or one part: spectral rendering and +//! caustics. + +mod caustics; +mod spectral; + +pub use caustics::Caustics; +pub use spectral::Spectral; + +use serde::{Deserialize, Serialize}; + +use crate::error::Result; + +/// Light transport options. Every field is defaulted, and the block is left out of the document when it equals the +/// default. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Transport { + /// Spectral rendering. + #[serde(skip_serializing_if = "Spectral::is_default")] + pub spectral: Spectral, + /// Caustics. + #[serde(skip_serializing_if = "Caustics::is_default")] + pub caustics: Caustics, +} + +impl Transport { + /// True when every field has its default value. + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// Checks every value. + pub fn validate(&self) -> Result<()> { + self.spectral.validate()?; + self.caustics.validate() + } +} diff --git a/native/crates/fsh-scene/src/transport/spectral.rs b/native/crates/fsh-scene/src/transport/spectral.rs new file mode 100644 index 00000000..e535b8e9 --- /dev/null +++ b/native/crates/fsh-scene/src/transport/spectral.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; + +use crate::error::Result; + +/// Spectral rendering settings. +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Spectral {} + +impl Spectral { + /// True when every field has its default value. + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// Checks every value. + pub fn validate(&self) -> Result<()> { + Ok(()) + } +} From 4cd2021b04da4784d3ef283d396865d75cf9e3fa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:11:27 -0500 Subject: [PATCH 003/471] feat(commands): reserve command groups for shots, animation, transport Shots, the configurator, material templates, measurements, animation, video and light transport each get an empty module under ext/ with its own command list and dispatcher, so they can be written side by side. The catalogue is unchanged. Ran cargo clippy on the workspace with -D warnings. --- native/crates/fsh-commands/src/ext/anim.rs | 12 ++++++ .../fsh-commands/src/ext/configurator.rs | 12 ++++++ native/crates/fsh-commands/src/ext/measure.rs | 12 ++++++ native/crates/fsh-commands/src/ext/mod.rs | 37 ++++++++++++++++++- native/crates/fsh-commands/src/ext/shots.rs | 12 ++++++ .../crates/fsh-commands/src/ext/templates.rs | 12 ++++++ .../crates/fsh-commands/src/ext/transport.rs | 12 ++++++ native/crates/fsh-commands/src/ext/video.rs | 12 ++++++ 8 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 native/crates/fsh-commands/src/ext/anim.rs create mode 100644 native/crates/fsh-commands/src/ext/configurator.rs create mode 100644 native/crates/fsh-commands/src/ext/measure.rs create mode 100644 native/crates/fsh-commands/src/ext/shots.rs create mode 100644 native/crates/fsh-commands/src/ext/templates.rs create mode 100644 native/crates/fsh-commands/src/ext/transport.rs create mode 100644 native/crates/fsh-commands/src/ext/video.rs diff --git a/native/crates/fsh-commands/src/ext/anim.rs b/native/crates/fsh-commands/src/ext/anim.rs new file mode 100644 index 00000000..9cc702fe --- /dev/null +++ b/native/crates/fsh-commands/src/ext/anim.rs @@ -0,0 +1,12 @@ +//! Animation: the engine's current time, playback and frame sequences (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/configurator.rs b/native/crates/fsh-commands/src/ext/configurator.rs new file mode 100644 index 00000000..753077ba --- /dev/null +++ b/native/crates/fsh-commands/src/ext/configurator.rs @@ -0,0 +1,12 @@ +//! The configurator: listing every valid configuration and rendering them all (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/measure.rs b/native/crates/fsh-commands/src/ext/measure.rs new file mode 100644 index 00000000..105e37cf --- /dev/null +++ b/native/crates/fsh-commands/src/ext/measure.rs @@ -0,0 +1,12 @@ +//! Measurements: picking points on the model and reading dimensions (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/mod.rs b/native/crates/fsh-commands/src/ext/mod.rs index 3e67a5ca..f194e72d 100644 --- a/native/crates/fsh-commands/src/ext/mod.rs +++ b/native/crates/fsh-commands/src/ext/mod.rs @@ -6,8 +6,10 @@ use crate::error::Result; use fsh_scene::ChangeLevel; use serde_json::Value; +pub(crate) mod anim; pub(crate) mod cad; mod camera; +pub(crate) mod configurator; pub(crate) mod denoise; mod handoff; mod image; @@ -15,7 +17,12 @@ pub(crate) mod import; mod library; pub(crate) mod lighting; mod materials; +pub(crate) mod measure; pub(crate) mod output; +pub(crate) mod shots; +pub(crate) mod templates; +pub(crate) mod transport; +pub(crate) mod video; /// One command of a group: catalogue fields and a function giving its argument schema. pub(crate) struct ExtCommand { @@ -40,6 +47,13 @@ pub(crate) fn commands() -> impl Iterator { .chain(image::COMMANDS.iter()) .chain(output::COMMANDS.iter()) .chain(denoise::COMMANDS.iter()) + .chain(shots::COMMANDS.iter()) + .chain(configurator::COMMANDS.iter()) + .chain(templates::COMMANDS.iter()) + .chain(measure::COMMANDS.iter()) + .chain(anim::COMMANDS.iter()) + .chain(video::COMMANDS.iter()) + .chain(transport::COMMANDS.iter()) } /// Answers `name` when one of the groups owns it. @@ -71,5 +85,26 @@ pub(crate) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value if let Some(r) = output::dispatch(engine, st, name, args) { return Some(r); } - denoise::dispatch(engine, st, name, args) + if let Some(r) = denoise::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = shots::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = configurator::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = templates::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = measure::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = anim::dispatch(engine, st, name, args) { + return Some(r); + } + if let Some(r) = video::dispatch(engine, st, name, args) { + return Some(r); + } + transport::dispatch(engine, st, name, args) } diff --git a/native/crates/fsh-commands/src/ext/shots.rs b/native/crates/fsh-commands/src/ext/shots.rs new file mode 100644 index 00000000..0de77bc3 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/shots.rs @@ -0,0 +1,12 @@ +//! Shots: rendering and listing named views of the scene (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/templates.rs b/native/crates/fsh-commands/src/ext/templates.rs new file mode 100644 index 00000000..3c19bd39 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/templates.rs @@ -0,0 +1,12 @@ +//! Material templates: rules that put library materials on imported parts by name (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/transport.rs b/native/crates/fsh-commands/src/ext/transport.rs new file mode 100644 index 00000000..4c4336c7 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/transport.rs @@ -0,0 +1,12 @@ +//! Light transport: which devices run spectral rendering, media, caustics, cutaways, rounded edges and fibres (0.10.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} diff --git a/native/crates/fsh-commands/src/ext/video.rs b/native/crates/fsh-commands/src/ext/video.rs new file mode 100644 index 00000000..7b3ff5f3 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/video.rs @@ -0,0 +1,12 @@ +//! Video: finding ffmpeg and encoding rendered frames into a movie (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} From 4de23babab4c987b4cf3fca7e697a2232dc50233 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:11:27 -0500 Subject: [PATCH 004/471] feat(backend): reserve a router for ffmpeg and rendered movies Movies are encoded by the family's LGPL ffmpeg, run as a separate program and fetched by the service when none is installed, so the video work gets an empty router registered with the others. Ran the service import. --- backend/app/main.py | 3 ++- backend/app/routers/video.py | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 backend/app/routers/video.py diff --git a/backend/app/main.py b/backend/app/main.py index b5236a9c..bfdd8d55 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -14,7 +14,7 @@ from app.agent import router as agent_router from app.engine import EngineError, EngineUnavailable, engine from app.local_guard import LocalGuard -from app.routers import cad, denoise, handoff, imports, library, mcp, output, textures +from app.routers import cad, denoise, handoff, imports, library, mcp, output, textures, video mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -52,6 +52,7 @@ async def lifespan(app): app.include_router(textures.router) app.include_router(denoise.router) app.include_router(output.router) +app.include_router(video.router) @app.middleware("http") diff --git a/backend/app/routers/video.py b/backend/app/routers/video.py new file mode 100644 index 00000000..5d989698 --- /dev/null +++ b/backend/app/routers/video.py @@ -0,0 +1,5 @@ +"""Video: finding or downloading the family's ffmpeg and serving the movies the engine writes (0.9.0).""" + +from fastapi import APIRouter + +router = APIRouter() From 0f71d11108002689f5a4189704d9dcbb8fae3014 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:18:10 -0500 Subject: [PATCH 005/471] feat(render): queue jobs for documents prepared by other commands render.queue_add's current-document branch becomes queue_documents, which shots, the configurator and animation call with prepared copies of the document, and file names gain the shot, config and variant tokens those jobs fill. Ran cargo clippy on fsh-commands, cargo check of fsh-wasm for wasm32, and queued a 64 by 48 render of the current document through the engine, which wrote Untitled_0001.png. --- native/crates/fsh-commands/src/ext/output.rs | 83 +++++++++++++++---- .../fsh-commands/src/ext/output/naming.rs | 3 +- .../crates/fsh-commands/src/ext/output/run.rs | 3 + .../fsh-commands/src/ext/output/spec.rs | 3 + 4 files changed, 73 insertions(+), 19 deletions(-) diff --git a/native/crates/fsh-commands/src/ext/output.rs b/native/crates/fsh-commands/src/ext/output.rs index 3fb5c34b..0e4829e0 100644 --- a/native/crates/fsh-commands/src/ext/output.rs +++ b/native/crates/fsh-commands/src/ext/output.rs @@ -4,8 +4,9 @@ use super::ExtCommand; use crate::engine::{Engine, State}; use crate::error::{EngineError, Result}; use crate::util::{get_bool, get_str, get_u32, key_of}; -use fsh_scene::{BackgroundMode, ChangeLevel, PassClass, PassKind, Passes}; +use fsh_scene::{BackgroundMode, ChangeLevel, Document, PassClass, PassKind, Passes}; use serde_json::{json, Value}; +use std::collections::BTreeMap; use std::sync::atomic::AtomicBool; use std::sync::Arc; @@ -346,24 +347,70 @@ fn add(engine: &Engine, st: &mut State, args: &Value) -> Result { } } else { let doc = st.editor.document().clone(); - let title = match doc.info().name.trim() { - "" => st.path.as_deref().map(crate::engine::title_from).unwrap_or_else(|| "Untitled".into()), - t => t.to_string(), + return queue_documents(engine, st, args, vec![Queued { doc, label: label.to_string(), tokens: BTreeMap::new() }]); + } + pushed(engine, jobs) + } +} + +/// One document for `queue_documents`: rendered once per camera the arguments pick, under its own label, filling +/// the file name tokens it carries (`shot`, `config`, `variant`). +pub(crate) struct Queued { + pub doc: Document, + pub label: String, + pub tokens: BTreeMap<&'static str, String>, +} + +/// Queues jobs for documents prepared by a command (the current document as it is, or a copy with a shot, a +/// configuration or a frame applied), with render.queue_add's output, settings, camera and device arguments. Frame +/// numbers count on from `frame` across every job. Answers like render.queue_add. +pub(crate) fn queue_documents(engine: &Engine, st: &mut State, args: &Value, items: Vec) -> Result { + if cfg!(target_arch = "wasm32") { + return Err(EngineError::Render { code: "unsupported", message: NO_QUEUE.into() }); + } + let output = spec::output(args)?; + let overrides = spec::overrides(args)?; + let pick = spec::pick(args)?; + let device = device_arg(args, st)?; + let failed = engine.failed_devices(); + let threads = st.threads; + let mut jobs = Vec::new(); + let mut k = 0u32; + for item in items { + let doc = item.doc; + let title = match doc.info().name.trim() { + "" => st.path.as_deref().map(crate::engine::title_from).unwrap_or_else(|| "Untitled".into()), + t => t.to_string(), + }; + let mut warnings = Vec::new(); + let env = spec::environment(&doc, &st.kept, &mut warnings); + for i in spec::cameras(&doc, &pick)? { + let (snapshot, samples, denoise, name) = spec::scene(&doc, i, &overrides)?; + let set = crate::textures::lookup(st, &snapshot.textures); + let textures = (!set.images.is_empty()).then_some(set); + let p = spec::Prepared { snapshot, env: env.clone(), textures, samples, denoise, camera_index: i, camera_name: name.clone(), title: title.clone(), warnings: warnings.clone() }; + let mut out = output.clone(); + out.frame = output.frame + k; + out.tokens = item.tokens.clone(); + k += 1; + let s = queue::Spec { + source: spec::Source::Ready(Box::new(p.clone())), + pick: spec::Pick::Index(i), + overrides: overrides.clone(), + device: device.clone(), + threads, + failed: failed.clone(), + output: out, }; - let mut warnings = Vec::new(); - let env = spec::environment(&doc, &st.kept, &mut warnings); - for (k, i) in spec::cameras(&doc, &pick)?.into_iter().enumerate() { - let (snapshot, samples, denoise, name) = spec::scene(&doc, i, &overrides)?; - let set = crate::textures::lookup(st, &snapshot.textures); - let textures = (!set.images.is_empty()).then_some(set); - let p = spec::Prepared { snapshot, env: env.clone(), textures, samples, denoise, camera_index: i, camera_name: name.clone(), title: title.clone(), warnings: warnings.clone() }; - let job = new_job(spec_for(k, spec::Source::Ready(Box::new(p.clone())), spec::Pick::Index(i)), label, Some(&p), &title, None, (i, name)); - jobs.push(job); - } + jobs.push(new_job(s, &item.label, Some(&p), &title, None, (i, name))); } - let ids = engine.queue().push(jobs)?; - let list = engine.queue().list(); - let made: Vec = list["jobs"].as_array().map(|a| a.iter().filter(|j| j["id"].as_u64().is_some_and(|id| ids.contains(&id))).cloned().collect()).unwrap_or_default(); - Ok(json!({"ok": true, "change": "none", "ids": ids, "jobs": made, "queue": list})) } + pushed(engine, jobs) +} + +fn pushed(engine: &Engine, jobs: Vec) -> Result { + let ids = engine.queue().push(jobs)?; + let list = engine.queue().list(); + let made: Vec = list["jobs"].as_array().map(|a| a.iter().filter(|j| j["id"].as_u64().is_some_and(|id| ids.contains(&id))).cloned().collect()).unwrap_or_default(); + Ok(json!({"ok": true, "change": "none", "ids": ids, "jobs": made, "queue": list})) } diff --git a/native/crates/fsh-commands/src/ext/output/naming.rs b/native/crates/fsh-commands/src/ext/output/naming.rs index a89b8312..7289d0d0 100644 --- a/native/crates/fsh-commands/src/ext/output/naming.rs +++ b/native/crates/fsh-commands/src/ext/output/naming.rs @@ -6,7 +6,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; pub(crate) const DEFAULT_NAME: &str = "{project}_{camera}_{pass}"; -pub(crate) const TOKENS: [&str; 10] = ["project", "camera", "pass", "date", "time", "frame", "job", "width", "height", "samples"]; +pub(crate) const TOKENS: [&str; 13] = + ["project", "camera", "pass", "date", "time", "frame", "job", "width", "height", "samples", "shot", "config", "variant"]; const MAX_NAME: usize = 200; diff --git a/native/crates/fsh-commands/src/ext/output/run.rs b/native/crates/fsh-commands/src/ext/output/run.rs index 5276bd26..d6153123 100644 --- a/native/crates/fsh-commands/src/ext/output/run.rs +++ b/native/crates/fsh-commands/src/ext/output/run.rs @@ -154,6 +154,9 @@ fn execute(shared: &Shared, id: u64, spec: &Spec, cancel: &AtomicBool) -> Result tokens.insert("width", w.to_string()); tokens.insert("height", h.to_string()); tokens.insert("samples", p.samples.to_string()); + for (k, v) in &spec.output.tokens { + tokens.entry(k).or_insert_with(|| naming::safe(v)); + } let cx = Context { snapshot: &p.snapshot, output: &spec.output, tokens, samples, camera: p.camera_name.clone(), title: p.title.clone() }; let planned = files::plan(&cx, &beauty, &passes, w, h).map_err(|e| Stop::Failed(e, "write_failed"))?; drop(passes); diff --git a/native/crates/fsh-commands/src/ext/output/spec.rs b/native/crates/fsh-commands/src/ext/output/spec.rs index f623a6cb..de56567c 100644 --- a/native/crates/fsh-commands/src/ext/output/spec.rs +++ b/native/crates/fsh-commands/src/ext/output/spec.rs @@ -13,6 +13,7 @@ use fsh_render_cpu::{EnvImage, STUDIO_PATH}; use fsh_scene::fsh_materials::TextureSet; use fsh_scene::{BackgroundMode, Document, Editor, EnvironmentSource, RenderSnapshot}; use serde_json::{json, Map, Value}; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -41,6 +42,7 @@ pub(crate) struct Output { pub folder: PathBuf, pub name: String, pub frame: u32, + pub tokens: BTreeMap<&'static str, String>, } /// A scene ready to render: snapshot with the job's camera and settings, its pictures, and what the list shows. @@ -162,6 +164,7 @@ pub(crate) fn output(args: &Value) -> Result { folder, name, frame: get_u32(args, "frame")?.unwrap_or(1), + tokens: BTreeMap::new(), }) } From 1ef64d4c5c3b38054945dc2daf53b42c069d1893 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:21:40 -0500 Subject: [PATCH 006/471] feat(commands): reserve a command group for variants and model sets Listing material variants and model sets, and what choosing one would change, is read-only engine work, so it gets its own empty module under ext/ beside the shots group. Ran cargo clippy on fsh-commands with -D warnings. --- native/crates/fsh-commands/src/ext/mod.rs | 5 +++++ native/crates/fsh-commands/src/ext/variants.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 native/crates/fsh-commands/src/ext/variants.rs diff --git a/native/crates/fsh-commands/src/ext/mod.rs b/native/crates/fsh-commands/src/ext/mod.rs index f194e72d..3d51f3a8 100644 --- a/native/crates/fsh-commands/src/ext/mod.rs +++ b/native/crates/fsh-commands/src/ext/mod.rs @@ -22,6 +22,7 @@ pub(crate) mod output; pub(crate) mod shots; pub(crate) mod templates; pub(crate) mod transport; +pub(crate) mod variants; pub(crate) mod video; /// One command of a group: catalogue fields and a function giving its argument schema. @@ -48,6 +49,7 @@ pub(crate) fn commands() -> impl Iterator { .chain(output::COMMANDS.iter()) .chain(denoise::COMMANDS.iter()) .chain(shots::COMMANDS.iter()) + .chain(variants::COMMANDS.iter()) .chain(configurator::COMMANDS.iter()) .chain(templates::COMMANDS.iter()) .chain(measure::COMMANDS.iter()) @@ -91,6 +93,9 @@ pub(crate) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value if let Some(r) = shots::dispatch(engine, st, name, args) { return Some(r); } + if let Some(r) = variants::dispatch(engine, st, name, args) { + return Some(r); + } if let Some(r) = configurator::dispatch(engine, st, name, args) { return Some(r); } diff --git a/native/crates/fsh-commands/src/ext/variants.rs b/native/crates/fsh-commands/src/ext/variants.rs new file mode 100644 index 00000000..c3848810 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/variants.rs @@ -0,0 +1,12 @@ +//! Material variants and model sets: listing them and what each would change (0.9.0). + +use super::ExtCommand; +use crate::engine::{Engine, State}; +use crate::error::Result; +use serde_json::Value; + +pub(super) static COMMANDS: &[ExtCommand] = &[]; + +pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { + None +} From 7017e04bb0cc0f223abca709df1eee6294a163e4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:28:31 -0500 Subject: [PATCH 007/471] feat(scene): add rig timing with eased ramps and a turn direction Rigs share one timing rule: a start and end time with constant-acceleration ramps in and out and linear speed between, plus a counterclockwise or clockwise direction seen from above. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 4 ++ .../fsh-scene/src/animation/rigs/timing.rs | 63 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 native/crates/fsh-scene/src/animation/rigs/timing.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index 6b000cf0..9bf5b939 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -1,5 +1,9 @@ //! Rigs: motion made from a few settings instead of keys (turntables, camera paths). +mod timing; + +pub use timing::{progress, Direction}; + use serde::{Deserialize, Serialize}; use crate::document::DocumentData; diff --git a/native/crates/fsh-scene/src/animation/rigs/timing.rs b/native/crates/fsh-scene/src/animation/rigs/timing.rs new file mode 100644 index 00000000..5dd7b467 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/timing.rs @@ -0,0 +1,63 @@ +//! When a rig moves: its start and end time, the ramps that ease it in and out, and its turning direction. + +use serde::{Deserialize, Serialize}; + +use crate::error::{finite, range, Result, SceneError}; + +/// Turning direction as seen from above (looking down the world up axis). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Direction { + /// Counterclockwise from above: a positive turn about +Y. + #[default] + Ccw, + /// Clockwise from above. + Cw, +} + +impl Direction { + /// +1 for counterclockwise, -1 for clockwise. + pub fn sign(self) -> f32 { + match self { + Direction::Ccw => 1.0, + Direction::Cw => -1.0, + } + } +} + +/// Share 0..1 of a rig's run, eased: before `start` it is 0, after `end` it is 1. `ease_in` and `ease_out` are the +/// fractions of the run spent speeding up from rest and slowing down to rest (constant acceleration); in between the +/// speed is constant, so with both 0 the motion is linear in time. +pub fn progress(start: f32, end: f32, ease_in: f32, ease_out: f32, time: f32) -> f32 { + let span = end as f64 - start as f64; + if span <= 0.0 || !span.is_finite() { + return if time >= end { 1.0 } else { 0.0 }; + } + let u = ((time as f64 - start as f64) / span).clamp(0.0, 1.0); + let a = (ease_in as f64).clamp(0.0, 1.0); + let b = (ease_out as f64).clamp(0.0, 1.0 - a); + let v = 1.0 / (1.0 - 0.5 * a - 0.5 * b); + let p = if u < a { + v * u * u / (2.0 * a) + } else if u > 1.0 - b { + 1.0 - v * (1.0 - u) * (1.0 - u) / (2.0 * b) + } else { + v * (u - 0.5 * a) + }; + p.clamp(0.0, 1.0) as f32 +} + +/// Checks a rig's times and ramps. +pub(crate) fn validate(field: &str, start: f32, end: f32, ease_in: f32, ease_out: f32) -> Result<()> { + finite(&format!("{field}.start"), start)?; + finite(&format!("{field}.end"), end)?; + if end <= start { + return Err(SceneError::value(format!("{field}.end"), "must be after start")); + } + range(&format!("{field}.ease_in"), ease_in, 0.0, 1.0)?; + range(&format!("{field}.ease_out"), ease_out, 0.0, 1.0)?; + if ease_in + ease_out > 1.0 + 1.0e-6 { + return Err(SceneError::value(format!("{field}.ease_in"), "ease_in and ease_out together must not exceed 1")); + } + Ok(()) +} From 2d3fcebbeb66e6b84e1e3ca1343218d50494bfab Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:29:15 -0500 Subject: [PATCH 008/471] feat(scene): turn a node or the product about its bounds centre The turntable rig turns a node, or every root holding visible product parts, about the world up axis through the centre of its bounds read before any rig moves the scene, whatever the node's pivot, and leaves it untouched at a zero angle. rigs::apply now prepares centres once and applies turntables in list order. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 60 +++++++++- .../fsh-scene/src/animation/rigs/scene.rs | 77 ++++++++++++ .../fsh-scene/src/animation/rigs/turntable.rs | 111 ++++++++++++++++++ 3 files changed, 243 insertions(+), 5 deletions(-) create mode 100644 native/crates/fsh-scene/src/animation/rigs/scene.rs create mode 100644 native/crates/fsh-scene/src/animation/rigs/turntable.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index 9bf5b939..440ea77b 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -1,19 +1,69 @@ //! Rigs: motion made from a few settings instead of keys (turntables, camera paths). +mod scene; mod timing; +mod turntable; pub use timing::{progress, Direction}; +pub use turntable::Turntable; use serde::{Deserialize, Serialize}; -use crate::document::DocumentData; +use crate::document::{Document, DocumentData}; +use crate::error::Result; /// One rig. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum Rig {} +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum Rig { + /// A node, or the whole product, turning about the up axis through its centre. + Turntable(Turntable), +} + +impl Rig { + /// The rig's id. + pub fn id(&self) -> &str { + match self { + Rig::Turntable(r) => &r.id, + } + } + + /// Stable kind name (the serde tag). + pub fn kind(&self) -> &'static str { + match self { + Rig::Turntable(_) => "turntable", + } + } + + /// Checks the settings against the document (nodes and cameras named must exist). + pub fn validate(&self, doc: &Document) -> Result<()> { + match self { + Rig::Turntable(r) => r.validate(doc), + } + } +} + +enum Prepared { + Turn(Vec), +} -/// Applies every rig at `time` seconds to the document data, after the keyed tracks. +/// Applies every rig at `time` seconds to the document data, after the keyed tracks. Centres are read from the data +/// as given, before any rig moves it; turntables apply first in list order, then the camera rigs. A rig naming a +/// node or camera that no longer exists does nothing. pub fn apply(rigs: &[Rig], d: &mut DocumentData, time: f32) { - let _ = (rigs, d, time); + if rigs.is_empty() { + return; + } + let prepared: Vec = scene::view(d, |doc| { + rigs.iter() + .map(|r| match r { + Rig::Turntable(t) => Prepared::Turn(t.prepare(doc)), + }) + .collect() + }); + for (r, p) in rigs.iter().zip(&prepared) { + match (r, p) { + (Rig::Turntable(t), Prepared::Turn(targets)) => t.apply(targets, d, time), + } + } } diff --git a/native/crates/fsh-scene/src/animation/rigs/scene.rs b/native/crates/fsh-scene/src/animation/rigs/scene.rs new file mode 100644 index 00000000..f123a8cc --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/scene.rs @@ -0,0 +1,77 @@ +//! What rigs read from the scene: centres of bounds, world and parent frames, the product's root nodes. + +use fsh_core::{Mat4, NodeId, Transform, Vec3}; + +use crate::document::{Document, DocumentData}; +use crate::lighting::studio::{parts_bounds, product_parts}; + +/// Runs `f` on the data seen as a `Document`, for the read-only helpers that take one. +pub(super) fn view(d: &mut DocumentData, f: impl FnOnce(&Document) -> R) -> R { + let doc = Document { d: std::mem::take(d) }; + let r = f(&doc); + *d = doc.d; + r +} + +/// Centre of the bounds of every visible product part (outside studio groups), or `None` without one. +pub(super) fn product_centre(doc: &Document) -> Option { + let parts = product_parts(doc, &[]).ok()?; + let b = parts_bounds(doc, &parts); + (!b.is_empty()).then(|| b.centroid()) +} + +/// Centre of the bounds of the visible parts under a node; its world origin when it has none. +pub(super) fn node_centre(doc: &Document, id: NodeId) -> Option { + doc.node(id)?; + let parts = product_parts(doc, &[id]).ok()?; + let b = parts_bounds(doc, &parts); + if b.is_empty() { + Some(world(&doc.d, id).point(Vec3::ZERO)) + } else { + Some(b.centroid()) + } +} + +/// Root nodes holding the visible product parts. +pub(super) fn product_roots(doc: &Document) -> Vec { + let mut out: Vec = Vec::new(); + for p in product_parts(doc, &[]).unwrap_or_default() { + let r = doc.ancestors(p).last().copied().unwrap_or(p); + if !out.contains(&r) { + out.push(r); + } + } + out +} + +/// Local-to-world transform of a node (identity for a missing node; a bad transform counts as identity). +pub(super) fn world(d: &DocumentData, id: NodeId) -> Transform { + let mut t = Transform::IDENTITY; + let mut cur = Some(id); + let mut guard = 0; + while let Some(c) = cur { + let Some(n) = d.nodes.get(&c) else { break }; + t = n.transform.to_transform().unwrap_or(Transform::IDENTITY).compose(&t); + cur = n.parent; + guard += 1; + if guard > d.nodes.len() { + break; + } + } + t +} + +/// Transform of a node's parent frame (identity for a root). +pub(super) fn parent_world(d: &DocumentData, id: NodeId) -> Transform { + match d.nodes.get(&id).and_then(|n| n.parent) { + Some(p) => world(d, p), + None => Transform::IDENTITY, + } +} + +/// Determinant of the linear part. +pub(super) fn det3(m: &Mat4) -> f32 { + let a = &m.m; + a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0]) + + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) +} diff --git a/native/crates/fsh-scene/src/animation/rigs/turntable.rs b/native/crates/fsh-scene/src/animation/rigs/turntable.rs new file mode 100644 index 00000000..c25c5a9e --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/turntable.rs @@ -0,0 +1,111 @@ +//! Turntable: a node, or the whole product, turned about the world up axis through the centre of its bounds. + +use fsh_core::{NodeId, Quat, Vec3}; +use serde::{Deserialize, Serialize}; + +use super::scene::{det3, node_centre, parent_world, product_centre, product_roots}; +use super::timing::{self, progress, Direction}; +use crate::document::{Document, DocumentData}; +use crate::error::{finite, Result, SceneError}; +use crate::ser; + +/// A turntable rig. Before `start` the node holds `start_angle` (so with the default 0 it is exactly where it was); +/// after `end` it holds the final angle. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Turntable { + /// Short id, unique among the rigs. + pub id: String, + /// Display name. + #[serde(skip_serializing_if = "String::is_empty")] + pub name: String, + /// The node turned (with everything under it); the whole product when absent. + #[serde(with = "ser::key_opt", skip_serializing_if = "Option::is_none")] + pub node: Option, + /// Full turns from start to end; fractions allowed. + pub turns: f32, + /// Start time in seconds. + pub start: f32, + /// End time in seconds. + pub end: f32, + /// Turning direction seen from above. + pub direction: Direction, + /// Fraction 0..1 of the run spent speeding up. + pub ease_in: f32, + /// Fraction 0..1 of the run spent slowing down. + pub ease_out: f32, + /// Angle in degrees already turned at the start, in the turning direction. + pub start_angle: f32, +} + +impl Default for Turntable { + fn default() -> Self { + Self { + id: String::new(), + name: String::new(), + node: None, + turns: 1.0, + start: 0.0, + end: 4.0, + direction: Direction::Ccw, + ease_in: 0.0, + ease_out: 0.0, + start_angle: 0.0, + } + } +} + +/// A node to turn and the turning centre in its parent's frame, read before any rig moves the scene. +pub(super) type Target = (NodeId, Vec3); + +impl Turntable { + /// Checks the settings and that the node exists. + pub fn validate(&self, doc: &Document) -> Result<()> { + finite("turntable.turns", self.turns)?; + finite("turntable.start_angle", self.start_angle)?; + timing::validate("turntable", self.start, self.end, self.ease_in, self.ease_out)?; + if let Some(n) = self.node { + if doc.node(n).is_none() { + return Err(SceneError::UnknownNode(n)); + } + } + Ok(()) + } + + /// Turn in radians at `time`, signed by the direction (positive is counterclockwise from above). + pub fn angle(&self, time: f32) -> f32 { + let p = progress(self.start, self.end, self.ease_in, self.ease_out, time) as f64; + let a = self.start_angle.to_radians() as f64 + std::f64::consts::TAU * self.turns as f64 * p; + (a * self.direction.sign() as f64) as f32 + } + + pub(super) fn prepare(&self, doc: &Document) -> Vec { + match self.node { + Some(id) => match node_centre(doc, id) { + Some(c) => vec![(id, parent_world(&doc.d, id).inverse().point(c))], + None => Vec::new(), + }, + None => match product_centre(doc) { + Some(c) => product_roots(doc).into_iter().map(|r| (r, c)).collect(), + None => Vec::new(), + }, + } + } + + pub(super) fn apply(&self, targets: &[Target], d: &mut DocumentData, time: f32) { + let theta = self.angle(time); + if theta == 0.0 || !theta.is_finite() { + return; + } + for (id, c) in targets { + let p = parent_world(d, *id); + let axis = p.inverse().vector(Vec3::Y); + let q = Quat::from_axis_angle(axis, if det3(&p.m) < 0.0 { -theta } else { theta }); + if let Some(n) = d.nodes.get_mut(id) { + let t = n.transform.translation; + n.transform.translation = *c + q.rotate(t - *c); + n.transform.rotation = (q * n.transform.rotation).normalize(); + } + } + } +} From d64994d415309bfd547858243d3d186c513b98c7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:29:52 -0500 Subject: [PATCH 009/471] feat(scene): add the camera orbit rig around the product centre An orbit moves a camera by index around the product's centre at its current horizontal distance and height, looking at the centre with the world up axis upright. Camera rigs apply after every turntable. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 20 ++++- .../fsh-scene/src/animation/rigs/orbit.rs | 80 +++++++++++++++++++ 2 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 native/crates/fsh-scene/src/animation/rigs/orbit.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index 440ea77b..a1427479 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -1,12 +1,15 @@ //! Rigs: motion made from a few settings instead of keys (turntables, camera paths). +mod orbit; mod scene; mod timing; mod turntable; +pub use orbit::Orbit; pub use timing::{progress, Direction}; pub use turntable::Turntable; +use fsh_core::Vec3; use serde::{Deserialize, Serialize}; use crate::document::{Document, DocumentData}; @@ -18,6 +21,8 @@ use crate::error::Result; pub enum Rig { /// A node, or the whole product, turning about the up axis through its centre. Turntable(Turntable), + /// A camera circling the product. + Orbit(Orbit), } impl Rig { @@ -25,6 +30,7 @@ impl Rig { pub fn id(&self) -> &str { match self { Rig::Turntable(r) => &r.id, + Rig::Orbit(r) => &r.id, } } @@ -32,6 +38,7 @@ impl Rig { pub fn kind(&self) -> &'static str { match self { Rig::Turntable(_) => "turntable", + Rig::Orbit(_) => "orbit", } } @@ -39,12 +46,14 @@ impl Rig { pub fn validate(&self, doc: &Document) -> Result<()> { match self { Rig::Turntable(r) => r.validate(doc), + Rig::Orbit(r) => r.validate(doc), } } } enum Prepared { Turn(Vec), + Centre(Option), } /// Applies every rig at `time` seconds to the document data, after the keyed tracks. Centres are read from the data @@ -55,15 +64,22 @@ pub fn apply(rigs: &[Rig], d: &mut DocumentData, time: f32) { return; } let prepared: Vec = scene::view(d, |doc| { + let product = rigs.iter().any(|r| !matches!(r, Rig::Turntable(_))).then(|| scene::product_centre(doc)).flatten(); rigs.iter() .map(|r| match r { Rig::Turntable(t) => Prepared::Turn(t.prepare(doc)), + Rig::Orbit(_) => Prepared::Centre(product), }) .collect() }); for (r, p) in rigs.iter().zip(&prepared) { - match (r, p) { - (Rig::Turntable(t), Prepared::Turn(targets)) => t.apply(targets, d, time), + if let (Rig::Turntable(t), Prepared::Turn(targets)) = (r, p) { + t.apply(targets, d, time); + } + } + for (r, p) in rigs.iter().zip(&prepared) { + if let (Rig::Orbit(o), Prepared::Centre(c)) = (r, p) { + o.apply(*c, d, time); } } } diff --git a/native/crates/fsh-scene/src/animation/rigs/orbit.rs b/native/crates/fsh-scene/src/animation/rigs/orbit.rs new file mode 100644 index 00000000..7608ff98 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/orbit.rs @@ -0,0 +1,80 @@ +//! Camera orbit: a camera circles the product at its current distance and height, looking at the product's centre. + +use fsh_core::Vec3; +use serde::{Deserialize, Serialize}; + +use super::timing::{self, progress, Direction}; +use crate::document::{Document, DocumentData}; +use crate::error::{finite, Result, SceneError}; + +/// A camera orbit rig. The camera keeps its horizontal distance and its height relative to the product's centre (read +/// before any rig moves the scene), always looks at that centre and keeps the world up axis upright. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Orbit { + /// Short id, unique among the rigs. + pub id: String, + /// Display name. + #[serde(skip_serializing_if = "String::is_empty")] + pub name: String, + /// Index of the camera that moves. + pub camera: usize, + /// Full turns from start to end; fractions allowed. + pub turns: f32, + /// Start time in seconds. + pub start: f32, + /// End time in seconds. + pub end: f32, + /// Direction the camera travels, seen from above. + pub direction: Direction, + /// Fraction 0..1 of the run spent speeding up. + pub ease_in: f32, + /// Fraction 0..1 of the run spent slowing down. + pub ease_out: f32, +} + +impl Default for Orbit { + fn default() -> Self { + Self { + id: String::new(), + name: String::new(), + camera: 0, + turns: 1.0, + start: 0.0, + end: 4.0, + direction: Direction::Ccw, + ease_in: 0.0, + ease_out: 0.0, + } + } +} + +impl Orbit { + /// Checks the settings and that the camera exists. + pub fn validate(&self, doc: &Document) -> Result<()> { + finite("orbit.turns", self.turns)?; + timing::validate("orbit", self.start, self.end, self.ease_in, self.ease_out)?; + if self.camera >= doc.cameras().len() { + return Err(SceneError::value("orbit.camera", format!("there is no camera {}", self.camera))); + } + Ok(()) + } + + /// Angle in radians travelled at `time`, positive counterclockwise from above. + pub fn angle(&self, time: f32) -> f32 { + let p = progress(self.start, self.end, self.ease_in, self.ease_out, time) as f64; + (std::f64::consts::TAU * self.turns as f64 * p * self.direction.sign() as f64) as f32 + } + + pub(super) fn apply(&self, centre: Option, d: &mut DocumentData, time: f32) { + let Some(cam) = d.cameras.get_mut(self.camera) else { return }; + let c = centre.unwrap_or(cam.target); + let o = cam.position - c; + let r = (o.x * o.x + o.z * o.z).sqrt(); + let phi = o.x.atan2(o.z) + self.angle(time); + let (s, k) = phi.sin_cos(); + cam.position = c + Vec3::new(r * s, o.y, r * k); + cam.target = c; + cam.up = Vec3::Y; + } +} From 1b01e1d0de216148b8bf28458d82af9e2bc09dc0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:30:31 -0500 Subject: [PATCH 010/471] feat(scene): add a centripetal catmull-rom curve walked by arc length ArcSpline builds an open or closed centripetal Catmull-Rom curve (alpha 0.5, Barry-Goldman form, in double precision) through control points and a table of 128 chords per segment, so a point can be found at any fraction of the curve's length. Camera paths walk it at constant speed. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 2 + .../fsh-scene/src/animation/rigs/spline.rs | 135 ++++++++++++++++++ 2 files changed, 137 insertions(+) create mode 100644 native/crates/fsh-scene/src/animation/rigs/spline.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index a1427479..f3df94a1 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -2,10 +2,12 @@ mod orbit; mod scene; +mod spline; mod timing; mod turntable; pub use orbit::Orbit; +pub use spline::ArcSpline; pub use timing::{progress, Direction}; pub use turntable::Turntable; diff --git a/native/crates/fsh-scene/src/animation/rigs/spline.rs b/native/crates/fsh-scene/src/animation/rigs/spline.rs new file mode 100644 index 00000000..fe8f320e --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/spline.rs @@ -0,0 +1,135 @@ +//! Centripetal Catmull-Rom curves through control points, walked at constant speed by arc length. + +use fsh_core::Vec3; + +type P = [f64; 3]; + +const SUB: usize = 128; +const ALPHA: f64 = 0.5; + +fn sub(a: P, b: P) -> P { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn dist(a: P, b: P) -> f64 { + let d = sub(a, b); + (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() +} + +fn mix(a: P, wa: f64, b: P, wb: f64) -> P { + [a[0] * wa + b[0] * wb, a[1] * wa + b[1] * wb, a[2] * wa + b[2] * wb] +} + +fn lerp(a: P, b: P, ta: f64, tb: f64, t: f64) -> P { + let w = (t - ta) / (tb - ta); + mix(a, 1.0 - w, b, w) +} + +struct Segment { + p: [P; 4], + t: [f64; 4], +} + +impl Segment { + fn new(p: [P; 4]) -> Self { + let mut t = [0.0; 4]; + for i in 1..4 { + t[i] = t[i - 1] + dist(p[i], p[i - 1]).powf(ALPHA).max(1.0e-12); + } + Self { p, t } + } + + fn at(&self, u: f64) -> P { + let [p0, p1, p2, p3] = self.p; + let [t0, t1, t2, t3] = self.t; + let t = t1 + (t2 - t1) * u; + let a1 = lerp(p0, p1, t0, t1, t); + let a2 = lerp(p1, p2, t1, t2, t); + let a3 = lerp(p2, p3, t2, t3, t); + let b1 = lerp(a1, a2, t0, t2, t); + let b2 = lerp(a2, a3, t1, t3, t); + lerp(b1, b2, t1, t2, t) + } +} + +/// A centripetal Catmull-Rom curve (alpha 0.5, so it neither loops nor cusps within a segment) through every control +/// point, with a table of arc length so it can be walked at constant speed. An open curve runs from the first point +/// to the last with mirrored end tangents; a closed one returns to its first point and joins smoothly. +pub struct ArcSpline { + segments: Vec, + lengths: Vec, + single: Option

, +} + +impl ArcSpline { + /// Builds the curve; repeated consecutive points are dropped. `None` without points. + pub fn new(points: &[Vec3], closed: bool) -> Option { + let mut pts: Vec

= Vec::with_capacity(points.len()); + for p in points { + let q = [p.x as f64, p.y as f64, p.z as f64]; + if pts.last().is_none_or(|l| dist(*l, q) > 1.0e-9) { + pts.push(q); + } + } + if closed && pts.len() > 2 && dist(pts[0], pts[pts.len() - 1]) <= 1.0e-9 { + pts.pop(); + } + let n = pts.len(); + if n == 0 { + return None; + } + if n == 1 { + return Some(Self { segments: Vec::new(), lengths: vec![0.0], single: Some(pts[0]) }); + } + let closed = closed && n > 2; + let segments: Vec = if closed { + (0..n).map(|i| Segment::new([pts[(i + n - 1) % n], pts[i], pts[(i + 1) % n], pts[(i + 2) % n]])).collect() + } else { + let first = mix(pts[0], 2.0, pts[1], -1.0); + let last = mix(pts[n - 1], 2.0, pts[n - 2], -1.0); + let mut ext = Vec::with_capacity(n + 2); + ext.push(first); + ext.extend_from_slice(&pts); + ext.push(last); + (0..n - 1).map(|i| Segment::new([ext[i], ext[i + 1], ext[i + 2], ext[i + 3]])).collect() + }; + let mut lengths = Vec::with_capacity(segments.len() * SUB + 1); + lengths.push(0.0); + let mut total = 0.0; + for s in &segments { + let mut prev = s.at(0.0); + for k in 1..=SUB { + let p = s.at(k as f64 / SUB as f64); + total += dist(p, prev); + lengths.push(total); + prev = p; + } + } + Some(Self { segments, lengths, single: None }) + } + + /// Length of the whole curve. + pub fn length(&self) -> f64 { + self.lengths.last().copied().unwrap_or(0.0) + } + + /// The point at a fraction 0..1 of the curve's length. + pub fn at_fraction(&self, f: f64) -> Vec3 { + if let Some(p) = self.single { + return to_vec3(p); + } + let total = self.length(); + let s = f.clamp(0.0, 1.0) * total; + let last = self.lengths.len() - 2; + let i = self.lengths.partition_point(|l| *l <= s).saturating_sub(1).min(last); + let (a, b) = (self.lengths[i], self.lengths[i + 1]); + let w = if b > a { ((s - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 }; + let seg = (i / SUB).min(self.segments.len() - 1); + let u = ((i - seg * SUB) as f64 + w) / SUB as f64; + to_vec3(self.segments[seg].at(u.min(1.0))) + } +} + +fn to_vec3(p: P) -> Vec3 { + Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32) +} From 7782526a2b1c9af0678baa999790232a5982f8d5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:31:35 -0500 Subject: [PATCH 011/471] feat(scene): add the camera path rig with a look-at and roll A camera path moves a camera along an open or closed curve through control points at constant speed along its length, looking at a fixed point, a node's centre that follows the node as turntables move it, or the product's centre, with an optional roll. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 17 +- .../fsh-scene/src/animation/rigs/path.rs | 151 ++++++++++++++++++ 2 files changed, 165 insertions(+), 3 deletions(-) create mode 100644 native/crates/fsh-scene/src/animation/rigs/path.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index f3df94a1..b4c31f35 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -1,12 +1,14 @@ -//! Rigs: motion made from a few settings instead of keys (turntables, camera paths). +//! Rigs: motion made from a few settings instead of keys (turntables, camera orbits, camera paths). mod orbit; +mod path; mod scene; mod spline; mod timing; mod turntable; pub use orbit::Orbit; +pub use path::{CameraPath, LookAt}; pub use spline::ArcSpline; pub use timing::{progress, Direction}; pub use turntable::Turntable; @@ -25,6 +27,8 @@ pub enum Rig { Turntable(Turntable), /// A camera circling the product. Orbit(Orbit), + /// A camera following a curve through control points. + CameraPath(CameraPath), } impl Rig { @@ -33,6 +37,7 @@ impl Rig { match self { Rig::Turntable(r) => &r.id, Rig::Orbit(r) => &r.id, + Rig::CameraPath(r) => &r.id, } } @@ -41,6 +46,7 @@ impl Rig { match self { Rig::Turntable(_) => "turntable", Rig::Orbit(_) => "orbit", + Rig::CameraPath(_) => "camera_path", } } @@ -49,6 +55,7 @@ impl Rig { match self { Rig::Turntable(r) => r.validate(doc), Rig::Orbit(r) => r.validate(doc), + Rig::CameraPath(r) => r.validate(doc), } } } @@ -56,6 +63,7 @@ impl Rig { enum Prepared { Turn(Vec), Centre(Option), + Look(path::Look), } /// Applies every rig at `time` seconds to the document data, after the keyed tracks. Centres are read from the data @@ -71,6 +79,7 @@ pub fn apply(rigs: &[Rig], d: &mut DocumentData, time: f32) { .map(|r| match r { Rig::Turntable(t) => Prepared::Turn(t.prepare(doc)), Rig::Orbit(_) => Prepared::Centre(product), + Rig::CameraPath(c) => Prepared::Look(c.prepare(doc, product)), }) .collect() }); @@ -80,8 +89,10 @@ pub fn apply(rigs: &[Rig], d: &mut DocumentData, time: f32) { } } for (r, p) in rigs.iter().zip(&prepared) { - if let (Rig::Orbit(o), Prepared::Centre(c)) = (r, p) { - o.apply(*c, d, time); + match (r, p) { + (Rig::Orbit(o), Prepared::Centre(c)) => o.apply(*c, d, time), + (Rig::CameraPath(c), Prepared::Look(l)) => c.apply(*l, d, time), + _ => {} } } } diff --git a/native/crates/fsh-scene/src/animation/rigs/path.rs b/native/crates/fsh-scene/src/animation/rigs/path.rs new file mode 100644 index 00000000..29b4da04 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/path.rs @@ -0,0 +1,151 @@ +//! Camera path: a camera follows a smooth curve through control points at constant speed, looking at a fixed point +//! or at a node's centre. + +use fsh_core::{NodeId, Vec3}; +use serde::{Deserialize, Serialize}; + +use super::scene::{node_centre, world}; +use super::spline::ArcSpline; +use super::timing::{self, progress}; +use crate::document::{Document, DocumentData}; +use crate::error::{finite, Result, SceneError}; +use crate::ser; + +/// What a camera on a path looks at. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LookAt { + /// A fixed world point, `{"point": [x, y, z]}`. + Point([f32; 3]), + /// The centre of a node's visible parts (its origin without parts), following the node as rigs move it, + /// `{"node": id}`. + Node(#[serde(with = "ser::key")] NodeId), +} + +/// A camera path rig. The camera travels the whole curve from `start` to `end` at constant speed along its length +/// (between the ease ramps), from the first point to the last, or back to the first when closed. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CameraPath { + /// Short id, unique among the rigs. + pub id: String, + /// Display name. + #[serde(skip_serializing_if = "String::is_empty")] + pub name: String, + /// Index of the camera that moves. + pub camera: usize, + /// Control points in metres; the curve passes through each. + pub points: Vec<[f32; 3]>, + /// The curve returns smoothly to its first point. + pub closed: bool, + /// What the camera looks at; the product's centre when absent (the camera's own target without a product). + #[serde(skip_serializing_if = "Option::is_none")] + pub look_at: Option, + /// Roll in degrees about the viewing direction; positive banks the camera to its right. + pub roll: f32, + /// Start time in seconds. + pub start: f32, + /// End time in seconds. + pub end: f32, + /// Fraction 0..1 of the run spent speeding up. + pub ease_in: f32, + /// Fraction 0..1 of the run spent slowing down. + pub ease_out: f32, +} + +impl Default for CameraPath { + fn default() -> Self { + Self { + id: String::new(), + name: String::new(), + camera: 0, + points: Vec::new(), + closed: false, + look_at: None, + roll: 0.0, + start: 0.0, + end: 4.0, + ease_in: 0.0, + ease_out: 0.0, + } + } +} + +/// Where a path's camera looks, read before any rig moves the scene. +#[derive(Clone, Copy, Debug)] +pub(super) enum Look { + Fixed(Vec3), + Follow(NodeId, Vec3), + Own, +} + +impl CameraPath { + /// Checks the settings, that the camera and node exist and that there are enough distinct points. + pub fn validate(&self, doc: &Document) -> Result<()> { + timing::validate("camera_path", self.start, self.end, self.ease_in, self.ease_out)?; + finite("camera_path.roll", self.roll)?; + if self.camera >= doc.cameras().len() { + return Err(SceneError::value("camera_path.camera", format!("there is no camera {}", self.camera))); + } + if self.points.iter().flatten().any(|v| !v.is_finite()) { + return Err(SceneError::value("camera_path.points", "must be finite")); + } + let need = if self.closed { 3 } else { 2 }; + let mut distinct = 0; + for (i, p) in self.points.iter().enumerate() { + if i == 0 || *p != self.points[i - 1] { + distinct += 1; + } + } + if distinct < need { + return Err(SceneError::value( + "camera_path.points", + format!("needs at least {need} points, each different from the one before"), + )); + } + match self.look_at { + Some(LookAt::Point(p)) if p.iter().any(|v| !v.is_finite()) => { + Err(SceneError::value("camera_path.look_at", "must be finite")) + } + Some(LookAt::Node(n)) if doc.node(n).is_none() => Err(SceneError::UnknownNode(n)), + _ => Ok(()), + } + } + + /// The curve through the control points. + pub fn spline(&self) -> Option { + let pts: Vec = self.points.iter().map(|p| Vec3::from_array(*p)).collect(); + ArcSpline::new(&pts, self.closed) + } + + pub(super) fn prepare(&self, doc: &Document, product: Option) -> Look { + match self.look_at { + Some(LookAt::Point(p)) => Look::Fixed(Vec3::from_array(p)), + Some(LookAt::Node(id)) => match node_centre(doc, id) { + Some(c) => Look::Follow(id, world(&doc.d, id).inverse().point(c)), + None => Look::Own, + }, + None => product.map(Look::Fixed).unwrap_or(Look::Own), + } + } + + pub(super) fn apply(&self, look: Look, d: &mut DocumentData, time: f32) { + let Some(spline) = self.spline() else { return }; + let target = match look { + Look::Fixed(p) => Some(p), + Look::Follow(id, local) => d.nodes.contains_key(&id).then(|| world(d, id).point(local)), + Look::Own => None, + }; + let Some(cam) = d.cameras.get_mut(self.camera) else { return }; + let p = progress(self.start, self.end, self.ease_in, self.ease_out, time); + cam.position = spline.at_fraction(p as f64); + if let Some(t) = target { + cam.target = t; + } + let Some(f) = (cam.target - cam.position).try_normalize() else { return }; + let up0 = Vec3::Y - f * f.dot(Vec3::Y); + let Some(up0) = up0.try_normalize() else { return }; + let (s, c) = self.roll.to_radians().sin_cos(); + cam.up = (up0 * c + f.cross(up0) * s).normalize(); + } +} From 3ab251310cb2666fd414e56576f05b4baeed9727 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:38:00 -0500 Subject: [PATCH 012/471] fix(scene): find the arc length point inside a chord by bisection Interpolating the curve parameter linearly within a table chord let the camera's speed vary by 1.6 percent where the parametric speed changes fast; the point is now found by bisecting the chord length inside the step. A scratch program walking a five-point open and closed path in 4000 steps now measures speed within 0.04 percent of the mean. --- .../fsh-scene/src/animation/rigs/spline.rs | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/native/crates/fsh-scene/src/animation/rigs/spline.rs b/native/crates/fsh-scene/src/animation/rigs/spline.rs index fe8f320e..cc44dc86 100644 --- a/native/crates/fsh-scene/src/animation/rigs/spline.rs +++ b/native/crates/fsh-scene/src/animation/rigs/spline.rs @@ -118,15 +118,25 @@ impl ArcSpline { if let Some(p) = self.single { return to_vec3(p); } - let total = self.length(); - let s = f.clamp(0.0, 1.0) * total; + let along = f.clamp(0.0, 1.0) * self.length(); let last = self.lengths.len() - 2; - let i = self.lengths.partition_point(|l| *l <= s).saturating_sub(1).min(last); - let (a, b) = (self.lengths[i], self.lengths[i + 1]); - let w = if b > a { ((s - a) / (b - a)).clamp(0.0, 1.0) } else { 0.0 }; + let i = self.lengths.partition_point(|l| *l <= along).saturating_sub(1).min(last); let seg = (i / SUB).min(self.segments.len() - 1); - let u = ((i - seg * SUB) as f64 + w) / SUB as f64; - to_vec3(self.segments[seg].at(u.min(1.0))) + let k = (i - seg * SUB) as f64; + let s = &self.segments[seg]; + let (u0, u1) = (k / SUB as f64, ((k + 1.0) / SUB as f64).min(1.0)); + let start = s.at(u0); + let want = (along - self.lengths[i]).max(0.0); + let (mut lo, mut hi) = (u0, u1); + for _ in 0..24 { + let mid = 0.5 * (lo + hi); + if dist(s.at(mid), start) < want { + lo = mid; + } else { + hi = mid; + } + } + to_vec3(s.at(0.5 * (lo + hi))) } } From e68e5cf791e230afe6b839f3cffeb51bef372ad7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:39:19 -0500 Subject: [PATCH 013/471] feat(scene): record the rig list in undo steps Tx gains rigs_mut, which stores the animation's rig list once per step so undo and redo restore it like the other document blocks. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/tx.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/native/crates/fsh-scene/src/tx.rs b/native/crates/fsh-scene/src/tx.rs index f55238a7..6118d769 100644 --- a/native/crates/fsh-scene/src/tx.rs +++ b/native/crates/fsh-scene/src/tx.rs @@ -22,6 +22,7 @@ pub(crate) enum UndoOp { Render(RenderSettings), Unit(LengthUnit), Info(DocumentInfo), + Rigs(Vec), } /// What a command overwrote, kept beside it in history so it can be undone. @@ -81,6 +82,7 @@ impl Document { UndoOp::Render(r) => self.d.render = r, UndoOp::Unit(u) => self.d.display_unit = u, UndoOp::Info(i) => self.d.info = i, + UndoOp::Rigs(r) => self.d.animation.rigs = r, } } } @@ -254,6 +256,13 @@ impl<'a> Tx<'a> { self.doc.d.info = i; } + pub(crate) fn rigs_mut(&mut self) -> &mut Vec { + if self.flag(1 << 8) { + self.rec.ops.push(UndoOp::Rigs(self.doc.d.animation.rigs.clone())); + } + &mut self.doc.d.animation.rigs + } + pub(crate) fn detach(&mut self, id: NodeId) -> Result<(Option, usize)> { let parent = self.doc.get_node(id)?.parent; let list = match parent { From db2d61b540b5c5aa82ba217f553e361e186672d6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:40:38 -0500 Subject: [PATCH 014/471] feat(scene): add commands that add, change and remove rigs anim.add_rig completes a partial rig (times from the animation's range, one frame longer for motion that cycles, the active camera, an id made of the kind's prefix and the lowest free number) and stores the full rig; anim.set_rig replaces the given fields, keeps id and kind and merges continuous edits of one rig; anim.remove_rig drops one. The range is read through a small adapter that answers 30 fps over 0 to 4 seconds until the animation stores its own. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/animation/rigs.rs | 3 + .../fsh-scene/src/animation/rigs/commands.rs | 193 ++++++++++++++++++ .../fsh-scene/src/animation/rigs/range.rs | 71 +++++++ native/crates/fsh-scene/src/command.rs | 10 + 4 files changed, 277 insertions(+) create mode 100644 native/crates/fsh-scene/src/animation/rigs/commands.rs create mode 100644 native/crates/fsh-scene/src/animation/rigs/range.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index b4c31f35..27b930a1 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -1,7 +1,9 @@ //! Rigs: motion made from a few settings instead of keys (turntables, camera orbits, camera paths). +pub mod commands; mod orbit; mod path; +mod range; mod scene; mod spline; mod timing; @@ -9,6 +11,7 @@ mod turntable; pub use orbit::Orbit; pub use path::{CameraPath, LookAt}; +pub use range::{Range, DEFAULT_END, DEFAULT_FPS, DEFAULT_START}; pub use spline::ArcSpline; pub use timing::{progress, Direction}; pub use turntable::Turntable; diff --git a/native/crates/fsh-scene/src/animation/rigs/commands.rs b/native/crates/fsh-scene/src/animation/rigs/commands.rs new file mode 100644 index 00000000..d0d562ca --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/commands.rs @@ -0,0 +1,193 @@ +//! Document commands that add, change and remove rigs, and the one-step helpers. + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use super::range::{self, Range}; +use super::Rig; +use crate::command::{full_value, ChangeLevel}; +use crate::document::Document; +use crate::error::{Result, SceneError}; +use crate::tx::Tx; + +/// `anim.add_rig` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimAddRig { + /// The rig with its `kind`; fields left out take their defaults, the times the animation's range (one frame past + /// its end for turntables, orbits and closed paths, so they loop), the camera the active one and the id the + /// kind's prefix with the lowest free number. Stored as the full rig. + pub rig: Value, + /// Position in the rig list; last when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub index: Option, +} + +/// `anim.set_rig` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimSetRig { + /// Rig id. + pub id: String, + /// Fields to change, each replacing the current value (null clears an optional field); stored as the full rig. + pub values: Value, +} + +/// `anim.remove_rig` arguments. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimRigRef { + /// Rig id. + pub id: String, +} + +fn invalid(msg: impl Into) -> SceneError { + SceneError::InvalidArguments(msg.into()) +} + +fn parse(v: &Value) -> Result { + serde_json::from_value(v.clone()).map_err(|e| invalid(format!("rig: {e}"))) +} + +fn prefix(kind: &str) -> &'static str { + match kind { + "turntable" => "turntable", + "orbit" => "orbit", + _ => "path", + } +} + +fn default_name(kind: &str) -> &'static str { + match kind { + "turntable" => "Turntable", + "orbit" => "Orbit", + _ => "Camera path", + } +} + +/// The kind's prefix with the lowest free number. +pub(crate) fn fresh_id(doc: &Document, kind: &str) -> String { + let p = prefix(kind); + let rigs = &doc.d.animation.rigs; + (1..).map(|n| format!("{p}{n}")).find(|id| rigs.iter().all(|r| r.id() != id)).unwrap_or_default() +} + +fn check_id(id: &str) -> Result<()> { + let ok = !id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'); + if ok { + Ok(()) + } else { + Err(SceneError::value("id", "must be 1 to 64 letters, digits, '_' or '-'")) + } +} + +fn index_of(doc: &Document, id: &str) -> Result { + doc.d.animation.rigs.iter().position(|r| r.id() == id).ok_or_else(|| SceneError::value("id", format!("there is no rig \"{id}\""))) +} + +/// Times a rig takes when none are given: the animation's range, one frame longer when the motion cycles, so the frame +/// after the last would repeat the first. +pub(crate) fn default_times(r: &Range, cyclic: bool) -> (f32, f32) { + let end = if cyclic { (r.end as f64 + 1.0 / r.fps as f64) as f32 } else { r.end }; + (r.start, end) +} + +fn fill(obj: &mut Map, key: &str, v: Value) { + if !obj.contains_key(key) || obj[key].is_null() { + obj.insert(key.to_string(), v); + } +} + +/// Completes a partial rig object: times, camera, id and name. +fn complete(doc: &Document, rig: &Value) -> Result { + let mut obj = rig.as_object().cloned().ok_or_else(|| invalid("rig must be an object with a kind"))?; + let kind = obj.get("kind").and_then(Value::as_str).ok_or_else(|| invalid("rig needs a kind: turntable, orbit or camera_path"))?.to_string(); + let cyclic = kind != "camera_path" || obj.get("closed").and_then(Value::as_bool).unwrap_or(false); + let (start, end) = default_times(&range::current(doc), cyclic); + fill(&mut obj, "start", start.into()); + fill(&mut obj, "end", end.into()); + if kind != "turntable" { + fill(&mut obj, "camera", doc.active_camera_index().into()); + } + fill(&mut obj, "id", fresh_id(doc, &kind).into()); + if obj.get("id").and_then(Value::as_str) == Some("") { + obj.insert("id".into(), fresh_id(doc, &kind).into()); + } + if obj.get("name").and_then(Value::as_str).is_none_or(str::is_empty) { + obj.insert("name".into(), default_name(&kind).into()); + } + parse(&Value::Object(obj)) +} + +/// Checks a rig and inserts it into the list in the step. +pub(crate) fn insert(tx: &mut Tx, rig: Rig, index: Option) -> Result<()> { + check_id(rig.id())?; + rig.validate(tx.doc)?; + if tx.doc.d.animation.rigs.iter().any(|r| r.id() == rig.id()) { + return Err(SceneError::value("id", format!("\"{}\" is already used by another rig", rig.id()))); + } + let list = tx.rigs_mut(); + let at = index.unwrap_or(list.len()).min(list.len()); + list.insert(at, rig); + Ok(()) +} + +impl AnimAddRig { + pub(crate) fn resolve(&mut self, doc: &mut Document) -> Result<()> { + self.rig = full_value(&complete(doc, &self.rig)?)?; + Ok(()) + } + + pub(crate) fn apply(&self, tx: &mut Tx) -> Result { + insert(tx, parse(&self.rig)?, self.index)?; + Ok(ChangeLevel::Full) + } +} + +impl AnimSetRig { + pub(crate) fn resolve(&mut self, doc: &mut Document) -> Result<()> { + let patch = self.values.as_object().ok_or_else(|| invalid("values must be an object"))?; + let cur = &doc.d.animation.rigs[index_of(doc, &self.id)?]; + let mut base = full_value(cur)?; + let obj = base.as_object_mut().ok_or_else(|| invalid("rig did not serialise to an object"))?; + for (k, v) in patch { + if k == "kind" && v.as_str() != Some(cur.kind()) { + return Err(SceneError::value("kind", "cannot change a rig's kind; remove it and add another")); + } + if k == "id" && v.as_str() != Some(self.id.as_str()) { + return Err(SceneError::value("id", "cannot change a rig's id")); + } + if v.is_null() { + obj.remove(k); + } else { + obj.insert(k.clone(), v.clone()); + } + } + self.values = full_value(&parse(&base)?)?; + Ok(()) + } + + pub(crate) fn apply(&self, tx: &mut Tx) -> Result { + let rig = parse(&self.values)?; + if rig.id() != self.id { + return Err(SceneError::value("id", "cannot change a rig's id")); + } + let i = index_of(tx.doc, &self.id)?; + rig.validate(tx.doc)?; + tx.rigs_mut()[i] = rig; + Ok(ChangeLevel::Full) + } +} + +impl AnimRigRef { + pub(crate) fn apply(&self, tx: &mut Tx) -> Result { + let i = index_of(tx.doc, &self.id)?; + tx.rigs_mut().remove(i); + Ok(ChangeLevel::Full) + } +} + +/// History merge target of a rig id (FNV-1a), so continuous edits of one rig merge into one step. +pub(crate) fn merge_target(id: &str) -> u64 { + id.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3)) +} diff --git a/native/crates/fsh-scene/src/animation/rigs/range.rs b/native/crates/fsh-scene/src/animation/rigs/range.rs new file mode 100644 index 00000000..c72cf45d --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/range.rs @@ -0,0 +1,71 @@ +//! The animation's frame rate and range as the rig commands read and set them, and the loop arithmetic of the +//! one-step helpers. + +use serde::{Deserialize, Serialize}; + +use crate::document::Document; +use crate::error::{Result, SceneError}; +use crate::tx::Tx; + +/// Frames per second when the animation gives none. +pub const DEFAULT_FPS: f32 = 30.0; +/// Range start in seconds when the animation gives none. +pub const DEFAULT_START: f32 = 0.0; +/// Range end in seconds when the animation gives none. +pub const DEFAULT_END: f32 = 4.0; + +/// Frame rate and range in seconds; frames run from `start` to `end` at `fps`, both ends included. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Range { + /// Frames per second. + pub fps: f32, + /// First frame's time. + pub start: f32, + /// Last frame's time. + pub end: f32, +} + +impl Default for Range { + fn default() -> Self { + Self { fps: DEFAULT_FPS, start: DEFAULT_START, end: DEFAULT_END } + } +} + +impl Range { + /// Duration of one frame. + pub fn frame(&self) -> f32 { + 1.0 / self.fps + } + + /// A range of `frames` frames from `start` at `fps`, with the span a cyclic rig needs so that the frame after the + /// last would repeat the first: the rig runs from `start` to `start + frames / fps`. + pub fn looping(fps: f32, start: f32, frames: u32) -> Result<(Self, f32)> { + check_fps(fps)?; + if frames < 2 { + return Err(SceneError::value("frames", "must be at least 2")); + } + let end = start as f64 + (frames - 1) as f64 / fps as f64; + let rig_end = start as f64 + frames as f64 / fps as f64; + Ok((Self { fps, start, end: end as f32 }, rig_end as f32)) + } +} + +pub(crate) fn check_fps(fps: f32) -> Result<()> { + if fps.is_finite() && (1.0..=1000.0).contains(&fps) { + Ok(()) + } else { + Err(SceneError::value("fps", "must be between 1 and 1000")) + } +} + +/// The document's frame rate and range. The animation does not store them yet, so this answers the defaults. +pub(crate) fn current(doc: &Document) -> Range { + let _ = doc; + Range::default() +} + +/// Sets the document's frame rate and range in the step. The animation does not store them yet, so nothing is kept +/// beyond the resolved command in history and the journal. +pub(crate) fn set(tx: &mut Tx, r: Range) { + let _ = (tx, r); +} diff --git a/native/crates/fsh-scene/src/command.rs b/native/crates/fsh-scene/src/command.rs index 8176da47..1e217851 100644 --- a/native/crates/fsh-scene/src/command.rs +++ b/native/crates/fsh-scene/src/command.rs @@ -1,3 +1,4 @@ +use crate::animation::rigs::commands::{AnimAddRig, AnimRigRef, AnimSetRig}; use crate::compile::{compile_material, TextureTable}; use crate::document::Document; use crate::error::{non_negative, Result, SceneError}; @@ -753,6 +754,9 @@ commands! { RenderSetSettings(PatchBlock) = "render.set_settings", Full, "Change resolution, samples, bounces, seed and denoising."; UnitsSetDisplay(UnitsSetDisplay) = "units.set_display", None, "Change the unit lengths are shown in; nothing moves."; DocumentSetInfo(PatchBlock) = "document.set_info", None, "Change document metadata (name, author, description)."; + AnimAddRig(AnimAddRig) = "anim.add_rig", Full, "Add a rig (turntable, orbit or camera_path): motion made from a few settings; fields left out take their defaults and the animation's range."; + AnimSetRig(AnimSetRig) = "anim.set_rig", Full, "Change a rig; give only the fields to change (null clears an optional one); its id and kind stay."; + AnimRemoveRig(AnimRigRef) = "anim.remove_rig", Full, "Remove a rig."; } fn deep_merge(base: &mut Value, patch: &Value) { @@ -978,6 +982,7 @@ impl Command { Command::EnvironmentSetPin(a) => k(a.id as u64), Command::EnvironmentSetImage(a) if a.path.is_none() && !a.clear => k(a.role as u64), Command::ImageSet(_) => k(0), + Command::AnimSetRig(a) => k(crate::animation::rigs::commands::merge_target(&a.id)), _ => None, } } @@ -1109,6 +1114,8 @@ impl Command { Command::EnvironmentSetPin(a) => a.resolve(doc)?, Command::EnvironmentSetImage(a) => a.resolve(doc)?, Command::StudioApplyPreset(a) => a.resolve(doc)?, + Command::AnimAddRig(a) => a.resolve(doc)?, + Command::AnimSetRig(a) => a.resolve(doc)?, _ => {} } Ok(()) @@ -1568,6 +1575,9 @@ impl Command { Command::EnvironmentRemovePin(a) => a.apply(tx).map(Applied::at), Command::EnvironmentSetImage(a) => a.apply(tx).map(|(level, created)| Applied { level, created }), Command::StudioApplyPreset(a) => a.apply(tx).map(|created| Applied { level: ChangeLevel::Full, created }), + Command::AnimAddRig(a) => a.apply(tx).map(Applied::at), + Command::AnimSetRig(a) => a.apply(tx).map(Applied::at), + Command::AnimRemoveRig(a) => a.apply(tx).map(Applied::at), } } } From ab97dea3189ed6f62e419c1d754c6600788c5181 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:41:47 -0500 Subject: [PATCH 015/471] feat(scene): add the one-step turntable helper with a seamless loop anim.turntable adds a turntable over the animation's range; with frames (or seconds rounded to frames) the range becomes exactly that many frames and the turn spans one frame more, so a 36-frame loop steps 10 degrees and never repeats its first frame. The rig and range are worked out on resolve so redo and replay repeat them; the orbit and camera path argument types land here too. Ran cargo check -p fsh-scene. --- .../fsh-scene/src/animation/rigs/commands.rs | 198 +++++++++++++++++- native/crates/fsh-scene/src/command.rs | 5 +- 2 files changed, 200 insertions(+), 3 deletions(-) diff --git a/native/crates/fsh-scene/src/animation/rigs/commands.rs b/native/crates/fsh-scene/src/animation/rigs/commands.rs index d0d562ca..bcb2f415 100644 --- a/native/crates/fsh-scene/src/animation/rigs/commands.rs +++ b/native/crates/fsh-scene/src/animation/rigs/commands.rs @@ -3,13 +3,207 @@ use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; -use super::range::{self, Range}; -use super::Rig; +use fsh_core::NodeId; + +use super::range::{self, check_fps, Range}; +use super::{Direction, Rig, Turntable}; use crate::command::{full_value, ChangeLevel}; use crate::document::Document; use crate::error::{Result, SceneError}; +use crate::ser; use crate::tx::Tx; +/// What a one-step helper adds and the frame rate and range it sets, worked out when the command is resolved so +/// redo and journal replay repeat it exactly. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct HelperPlan { + /// The rig added. + pub rig: Rig, + /// The animation's new frame rate and range, when the helper sets them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub range: Option, +} + +/// `anim.turntable` arguments. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimTurntable { + /// The node to turn; the whole product when absent. + #[serde(default, with = "ser::key_opt", skip_serializing_if = "Option::is_none")] + pub node: Option, + /// Full turns over the loop; 1 when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turns: Option, + /// Frames in the loop: the range becomes exactly this many frames and the turn spans one frame more, so the + /// frame after the last would repeat the first. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub frames: Option, + /// Frames per second; the animation's when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fps: Option, + /// Loop length in seconds, used when `frames` is absent (rounded to whole frames). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seconds: Option, + /// Turning direction seen from above; counterclockwise when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub direction: Option, + /// Id of the new rig; the lowest free `turntable` when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Filled in when resolved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, +} + +const MAX_FRAMES: u32 = 1_000_000; + +impl AnimTurntable { + pub(crate) fn resolve(&mut self, doc: &mut Document) -> Result<()> { + let cur = range::current(doc); + let fps = self.fps.unwrap_or(cur.fps); + check_fps(fps)?; + let frames = match (self.frames, self.seconds) { + (Some(n), _) => Some(n), + (None, Some(s)) if s.is_finite() && s > 0.0 => Some((s as f64 * fps as f64).round().max(2.0).min(MAX_FRAMES as f64) as u32), + (None, Some(_)) => return Err(SceneError::value("seconds", "must be a positive number")), + (None, None) => None, + }; + if frames.is_some_and(|n| n > MAX_FRAMES) { + return Err(SceneError::value("frames", format!("must be at most {MAX_FRAMES}"))); + } + let (new_range, start, end) = match frames { + Some(n) => { + let (r, end) = Range::looping(fps, cur.start, n)?; + (Some(r), cur.start, end) + } + None => { + let r = Range { fps, ..cur }; + let (start, end) = default_times(&r, true); + (self.fps.map(|_| r), start, end) + } + }; + let rig = Turntable { + id: self.id.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| fresh_id(doc, "turntable")), + name: default_name("turntable").into(), + node: self.node, + turns: self.turns.unwrap_or(1.0), + start, + end, + direction: self.direction.unwrap_or_default(), + ..Turntable::default() + }; + self.plan = Some(HelperPlan { rig: Rig::Turntable(rig), range: new_range }); + Ok(()) + } +} + +/// `anim.orbit` arguments. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimOrbit { + /// Camera index; the active camera when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub camera: Option, + /// Full turns; 1 when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub turns: Option, + /// Direction the camera travels seen from above; counterclockwise when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub direction: Option, + /// Start time in seconds; the range's start when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, + /// End time in seconds; one frame past the range's end when absent, so the orbit loops. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end: Option, + /// Fraction 0..1 of the run spent speeding up. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ease_in: Option, + /// Fraction 0..1 of the run spent slowing down. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ease_out: Option, + /// Id of the new rig; the lowest free `orbit` when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Filled in when resolved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, +} + +/// `anim.camera_path` arguments. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AnimCameraPath { + /// Camera index; the active camera when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub camera: Option, + /// Control points in metres. + #[serde(default)] + pub points: Vec<[f32; 3]>, + /// What the camera looks at, `{"point": [x, y, z]}` or `{"node": id}`; the product's centre when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub look_at: Option, + /// The curve returns to its first point. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub closed: Option, + /// Roll in degrees; positive banks to the right. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub roll: Option, + /// Start time in seconds; the range's start when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, + /// End time in seconds; the range's end when absent (one frame past it for a closed path). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub end: Option, + /// Fraction 0..1 of the run spent speeding up. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ease_in: Option, + /// Fraction 0..1 of the run spent slowing down. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ease_out: Option, + /// Id of the new rig; the lowest free `path` when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id: Option, + /// Filled in when resolved. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub plan: Option, +} + +fn helper_plan(doc: &Document, args: &T, kind: &str) -> Result { + let mut v = full_value(args)?; + let obj = v.as_object_mut().ok_or_else(|| invalid("arguments must be an object"))?; + obj.remove("plan"); + obj.insert("kind".into(), kind.into()); + Ok(HelperPlan { rig: complete(doc, &v)?, range: None }) +} + +impl AnimOrbit { + pub(crate) fn resolve(&mut self, doc: &mut Document) -> Result<()> { + self.plan = None; + self.plan = Some(helper_plan(doc, self, "orbit")?); + Ok(()) + } +} + +impl AnimCameraPath { + pub(crate) fn resolve(&mut self, doc: &mut Document) -> Result<()> { + self.plan = None; + self.plan = Some(helper_plan(doc, self, "camera_path")?); + Ok(()) + } +} + +/// Adds a helper's planned rig and sets its range in the step. +pub(crate) fn apply_plan(tx: &mut Tx, plan: &Option) -> Result { + let plan = plan.as_ref().ok_or_else(crate::command::unresolved)?; + insert(tx, plan.rig.clone(), None)?; + if let Some(r) = plan.range { + check_fps(r.fps)?; + range::set(tx, r); + } + Ok(ChangeLevel::Full) +} + /// `anim.add_rig` arguments. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/native/crates/fsh-scene/src/command.rs b/native/crates/fsh-scene/src/command.rs index 1e217851..f5e0a164 100644 --- a/native/crates/fsh-scene/src/command.rs +++ b/native/crates/fsh-scene/src/command.rs @@ -1,4 +1,4 @@ -use crate::animation::rigs::commands::{AnimAddRig, AnimRigRef, AnimSetRig}; +use crate::animation::rigs::commands::{apply_plan, AnimAddRig, AnimRigRef, AnimSetRig, AnimTurntable}; use crate::compile::{compile_material, TextureTable}; use crate::document::Document; use crate::error::{non_negative, Result, SceneError}; @@ -757,6 +757,7 @@ commands! { AnimAddRig(AnimAddRig) = "anim.add_rig", Full, "Add a rig (turntable, orbit or camera_path): motion made from a few settings; fields left out take their defaults and the animation's range."; AnimSetRig(AnimSetRig) = "anim.set_rig", Full, "Change a rig; give only the fields to change (null clears an optional one); its id and kind stay."; AnimRemoveRig(AnimRigRef) = "anim.remove_rig", Full, "Remove a rig."; + AnimTurntable(AnimTurntable) = "anim.turntable", Full, "Turn the product (or one node) about its centre as a seamless loop over the animation's range; frames or seconds set the range to exactly that many frames, the turn spanning one frame more so no frame repeats."; } fn deep_merge(base: &mut Value, patch: &Value) { @@ -1116,6 +1117,7 @@ impl Command { Command::StudioApplyPreset(a) => a.resolve(doc)?, Command::AnimAddRig(a) => a.resolve(doc)?, Command::AnimSetRig(a) => a.resolve(doc)?, + Command::AnimTurntable(a) => a.resolve(doc)?, _ => {} } Ok(()) @@ -1578,6 +1580,7 @@ impl Command { Command::AnimAddRig(a) => a.apply(tx).map(Applied::at), Command::AnimSetRig(a) => a.apply(tx).map(Applied::at), Command::AnimRemoveRig(a) => a.apply(tx).map(Applied::at), + Command::AnimTurntable(a) => apply_plan(tx, &a.plan).map(Applied::at), } } } From fc2aef74c17c65566f7fe20bf338b04549ed4823 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:42:08 -0500 Subject: [PATCH 016/471] feat(scene): add the one-step orbit and camera path helpers anim.orbit and anim.camera_path add an orbit or a camera path for the active camera unless one is named, over the animation's range, through the same completion as anim.add_rig. Ran cargo check -p fsh-scene. --- native/crates/fsh-scene/src/command.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/native/crates/fsh-scene/src/command.rs b/native/crates/fsh-scene/src/command.rs index f5e0a164..c8eca0e4 100644 --- a/native/crates/fsh-scene/src/command.rs +++ b/native/crates/fsh-scene/src/command.rs @@ -1,4 +1,6 @@ -use crate::animation::rigs::commands::{apply_plan, AnimAddRig, AnimRigRef, AnimSetRig, AnimTurntable}; +use crate::animation::rigs::commands::{ + apply_plan, AnimAddRig, AnimCameraPath, AnimOrbit, AnimRigRef, AnimSetRig, AnimTurntable, +}; use crate::compile::{compile_material, TextureTable}; use crate::document::Document; use crate::error::{non_negative, Result, SceneError}; @@ -758,6 +760,8 @@ commands! { AnimSetRig(AnimSetRig) = "anim.set_rig", Full, "Change a rig; give only the fields to change (null clears an optional one); its id and kind stay."; AnimRemoveRig(AnimRigRef) = "anim.remove_rig", Full, "Remove a rig."; AnimTurntable(AnimTurntable) = "anim.turntable", Full, "Turn the product (or one node) about its centre as a seamless loop over the animation's range; frames or seconds set the range to exactly that many frames, the turn spanning one frame more so no frame repeats."; + AnimOrbit(AnimOrbit) = "anim.orbit", Full, "Circle a camera (the active one by default) around the product at its current distance and height, looking at the product's centre, as a loop over the animation's range."; + AnimCameraPath(AnimCameraPath) = "anim.camera_path", Full, "Move a camera (the active one by default) along a smooth curve through points at constant speed over the animation's range, looking at a point, a node or the product's centre."; } fn deep_merge(base: &mut Value, patch: &Value) { @@ -1118,6 +1122,8 @@ impl Command { Command::AnimAddRig(a) => a.resolve(doc)?, Command::AnimSetRig(a) => a.resolve(doc)?, Command::AnimTurntable(a) => a.resolve(doc)?, + Command::AnimOrbit(a) => a.resolve(doc)?, + Command::AnimCameraPath(a) => a.resolve(doc)?, _ => {} } Ok(()) @@ -1581,6 +1587,8 @@ impl Command { Command::AnimSetRig(a) => a.apply(tx).map(Applied::at), Command::AnimRemoveRig(a) => a.apply(tx).map(Applied::at), Command::AnimTurntable(a) => apply_plan(tx, &a.plan).map(Applied::at), + Command::AnimOrbit(a) => apply_plan(tx, &a.plan).map(Applied::at), + Command::AnimCameraPath(a) => apply_plan(tx, &a.plan).map(Applied::at), } } } From 77fa098e5c59bd5eb2a3377766614560f6cbf8f1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:48:21 -0500 Subject: [PATCH 017/471] feat(scene): describe the rig commands in the catalogue The six anim rig commands get argument schemas (a rig is one of three object shapes told apart by kind) and anim.set_rig is listed as mergeable. A scratch program printed the catalogue entries, ran each command with good and bad arguments, undo and redo, and round-tripped a resolved command and the document through JSON. --- native/crates/fsh-scene/src/animation/rigs.rs | 1 + .../fsh-scene/src/animation/rigs/schema.rs | 158 ++++++++++++++++++ native/crates/fsh-scene/src/catalogue.rs | 4 + 3 files changed, 163 insertions(+) create mode 100644 native/crates/fsh-scene/src/animation/rigs/schema.rs diff --git a/native/crates/fsh-scene/src/animation/rigs.rs b/native/crates/fsh-scene/src/animation/rigs.rs index 27b930a1..1ec29de9 100644 --- a/native/crates/fsh-scene/src/animation/rigs.rs +++ b/native/crates/fsh-scene/src/animation/rigs.rs @@ -5,6 +5,7 @@ mod orbit; mod path; mod range; mod scene; +pub(crate) mod schema; mod spline; mod timing; mod turntable; diff --git a/native/crates/fsh-scene/src/animation/rigs/schema.rs b/native/crates/fsh-scene/src/animation/rigs/schema.rs new file mode 100644 index 00000000..223d59d8 --- /dev/null +++ b/native/crates/fsh-scene/src/animation/rigs/schema.rs @@ -0,0 +1,158 @@ +//! JSON Schemas of the rig commands, for the catalogue. + +use serde_json::{json, Map, Value}; + +fn obj(props: Vec<(&str, Value)>, required: &[&str]) -> Value { + let mut p = Map::new(); + for (k, v) in props { + p.insert(k.to_string(), v); + } + json!({"type": "object", "properties": p, "required": required, "additionalProperties": false}) +} + +fn num(desc: &str) -> Value { + json!({"type": "number", "description": desc}) +} + +fn fraction(desc: &str) -> Value { + json!({"type": "number", "minimum": 0.0, "maximum": 1.0, "description": desc}) +} + +fn id(desc: &str) -> Value { + json!({"type": "string", "pattern": "^[A-Za-z0-9_-]{1,64}$", "description": desc}) +} + +fn camera() -> Value { + json!({"type": "integer", "minimum": 0, "description": "Camera index; the active camera when absent"}) +} + +fn node(desc: &str) -> Value { + json!({"type": "integer", "minimum": 1, "description": desc}) +} + +fn direction() -> Value { + json!({"type": "string", "enum": ["ccw", "cw"], "description": "Direction seen from above: ccw (counterclockwise, default) or cw"}) +} + +fn points() -> Value { + json!({ + "type": "array", + "items": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}, + "description": "Control points [x, y, z] in metres; the curve passes through each (2 or more, 3 or more when closed)" + }) +} + +fn look_at() -> Value { + json!({ + "anyOf": [ + {"type": "object", "properties": {"point": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3}}, "required": ["point"], "additionalProperties": false}, + {"type": "object", "properties": {"node": {"type": "integer", "minimum": 1}}, "required": ["node"], "additionalProperties": false}, + {"type": "null"} + ], + "description": "What the camera looks at: {\"point\": [x, y, z]} or {\"node\": id} (its centre, following it); the product's centre when absent" + }) +} + +fn timing() -> Vec<(&'static str, Value)> { + vec![ + ("start", num("Start time in seconds; the animation's start when absent")), + ("end", num("End time in seconds; when absent the animation's end, one frame past it for motion that loops")), + ("ease_in", fraction("Share of the run spent speeding up from rest (0, the default, starts at full speed)")), + ("ease_out", fraction("Share of the run spent slowing down to rest; ease_in + ease_out at most 1")), + ] +} + +fn common(kind: &str) -> Vec<(&'static str, Value)> { + vec![ + ("kind", json!({"type": "string", "const": kind})), + ("id", id("Rig id; the kind's prefix with the lowest free number when absent")), + ("name", json!({"type": "string", "description": "Display name"})), + ] +} + +fn turntable_props() -> Vec<(&'static str, Value)> { + vec![ + ("node", node("Node turned with everything under it; the whole product when absent")), + ("turns", num("Full turns from start to end; fractions allowed (default 1)")), + ("direction", direction()), + ("start_angle", num("Degrees already turned at the start (default 0)")), + ] +} + +fn orbit_props() -> Vec<(&'static str, Value)> { + vec![("camera", camera()), ("turns", num("Full turns from start to end (default 1)")), ("direction", direction())] +} + +fn path_props() -> Vec<(&'static str, Value)> { + vec![ + ("camera", camera()), + ("points", points()), + ("closed", json!({"type": "boolean", "description": "The curve returns smoothly to its first point"})), + ("look_at", look_at()), + ("roll", num("Roll in degrees about the viewing direction; positive banks to the right")), + ] +} + +fn rig_of(kind: &str, extra: Vec<(&'static str, Value)>) -> Value { + let mut p = common(kind); + p.extend(extra); + p.extend(timing()); + obj(p, &["kind"]) +} + +fn rig() -> Value { + json!({ + "anyOf": [ + rig_of("turntable", turntable_props()), + rig_of("orbit", orbit_props()), + rig_of("camera_path", path_props()), + ], + "description": "A rig with its kind: turntable, orbit or camera_path; fields left out take their defaults" + }) +} + +fn values() -> Value { + let mut p = Map::new(); + for (k, v) in turntable_props().into_iter().chain(orbit_props()).chain(path_props()).chain(timing()) { + p.insert(k.to_string(), v); + } + p.insert("name".into(), json!({"type": "string", "description": "Display name"})); + json!({"type": "object", "properties": p, "description": "Fields to change; null clears an optional one"}) +} + +/// The argument schema of a rig command, or `None` for other names. +pub(crate) fn command_schema(name: &str) -> Option { + Some(match name { + "anim.add_rig" => obj( + vec![("rig", rig()), ("index", json!({"type": "integer", "minimum": 0, "description": "Position in the rig list; last when absent"}))], + &["rig"], + ), + "anim.set_rig" => obj(vec![("id", id("Rig id")), ("values", values())], &["id", "values"]), + "anim.remove_rig" => obj(vec![("id", id("Rig id"))], &["id"]), + "anim.turntable" => obj( + vec![ + ("node", node("Node to turn; the whole product when absent")), + ("turns", num("Full turns over the loop (default 1)")), + ("frames", json!({"type": "integer", "minimum": 2, "description": "Frames in the loop: the range becomes exactly this many frames and the turn spans one more, so the loop is seamless"})), + ("fps", json!({"type": "number", "minimum": 1, "maximum": 1000, "description": "Frames per second; the animation's when absent"})), + ("seconds", json!({"type": "number", "exclusiveMinimum": 0, "description": "Loop length in seconds when frames is absent (rounded to whole frames)"})), + ("direction", direction()), + ("id", id("Id of the new rig; turntable when absent")), + ], + &[], + ), + "anim.orbit" => { + let mut p = orbit_props(); + p.extend(timing()); + p.push(("id", id("Id of the new rig; orbit when absent"))); + obj(p, &[]) + } + "anim.camera_path" => { + let mut p = path_props(); + p.extend(timing()); + p.push(("id", id("Id of the new rig; path when absent"))); + obj(p, &["points"]) + } + _ => return None, + }) +} diff --git a/native/crates/fsh-scene/src/catalogue.rs b/native/crates/fsh-scene/src/catalogue.rs index 5be8808e..6cf808b6 100644 --- a/native/crates/fsh-scene/src/catalogue.rs +++ b/native/crates/fsh-scene/src/catalogue.rs @@ -40,6 +40,7 @@ const MERGEABLE: &[&str] = &[ "light.set_ies", "environment.set_pin", "environment.set_image", + "anim.set_rig", ]; /// Every command with its name, description, argument schema and change level. @@ -713,6 +714,9 @@ fn schema(name: &str) -> Value { &["unit"], ), "document.set_info" => patch(block::()), + "anim.add_rig" | "anim.set_rig" | "anim.remove_rig" | "anim.turntable" | "anim.orbit" | "anim.camera_path" => { + crate::animation::rigs::schema::command_schema(name).unwrap_or_else(|| obj(vec![], &[])) + } _ => crate::lighting::schema::command_schema(name, lighting_block).unwrap_or_else(|| obj(vec![], &[])), } } From 5511c1b736c2b93f4a47202b6801d8fe9de66f9e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 14:01:28 -0500 Subject: [PATCH 018/471] feat(scene): keep an explicit focus distance on cameras moved by rigs Orbits and camera paths now carry a camera's explicit focus distance along with its distance to the target when the camera keeps focus, as camera moves already do. A scratch program moved a keep-focus camera along a path and saw the gap between focus and target distance stay at -1.1662 m at 0, 2 and 4 seconds. --- native/crates/fsh-scene/src/animation/rigs/orbit.rs | 2 ++ native/crates/fsh-scene/src/animation/rigs/path.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/native/crates/fsh-scene/src/animation/rigs/orbit.rs b/native/crates/fsh-scene/src/animation/rigs/orbit.rs index 7608ff98..98b5ca5d 100644 --- a/native/crates/fsh-scene/src/animation/rigs/orbit.rs +++ b/native/crates/fsh-scene/src/animation/rigs/orbit.rs @@ -68,6 +68,7 @@ impl Orbit { pub(super) fn apply(&self, centre: Option, d: &mut DocumentData, time: f32) { let Some(cam) = d.cameras.get_mut(self.camera) else { return }; + let before = cam.clone(); let c = centre.unwrap_or(cam.target); let o = cam.position - c; let r = (o.x * o.x + o.z * o.z).sqrt(); @@ -76,5 +77,6 @@ impl Orbit { cam.position = c + Vec3::new(r * s, o.y, r * k); cam.target = c; cam.up = Vec3::Y; + cam.focus_distance = cam.kept_focus(&before); } } diff --git a/native/crates/fsh-scene/src/animation/rigs/path.rs b/native/crates/fsh-scene/src/animation/rigs/path.rs index 29b4da04..5ce6494d 100644 --- a/native/crates/fsh-scene/src/animation/rigs/path.rs +++ b/native/crates/fsh-scene/src/animation/rigs/path.rs @@ -137,11 +137,13 @@ impl CameraPath { Look::Own => None, }; let Some(cam) = d.cameras.get_mut(self.camera) else { return }; + let before = cam.clone(); let p = progress(self.start, self.end, self.ease_in, self.ease_out, time); cam.position = spline.at_fraction(p as f64); if let Some(t) = target { cam.target = t; } + cam.focus_distance = cam.kept_focus(&before); let Some(f) = (cam.target - cam.position).try_normalize() else { return }; let up0 = Vec3::Y - f * f.dot(Vec3::Y); let Some(up0) = up0.try_normalize() else { return }; From 41921f986a7a89e4359dfd08a48480398d83b8f5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:03 -0500 Subject: [PATCH 019/471] feat(video): find ffmpeg through the env, family folder and path Adds the ffmpeg finder: FORMSHOT_FFMPEG first, then the Form family's shared install folder (formcut-binaries/ffmpeg-/ffmpeg-, the pinned release before others), then ffmpeg on the PATH. Checked with cargo check -p fsh-commands. --- .../crates/fsh-commands/src/ext/video/find.rs | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 native/crates/fsh-commands/src/ext/video/find.rs diff --git a/native/crates/fsh-commands/src/ext/video/find.rs b/native/crates/fsh-commands/src/ext/video/find.rs new file mode 100644 index 00000000..76787f1c --- /dev/null +++ b/native/crates/fsh-commands/src/ext/video/find.rs @@ -0,0 +1,105 @@ +//! Where ffmpeg is: `FORMSHOT_FFMPEG`, the Form family's shared install folder, then the PATH. + +use std::path::{Path, PathBuf}; + +/// The family build FormShot pins (formai-binaries release `ffmpeg-`); the service downloads it. +pub(crate) const RELEASE: &str = "7.1.5-2"; + +/// The variable that names an ffmpeg program to use before any other. +pub(crate) const ENV: &str = "FORMSHOT_FFMPEG"; + +/// An ffmpeg program and how it was found. +#[derive(Clone, Debug)] +pub(crate) struct Found { + pub path: PathBuf, + pub source: &'static str, + pub release: Option, +} + +/// The target triple the family names its builds by. +pub(crate) fn triple() -> &'static str { + match (cfg!(target_arch = "aarch64"), cfg!(target_os = "macos"), cfg!(windows)) { + (true, true, _) => "aarch64-apple-darwin", + (false, true, _) => "x86_64-apple-darwin", + (_, _, true) => "x86_64-pc-windows-msvc", + _ => "x86_64-unknown-linux-gnu", + } +} + +fn exe(stem: &str) -> String { + if cfg!(windows) { + format!("{stem}.exe") + } else { + stem.to_string() + } +} + +fn env_dir(name: &str) -> Option { + std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from) +} + +/// The user data folder the Form apps share (`~/Library/Application Support`, `%LOCALAPPDATA%`, or +/// `$XDG_DATA_HOME`, else `~/.local/share`). +fn data_dir() -> Option { + let home = env_dir("HOME").or_else(|| env_dir("USERPROFILE")); + if cfg!(target_os = "macos") { + home.map(|h| h.join("Library").join("Application Support")) + } else if cfg!(windows) { + env_dir("LOCALAPPDATA").or_else(|| home.map(|h| h.join("AppData").join("Local"))) + } else { + env_dir("XDG_DATA_HOME").or_else(|| home.map(|h| h.join(".local").join("share"))) + } +} + +/// The family's install root, `/formcut-binaries`, where every Form app puts the ffmpeg it downloads. +pub(crate) fn family_root() -> Option { + data_dir().map(|d| d.join("formcut-binaries")) +} + +/// The folder the pinned release installs into. +pub(crate) fn family_folder() -> Option { + family_root().map(|r| r.join(format!("ffmpeg-{RELEASE}"))) +} + +fn family_program(folder: &Path) -> PathBuf { + folder.join(exe(&format!("ffmpeg-{}", triple()))) +} + +/// Installed family builds, the pinned release first, then the others newest name first. +fn family() -> Vec<(String, PathBuf)> { + let Some(root) = family_root() else { return Vec::new() }; + let mut others: Vec<(String, PathBuf)> = std::fs::read_dir(&root) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let name = e.file_name().to_str()?.to_string(); + let release = name.strip_prefix("ffmpeg-")?.to_string(); + let program = family_program(&e.path()); + (release != RELEASE && program.is_file()).then_some((release, program)) + }) + .collect(); + others.sort_by(|a, b| b.0.cmp(&a.0)); + let pinned = family_folder().map(|f| family_program(&f)).filter(|p| p.is_file()).map(|p| (RELEASE.to_string(), p)); + pinned.into_iter().chain(others).collect() +} + +fn on_path() -> Option { + let paths = std::env::var_os("PATH")?; + std::env::split_paths(&paths).map(|d| d.join(exe("ffmpeg"))).find(|p| p.is_file()) +} + +/// The ffmpeg to run, and notes on places that were looked at and passed over. +pub(crate) fn find() -> (Option, Vec) { + let mut notes = Vec::new(); + if let Some(p) = env_dir(ENV) { + if p.is_file() { + return (Some(Found { path: p, source: "FORMSHOT_FFMPEG", release: None }), notes); + } + notes.push(format!("{ENV} names {}, which is not a file; looking further", p.display())); + } + if let Some((release, path)) = family().into_iter().next() { + return (Some(Found { path, source: "family", release: Some(release) }), notes); + } + (on_path().map(|path| Found { path, source: "PATH", release: None }), notes) +} From 35fe35f01da2ecd68a3c2c7d60c910c7e0427994 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:03 -0500 Subject: [PATCH 020/471] feat(video): probe ffmpeg's version and encoders once per program Reads the version line, the configuration and the video encoders of an ffmpeg program once per file, and tests a listed hardware H.264 encoder with two small frames before trusting it. Checked with cargo check -p fsh-commands. --- .../fsh-commands/src/ext/video/probe.rs | 146 ++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 native/crates/fsh-commands/src/ext/video/probe.rs diff --git a/native/crates/fsh-commands/src/ext/video/probe.rs b/native/crates/fsh-commands/src/ext/video/probe.rs new file mode 100644 index 00000000..ae0f0b60 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/video/probe.rs @@ -0,0 +1,146 @@ +//! What an ffmpeg program is: its version line and its video encoders, read once per program file, and whether a +//! hardware H.264 encoder it lists really opens on this machine. + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +/// One ffmpeg program as probed. +#[derive(Debug)] +pub(crate) struct Probe { + pub version: String, + pub encoders: BTreeSet, + pub configuration: String, + hardware: Mutex>, +} + +type Key = (PathBuf, Option, u64); + +static PROBES: Mutex>> = Mutex::new(BTreeMap::new()); + +/// Runs `program args`, waiting at most `limit`; answers the exit status's success, stdout and stderr. +pub(crate) fn run(program: &Path, args: &[&str], limit: Duration) -> Result<(bool, String, String), String> { + let mut child = Command::new(program) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("{} could not be started: {e}", program.display()))?; + let mut out = child.stdout.take(); + let mut err = child.stderr.take(); + let reader = std::thread::spawn(move || { + let mut s = String::new(); + if let Some(o) = out.as_mut() { + let _ = o.read_to_string(&mut s); + } + s + }); + let err_reader = std::thread::spawn(move || { + let mut s = String::new(); + if let Some(e) = err.as_mut() { + let _ = e.read_to_string(&mut s); + } + s + }); + let t0 = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(s)) => break Some(s), + Ok(None) if t0.elapsed() > limit => { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + Ok(None) => std::thread::sleep(Duration::from_millis(20)), + Err(e) => return Err(format!("{} could not be waited for: {e}", program.display())), + } + }; + let stdout = reader.join().unwrap_or_default(); + let stderr = err_reader.join().unwrap_or_default(); + match status { + Some(s) => Ok((s.success(), stdout, stderr)), + None => Err(format!("{} did not answer within {} s", program.display(), limit.as_secs())), + } +} + +fn parse_encoders(listing: &str) -> BTreeSet { + listing + .lines() + .skip_while(|l| !l.trim_start().starts_with("------")) + .skip(1) + .filter_map(|l| { + let mut words = l.split_whitespace(); + let flags = words.next()?; + let name = words.next()?; + flags.starts_with('V').then(|| name.to_string()) + }) + .collect() +} + +/// The probe of `program`, made once per program file (path, modification time and size). +pub(crate) fn probe(program: &Path) -> Result, String> { + let meta = std::fs::metadata(program).map_err(|e| format!("{} cannot be read: {e}", program.display()))?; + let key = (program.to_path_buf(), meta.modified().ok(), meta.len()); + if let Some(p) = PROBES.lock().unwrap_or_else(|p| p.into_inner()).get(&key) { + return Ok(Arc::clone(p)); + } + let (ok, version_text, err) = run(program, &["-hide_banner", "-version"], Duration::from_secs(20))?; + if !ok { + return Err(format!("{} -version failed: {}", program.display(), tail(&err, 300))); + } + let first = version_text.lines().next().unwrap_or("").trim(); + let version = first.strip_prefix("ffmpeg version ").and_then(|v| v.split_whitespace().next()).unwrap_or(first).to_string(); + let configuration = version_text + .lines() + .find_map(|l| l.trim().strip_prefix("configuration:")) + .unwrap_or("") + .trim() + .to_string(); + let (ok, listing, err) = run(program, &["-hide_banner", "-encoders"], Duration::from_secs(20))?; + if !ok { + return Err(format!("{} -encoders failed: {}", program.display(), tail(&err, 300))); + } + let p = Arc::new(Probe { version, encoders: parse_encoders(&listing), configuration, hardware: Mutex::new(BTreeMap::new()) }); + PROBES.lock().unwrap_or_else(|p| p.into_inner()).insert(key, Arc::clone(&p)); + Ok(p) +} + +/// The last `max` bytes of ffmpeg's messages, on a character boundary, trimmed. +pub(crate) fn tail(text: &str, max: usize) -> String { + let t = text.trim(); + let mut start = t.len().saturating_sub(max); + while !t.is_char_boundary(start) { + start += 1; + } + t[start..].trim().to_string() +} + +impl Probe { + /// True when ffmpeg lists `encoder`. + pub(crate) fn has(&self, encoder: &str) -> bool { + self.encoders.contains(encoder) + } + + /// True when the listed hardware encoder opens and encodes two small frames here (tested once per program). + pub(crate) fn hardware_works(&self, program: &Path, encoder: &str) -> bool { + if !self.has(encoder) { + return false; + } + if let Some(ok) = self.hardware.lock().unwrap_or_else(|p| p.into_inner()).get(encoder) { + return *ok; + } + let mut args: Vec = vec!["-hide_banner".into(), "-loglevel".into(), "error".into()]; + args.extend(super::encoders::device_args(encoder)); + args.extend(["-f", "lavfi", "-i", "color=c=gray:s=256x256:r=10:d=0.3", "-frames:v", "2"].map(String::from)); + args.extend(super::encoders::hardware_filter(encoder).into_iter().flat_map(|f| ["-vf".to_string(), f])); + args.extend(["-c:v", encoder, "-b:v", "1M", "-f", "null", "-"].map(String::from)); + let refs: Vec<&str> = args.iter().map(String::as_str).collect(); + let ok = matches!(run(program, &refs, Duration::from_secs(20)), Ok((true, _, _))); + self.hardware.lock().unwrap_or_else(|p| p.into_inner()).insert(encoder.to_string(), ok); + ok + } +} From 764322c0daf4ec22cb44cbc4f5c11992e209f04a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:03 -0500 Subject: [PATCH 021/471] feat(video): choose an encoder per movie format with its arguments MP4 prefers a working hardware H.264 encoder, then libx264 when listed, then MPEG-4 Part 2; WebM uses libvpx-vp9, MOV ProRes through prores_ks and GIF a generated palette, with even sizes, yuv420p and one quality scale mapped to each encoder. Checked with cargo check -p fsh-commands. --- .../fsh-commands/src/ext/video/encoders.rs | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 native/crates/fsh-commands/src/ext/video/encoders.rs diff --git a/native/crates/fsh-commands/src/ext/video/encoders.rs b/native/crates/fsh-commands/src/ext/video/encoders.rs new file mode 100644 index 00000000..ef2093c7 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/video/encoders.rs @@ -0,0 +1,209 @@ +//! The movie formats, the encoder each one prefers from what ffmpeg lists, and the ffmpeg arguments of each encoder. + +/// A movie container and the codec family it holds. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Format { + Mp4, + Webm, + Mov, + Gif, +} + +impl Format { + pub(crate) const ALL: [Format; 4] = [Format::Mp4, Format::Webm, Format::Mov, Format::Gif]; + + pub(crate) fn parse(s: &str) -> Option { + match s.trim().trim_start_matches('.').to_ascii_lowercase().as_str() { + "mp4" | "m4v" => Some(Format::Mp4), + "webm" => Some(Format::Webm), + "mov" | "prores" => Some(Format::Mov), + "gif" => Some(Format::Gif), + _ => None, + } + } + + /// The name, which is also the file extension and ffmpeg's muxer name. + pub(crate) fn name(self) -> &'static str { + match self { + Format::Mp4 => "mp4", + Format::Webm => "webm", + Format::Mov => "mov", + Format::Gif => "gif", + } + } + + /// True when the codec needs an even width and height. + fn even(self) -> bool { + !matches!(self, Format::Gif) + } +} + +/// The hardware H.264 encoders tried for MP4, in order, when ffmpeg lists them. +pub(crate) const HARDWARE_H264: [&str; 6] = ["h264_videotoolbox", "h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "h264_vaapi"]; + +/// Every encoder FormShot can use. +pub(crate) const OURS: [&str; 11] = + ["h264_videotoolbox", "h264_nvenc", "h264_qsv", "h264_amf", "h264_mf", "h264_vaapi", "libx264", "mpeg4", "libvpx-vp9", "prores_ks", "gif"]; + +/// The encoders to try for `format`, best first: a hardware H.264 encoder that opens here, libx264 when this +/// ffmpeg has it (the family's LGPL build never does), then MPEG-4 Part 2 for MP4; VP9, ProRes and GIF otherwise. +pub(crate) fn candidates(format: Format, listed: &dyn Fn(&str) -> bool, hardware_ok: &mut dyn FnMut(&str) -> bool) -> Vec<&'static str> { + match format { + Format::Mp4 => { + let mut out: Vec<&'static str> = HARDWARE_H264.iter().copied().filter(|e| listed(e) && hardware_ok(e)).collect(); + out.extend(["libx264", "mpeg4"].into_iter().filter(|e| listed(e))); + out + } + Format::Webm => ["libvpx-vp9"].into_iter().filter(|e| listed(e)).collect(), + Format::Mov => ["prores_ks"].into_iter().filter(|e| listed(e)).collect(), + Format::Gif => ["gif"].into_iter().filter(|e| listed(e)).collect(), + } +} + +/// What a format needs that ffmpeg did not list, for the refusal. +pub(crate) fn needs(format: Format) -> &'static str { + match format { + Format::Mp4 => "an H.264 encoder (hardware or libx264) or mpeg4", + Format::Webm => "the libvpx-vp9 encoder", + Format::Mov => "the prores_ks encoder", + Format::Gif => "the gif encoder", + } +} + +/// The codec an encoder writes, in words. +pub(crate) fn codec(encoder: &str, alpha: bool) -> &'static str { + match encoder { + "mpeg4" => "MPEG-4 Part 2", + "libvpx-vp9" => "VP9", + "prores_ks" if alpha => "ProRes 4444", + "prores_ks" => "ProRes 422", + "gif" => "GIF", + _ => "H.264", + } +} + +/// True for the hardware encoders. +pub(crate) fn hardware(encoder: &str) -> bool { + HARDWARE_H264.contains(&encoder) +} + +/// Arguments a hardware encoder needs before the input (the VA-API device). +pub(crate) fn device_args(encoder: &str) -> Vec { + match encoder { + "h264_vaapi" => vec!["-vaapi_device".into(), "/dev/dri/renderD128".into()], + _ => Vec::new(), + } +} + +/// The upload filter a hardware encoder needs at the end of the chain. +pub(crate) fn hardware_filter(encoder: &str) -> Option { + match encoder { + "h264_vaapi" => Some("format=nv12,hwupload".into()), + "h264_qsv" => Some("format=nv12".into()), + _ => None, + } +} + +/// What the encode knows about the movie. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Settings { + pub format: Format, + pub fps: f32, + pub quality: u32, + pub width: u32, + pub height: u32, + pub alpha: bool, +} + +/// The frame rate as ffmpeg takes it: whole numbers as they are, the NTSC rates as n*1000/1001, others as a +/// fraction over 1000. +pub(crate) fn rate(fps: f32) -> String { + let fps = fps.clamp(0.1, 1000.0) as f64; + for n in [24.0, 30.0, 60.0, 120.0] { + if (fps - n * 1000.0 / 1001.0).abs() < 0.005 { + return format!("{}/1001", n * 1000.0); + } + } + if (fps - fps.round()).abs() < 1e-4 { + return format!("{}", fps.round() as u32); + } + let (mut a, mut b) = ((fps * 1000.0).round() as u64, 1000u64); + let mut g = (a, b); + while g.1 != 0 { + g = (g.1, g.0 % g.1); + } + a /= g.0.max(1); + b /= g.0.max(1); + format!("{a}/{b}") +} + +fn lerp(q: u32, at1: f32, at100: f32) -> f32 { + let t = (q.clamp(1, 100) - 1) as f32 / 99.0; + at1 + (at100 - at1) * t +} + +/// The ffmpeg arguments between the input and the output file: filters, codec, quality and container flags. +pub(crate) fn output_args(encoder: &str, s: &Settings) -> Vec { + let mut a: Vec = Vec::new(); + let mut push = |xs: &[&str]| a.extend(xs.iter().map(|x| x.to_string())); + let q = s.quality; + if s.format == Format::Gif { + let colours = lerp(q, 32.0, 256.0).round() as u32; + let dither = if q >= 50 { "sierra2_4a" } else { "bayer:bayer_scale=4" }; + let graph = format!("[0:v]split[a][b];[a]palettegen=max_colors={colours}:stats_mode=diff[p];[b][p]paletteuse=dither={dither}:diff_mode=rectangle"); + push(&["-filter_complex", &graph, "-c:v", "gif", "-loop", "0"]); + return a; + } + let mut chain: Vec = Vec::new(); + if s.format.even() { + chain.push("crop=trunc(iw/2)*2:trunc(ih/2)*2".into()); + } + let pix = match encoder { + "prores_ks" if s.alpha => "yuva444p10le", + "prores_ks" => "yuv422p10le", + _ => "yuv420p", + }; + match hardware_filter(encoder) { + Some(f) => chain.push(f), + None => chain.push(format!("format={pix}")), + } + push(&["-vf", &chain.join(",")]); + match encoder { + "libx264" => { + let crf = lerp(q, 35.0, 14.0).round().to_string(); + push(&["-c:v", "libx264", "-preset", "medium", "-crf", &crf, "-pix_fmt", "yuv420p"]); + } + "mpeg4" => { + let qv = lerp(q, 24.0, 2.0).round().to_string(); + push(&["-c:v", "mpeg4", "-q:v", &qv, "-pix_fmt", "yuv420p"]); + } + "libvpx-vp9" => { + let crf = lerp(q, 52.0, 15.0).round().to_string(); + push(&["-c:v", "libvpx-vp9", "-crf", &crf, "-b:v", "0", "-row-mt", "1", "-deadline", "good", "-cpu-used", "4", "-pix_fmt", "yuv420p"]); + } + "prores_ks" => { + let profile = if s.alpha { + "4" + } else if q >= 90 { + "3" + } else if q < 40 { + "1" + } else { + "2" + }; + push(&["-c:v", "prores_ks", "-profile:v", profile, "-vendor", "apl0", "-pix_fmt", pix]); + } + hw => { + let (w, h) = if s.width > 0 && s.height > 0 { (s.width, s.height) } else { (1920, 1080) }; + let bits = (w as f64 * h as f64 * s.fps.max(1.0) as f64 * lerp(q, 0.03, 0.3) as f64).round().max(200_000.0) as u64; + push(&["-c:v", hw, "-b:v", &bits.to_string()]); + if hardware_filter(hw).is_none() { + push(&["-pix_fmt", "yuv420p"]); + } + } + } + if s.format == Format::Mp4 || s.format == Format::Mov { + push(&["-movflags", "+faststart"]); + } + a +} From a539ee98583edbecbcb44ce311102541f4b15bca Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:03 -0500 Subject: [PATCH 022/471] feat(video): encode frames into a part file renamed on success Links the frames into a numbered staging folder, runs ffmpeg as a separate program writing .part with progress and cancel, falls back from a failing hardware encoder, and renames only when ffmpeg succeeds. Checked with cargo check -p fsh-commands. --- .../fsh-commands/src/ext/video/encode.rs | 242 ++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 native/crates/fsh-commands/src/ext/video/encode.rs diff --git a/native/crates/fsh-commands/src/ext/video/encode.rs b/native/crates/fsh-commands/src/ext/video/encode.rs new file mode 100644 index 00000000..ac34bc14 --- /dev/null +++ b/native/crates/fsh-commands/src/ext/video/encode.rs @@ -0,0 +1,242 @@ +//! Encoding frames on disk into a movie by running ffmpeg as a separate program: the frames are linked into a +//! numbered staging folder, ffmpeg writes `.part`, and the part file is renamed only when ffmpeg succeeds. + +use super::encoders::{self, Settings}; +use super::{find, probe}; +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +/// A finished movie. +#[derive(Clone, Debug)] +pub(crate) struct Encoded { + pub path: PathBuf, + pub bytes: u64, + pub encoder: String, + pub codec: &'static str, + pub ffmpeg: PathBuf, + pub source: &'static str, + pub version: String, + pub frames: usize, + pub tried: Vec, +} + +/// Why an encode stopped. +#[derive(Debug)] +pub(crate) enum Stop { + Cancelled, + Failed(String, &'static str), +} + +const TAIL: usize = 600; + +/// Advice when no ffmpeg is found. +pub(crate) const MISSING: &str = "ffmpeg was not found: set FORMSHOT_FFMPEG to an ffmpeg program, download the Form family's build through the FormShot service (POST /api/video/ffmpeg/fetch), or install ffmpeg on the PATH"; + +fn part_path(p: &Path) -> PathBuf { + let mut s = p.as_os_str().to_owned(); + s.push(".part"); + PathBuf::from(s) +} + +/// `path`, or `_2.`, `_3`, ... when it (or its part file) is taken and not to be overwritten. +pub(crate) fn free_path(path: &Path, overwrite: bool) -> PathBuf { + if overwrite || !(path.exists() || part_path(path).exists()) { + return path.to_path_buf(); + } + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("movie").to_string(); + let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("").to_string(); + let folder = path.parent().map(Path::to_path_buf).unwrap_or_default(); + (2..) + .map(|k| folder.join(format!("{stem}_{k}.{ext}"))) + .find(|p| !(p.exists() || part_path(p).exists())) + .unwrap_or_else(|| path.to_path_buf()) +} + +fn frame_extension(frames: &[PathBuf]) -> Result { + let ext = |p: &PathBuf| p.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); + let first = frames.first().map(ext).ok_or_else(|| Stop::Failed("there are no frames to encode".into(), "no_frames"))?; + if !["png", "jpg", "jpeg", "tif", "tiff"].contains(&first.as_str()) { + return Err(Stop::Failed(format!("frames must be png, jpeg or tiff files, not .{first}"), "invalid_arguments")); + } + if let Some(odd) = frames.iter().find(|p| ext(p) != first) { + return Err(Stop::Failed(format!("every frame must be a .{first} file; {} is not", odd.display()), "invalid_arguments")); + } + Ok(first) +} + +/// Links (or copies) the frames into `dir` as f000001., f000002., ... so ffmpeg reads one numbered sequence. +fn stage(frames: &[PathBuf], dir: &Path, ext: &str, cancel: &AtomicBool) -> Result<(), Stop> { + let _ = std::fs::remove_dir_all(dir); + std::fs::create_dir_all(dir).map_err(|e| Stop::Failed(format!("cannot make {}: {e}", dir.display()), "write_failed"))?; + for (i, f) in frames.iter().enumerate() { + if cancel.load(Ordering::SeqCst) { + return Err(Stop::Cancelled); + } + if !f.is_file() { + return Err(Stop::Failed(format!("frame {} is missing", f.display()), "no_frames")); + } + let to = dir.join(format!("f{:06}.{ext}", i + 1)); + if std::fs::hard_link(f, &to).is_err() { + std::fs::copy(f, &to).map_err(|e| Stop::Failed(format!("cannot copy {} for ffmpeg: {e}", f.display()), "write_failed"))?; + } + } + Ok(()) +} + +enum Outcome { + Done, + Cancelled, + Failed(String), +} + +fn run_ffmpeg(program: &Path, args: &[String], total: usize, cancel: &AtomicBool, progress: &mut dyn FnMut(f32)) -> Outcome { + let mut child = match Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() { + Ok(c) => c, + Err(e) => return Outcome::Failed(format!("{} could not be started: {e}", program.display())), + }; + let frame = Arc::new(AtomicU64::new(0)); + let seen = Arc::clone(&frame); + let out = child.stdout.take(); + let reader = std::thread::spawn(move || { + if let Some(o) = out { + for line in BufReader::new(o).lines().map_while(Result::ok) { + if let Some(n) = line.strip_prefix("frame=").and_then(|v| v.trim().parse::().ok()) { + seen.store(n, Ordering::SeqCst); + } + } + } + }); + let mut err = child.stderr.take(); + let err_reader = std::thread::spawn(move || { + let mut s = String::new(); + if let Some(e) = err.as_mut() { + let _ = e.read_to_string(&mut s); + } + s + }); + let status = loop { + if cancel.load(Ordering::SeqCst) { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + let _ = err_reader.join(); + return Outcome::Cancelled; + } + match child.try_wait() { + Ok(Some(s)) => break s, + Ok(None) => { + progress((frame.load(Ordering::SeqCst) as f32 / total.max(1) as f32).min(1.0)); + std::thread::sleep(Duration::from_millis(50)); + } + Err(e) => { + let _ = child.kill(); + return Outcome::Failed(format!("ffmpeg could not be waited for: {e}")); + } + } + }; + let _ = reader.join(); + let messages = err_reader.join().unwrap_or_default(); + if status.success() { + Outcome::Done + } else { + let code = status.code().map(|c| format!("exit code {c}")).unwrap_or_else(|| "a signal".into()); + let tail = probe::tail(&messages, TAIL); + Outcome::Failed(if tail.is_empty() { format!("ffmpeg stopped with {code}") } else { format!("ffmpeg stopped with {code}: {tail}") }) + } +} + +/// Encodes `frames` (in order) into the movie `out` with the best encoder this ffmpeg has for the format, trying the +/// next one when a hardware encoder fails. Nothing is left under `out` unless ffmpeg finished. +pub(crate) fn encode(frames: &[PathBuf], out: &Path, s: Settings, cancel: &AtomicBool, progress: &mut dyn FnMut(f32)) -> Result { + let ext = frame_extension(frames)?; + let (found, notes) = find::find(); + let found = found.ok_or_else(|| { + let mut m = MISSING.to_string(); + for n in notes { + m.push_str("; "); + m.push_str(&n); + } + Stop::Failed(m, "ffmpeg_missing") + })?; + let p = probe::probe(&found.path).map_err(|e| Stop::Failed(e, "ffmpeg_failed"))?; + let listed = |e: &str| p.has(e); + let mut works = |e: &str| p.hardware_works(&found.path, e); + let list = encoders::candidates(s.format, &listed, &mut works); + if list.is_empty() { + return Err(Stop::Failed(format!("{} has no encoder for {}: it needs {}", found.path.display(), s.format.name(), encoders::needs(s.format)), "encoder_missing")); + } + let folder = out.parent().ok_or_else(|| Stop::Failed(format!("{} has no folder", out.display()), "invalid_arguments"))?; + std::fs::create_dir_all(folder).map_err(|e| Stop::Failed(format!("cannot make the folder {}: {e}", folder.display()), "write_failed"))?; + let stem = out.file_name().and_then(|n| n.to_str()).unwrap_or("movie"); + let staging = folder.join(format!(".{stem}.frames.part")); + let result = stage(frames, &staging, &ext, cancel).and_then(|()| run_all(&found, &p.version, &list, frames.len(), &staging, &ext, out, s, cancel, progress)); + let _ = std::fs::remove_dir_all(&staging); + result +} + +#[allow(clippy::too_many_arguments)] +fn run_all( + found: &find::Found, + version: &str, + list: &[&'static str], + total: usize, + staging: &Path, + ext: &str, + out: &Path, + s: Settings, + cancel: &AtomicBool, + progress: &mut dyn FnMut(f32), +) -> Result { + let part = part_path(out); + let rate = encoders::rate(s.fps); + let input = staging.join(format!("f%06d.{ext}")); + let mut tried = Vec::new(); + for (k, encoder) in list.iter().enumerate() { + let mut args: Vec = ["-hide_banner", "-nostdin", "-loglevel", "error", "-y"].map(String::from).to_vec(); + if encoders::hardware(encoder) { + args.extend(encoders::device_args(encoder)); + } + args.extend(["-framerate", &rate, "-start_number", "1", "-i"].map(String::from)); + args.push(input.to_string_lossy().into_owned()); + args.extend(encoders::output_args(encoder, &s)); + args.extend(["-r", &rate, "-an", "-progress", "pipe:1", "-nostats", "-f", s.format.name()].map(String::from)); + args.push(part.to_string_lossy().into_owned()); + match run_ffmpeg(&found.path, &args, total, cancel, progress) { + Outcome::Done => { + let bytes = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0); + if let Err(e) = std::fs::rename(&part, out) { + let _ = std::fs::remove_file(&part); + return Err(Stop::Failed(format!("cannot rename {} to {}: {e}", part.display(), out.display()), "write_failed")); + } + return Ok(Encoded { + path: out.to_path_buf(), + bytes, + encoder: encoder.to_string(), + codec: encoders::codec(encoder, s.alpha), + ffmpeg: found.path.clone(), + source: found.source, + version: version.to_string(), + frames: total, + tried, + }); + } + Outcome::Cancelled => { + let _ = std::fs::remove_file(&part); + return Err(Stop::Cancelled); + } + Outcome::Failed(m) => { + let _ = std::fs::remove_file(&part); + if encoders::hardware(encoder) && k + 1 < list.len() { + tried.push(format!("{encoder}: {m}")); + continue; + } + return Err(Stop::Failed(format!("{encoder}: {m}"), "encode_failed")); + } + } + } + Err(Stop::Failed("no encoder finished".into(), "encode_failed")) +} From ceaa4ff301bf26b70b8a0b9b54609054b7d884d6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:08 -0500 Subject: [PATCH 023/471] feat(render): queue movie jobs that encode the frames before them A movie job sits in the render queue like any job, keeps its movie in the queue state by job id and borrows the last frame job's settings for the list. Checked with cargo check -p fsh-commands. --- .../fsh-commands/src/ext/output/queue.rs | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/native/crates/fsh-commands/src/ext/output/queue.rs b/native/crates/fsh-commands/src/ext/output/queue.rs index a53675f9..2e2ec3aa 100644 --- a/native/crates/fsh-commands/src/ext/output/queue.rs +++ b/native/crates/fsh-commands/src/ext/output/queue.rs @@ -134,6 +134,7 @@ pub(crate) struct QState { paused: bool, revision: u64, quit: bool, + pub movies: std::collections::BTreeMap>, } impl QState { @@ -351,3 +352,89 @@ impl Drop for Queue { } } } + +fn movie_spec(movie: &crate::ext::video::Movie) -> Spec { + let folder = movie.path.parent().map(std::path::Path::to_path_buf).unwrap_or_default(); + let name = movie.path.file_stem().and_then(|s| s.to_str()).unwrap_or("movie").to_string(); + Spec { + source: Source::Project(movie.path.clone()), + pick: Pick::Active, + overrides: Overrides::default(), + device: "cpu".into(), + threads: 1, + failed: Failed::default(), + output: Output { + options: fsh_io::write::WriteOptions::Png(Default::default()), + alpha: Some(movie.settings.alpha), + overwrite: movie.overwrite, + folder, + name, + frame: 1, + tokens: Default::default(), + }, + } +} + +impl Queue { + /// Queues a movie job: ffmpeg encodes its frames (the beauty files of earlier jobs, or files on disk) when the + /// worker reaches it. The run thread answers it instead of rendering (run.rs `movie_job`); answers its id. + pub(crate) fn push_movie(&self, movie: crate::ext::video::Movie, label: &str) -> crate::error::Result { + use crate::ext::video::MovieFrames; + self.start()?; + let mut q = lock(&self.shared); + let last = match &movie.frames { + MovieFrames::Jobs(ids) => ids.last().and_then(|id| q.jobs.iter().find(|j| j.id == *id)), + MovieFrames::Files(_) => None, + }; + let count = match &movie.frames { + MovieFrames::Jobs(ids) => ids.len(), + MovieFrames::Files(f) => f.len(), + }; + let file = movie.path.file_name().and_then(|s| s.to_str()).unwrap_or("movie").to_string(); + let job = Job { + id: q.next, + label: if label.is_empty() { format!("Movie of {count} frames") } else { label.to_string() }, + spec: last.map_or_else(|| Arc::new(movie_spec(&movie)), |j| Arc::clone(&j.spec)), + state: JobState::Queued, + cancel: Arc::new(AtomicBool::new(false)), + remove_when_stopped: false, + progress: 0.0, + samples_done: 0, + samples: 0, + width: last.map_or(0, |j| j.width), + height: last.map_or(0, |j| j.height), + title: file, + source_path: None, + camera_index: last.map_or(0, |j| j.camera_index), + camera_name: last.map_or_else(String::new, |j| j.camera_name.clone()), + passes: vec!["movie".into()], + denoise: false, + transparent: movie.settings.alpha, + drew: Some("ffmpeg".into()), + backend: None, + note: Some(format!("{} movie of {count} frames at {} fps", movie.settings.format.name(), movie.settings.fps)), + denoiser: None, + files: Vec::new(), + error: None, + created_ms: super::naming::now_ms(), + started_ms: None, + finished_ms: None, + seconds: 0.0, + warnings: Vec::new(), + }; + let id = job.id; + q.next += 1; + let ids: Vec = q.jobs.iter().map(|j| j.id).collect(); + q.movies.retain(|k, _| ids.contains(k)); + q.movies.insert(id, Arc::new(movie)); + q.jobs.push(job); + q.touch(); + self.shared.wake.notify_all(); + Ok(id) + } +} + +/// The movie a job encodes, when it is a movie job. +pub(crate) fn movie_of(shared: &Shared, id: u64) -> Option> { + lock(shared).movies.get(&id).cloned() +} From 7676c92540a1e4dd69350f7e1ed1052c942f5e0d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:08 -0500 Subject: [PATCH 024/471] feat(render): run movie jobs on the queue thread The queue thread answers a movie job by collecting the frame jobs' beauty files, encoding them with ffmpeg and listing the movie, the encoder and the encode in the job; a cancelled or failed frame stops the movie, and frames are removed unless kept. Checked with cargo check -p fsh-commands. --- .../crates/fsh-commands/src/ext/output/run.rs | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/native/crates/fsh-commands/src/ext/output/run.rs b/native/crates/fsh-commands/src/ext/output/run.rs index d6153123..3b94fee9 100644 --- a/native/crates/fsh-commands/src/ext/output/run.rs +++ b/native/crates/fsh-commands/src/ext/output/run.rs @@ -82,6 +82,9 @@ fn film(shared: &Shared, id: u64, r: &mut JobRenderer, target: u32, cancel: &Ato } fn execute(shared: &Shared, id: u64, spec: &Spec, cancel: &AtomicBool) -> Result<(), Stop> { + if let Some(movie) = super::queue::movie_of(shared, id) { + return movie_job(shared, id, &movie, cancel); + } let p: Prepared = match &spec.source { Source::Ready(p) => (**p).clone(), Source::Project(path) => spec::from_project(path, &spec.pick, &spec.overrides).map_err(|e| Stop::Failed(e.to_string(), e.code()))?, @@ -173,3 +176,91 @@ fn execute(shared: &Shared, id: u64, spec: &Spec, cancel: &AtomicBool) -> Result update(shared, id, |j| j.files = written); Ok(()) } + +/// The beauty files of the frame jobs, in order, and every file they wrote; a frame job that did not finish stops +/// the movie (cancelled with it, or failed with its reason). +fn movie_frames(shared: &Shared, ids: &[u64], s: &mut crate::ext::video::Settings) -> Result<(Vec, Vec), Stop> { + let q = lock(shared); + let mut beauty = Vec::with_capacity(ids.len()); + let mut all = Vec::new(); + for id in ids { + let j = q.jobs.iter().find(|j| j.id == *id).ok_or_else(|| Stop::Failed(format!("frame job {id} was removed from the queue, so the movie cannot be made"), "frames_missing"))?; + match j.state { + JobState::Done => {} + JobState::Cancelled => return Err(Stop::Cancelled), + JobState::Failed => { + let why = j.error.as_ref().map(|(m, _)| m.as_str()).unwrap_or("it failed"); + return Err(Stop::Failed(format!("frame job {id} failed ({why}), so the movie was not made"), "frames_missing")); + } + other => { + return Err(Stop::Failed(format!("frame job {id} is {} when the movie job started; keep the movie job after its frames", other.as_str()), "frames_missing")) + } + } + let file = j.files.iter().find(|f| f.0 == "beauty").or(j.files.first()).ok_or_else(|| Stop::Failed(format!("frame job {id} wrote no file"), "frames_missing"))?; + beauty.push(std::path::PathBuf::from(&file.1)); + all.extend(j.files.iter().map(|f| f.1.clone())); + if s.width == 0 { + s.width = j.width; + s.height = j.height; + } + } + Ok((beauty, all)) +} + +/// A movie job: ffmpeg encodes the frames into `.part`, renamed when it finishes; the job lists the movie as +/// its one file, the encoder as its backend and the encode in its note, and drops the frames unless they are kept. +fn movie_job(shared: &Shared, id: u64, movie: &crate::ext::video::Movie, cancel: &AtomicBool) -> Result<(), Stop> { + use crate::ext::video::{encode, MovieFrames}; + let t0 = Moment::now(); + let mut s = movie.settings; + let (frames, written) = match &movie.frames { + MovieFrames::Files(f) => (f.clone(), Vec::new()), + MovieFrames::Jobs(ids) => movie_frames(shared, ids, &mut s)?, + }; + let path = encode::free_path(&movie.path, movie.overwrite); + let out = encode::encode(&frames, &path, s, cancel, &mut |f| { + update(shared, id, |j| { + j.progress = 0.99 * f; + j.seconds = t0.elapsed().as_secs_f64(); + }) + }); + lock(shared).movies.remove(&id); + let e = out.map_err(|e| match e { + encode::Stop::Cancelled => Stop::Cancelled, + encode::Stop::Failed(m, code) => Stop::Failed(m, code), + })?; + let mut note = format!( + "{} ({}) in {}, {} frames at {} fps, {}x{}; ffmpeg {} ({}, found through {})", + e.codec, + e.encoder, + s.format.name(), + e.frames, + crate::ext::video::encoders::rate(s.fps), + s.width, + s.height, + e.version, + e.ffmpeg.display(), + e.source + ); + for t in &e.tried { + note.push_str(&format!("; {t}")); + } + if !movie.keep_frames { + for f in &written { + let _ = std::fs::remove_file(f); + } + if let Some(dir) = frames.first().and_then(|f| f.parent()).filter(|d| Some(*d) != e.path.parent()) { + let _ = std::fs::remove_dir(dir); + } + } + let (w, h) = (s.width, s.height); + update(shared, id, |j| { + j.backend = Some(e.encoder.clone()); + j.note = Some(note); + j.width = w; + j.height = h; + j.seconds = t0.elapsed().as_secs_f64(); + j.files = vec![("movie".into(), e.path.to_string_lossy().into_owned(), e.bytes)]; + }); + Ok(()) +} From e4184d137cc3d59e52ec9c492b26f1c0ed00a4d8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:08 -0500 Subject: [PATCH 025/471] feat(anim): render frame sequences through the render queue anim.render queues one job per frame through queue_documents with {frame} file names and, with video, a movie job after them; the render.queue_add schema is shared by making add_schema crate-visible. Checked with cargo check -p fsh-commands. --- native/crates/fsh-commands/src/ext/anim.rs | 117 +++++++++++++++++++ native/crates/fsh-commands/src/ext/output.rs | 2 +- 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/native/crates/fsh-commands/src/ext/anim.rs b/native/crates/fsh-commands/src/ext/anim.rs index 9cc702fe..b4842fad 100644 --- a/native/crates/fsh-commands/src/ext/anim.rs +++ b/native/crates/fsh-commands/src/ext/anim.rs @@ -10,3 +10,120 @@ pub(super) static COMMANDS: &[ExtCommand] = &[]; pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { None } + +const SEQUENCE_NAME: &str = "{project}_{camera}_{frame}"; + +fn render_schema() -> Value { + let mut s = super::output::add_schema(); + if let Some(p) = s["properties"].as_object_mut() { + p.remove("frame"); + p.remove("project"); + p["name"]["description"] = serde_json::json!(format!("File name template of each frame (tokens as render.queue_add; {{frame}} is the frame number, 4 digits); default {SEQUENCE_NAME}")); + p.insert("frames".into(), serde_json::json!({"type": "array", "items": {"type": "integer", "minimum": 1}, "minItems": 2, "maxItems": 2, "description": "[first, last] frame numbers to render, 1 being the animation's start; the whole range when absent"})); + p.insert("step".into(), serde_json::json!({"type": "integer", "minimum": 1, "default": 1, "description": "Render every step-th frame of the range"})); + p.insert("video".into(), serde_json::json!({"type": "object", "properties": { + "format": {"type": "string", "enum": ["mp4", "webm", "mov", "gif"], "description": "mp4 (H.264, or MPEG-4 Part 2 without an H.264 encoder), webm (VP9), mov (ProRes 422; 4444 with a transparent background) or gif"}, + "fps": {"type": "number", "exclusiveMinimum": 0, "maximum": 240, "description": "Frames per second; the animation's when absent (divided by step)"}, + "quality": {"type": "integer", "minimum": 1, "maximum": 100, "default": super::video::QUALITY, "description": "1 (smallest file) to 100 (best picture)"}, + "keep_frames": {"type": "boolean", "default": false, "description": "Keep the frame files after the movie is written"}, + "name": {"type": "string", "description": "Movie file name without extension; default _"}, + "folder": {"type": "string", "description": "Absolute folder of the movie; the frames' folder when absent"} + }, "required": ["format"], "additionalProperties": false, "description": "Encode a movie with ffmpeg after the last frame is written (a movie job queued after the frame jobs)"})); + } + s +} + +/// anim.render's catalogue entry; the video group lists it and answers it. +pub(super) const RENDER: ExtCommand = ExtCommand { + name: "anim.render", + description: "Render frames of the animation through the render queue, one job per frame (each with its own progress and cancel), named {project}_{camera}_{frame} by default with 4-digit frame numbers; with video, a movie job after the frames encodes them with ffmpeg into mp4, webm, mov or gif and reports the encoder, the movie's path and any ffmpeg error. Takes every render.queue_add argument but frame and project.", + level: fsh_scene::ChangeLevel::None, + mutates: false, + read_only: false, + schema: render_schema, +}; + +fn sequence_range(args: &Value, count: usize) -> Result<(usize, usize, usize)> { + let bad = |m: String| crate::error::EngineError::args(m); + let (first, last) = match args.get("frames") { + None | Some(Value::Null) => (1, count), + Some(Value::Array(a)) if a.len() == 2 => { + let n = |v: &Value| v.as_u64().filter(|n| *n >= 1).map(|n| n as usize).ok_or_else(|| bad("frames holds two frame numbers of 1 or more".into())); + (n(&a[0])?, n(&a[1])?) + } + Some(_) => return Err(bad("frames must be [first, last]".into())), + }; + if first > last || last > count { + return Err(bad(format!("frames [{first}, {last}] is outside the animation's frames 1 to {count}"))); + } + let step = crate::util::get_u32(args, "step")?.unwrap_or(1); + if step == 0 { + return Err(bad("step must be 1 or more".into())); + } + Ok((first, last, step as usize)) +} + +/// anim.render: one queued job per frame (through `queue_documents`, the frame's document evaluated from the +/// animation), then, with `video`, one movie job that encodes the frames' beauty files once they are all written. +pub(super) fn render_sequence(engine: &Engine, st: &mut State, args: &Value) -> Result { + use super::video::{self, Movie, MovieFrames}; + let doc = st.editor.document().clone(); + let (fps, times, evaluate) = video::timeline(&doc); + let (first, last, step) = sequence_range(args, times.len())?; + let mut q = args.clone(); + let o = q.as_object_mut().ok_or_else(|| crate::error::EngineError::args("anim.render takes an object of arguments"))?; + let movie = o.remove("video").filter(|v| !v.is_null()); + for k in ["frames", "step", "frame", "project"] { + o.remove(k); + } + o.entry("name").or_insert_with(|| serde_json::json!(SEQUENCE_NAME)); + let format = match &movie { + Some(m) => { + let f = video::format_of(m, None)?; + if !matches!(crate::util::get_str(&q, "format").unwrap_or("png"), "png" | "jpeg" | "jpg") { + return Err(crate::error::EngineError::args("a movie is made from png or jpeg frames: leave format out or set png or jpeg")); + } + if crate::util::get_str(&q, "camera") == Some("all") { + return Err(crate::error::EngineError::args("a movie shows one camera: pick one instead of all")); + } + Some(f) + } + None => None, + }; + let label = crate::util::get_str(args, "label").filter(|l| !l.is_empty()).unwrap_or("Sequence").to_string(); + let mut ids: Vec = Vec::new(); + for f in (first..=last).step_by(step) { + q["frame"] = serde_json::json!(f); + let item = super::output::Queued { doc: evaluate(&doc, times[f - 1]), label: format!("{label} frame {f:04}"), tokens: Default::default() }; + let r = super::output::queue_documents(engine, st, &q, vec![item])?; + ids.extend(r["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64)); + } + let mut answer = serde_json::json!({"ok": true, "change": "none", "frames": ids.len(), "range": [first, last], "step": step, "fps": fps, "ids": ids}); + if let (Some(m), Some(format)) = (movie, format) { + let mut settings = video::settings(&m, format, fps / step as f32)?; + settings.alpha = crate::util::get_bool(&m, "alpha").or(crate::util::get_bool(&q, "transparent")).unwrap_or(false) && format == video::Format::Mov; + let first_job = ids.first().map(|id| engine.queue().job(*id)).transpose()?.unwrap_or(Value::Null); + let folder = match crate::util::get_str(&m, "folder").filter(|f| !f.trim().is_empty()) { + Some(f) if std::path::Path::new(f).is_absolute() => std::path::PathBuf::from(f), + Some(f) => return Err(crate::error::EngineError::args(format!("video.folder \"{f}\" must be an absolute path"))), + None => std::path::PathBuf::from(crate::util::get_str(&q, "folder").unwrap_or_default()), + }; + let stem = match crate::util::get_str(&m, "name").filter(|n| !n.trim().is_empty()) { + Some(n) if n.contains('/') || n.contains('\\') || n.contains("..") => return Err(crate::error::EngineError::args(format!("video.name \"{n}\" must be a file name"))), + Some(n) => n.to_string(), + None => format!("{}_{}", video::safe_name(first_job["source"]["title"].as_str().unwrap_or("movie")), video::safe_name(first_job["camera"]["name"].as_str().unwrap_or("camera"))), + }; + let path = video::with_extension(&folder.join(stem), format); + let movie = Movie { + frames: MovieFrames::Jobs(ids.clone()), + path: path.clone(), + overwrite: crate::util::get_bool(&q, "overwrite").unwrap_or(false), + settings, + keep_frames: crate::util::get_bool(&m, "keep_frames").unwrap_or(false), + }; + let id = engine.queue().push_movie(movie, &format!("{label} movie"))?; + answer["movie"] = serde_json::json!({"id": id, "path": path.to_string_lossy(), "format": format.name(), "fps": settings.fps, "quality": settings.quality}); + } + answer["queue"] = engine.queue().list(); + Ok(answer) +} diff --git a/native/crates/fsh-commands/src/ext/output.rs b/native/crates/fsh-commands/src/ext/output.rs index 0e4829e0..04620e38 100644 --- a/native/crates/fsh-commands/src/ext/output.rs +++ b/native/crates/fsh-commands/src/ext/output.rs @@ -44,7 +44,7 @@ fn pause_schema() -> Value { json!({"type": "object", "properties": {"paused": {"type": "boolean", "description": "True holds new jobs back; the running job finishes"}}, "required": ["paused"], "additionalProperties": false}) } -fn add_schema() -> Value { +pub(crate) fn add_schema() -> Value { let mut passes: Vec<&str> = PassKind::ALL.iter().map(|k| k.name()).collect(); passes.extend(Passes::GROUPS); let s = |d: &str| json!({"type": "string", "description": d}); From a9e87a50f96f6f3e96bdf86604c9eb4e5274ca49 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:33:09 -0500 Subject: [PATCH 026/471] feat(video): add video.ffmpeg, video.encode and list anim.render video.ffmpeg reports the ffmpeg found, its version, our encoders, each format's choice and the licence; video.encode queues a movie from frames on disk; the timeline adapter returns one still frame until the animation is connected. Checked with cargo check -p fsh-commands. --- native/crates/fsh-commands/src/ext/video.rs | 288 +++++++++++++++++++- 1 file changed, 282 insertions(+), 6 deletions(-) diff --git a/native/crates/fsh-commands/src/ext/video.rs b/native/crates/fsh-commands/src/ext/video.rs index 7b3ff5f3..87d85286 100644 --- a/native/crates/fsh-commands/src/ext/video.rs +++ b/native/crates/fsh-commands/src/ext/video.rs @@ -1,12 +1,288 @@ -//! Video: finding ffmpeg and encoding rendered frames into a movie (0.9.0). +//! Video: finding ffmpeg and encoding rendered frames into a movie (0.9.0). ffmpeg is run as a separate program, +//! never linked; the engine never downloads it (the service does, on request). use super::ExtCommand; use crate::engine::{Engine, State}; -use crate::error::Result; -use serde_json::Value; +use crate::error::{EngineError, Result}; +use crate::util::{get_bool, get_f32, get_str, get_u32}; +use fsh_scene::ChangeLevel; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; -pub(super) static COMMANDS: &[ExtCommand] = &[]; +pub(crate) mod encoders; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) mod encode; +#[cfg(not(target_arch = "wasm32"))] +mod find; +#[cfg(not(target_arch = "wasm32"))] +mod probe; -pub(super) fn dispatch(_engine: &Engine, _st: &mut State, _name: &str, _args: &Value) -> Option> { - None +pub(crate) use encoders::{Format, Settings}; + +const NO_FFMPEG: &str = "movies are encoded by ffmpeg in the desktop app and the service's engine (this build cannot run programs)"; + +/// Default quality of a movie, 1 to 100. +pub(crate) const QUALITY: u32 = 80; + +/// The frames a movie job encodes: the beauty files of render jobs before it, or files already on disk. +#[derive(Clone, Debug)] +pub(crate) enum MovieFrames { + Jobs(Vec), + Files(Vec), +} + +/// A movie job of the render queue: encoded after its frames are written. +#[derive(Clone, Debug)] +pub(crate) struct Movie { + pub frames: MovieFrames, + pub path: PathBuf, + pub overwrite: bool, + pub settings: Settings, + pub keep_frames: bool, +} + +/// The document at one time of its animation. +pub(crate) type Evaluate = fn(&fsh_scene::Document, f32) -> fsh_scene::Document; + +fn unchanged(doc: &fsh_scene::Document, _time: f32) -> fsh_scene::Document { + doc.clone() +} + +/// The animation as frame sequences see it: frames per second, one time per frame (seconds, both ends included) +/// and the function that applies the animation at a time. Until fsh_scene::animation's `frame_times` and +/// `evaluate` are connected here, this is one frame at 24 fps of the document unchanged. +pub(crate) fn timeline(doc: &fsh_scene::Document) -> (f32, Vec, Evaluate) { + let _ = doc; + (24.0, vec![0.0], unchanged) +} + +/// A value made safe for a file name. +pub(crate) fn safe_name(v: &str) -> String { + let s: String = v.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.' | '(' | ')') { c } else { '_' }).collect(); + let s = s.trim().trim_matches('.').to_string(); + if s.is_empty() { + "movie".into() + } else { + s + } +} + +fn no_args() -> Value { + json!({"type": "object", "properties": {}, "additionalProperties": false}) +} + +fn quality_schema() -> Value { + json!({"type": "integer", "minimum": 1, "maximum": 100, "default": QUALITY, "description": "1 (smallest file) to 100 (best picture); maps to each encoder's own scale"}) +} + +fn format_schema() -> Value { + json!({"type": "string", "enum": ["mp4", "webm", "mov", "gif"], "description": "mp4: H.264 (a hardware encoder, else libx264 when this ffmpeg has it, else MPEG-4 Part 2); webm: VP9; mov: ProRes 422 (4444 with alpha); gif: palette GIF"}) +} + +fn encode_schema() -> Value { + json!({"type": "object", "properties": { + "frames": {"type": "object", "properties": { + "folder": {"type": "string", "description": "Absolute folder holding the frames"}, + "pattern": {"type": "string", "description": "File names of the frames with {frame} for the frame number (digits) or * for any text, e.g. shot_{frame}.png; matching files are taken in frame-number order"} + }, "required": ["folder", "pattern"], "additionalProperties": false}, + "out": {"type": "string", "description": "Absolute path of the movie; its extension picks the format when format is absent"}, + "format": format_schema(), + "fps": {"type": "number", "exclusiveMinimum": 0, "maximum": 240, "default": 24, "description": "Frames per second"}, + "quality": quality_schema(), + "alpha": {"type": "boolean", "description": "Keep the frames' alpha (mov writes ProRes 4444; other formats have none)"}, + "overwrite": {"type": "boolean", "description": "Replace an existing movie; otherwise _2, _3, ... is added"}, + "label": {"type": "string", "description": "Free text shown in the queue list"} + }, "required": ["frames", "out"], "additionalProperties": false}) +} + +pub(super) static COMMANDS: &[ExtCommand] = &[ + super::anim::RENDER, + ExtCommand { + name: "video.ffmpeg", + description: "The ffmpeg program movies are encoded with: whether one is found and where (FORMSHOT_FFMPEG, the Form family's shared install folder, or the PATH), its version, which of FormShot's encoders it lists, the encoder each movie format would use, and the licence of the build. The engine never downloads ffmpeg; the service fetches the family's LGPL build on request.", + level: ChangeLevel::None, + mutates: false, + read_only: true, + schema: no_args, + }, + ExtCommand { + name: "video.encode", + description: "Queue a movie (mp4, webm, mov or gif) encoded by ffmpeg from frames already on disk (a folder and a file name pattern). The job runs in the render queue: render.queue_list shows its progress, the encoder used, the movie's path and any ffmpeg error; a cancelled job leaves no movie.", + level: ChangeLevel::None, + mutates: false, + read_only: false, + schema: encode_schema, + }, +]; + +pub(super) fn dispatch(engine: &Engine, st: &mut State, name: &str, args: &Value) -> Option> { + Some(match name { + "anim.render" => super::anim::render_sequence(engine, st, args), + "video.ffmpeg" => ffmpeg_status(), + "video.encode" => encode_files(engine, args), + _ => return None, + }) +} + +/// The movie settings shared by video.encode and anim.render's `video` argument. +pub(crate) fn settings(args: &Value, format: Format, default_fps: f32) -> Result { + let fps = get_f32(args, "fps")?.unwrap_or(default_fps); + if !(fps > 0.0 && fps <= 240.0) { + return Err(EngineError::args(format!("fps must be above 0 and at most 240, got {fps}"))); + } + let quality = get_u32(args, "quality")?.unwrap_or(QUALITY); + if !(1..=100).contains(&quality) { + return Err(EngineError::args(format!("quality must be 1 to 100, got {quality}"))); + } + Ok(Settings { format, fps, quality, width: 0, height: 0, alpha: get_bool(args, "alpha").unwrap_or(false) }) +} + +/// The format named by `format`, else by the extension of `path`. +pub(crate) fn format_of(args: &Value, path: Option<&Path>) -> Result { + match get_str(args, "format") { + Some(f) => Format::parse(f).ok_or_else(|| EngineError::args(format!("format \"{f}\" is not one of mp4, webm, mov, gif"))), + None => path + .and_then(|p| p.extension()) + .and_then(|e| e.to_str()) + .and_then(Format::parse) + .ok_or_else(|| EngineError::args("give format (mp4, webm, mov or gif) or a movie path ending in .mp4, .webm, .mov or .gif")), + } +} + +/// The movie's path with the format's extension. +pub(crate) fn with_extension(path: &Path, format: Format) -> PathBuf { + match path.extension().and_then(|e| e.to_str()).and_then(Format::parse) { + Some(f) if f == format => path.to_path_buf(), + _ => { + let mut s = path.as_os_str().to_owned(); + s.push("."); + s.push(format.name()); + PathBuf::from(s) + } + } +} + +fn frame_number(middle: &str, digits: bool) -> Option { + if digits && !middle.chars().all(|c| c.is_ascii_digit()) { + return None; + } + let d: String = middle.chars().filter(char::is_ascii_digit).collect(); + d.parse().ok().or(if digits { None } else { Some(u64::MAX) }) +} + +/// The files of `folder` matching `pattern` (one `{frame}` or `*`), in frame-number order, then by name. +fn list_frames(folder: &Path, pattern: &str) -> Result> { + let (split, digits) = match (pattern.find("{frame}"), pattern.find('*')) { + (Some(i), None) => ((&pattern[..i], &pattern[i + 7..]), true), + (None, Some(i)) => ((&pattern[..i], &pattern[i + 1..]), false), + _ => return Err(EngineError::args(format!("pattern \"{pattern}\" needs exactly one {{frame}} or one *"))), + }; + if pattern.contains('/') || pattern.contains('\\') || split.1.contains('*') || split.1.contains("{frame}") { + return Err(EngineError::args(format!("pattern \"{pattern}\" must be a file name with one {{frame}} or one *"))); + } + let entries = std::fs::read_dir(folder).map_err(|e| EngineError::File(format!("cannot read the folder {}: {e}", folder.display())))?; + let mut found: Vec<(u64, String, PathBuf)> = entries + .flatten() + .filter_map(|e| { + let name = e.file_name().to_str()?.to_string(); + let middle = name.strip_prefix(split.0)?.strip_suffix(split.1)?; + if middle.is_empty() || !e.path().is_file() { + return None; + } + Some((frame_number(middle, digits)?, name, e.path())) + }) + .collect(); + found.sort(); + if found.is_empty() { + return Err(EngineError::File(format!("no file in {} matches \"{pattern}\"", folder.display()))); + } + Ok(found.into_iter().map(|(_, _, p)| p).collect()) +} + +fn encode_files(engine: &Engine, args: &Value) -> Result { + if cfg!(target_arch = "wasm32") { + return Err(EngineError::Render { code: "unsupported", message: NO_FFMPEG.into() }); + } + let frames = args.get("frames").ok_or_else(|| EngineError::args("video.encode needs frames {folder, pattern}"))?; + let folder = get_str(frames, "folder").filter(|f| !f.trim().is_empty()).ok_or_else(|| EngineError::args("frames needs folder"))?; + let pattern = get_str(frames, "pattern").filter(|f| !f.trim().is_empty()).ok_or_else(|| EngineError::args("frames needs pattern"))?; + let out = get_str(args, "out").filter(|f| !f.trim().is_empty()).ok_or_else(|| EngineError::args("video.encode needs out (the movie's absolute path)"))?; + let (folder, out) = (PathBuf::from(folder), PathBuf::from(out)); + if !folder.is_absolute() || !out.is_absolute() { + return Err(EngineError::args("frames.folder and out must be absolute paths")); + } + let format = format_of(args, Some(&out))?; + let settings = settings(args, format, 24.0)?; + let files = list_frames(&folder, pattern)?; + let movie = Movie { + frames: MovieFrames::Files(files), + path: with_extension(&out, format), + overwrite: get_bool(args, "overwrite").unwrap_or(false), + settings, + keep_frames: true, + }; + let id = engine.queue().push_movie(movie, get_str(args, "label").unwrap_or(""))?; + Ok(json!({"ok": true, "change": "none", "ids": [id], "job": engine.queue().job(id)?, "queue": engine.queue().list()})) +} + +#[cfg(not(target_arch = "wasm32"))] +fn ffmpeg_status() -> Result { + let (found, notes) = find::find(); + let family = json!({ + "release": find::RELEASE, + "triple": find::triple(), + "folder": find::family_folder().map(|f| f.to_string_lossy().into_owned()), + "licence": "LGPL-2.1-or-later (built with --disable-gpl --disable-nonfree; libvpx and libopus BSD-3-Clause); no libx264, so MP4 uses a hardware H.264 encoder or MPEG-4 Part 2", + "source": format!("published with the release ffmpeg-{} of nodemode-dev/formai-binaries", find::RELEASE), + }); + let Some(f) = found else { + return Ok(json!({"found": false, "reason": encode::MISSING, "notes": notes, "family": family, "env": find::ENV})); + }; + let p = match probe::probe(&f.path) { + Ok(p) => p, + Err(e) => { + return Ok(json!({"found": false, "path": f.path.to_string_lossy(), "source": f.source, "reason": e, "notes": notes, "family": family, "env": find::ENV})) + } + }; + let ours: serde_json::Map = encoders::OURS.iter().map(|e| (e.to_string(), json!(p.has(e)))).collect(); + let listed = |e: &str| p.has(e); + let mut works = |e: &str| p.hardware_works(&f.path, e); + let formats: serde_json::Map = Format::ALL + .iter() + .map(|fmt| { + let list = encoders::candidates(*fmt, &listed, &mut works); + let v = match list.first() { + Some(e) => json!({"encoder": e, "codec": encoders::codec(e, false), "hardware": encoders::hardware(e), "fallbacks": &list[1..]}), + None => json!({"encoder": null, "reason": format!("this ffmpeg lacks {}", encoders::needs(*fmt))}), + }; + (fmt.name().to_string(), v) + }) + .collect(); + let gpl = p.configuration.contains("--enable-gpl"); + let licence = if f.source == "family" { + format!("the Form family's LGPL-2.1-or-later build (formai-binaries ffmpeg-{}), run as a separate program; its exact source is published with that release", f.release.as_deref().unwrap_or(find::RELEASE)) + } else if gpl { + "this ffmpeg was built with --enable-gpl, so it is GPL; FormShot only runs it as a separate program and never ships it".to_string() + } else { + "this ffmpeg is the user's own; FormShot only runs it as a separate program and never ships it".to_string() + }; + Ok(json!({ + "found": true, + "path": f.path.to_string_lossy(), + "source": f.source, + "release": f.release, + "version": p.version, + "gpl": gpl, + "encoders": ours, + "formats": formats, + "licence": licence, + "notes": notes, + "family": family, + "env": find::ENV, + })) +} + +#[cfg(target_arch = "wasm32")] +fn ffmpeg_status() -> Result { + Err(EngineError::Render { code: "unsupported", message: NO_FFMPEG.into() }) } From e6286c5dd66f56a0540e802f3f20c591e6ca0d28 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:37:34 -0500 Subject: [PATCH 027/471] feat(cli): render frame ranges, turntables and movies render learns --frames A-B, --turntable N (reported unavailable until anim.turntable is in the catalogue), and movie outputs ending in .mp4, .webm, .mov or .gif with --fps, --quality and --keep-frames, all through anim.render and the queue. Checked with cargo check -p fsh-cli. --- native/crates/fsh-cli/src/main.rs | 153 +++++++++++++++++++++++++++++- 1 file changed, 152 insertions(+), 1 deletion(-) diff --git a/native/crates/fsh-cli/src/main.rs b/native/crates/fsh-cli/src/main.rs index 18deb0cf..777d60a8 100644 --- a/native/crates/fsh-cli/src/main.rs +++ b/native/crates/fsh-cli/src/main.rs @@ -29,6 +29,13 @@ Usage: --depth, --float or a jpg, tif or psd output the render goes through the render queue --depth D 8 or 16 bits for png, psd and tiff --float 32-bit float scene-linear tiff + --frames A-B render frames A to B of the animation (from 1) as _ files + --turntable N add a turntable of N frames to the working copy and render every frame + an .mp4, .webm, .mov or .gif output renders every frame and encodes a movie with ffmpeg + (FORMSHOT_FFMPEG, the Form family's install folder, or the PATH): + --fps F movie frame rate (default: the animation's) + --quality Q movie quality 1 to 100 (default 80) + --keep-frames D keep the movie's frames in folder D and the import options below formshot-engine info [import options] [--json] what a model or .fshot project holds; for a model, also the @@ -262,6 +269,7 @@ fn load(engine: &Engine, input: &str, import: &Value) -> Result fn render(args: &[String]) -> Outcome { let known = with_import_options(&[ "samples", "width", "height", "threads", "seed", "exposure", "tonemap", "denoise", "environment", "transparent", "device", "passes", "format", "depth", "float", + "frames", "turntable", "fps", "quality", "keep-frames", ]); let p = parse(args, &known)?; let [input, output] = p.positional.as_slice() else { @@ -281,7 +289,10 @@ fn render(args: &[String]) -> Outcome { } } let ext = Path::new(output).extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); - let layered = ["passes", "format", "depth"].iter().any(|k| p.value(k).is_some()) || p.flag("float"); + if MOVIES.contains(&ext.as_str()) || ["frames", "turntable"].iter().any(|k| p.value(k).is_some()) { + return render_sequence(&engine, &p, output, &ext, selected); + } + let layered =["passes", "format", "depth"].iter().any(|k| p.value(k).is_some()) || p.flag("float"); if layered || matches!(ext.as_str(), "jpg" | "jpeg" | "tif" | "tiff" | "psd") { return render_queued(&engine, &p, output, &ext, selected); } @@ -405,6 +416,146 @@ fn render_queued(engine: &Engine, p: &Parsed, output: &str, ext: &str, selected: Ok(()) } +const MOVIES: [&str; 4] = ["mp4", "webm", "mov", "gif"]; + +/// `--turntable N`: a turntable rig of N frames added to the working copy through anim.turntable (the rigs' +/// command). The one place `render` depends on it: until the catalogue lists it, the option is reported unavailable. +fn add_turntable(engine: &Engine, frames: u32) -> Outcome { + let catalogue = fsh_commands::catalogue_value(); + if !catalogue["commands"].as_array().is_some_and(|a| a.iter().any(|c| c["name"] == "anim.turntable")) { + return Err(Failure::Run("--turntable is not available yet: this build has no anim.turntable command".into())); + } + run(engine, "anim.turntable", json!({"frames": frames}))?; + Ok(()) +} + +fn frame_range(v: &str) -> Result<[u32; 2], Failure> { + let bad = || Failure::Usage(format!("--frames takes A-B or A (frame numbers from 1), got \"{v}\"")); + let (a, b) = v.split_once('-').unwrap_or((v, v)); + let a: u32 = a.trim().parse().map_err(|_| bad())?; + let b: u32 = b.trim().parse().map_err(|_| bad())?; + if a == 0 || b < a { + return Err(bad()); + } + Ok([a, b]) +} + +/// `render` of an animation through anim.render: frames named `_`, or, for an .mp4, .webm, .mov or +/// .gif output, a movie encoded by ffmpeg from frames in a hidden folder beside it (removed after, unless +/// `--keep-frames DIR` keeps them there). +fn render_sequence(engine: &Engine, p: &Parsed, output: &str, ext: &str, selected: Option) -> Outcome { + if let Some(e) = p.number::("exposure")? { + run(engine, "image.set", json!({"exposure": e}))?; + } + if let Some(t) = p.value("tonemap") { + let t = parse_tone_map(t).map_err(|e| Failure::Usage(e.to_string()))?; + run(engine, "image.set", json!({"tone_map": t}))?; + } + if let Some(n) = p.number::("turntable")? { + if n < 2 { + return Err(Failure::Usage(format!("--turntable needs 2 frames or more, got {n}"))); + } + add_turntable(engine, n)?; + } + let out = std::path::absolute(output).map_err(|e| Failure::Run(format!("{output}: {e}")))?; + let folder = out.parent().ok_or_else(|| Failure::Usage(format!("{output} has no folder")))?.to_path_buf(); + let stem = out.file_stem().and_then(|s| s.to_str()).ok_or_else(|| Failure::Usage(format!("{output} has no file name")))?.to_string(); + let movie = MOVIES.contains(&ext); + let mut args = json!({"overwrite": true, "denoise": p.flag("denoise")}); + for k in ["width", "height", "samples", "seed", "depth"] { + if let Some(v) = p.number::(k)? { + args[k] = json!(v); + } + } + if p.flag("transparent") { + args["transparent"] = json!(true); + } + if let Some(f) = p.value("frames") { + args["frames"] = json!(frame_range(f)?); + } + if movie { + let keep = p.value("keep-frames").map(std::path::absolute).transpose().map_err(|e| Failure::Run(format!("--keep-frames: {e}")))?; + let frames = keep.clone().unwrap_or_else(|| folder.join(format!(".{stem}.{ext}.frames"))); + args["folder"] = json!(frames); + args["name"] = json!("frame_{frame}"); + let mut video = json!({"format": ext, "folder": folder, "name": stem, "keep_frames": keep.is_some()}); + if let Some(f) = p.number::("fps")? { + video["fps"] = json!(f); + } + if let Some(q) = p.number::("quality")? { + video["quality"] = json!(q); + } + args["video"] = video; + } else { + let format = p.value("format").unwrap_or(match ext { + "jpg" | "jpeg" => "jpeg", + "tif" | "tiff" => "tiff", + "psd" => "psd", + "exr" => "exr", + _ => "png", + }); + args["format"] = json!(format); + args["folder"] = json!(folder); + args["name"] = json!(format!("{stem}_{{frame}}")); + if let Some(list) = p.value("passes") { + args["passes"] = json!(list.split(',').map(str::trim).filter(|s| !s.is_empty()).collect::>()); + } + } + let added = run(engine, "anim.render", args)?; + let ids: Vec = added["ids"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + let movie_id = added["movie"]["id"].as_u64(); + let start = Instant::now(); + let mut shown = (usize::MAX, -1i64); + let list = loop { + let list = run(engine, "render.queue_list", json!({}))?; + let jobs = list["jobs"].as_array().cloned().unwrap_or_default(); + let state = |id: u64| jobs.iter().find(|j| j["id"].as_u64() == Some(id)).map(|j| j["state"].as_str().unwrap_or("").to_string()); + let finished = |id: u64| state(id).is_none_or(|s| matches!(s.as_str(), "done" | "failed" | "cancelled")); + let done = ids.iter().filter(|id| finished(**id)).count(); + let encoding = movie_id.and_then(|m| jobs.iter().find(|j| j["id"].as_u64() == Some(m))).filter(|j| j["state"] == "running").map(|j| (j["progress"].as_f64().unwrap_or(0.0) * 10.0) as i64).unwrap_or(-1); + if (done, encoding) != shown { + if encoding >= 0 { + eprintln!("formshot-engine: encoding the movie, {}%, {:.1} s", encoding * 10, start.elapsed().as_secs_f64()); + } else { + eprintln!("formshot-engine: {done}/{} frames, {:.1} s", ids.len(), start.elapsed().as_secs_f64()); + } + shown = (done, encoding); + } + if ids.iter().chain(movie_id.iter()).all(|id| finished(*id)) { + break jobs; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + }; + let job = |id: u64| list.iter().find(|j| j["id"].as_u64() == Some(id)).cloned().unwrap_or(Value::Null); + let first = ids.first().map(|id| job(*id)).unwrap_or(Value::Null); + println!("device: {} ({})", first["drew"].as_str().unwrap_or("?"), first["backend"].as_str().unwrap_or("?")); + if let Some(n) = first["note"].as_str().map(str::to_string).or(selected) { + println!("note: {n}"); + } + if let Some(bad) = ids.iter().map(|id| job(*id)).find(|j| j["state"] != "done") { + let why = bad["error"]["message"].as_str().unwrap_or("the frame did not finish"); + return Err(Failure::Run(format!("frame {}: {why}", bad["frame"]))); + } + println!("{} frames {}x{}, {} samples, in {:.2} s", ids.len(), first["width"], first["height"], first["samples"], start.elapsed().as_secs_f64()); + let Some(m) = movie_id.map(job) else { + for j in ids.iter().map(|id| job(*id)) { + for f in j["files"].as_array().into_iter().flatten() { + println!("{} {} ({} bytes)", f["pass"].as_str().unwrap_or("?"), f["path"].as_str().unwrap_or("?"), f["bytes"]); + } + } + return Ok(()); + }; + if m["state"] != "done" { + return Err(Failure::Run(format!("the movie was not written: {}", m["error"]["message"].as_str().unwrap_or("the job did not finish")))); + } + println!("encoder: {}", m["backend"].as_str().unwrap_or("?")); + println!("encode: {}", m["note"].as_str().unwrap_or("")); + for f in m["files"].as_array().into_iter().flatten() { + println!("movie {} ({} bytes)", f["path"].as_str().unwrap_or("?"), f["bytes"]); + } + Ok(()) +} + /// Selects `cpu`, `gpu` (the best adapter) or `gpu:` for the session; the engine falls back to the CPU with a /// note when a GPU cannot render, and the still's report says which device drew it. fn select_device(engine: &Engine, id: &str) -> Result, Failure> { From 081a81eeaec223cf038db8a48d6b474f75e9dc75 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:50:16 -0500 Subject: [PATCH 028/471] feat(backend): pin the family ffmpeg build and install it on request ffmpeg_fetch.py carries the file and licence-document SHA-256 pins of formai-binaries' ffmpeg 7.1.5-2 record and installs the build into the family's shared formcut-binaries/ffmpeg- folder, checking every file before anything is placed. Run against a fake release folder through FORMCUT_FFMPEG_RELEASE: the real pins and a single wrong hash both left nothing installed, matching pins installed the tree. --- backend/app/ffmpeg_fetch.py | 248 ++++++++++++++++++++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 backend/app/ffmpeg_fetch.py diff --git a/backend/app/ffmpeg_fetch.py b/backend/app/ffmpeg_fetch.py new file mode 100644 index 00000000..5608365b --- /dev/null +++ b/backend/app/ffmpeg_fetch.py @@ -0,0 +1,248 @@ +"""The Form family's ffmpeg (0.9.0): the build FormShot pins, and installing it on request into the folder every Form +app shares (`/formcut-binaries/ffmpeg-`, named exactly as the other Form apps name it), so a build +another Form app downloaded is used and one FormShot downloads is shared. Every file is checked against the SHA-256 +recorded here before anything is installed. Nothing is downloaded on startup; the engine finds the folder itself +and runs ffmpeg as a separate program. + +The pins are copied from formai-binaries' ffmpeg-licence.json (release 7.1.5-2, record written 2026-09-22): each +target's files with their SHA-256 and size, and the two licence documents.""" + +import os +import shutil +import sys +import tarfile +import tempfile +import time +from pathlib import Path +from urllib.parse import quote + +from app.routers.cad import FetchError, download, host_triple, sha256_file + +RELEASE = "7.1.5-2" +FFMPEG = "7.1.5" +LICENCE = "LGPL-2.1-or-later" +SOURCE_URL = "https://ffmpeg.org/releases/ffmpeg-7.1.5.tar.xz" +SOURCE_SHA256 = "de668509caf9e35e3cd162473441fdb29538c6d96ed080292b3cf9e6fc5d558f" +BASES = ( + "https://github.com/nodemode-dev/formai-binaries/releases/download", + "https://github.com/nodemode-dev/formcut-binaries/releases/download", +) +MIRROR_ENV = "FORMCUT_FFMPEG_RELEASE" + +DOCUMENTS = { + "LGPL-2.1.txt": "246041b6ecf9bc32d718a62c57877c78b5eb397b6467e74ed7ae2626ab189c30", + "THIRD-PARTY-NOTICES.txt": "b0e7f25e1c096dd262c7d0253641008cdc5203a1c36cf419aed62b252ead7c1b", +} + +FILES = { + "aarch64-apple-darwin": ( + ("ffmpeg-aarch64-apple-darwin", "58821a3cc7409caa3e54571584fc89f3b336fde5fa0b2dc72598d94a64ed2db4", 370688), + ("ffprobe-aarch64-apple-darwin", "5e3358b2fdab1130588a7348e46654e265e19da844a1d9995d3edd92e9cc2370", 267568), + ("lib-aarch64-apple-darwin/libavcodec.61.dylib", "5d162dc69f296070db400bc29710f138dd28a80ebfa4d5e195607bd4cdfd5672", 15823520), + ("lib-aarch64-apple-darwin/libavdevice.61.dylib", "e3d2eea06a53a4553c0663470a18362c245b58ff87038eccc34c46f09523188e", 114688), + ("lib-aarch64-apple-darwin/libavfilter.10.dylib", "046cf48af9a34ec8dce1781a8c87b585650d70369f734d7f081060ec6d0e94a9", 3927248), + ("lib-aarch64-apple-darwin/libavformat.61.dylib", "75f42a9bab8815ea69ba63237ac17ab92a863a76a3367d02b7fd949234060e8b", 2473744), + ("lib-aarch64-apple-darwin/libavutil.59.dylib", "78ed8424177581aef4e55302631057e86f9fe6e47f615bb5aeacef18a9e98c83", 722384), + ("lib-aarch64-apple-darwin/libswresample.5.dylib", "47176afc562ea09b9c07c6f5382af3733645d767bb31cd9fa632d2882e90207e", 136128), + ("lib-aarch64-apple-darwin/libswscale.8.dylib", "64c454dfd1ad035876e9cd1235c1e901ca36493bdce6b08fb4aa4fa1bd8455d5", 794560), + ), + "x86_64-apple-darwin": ( + ("ffmpeg-x86_64-apple-darwin", "286c5a054124386e074589a296da40fbc3870bc82a06faec8a18713ff34c169a", 348256), + ("ffprobe-x86_64-apple-darwin", "661bce6e4cfa012b9f318791b3ab1e7a2248326a904eacf610866cacabf65dd6", 240288), + ("lib-x86_64-apple-darwin/libavcodec.61.dylib", "7d3ae2916e6a89fdd01093f795144f18d2cf91355b2bdc7f19cb913a4cc90565", 19839872), + ("lib-x86_64-apple-darwin/libavdevice.61.dylib", "842e9c16442d8dd4bfc47885743c71c99bd5a59120e1d17d9d4ad3aea8868457", 90592), + ("lib-x86_64-apple-darwin/libavfilter.10.dylib", "ecee537500a9b50712ea714dc2fdd764a412764ea23bb557768b6d8f6a48061b", 4637920), + ("lib-x86_64-apple-darwin/libavformat.61.dylib", "c65ef7cb0dd65b4d1448fd9bfe8d93de101a83a51d583029495339e3dcd3f368", 2394432), + ("lib-x86_64-apple-darwin/libavutil.59.dylib", "485c43b7cd2d993653e035742ee81e2ce668bb588abe9f5bd8aa9a76d7c08031", 855536), + ("lib-x86_64-apple-darwin/libswresample.5.dylib", "d1d9539ebeb0f23880a8a7438fc4620ab74b1703bb56a0374548324d677b4e2c", 149952), + ("lib-x86_64-apple-darwin/libswscale.8.dylib", "6bcdceb425989d0afb7291611b2a2322858c14c29fc5091f1b0f9122492889e2", 1061056), + ), + "x86_64-unknown-linux-gnu": ( + ("ffmpeg-x86_64-unknown-linux-gnu", "3d69dc24197a0d22cbc14228438c4ab9ff467dd24e45010841f30efb0ea610f1", 383392), + ("ffprobe-x86_64-unknown-linux-gnu", "d960b1e97d28eef08abdc461699fc250e4d751761b513e26a2e73955259970ba", 215968), + ("lib-x86_64-unknown-linux-gnu/libavcodec.so.61", "a055665593e70140f9392e7162766827c580282fc169697cb0788be10636d287", 17711648), + ("lib-x86_64-unknown-linux-gnu/libavdevice.so.61", "e079c97aa5c81d6112e2d4b69a8dd2f843663094d1849b4f23781501ba9b45e8", 77296), + ("lib-x86_64-unknown-linux-gnu/libavfilter.so.10", "0f44b5565e3ae3d5a9d27fa6e2ff2e2ea6c6dd14dcfa2f3a60e7d0782ffebb47", 4519256), + ("lib-x86_64-unknown-linux-gnu/libavformat.so.61", "86527012dc434a83823808453da66472df3c859b763854ad2573b922fea4f27c", 2733424), + ("lib-x86_64-unknown-linux-gnu/libavutil.so.59", "4c65e32eb4f806633ff9370013f3c649a0c849c133d595bfa3a9490f6771bd89", 1067936), + ("lib-x86_64-unknown-linux-gnu/libdrm.so.2", "cdce5fe2f157f623f90e6ff3bd99e74d46568b6d9afcd0c9eecc8e3d41bfeb2f", 330504), + ("lib-x86_64-unknown-linux-gnu/libswresample.so.5", "b41ebec6de028e67a1e450f3d3a2ae9a13ba2aaa838c8658b25f0887f417de2e", 125008), + ("lib-x86_64-unknown-linux-gnu/libswscale.so.8", "7c831badc3a05759bc70bca19a2a500e0eac753b2ff93d540f7360035fbd69c7", 616696), + ("lib-x86_64-unknown-linux-gnu/libva-drm.so.2", "197d126a11deaefdd24eb0de94d83547f04e0ff39cc7b44b12c15ef61834e300", 50696), + ("lib-x86_64-unknown-linux-gnu/libva.so.2", "a3a7746c58252d0318dad512fce3b7dea485e49119083f3da8164a7fea4d605c", 814648), + ), + "x86_64-pc-windows-msvc": ( + ("ffmpeg-x86_64-pc-windows-msvc.exe", "842ed489ba43db2deb4386f821a583e44765554a335ceb2f52a2ad1828920006", 377344), + ("ffprobe-x86_64-pc-windows-msvc.exe", "7b6401a2d0f1bb92b0017c3c9a60d99d4530309591614128a249f34ffc7f95d2", 204800), + ("lib-x86_64-pc-windows-msvc/avcodec-61.dll", "87bd9679bd98d5280341a9f8bc6cf520e66cb05dba5f067fe8e992471724dcec", 17740288), + ("lib-x86_64-pc-windows-msvc/avdevice-61.dll", "76348cb9eabab6799c70355184623d6b9c11972b1857692ee76866ed4486141a", 137216), + ("lib-x86_64-pc-windows-msvc/avfilter-10.dll", "479fcde9aded8f3307a1f4292ae7484b67235dd5c6a8d287dd98325e2215019b", 6840320), + ("lib-x86_64-pc-windows-msvc/avformat-61.dll", "f17d8f99fb5dbbcb98bec2d860859734c4523b80747b525daaef3eb2f4036d07", 2556928), + ("lib-x86_64-pc-windows-msvc/avutil-59.dll", "2bd68edeb5507c40d32f36a784ae529b519d6996605ba2739e65e6131e576e1c", 1051648), + ("lib-x86_64-pc-windows-msvc/swresample-5.dll", "5bfdf8dba05ca916b985ce07532c9f03e59f0777d1fd2d1cafe65dd88e5a0a06", 123392), + ("lib-x86_64-pc-windows-msvc/swscale-8.dll", "0231c1f6eedbdbdcf06a964c28d25d1a1f214f5860494901d52fa2fc2aa851f9", 650752), + ), +} + + +def windows() -> bool: + return sys.platform.startswith("win") + + +def data_dir() -> Path: + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" + if windows(): + return Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") + xdg = os.environ.get("XDG_DATA_HOME", "").strip() + return Path(xdg) if xdg else Path.home() / ".local" / "share" + + +def family_root() -> Path: + return data_dir() / "formcut-binaries" + + +def folder() -> Path: + return family_root() / f"ffmpeg-{RELEASE}" + + +def program_name(triple: str | None = None) -> str: + return f"ffmpeg-{triple or host_triple()}" + (".exe" if windows() else "") + + +def archive_name(triple: str | None = None) -> str: + return f"ffmpeg-lgpl-{RELEASE}-{triple or host_triple()}.tar.gz" + + +def pins(triple: str | None = None) -> tuple: + triple = triple or host_triple() + found = FILES.get(triple) + if not found: + raise FetchError(f"The Form family's ffmpeg {RELEASE} has no build for this computer ({triple}); it has {', '.join(sorted(FILES))}. Nothing was downloaded.") + return found + + +def sources() -> list[str]: + mirror = os.environ.get(MIRROR_ENV, "").strip() + if mirror: + if "://" not in mirror: + mirror = "file://" + quote(str(Path(mirror).expanduser().resolve())) + return [f"{mirror.rstrip('/')}/{archive_name()}"] + return [f"{base}/ffmpeg-{RELEASE}/{archive_name()}" for base in BASES] + + +def safe_rel(rel: str) -> str: + parts = Path(rel).parts + if not rel or rel.startswith(("/", "\\")) or ".." in parts or ":" in rel or "\\" in rel: + raise FetchError(f"The record names an unsafe path {rel!r}. Nothing was installed.") + return rel + + +def expected() -> dict[str, tuple[str, int | None]]: + out: dict[str, tuple[str, int | None]] = {safe_rel(path): (digest, size) for path, digest, size in pins()} + out.update({name: (digest, None) for name, digest in DOCUMENTS.items()}) + return out + + +def check_file(path: Path, rel: str, digest: str, size: int | None) -> None: + if path.is_symlink() or not path.is_file(): + raise FetchError(f"{rel} is not a plain file. Nothing was installed.") + if size is not None and path.stat().st_size != size: + raise FetchError(f"{rel} is {path.stat().st_size} bytes, the record says {size}. Nothing was installed.") + if sha256_file(path) != digest: + raise FetchError(f"{rel} does not match the SHA-256 in the record. Nothing was installed.") + + +def verify(tree: Path, report=None) -> None: + want = expected() + for i, (rel, (digest, size)) in enumerate(want.items()): + if report: + report("verify", i / len(want), f"Checking {rel}.") + check_file(tree / rel, rel, digest, size) + + +def package_root(unpacked: Path) -> Path: + first = pins()[0][0] + for hit in unpacked.rglob(first): + if hit.is_file() and not hit.is_symlink(): + return hit.parent + raise FetchError(f"The archive has no {first}. Nothing was installed.") + + +def unpack(bundle: Path, work: Path, report) -> Path: + report("unpack", 0.0, f"Unpacking {bundle.name}.") + unpacked = work / "archive" + try: + with tarfile.open(bundle) as t: + t.extractall(unpacked, filter="data") + except (tarfile.TarError, OSError) as error: + raise FetchError(f"{bundle.name} could not be unpacked ({error}). Nothing was installed.") from None + root = package_root(unpacked) + verify(root, report) + staged = work / "staged" + for rel in expected(): + (staged / rel).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(root / rel, staged / rel) + for path, _, _ in pins(): + if not path.startswith("lib-") and not windows(): + (staged / path).chmod(0o755) + verify(staged) + return staged + + +def install(report=print) -> Path: + triple = host_triple() + report("record", 0.0, f"Checking the record of ffmpeg {RELEASE} for {triple}.") + pins(triple) + root = family_root() + root.mkdir(parents=True, exist_ok=True) + for stale in root.glob(".formshot-fetch-*"): + if stale.is_dir() and time.time() - stale.stat().st_mtime > 3600: + shutil.rmtree(stale, ignore_errors=True) + work = Path(tempfile.mkdtemp(prefix=".formshot-fetch-", dir=root)) + destination = folder() + try: + bundle = work / archive_name(triple) + reasons = [] + staged = None + for url in sources(): + report("download", 0.0, f"Downloading {bundle.name}.") + try: + download(url, bundle, lambda done, total: report("download", done / total if total else 0.0, f"Downloading {bundle.name}."), timeout=120.0) + staged = unpack(bundle, work, report) + break + except FetchError as error: + reasons.append(f"{url}: {error}") + shutil.rmtree(work / "archive", ignore_errors=True) + shutil.rmtree(work / "staged", ignore_errors=True) + report("download", 0.0, f"{error} Trying the next source.") + if staged is None: + raise FetchError(" ".join(reasons) if reasons else "No source was tried. Nothing was installed.") + if destination.exists(): + os.replace(destination, work / "old") + os.replace(staged, destination) + finally: + shutil.rmtree(work, ignore_errors=True) + report("done", 1.0, f"ffmpeg {RELEASE} is installed in {destination}.") + return destination + + +def installed() -> dict: + where = folder() + program = where / program_name() + out = {"release": RELEASE, "folder": str(where), "program": str(program), "present": program.is_file()} + others = sorted(p.name.removeprefix("ffmpeg-") for p in family_root().glob("ffmpeg-*") if p.is_dir() and p != where) if family_root().is_dir() else [] + out["other_releases"] = others + return out + + +def published() -> dict: + triple = host_triple() + out = {"release": RELEASE, "ffmpeg": FFMPEG, "triple": triple, "licence": LICENCE, "source": {"url": SOURCE_URL, "sha256": SOURCE_SHA256}} + try: + files = pins(triple) + except FetchError as error: + out.update(available=False, reason=str(error)) + return out + out.update(available=True, archive=archive_name(triple), sources=sources(), files=len(files) + len(DOCUMENTS), bytes=sum(size for _, _, size in files)) + return out From cf73889136cd9fe25817e0844bd518031dec15df Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:50:16 -0500 Subject: [PATCH 029/471] feat(backend): ffmpeg status, download on request and movie files The video router answers the engine's video.ffmpeg with the pinned release and the install, starts the family download only on a window request, and serves finished movies. Ran the service import and the fetch route against a fake release: no key gave 403, the bad checksum failed with nothing installed. --- backend/app/routers/video.py | 137 ++++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 3 deletions(-) diff --git a/backend/app/routers/video.py b/backend/app/routers/video.py index 5d989698..2f7f450b 100644 --- a/backend/app/routers/video.py +++ b/backend/app/routers/video.py @@ -1,5 +1,136 @@ -"""Video: finding or downloading the family's ffmpeg and serving the movies the engine writes (0.9.0).""" +"""Video: finding or downloading the family's ffmpeg and serving the movies the engine writes (0.9.0). -from fastapi import APIRouter +The download runs only when the window (or `python -m app.routers.video fetch`) asks for it, never on startup. It +installs the Form family's LGPL build into the folder every Form app shares, where the engine finds it on its next +encode; FORMSHOT_FFMPEG still comes first for the engine when it is set.""" -router = APIRouter() +import json +import sys +import threading +import time +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Query, Request +from fastapi.responses import FileResponse +from starlette.concurrency import run_in_threadpool + +from app import ffmpeg_fetch, window_key +from app.routers.cad import FetchError + +router = APIRouter(prefix="/api/video", tags=["video"]) + +MOVIES = {".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".gif": "image/gif"} + +_lock = threading.Lock() +_job = {"state": "idle", "stage": "", "fraction": 0.0, "message": "", "release": ffmpeg_fetch.RELEASE} + + +def _set(state: str, stage: str, fraction: float, message: str) -> None: + with _lock: + _job.update(state=state, stage=stage, fraction=round(max(0.0, min(1.0, fraction)), 4), message=message, at=time.time()) + snapshot = dict(_job) + try: + from app.agent import events + + events.publish("video.ffmpeg", **snapshot) + except Exception: + pass + + +def _run() -> None: + last = {"at": 0.0, "stage": ""} + + def report(stage: str, fraction: float, message: str) -> None: + now = time.monotonic() + if stage != last["stage"] or now - last["at"] > 0.25 or fraction >= 1.0: + last.update(at=now, stage=stage) + _set("done" if stage == "done" else "running", stage, fraction, message) + + try: + ffmpeg_fetch.install(report) + except FetchError as error: + _set("failed", "", 0.0, str(error)) + except Exception as error: + _set("failed", "", 0.0, f"ffmpeg could not be installed ({error}). Nothing was installed.") + + +def engine_status() -> dict: + try: + from app.engine import EngineError, EngineUnavailable, engine + + try: + return engine.dispatch("video.ffmpeg", {}) + except (EngineError, EngineUnavailable) as error: + return {"found": False, "reason": f"The engine could not be asked ({error})."} + except Exception as error: + return {"found": False, "reason": f"The engine could not be asked ({error})."} + + +def status() -> dict: + with _lock: + job = dict(_job) + return {"engine": engine_status(), "published": ffmpeg_fetch.published(), "installed": ffmpeg_fetch.installed(), "fetch": job} + + +@router.get("/ffmpeg") +async def ffmpeg_status() -> dict: + return await run_in_threadpool(status) + + +@router.post("/ffmpeg/fetch") +async def ffmpeg_fetch_start(request: Request) -> dict: + window_key.require(request) + try: + ffmpeg_fetch.pins() + except FetchError as error: + raise HTTPException(409, str(error)) from None + with _lock: + if _job["state"] == "running": + return {"started": False, "fetch": dict(_job)} + _job.update(state="running", stage="record", fraction=0.0, message="Starting.") + threading.Thread(target=_run, name="ffmpeg-fetch", daemon=True).start() + with _lock: + return {"started": True, "fetch": dict(_job)} + + +def movie_file(path: str) -> Path: + p = Path(path).expanduser() + if not p.is_absolute(): + raise HTTPException(400, "path must be an absolute path") + if p.suffix.lower() not in MOVIES: + raise HTTPException(400, f"{p.name} is not a movie ({', '.join(sorted(MOVIES))})") + if not p.is_file(): + raise HTTPException(404, f"{p} does not exist") + return p + + +@router.get("/movie") +async def movie(path: str = Query(..., min_length=1, max_length=4096)): + p = movie_file(path) + return FileResponse(p, media_type=MOVIES[p.suffix.lower()], filename=p.name) + + +def main(argv: list[str]) -> int: + command = argv[0] if argv else "status" + if command == "status": + print(json.dumps({"published": ffmpeg_fetch.published(), "installed": ffmpeg_fetch.installed()}, indent=2)) + return 0 + if command != "fetch": + print("usage: python -m app.routers.video [status|fetch]", file=sys.stderr) + return 2 + + def report(stage: str, fraction: float, message: str) -> None: + if stage != "download" or fraction in (0.0, 1.0): + print(f"[formshot] {stage:8} {fraction * 100:5.1f}% {message}", flush=True) + + try: + where = ffmpeg_fetch.install(report) + except FetchError as error: + print(f"[formshot] error: {error}", file=sys.stderr) + return 1 + print(f"[formshot] ffmpeg ready: {where / ffmpeg_fetch.program_name()}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) From 6a3186dd10ec926dfc484eb247118bec11600c55 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:50:26 -0500 Subject: [PATCH 030/471] docs(notice): add the ffmpeg section NOTICE.md says how ffmpeg is found and run as a separate program, that it is not shipped in the installer, the family build's LGPL-2.1-or-later and BSD and MIT parts, the hash-checked download on request and where its source is published. Not run. --- NOTICE.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/NOTICE.md b/NOTICE.md index bd37912a..652b0078 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -63,6 +63,15 @@ FormShot 0.8.0 is unreleased. Licences marked "to confirm" below were not read f | FormCAD kernel worker `formcad-kernel` (release occt-8.0.1, built on OpenCascade by nodemode-ai) | as listed in its release record `occt-licence.json`, which is pinned by SHA-256 and checked before install | opens STEP and IGES files; downloaded into the user cache folder only when the person asks (`./formshot cad fetch` or Preferences > CAD Import), run as a separate process and never linked into FormShot | | Intel Open Image Denoise 2.5.1 (the upstream release archives of RenderKit/oidn, unchanged) with oneTBB | Apache-2.0 (OIDN and oneTBB); its third-party notices list PyTorch (BSD-3-Clause), pytorch-msssim (MIT), CUTLASS (BSD-3-Clause), Catch2 (BSL-1.0, tests only) and oneTBB's own BSD and MIT notices | the optional denoiser; downloaded into the user cache only when the person asks (the Final Render window or `./formshot oidn fetch`), every archive and unpacked file checked against SHA-256 pins carried in `backend/app/routers/denoise.py`; the three licence files (`LICENSE.txt`, `third-party-programs.txt`, `third-party-programs-oneTBB.txt`) are unpacked beside the libraries; loaded at run time, never linked or shipped | +## ffmpeg + +FormShot encodes movies (MP4, WebM, MOV, GIF) from rendered frames by running ffmpeg as a separate program. ffmpeg is never linked into FormShot and is not shipped in its installer. The engine runs the program named by `FORMSHOT_FFMPEG`, else the Form family's build in the shared install folder (`formcut-binaries/ffmpeg-` in the user data folder), else `ffmpeg` on the PATH; it never downloads anything. + +| Program | License | Notes | +| --- | --- | --- | +| FFmpeg 7.1.5, the Form family's build (release `ffmpeg-7.1.5-2` of nodemode-dev/formai-binaries), with libvpx 1.17.0 and libopus 1.6.1 built in, and libva and libdrm (Linux) beside it | FFmpeg: LGPL-2.1-or-later (configured with `--disable-gpl --disable-nonfree`, no libx264 or libx265); libvpx and libopus: BSD-3-Clause; libva, libdrm, nv-codec-headers and AMF: MIT | downloaded by the service only when the person asks (`POST /api/video/ffmpeg/fetch`), every file checked against the SHA-256 pins carried in `backend/app/ffmpeg_fetch.py` before anything is installed; the shared libraries sit beside the program and can be replaced, as the LGPL requires. The exact source (`ffmpeg-7.1.5.tar.xz`, libvpx and libopus) is published with that release, and `LGPL-2.1.txt` and `THIRD-PARTY-NOTICES.txt` are installed beside the program | +| an ffmpeg the person installed | the licence it was built under (an ffmpeg built with `--enable-gpl` is GPL) | used when found; `video.ffmpeg` reports whether it is a GPL build. FormShot only runs it and never redistributes it | + ## Data in the material library The presets in `assets/library/` are our own work under Apache-2.0. Their numbers come from these sources, cited in each preset's `source` field and in `assets/library/README.md`: From 618f6c9890561dec58f647d7edf84239a4443f9a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 13:51:00 -0500 Subject: [PATCH 031/471] docs(video): describe sequences, movie formats, encoders and ffmpeg VIDEO.md covers anim.render and its queue jobs, video.encode, what a movie job reports, the encoder chosen per format and the quality scale, where ffmpeg is found and downloaded, the command line and the licences. Not run. --- docs/VIDEO.md | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/VIDEO.md diff --git a/docs/VIDEO.md b/docs/VIDEO.md new file mode 100644 index 00000000..9a7db226 --- /dev/null +++ b/docs/VIDEO.md @@ -0,0 +1,76 @@ +# Image sequences and movies + +FormShot renders an animation frame by frame through the render queue and, when asked, encodes the frames into a movie with ffmpeg. This page covers the commands, how the frames run in the queue, the movie formats and the encoder each one uses, where ffmpeg comes from and the licences involved. + +## Frame sequences: `anim.render` + +`anim.render` takes every argument of `render.queue_add` (folder, name template, image format and its options, size, samples, passes, denoise, camera, device, overwrite, label) except `frame` and `project`, plus: + +| Argument | Meaning | +| --- | --- | +| `frames` | `[first, last]`, frame numbers counted from 1 at the animation's start; the whole range when absent | +| `step` | render every step-th frame of the range (default 1) | +| `video` | `{format, fps?, quality?, keep_frames?, name?, folder?}`: encode a movie after the last frame | + +Frame numbers are the animation's: frame 1 is its start, and the animation's `frame_times` give one time per frame from start to end at its frame rate, both ends included. With a step of 2 the files are numbered 1, 3, 5, ... so the numbers always say which frame a file holds. + +**How frames run in the queue.** Each frame is one ordinary queue job, made through `queue_documents` from a copy of the document evaluated at the frame's time. Every frame therefore has its own progress, samples, device, cancel and files in `render.queue_list`, labelled `

+ +
+ + +
`); + host.appendChild(root); + const list = q(root, '.fsh-shots-list'); + const pending = q(root, '.fsh-shots-row.is-pending'); + const empty = q(root, '.fsh-shots-empty'); + const addBtn = q(root, '.fsh-shots-add'); + setAttr(list, 'aria-label', t('Shots')); + setAttr(q(root, '.fsh-shots-tools'), 'aria-label', t('Shot actions')); + setStyleVar(list, '--fsh-shots-reserve', String(store.remembered.shots)); + setClass(list, 'is-reserved', store.remembered.shots > 0); + + const selected = new Set(); + let pendingTimer: number | undefined; + let adding = false; + + const shots = (): ShotView[] => store.ordered('shots.order', store.shots); + const byId = (id: string): ShotView | undefined => store.shots.find((s) => s.id === id); + + const endPending = (): void => { + window.clearTimeout(pendingTimer); + adding = false; + setHidden(pending, true); + }; + const beginPending = (): void => { + setText(q(pending, '.fsh-shots-name'), t('Shot {n}', { n: store.shots.length + 1 })); + setText(q(pending, '.fsh-shots-sub'), t('Capturing the view')); + adding = true; + setHidden(pending, false); + setHidden(empty, true); + window.clearTimeout(pendingTimer); + pendingTimer = window.setTimeout(() => { endPending(); update(); }, PENDING_MS); + }; + + const apply = async (id: string): Promise => { + const s = byId(id); + if (!s || !ws.canRun(SHOT_CMD.apply)) return; + const reply = await store.act(SHOT_CMD.apply, { id }); + const o = reply && typeof reply === 'object' ? reply as Record : {}; + const skipped = Array.isArray(o.skipped) ? o.skipped.length : 0; + if (skipped) ws.ctx.toast(t('{name} applied; {n} nodes it names are gone and were skipped.', { name: s.name, n: skipped }), 'info'); + }; + + const add = async (): Promise => { + if (adding || !ws.canRun(SHOT_CMD.add)) return; + const before = new Set(store.shots.map((s) => s.id)); + beginPending(); + const reply = await store.act(SHOT_CMD.add, {}); + endPending(); + const id = createdString(reply) || store.shots.find((s) => !before.has(s.id))?.id || ''; + update(); + if (!id) return; + selected.clear(); + selected.add(id); + update(); + list.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`)?.focus(); + }; + + const paintRow = (row: HTMLElement, s: ShotView): void => { + setAttr(row, 'aria-selected', selected.has(s.id) ? 'true' : 'false'); + setText(q(row, '.fsh-shots-name'), s.name); + const sub = s.missing.length ? `${t('{n} nodes it names are gone', { n: s.missing.length })} · ${s.summary}` : s.summary; + setText(q(row, '.fsh-shots-sub'), sub); + setTitle(q(row, '.fsh-shots-text'), sub); + setClass(row, 'is-warn', s.missing.length > 0); + setClass(row, 'is-current', s.matches); + const mark = q(row, '.fsh-shots-mark'); + setAttr(mark, 'aria-hidden', s.matches ? null : 'true'); + setTitle(mark, s.matches ? t('The document matches this shot') : ''); + action(q(row, '.fsh-shots-apply'), 'Apply shot', ws.canRun(SHOT_CMD.apply), ws.why(SHOT_CMD.apply)); + }; + + const createRow = (s: ShotView): HTMLElement => { + const row = el(`
+${glyph('grip', 14)} + +${glyph('current', 14)} + +
`); + setAttr(q(row, '.fsh-shots-mark'), 'aria-label', t('Current')); + paintRow(row, s); + return row; + }; + + const update = (): void => { + const all = shots(); + for (const id of [...selected]) if (!byId(id)) selected.delete(id); + patchList(list, all, { key: (s) => s.id, create: createRow, update: paintRow }); + if (store.loaded) setClass(list, 'is-reserved', false); + const ready = ws.client.state === 'ready' && store.loaded; + const msg = !ws.client.has(SHOT_CMD.list) && ws.client.state === 'ready' ? t('This engine has no shots yet.') + : !ready || adding || all.length ? '' + : t('No shots yet. Set up the view, then Add shot keeps the camera, image style, environment, lights and render settings under a name.'); + setText(empty, msg); + setHidden(empty, msg === ''); + action(addBtn, 'Add shot', ws.canRun(SHOT_CMD.add) && !adding, ws.why(SHOT_CMD.add)); + }; + + const rowOf = (target: EventTarget | null): HTMLElement | null => { + const row = (target as HTMLElement | null)?.closest('.fsh-shots-row'); + return row && row.parentElement === list ? row : null; + }; + let anchor = ''; + const pick = (id: string, e: MouseEvent | KeyboardEvent): void => { + const keys = shots().map((s) => s.id); + if (e.shiftKey && anchor && keys.includes(anchor)) { + const [a, b] = [keys.indexOf(anchor), keys.indexOf(id)].sort((x, y) => x - y); + selected.clear(); + for (const k of keys.slice(a, b + 1)) selected.add(k); + } else if (e.metaKey || e.ctrlKey) { + if (selected.has(id)) selected.delete(id); else selected.add(id); + anchor = id; + } else { + selected.clear(); + selected.add(id); + anchor = id; + } + update(); + }; + + addBtn.addEventListener('click', () => { void add(); }); + list.addEventListener('click', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id) return; + if ((e.target as HTMLElement).closest('.fsh-shots-apply')) { void apply(id); return; } + row.focus(); + pick(id, e); + }); + list.addEventListener('dblclick', (e) => { + const row = rowOf(e.target); + if (!row?.dataset.key || (e.target as HTMLElement).closest('button')) return; + void apply(row.dataset.key); + }); + list.addEventListener('keydown', (e) => { + const row = rowOf(e.target); + const id = row?.dataset.key; + if (!row || !id || e.target !== row) return; + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; + if (next?.dataset.key) { next.focus(); pick(next.dataset.key, e); } + } else if (e.key === 'Enter') { + void apply(id); + } else if (e.key === ' ') { + pick(id, e); + } else if (e.key === 'Escape' && selected.size) { + selected.clear(); + update(); + } else return; + e.preventDefault(); + e.stopPropagation(); + }); + + update(); + return { + update, + add, + dispose: () => { window.clearTimeout(pendingTimer); }, + }; +} From 2f561eb2b7aca17c37c935078ee567037a4af2b6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 15:48:38 -0500 Subject: [PATCH 099/471] feat(shots): rename shots in place A shot's name turns into a field in its own row (F2, or straight after Add shot with the text selected); Enter or leaving the field runs shot.set, Escape cancels, and the typed name is held until the list agrees. Ran npx tsc --noEmit. --- frontend/src/ui/shots/rename.ts | 38 +++++++++++++++++++++++++++++++++ frontend/src/ui/shots/shots.ts | 27 ++++++++++++++++++++--- 2 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 frontend/src/ui/shots/rename.ts diff --git a/frontend/src/ui/shots/rename.ts b/frontend/src/ui/shots/rename.ts new file mode 100644 index 00000000..8faf762e --- /dev/null +++ b/frontend/src/ui/shots/rename.ts @@ -0,0 +1,38 @@ +import { setHidden } from '../../shell/dom'; + +export interface InlineName { + begin(value: string): void; + editing(): boolean; +} + +export function inlineName(label: HTMLElement, input: HTMLInputElement, commit: (value: string) => void): InlineName { + let start = ''; + let open = false; + const end = (save: boolean): void => { + if (!open) return; + open = false; + const v = input.value.trim(); + setHidden(input, true); + setHidden(label, false); + if (save && v && v !== start) commit(v); + }; + input.addEventListener('keydown', (e) => { + e.stopPropagation(); + if (e.key === 'Enter') { e.preventDefault(); end(true); label.closest('[tabindex]')?.focus(); } + else if (e.key === 'Escape') { e.preventDefault(); end(false); label.closest('[tabindex]')?.focus(); } + }); + input.addEventListener('blur', () => end(true)); + for (const type of ['click', 'dblclick', 'pointerdown'] as const) input.addEventListener(type, (e) => e.stopPropagation()); + return { + begin: (value) => { + start = value; + input.value = value; + open = true; + setHidden(label, true); + setHidden(input, false); + input.focus(); + input.select(); + }, + editing: () => open, + }; +} diff --git a/frontend/src/ui/shots/shots.ts b/frontend/src/ui/shots/shots.ts index a527a97e..70f1c422 100644 --- a/frontend/src/ui/shots/shots.ts +++ b/frontend/src/ui/shots/shots.ts @@ -3,6 +3,7 @@ import { icon } from '../../shell/icons'; import { t } from '../../i18n'; import type { Workspace } from '../context'; import { glyph } from './glyphs'; +import { inlineName, type InlineName } from './rename'; import { createdString, SHOT_CMD, type ShotView } from './model'; import type { ShotsStore } from './store'; @@ -42,6 +43,19 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): setClass(list, 'is-reserved', store.remembered.shots > 0); const selected = new Set(); + const names = new WeakMap(); + const rowFor = (id: string): HTMLElement | null => list.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`); + const rename = (id: string): void => { + const row = rowFor(id); + const s = byId(id); + if (!row || !s || !ws.canRun(SHOT_CMD.set)) return; + row.dataset.editing = 'true'; + names.get(row)?.begin(store.shown(`shot.name.${id}`, s.name)); + }; + const commitName = (id: string, name: string): void => { + store.hold(`shot.name.${id}`, name); + void store.act(SHOT_CMD.set, { id, name }); + }; let pendingTimer: number | undefined; let adding = false; @@ -84,12 +98,13 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): selected.clear(); selected.add(id); update(); - list.querySelector(`:scope > [data-key="${CSS.escape(id)}"]`)?.focus(); + rowFor(id)?.focus(); + rename(id); }; const paintRow = (row: HTMLElement, s: ShotView): void => { setAttr(row, 'aria-selected', selected.has(s.id) ? 'true' : 'false'); - setText(q(row, '.fsh-shots-name'), s.name); + setText(q(row, '.fsh-shots-name'), store.shown(`shot.name.${s.id}`, s.name)); const sub = s.missing.length ? `${t('{n} nodes it names are gone', { n: s.missing.length })} · ${s.summary}` : s.summary; setText(q(row, '.fsh-shots-sub'), sub); setTitle(q(row, '.fsh-shots-text'), sub); @@ -104,11 +119,15 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): const createRow = (s: ShotView): HTMLElement => { const row = el(`
${glyph('grip', 14)} - + ${glyph('current', 14)}
`); setAttr(q(row, '.fsh-shots-mark'), 'aria-label', t('Current')); + const input = q(row, '.fsh-shots-name-input'); + setAttr(input, 'aria-label', t('Shot name')); + names.set(row, inlineName(q(row, '.fsh-shots-name'), input, (v) => commitName(s.id, v))); + input.addEventListener('blur', () => { delete row.dataset.editing; }); paintRow(row, s); return row; }; @@ -170,6 +189,8 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; if (next?.dataset.key) { next.focus(); pick(next.dataset.key, e); } + } else if (e.key === 'F2') { + rename(id); } else if (e.key === 'Enter') { void apply(id); } else if (e.key === ' ') { From 31ee3ea1e72894631b715636670e723a75c76c1a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 15:49:39 -0500 Subject: [PATCH 100/471] feat(shots): shot actions and include flags in a popover Each row's options popover renames, recaptures (shot.update), duplicates, moves up or down and removes a shot, and toggles the seven include flags through shot.set; keyboard: Alt+arrows move, Delete removes, the context key opens it. Ran npx tsc --noEmit. --- frontend/src/ui/shots/popover.ts | 63 +++++++++++++++++ frontend/src/ui/shots/shots.css | 17 +++++ frontend/src/ui/shots/shots.ts | 118 +++++++++++++++++++++++++++++-- 3 files changed, 194 insertions(+), 4 deletions(-) create mode 100644 frontend/src/ui/shots/popover.ts diff --git a/frontend/src/ui/shots/popover.ts b/frontend/src/ui/shots/popover.ts new file mode 100644 index 00000000..26c5e508 --- /dev/null +++ b/frontend/src/ui/shots/popover.ts @@ -0,0 +1,63 @@ +import { el, setHidden, setStyleVar } from '../../shell/dom'; + +export class ShotsPopover { + readonly root: HTMLElement; + private anchor: HTMLElement | null = null; + private readonly closeFns = new Set<() => void>(); + private readonly outside = (e: PointerEvent): void => { + const target = e.target as Node; + if (!this.root.contains(target) && !this.anchor?.contains(target)) this.close(); + }; + + constructor(className: string, label: string) { + this.root = el(``); + this.root.setAttribute('aria-label', label); + this.root.addEventListener('keydown', (e) => { + if (e.key !== 'Escape') return; + e.stopPropagation(); + const back = this.anchor; + this.close(); + if (back?.isConnected) back.focus(); + }); + (document.getElementById('overlay-root') ?? document.body).appendChild(this.root); + } + + get isOpen(): boolean { return !this.root.hidden; } + get owner(): HTMLElement | null { return this.isOpen ? this.anchor : null; } + + onClose(fn: () => void): void { this.closeFns.add(fn); } + + open(anchor: HTMLElement): void { + this.anchor = anchor; + setHidden(this.root, false); + this.place(); + document.addEventListener('pointerdown', this.outside, true); + this.root.querySelector('input:not([disabled]), button:not([disabled])')?.focus(); + } + + place(): void { + if (!this.anchor || this.root.hidden) return; + const r = this.anchor.getBoundingClientRect(); + const w = this.root.offsetWidth; + const h = this.root.offsetHeight; + const left = Math.max(8, Math.min(window.innerWidth - w - 8, r.right - w)); + const below = r.bottom + 4; + const top = below + h > window.innerHeight - 8 ? Math.max(8, r.top - h - 4) : below; + setStyleVar(this.root, '--fsh-shots-pop-x', `${Math.round(left)}px`); + setStyleVar(this.root, '--fsh-shots-pop-y', `${Math.round(top)}px`); + } + + toggle(anchor: HTMLElement): void { + if (this.isOpen && this.anchor === anchor) this.close(); + else this.open(anchor); + } + + close(): void { + if (this.root.hidden) return; + setHidden(this.root, true); + document.removeEventListener('pointerdown', this.outside, true); + for (const fn of this.closeFns) fn(); + } + + dispose(): void { this.close(); this.root.remove(); } +} diff --git a/frontend/src/ui/shots/shots.css b/frontend/src/ui/shots/shots.css index f8798c42..64852657 100644 --- a/frontend/src/ui/shots/shots.css +++ b/frontend/src/ui/shots/shots.css @@ -30,3 +30,20 @@ .fsh-shots-row .fsh-icon-btn:disabled { opacity: 0.45; cursor: default; } .fsh-shots-empty { margin: var(--space-1) 0 0; color: var(--text-muted); font-size: var(--fs-12); line-height: var(--lh); } .fsh-shots-empty[hidden] { display: none; } + +.fsh-shots-pop { position: fixed; left: var(--fsh-shots-pop-x, 0); top: var(--fsh-shots-pop-y, 0); z-index: var(--z-menu); max-height: min(70vh, 520px); overflow-y: auto; padding: var(--space-1); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); background: var(--glass-bg); box-shadow: inset 0 1px 0 var(--glass-highlight), var(--glass-shadow); backdrop-filter: var(--glass-filter); -webkit-backdrop-filter: var(--glass-filter); pointer-events: auto; } +.fsh-shots-pop[hidden] { display: none; } +.fsh-shots-options { width: 250px; } +.fsh-shots-menu { display: flex; flex-direction: column; gap: 1px; } +.fsh-shots-menu-item { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-primary); font: inherit; font-size: var(--fs-12); text-align: left; cursor: pointer; } +.fsh-shots-menu-item > span:not(.fsh-icon) { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fsh-shots-menu-item kbd { color: var(--text-faint); font: var(--fs-10) var(--mono); } +.fsh-shots-menu-item:hover, .fsh-shots-menu-item:focus-visible { background: var(--bg-hover); outline: none; } +.fsh-shots-menu-item:disabled { opacity: 0.45; cursor: default; } +.fsh-shots-menu-item:disabled:hover { background: transparent; } +.fsh-shots-menu-item.is-danger { color: var(--danger-text); } +.fsh-shots-menu-rule { height: 1px; margin: var(--space-1) var(--space-1); background: var(--line-1); } +.fsh-shots-pop-title { margin: var(--space-1) var(--space-2); color: var(--text-faint); font-size: var(--fs-10); font-weight: var(--fw-semibold); letter-spacing: 0.06em; text-transform: uppercase; } +.fsh-shots-flag { display: flex; align-items: center; gap: var(--space-2); height: var(--ctl-sm); padding: 0 var(--space-2); border-radius: var(--radius); color: var(--text-primary); font-size: var(--fs-12); cursor: pointer; } +.fsh-shots-flag:hover { background: var(--bg-hover); } +.fsh-shots-flag input { flex: none; width: 14px; height: 14px; margin: 0; accent-color: var(--accent-color); } diff --git a/frontend/src/ui/shots/shots.ts b/frontend/src/ui/shots/shots.ts index 70f1c422..67dd0485 100644 --- a/frontend/src/ui/shots/shots.ts +++ b/frontend/src/ui/shots/shots.ts @@ -1,10 +1,11 @@ -import { el, escapeHtml, patchList, q, setAttr, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; +import { el, escapeHtml, patchList, q, setAttr, setChecked, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from '../../shell/dom'; import { icon } from '../../shell/icons'; import { t } from '../../i18n'; import type { Workspace } from '../context'; import { glyph } from './glyphs'; +import { createdString, INCLUDE_KEYS, INCLUDE_LABELS, SHOT_CMD, type Include, type IncludeKey, type ShotView } from './model'; +import { ShotsPopover } from './popover'; import { inlineName, type InlineName } from './rename'; -import { createdString, SHOT_CMD, type ShotView } from './model'; import type { ShotsStore } from './store'; const PENDING_MS = 6000; @@ -56,6 +57,103 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): store.hold(`shot.name.${id}`, name); void store.act(SHOT_CMD.set, { id, name }); }; + + const menu = new ShotsPopover('fsh-shots-options', t('Shot options')); + menu.root.innerHTML = `
+ + + + + + +

${escapeHtml(t('Applying the shot restores'))}

+${INCLUDE_KEYS.map((k) => ``).join('')} + + +
`; + let menuFor = ''; + const paintMenu = (): void => { + if (!menu.isOpen) return; + const s = byId(menuFor); + if (!s) { menu.close(); return; } + const keys = shots().map((x) => x.id); + const at = keys.indexOf(s.id); + const can = (b: string, ok: boolean, why = ''): void => { + const btn = q(menu.root, `[data-act="${b}"]`); + setDisabled(btn, !ok); + setTitle(btn, ok ? '' : why); + }; + can('rename', ws.canRun(SHOT_CMD.set), ws.why(SHOT_CMD.set)); + can('recapture', ws.canRun(SHOT_CMD.update), ws.why(SHOT_CMD.update)); + can('duplicate', ws.canRun(SHOT_CMD.duplicate), ws.why(SHOT_CMD.duplicate)); + can('up', at > 0 && ws.canRun(SHOT_CMD.move), ws.why(SHOT_CMD.move)); + can('down', at >= 0 && at < keys.length - 1 && ws.canRun(SHOT_CMD.move), ws.why(SHOT_CMD.move)); + can('remove', ws.canRun(SHOT_CMD.remove), ws.why(SHOT_CMD.remove)); + const flags = store.shown(`shot.include.${s.id}`, s.include); + for (const box of menu.root.querySelectorAll('input[data-flag]')) { + setChecked(box, flags[box.dataset.flag as IncludeKey]); + setDisabled(box, !ws.canRun(SHOT_CMD.set)); + } + }; + const openMenu = (id: string, anchor: HTMLElement): void => { + if (menu.isOpen && menuFor === id) { menu.close(); return; } + menuFor = id; + menu.open(anchor); + paintMenu(); + menu.place(); + }; + const move = (id: string, index: number): void => { + const keys = shots().map((s) => s.id).filter((k) => k !== id); + const at = Math.max(0, Math.min(keys.length, index)); + keys.splice(at, 0, id); + store.hold('shots.order', keys); + void store.act(SHOT_CMD.move, { id, index: at }); + }; + const nudge = (id: string, by: number): void => { + const at = shots().findIndex((s) => s.id === id); + if (at < 0 || at + by < 0 || at + by >= store.shots.length) return; + move(id, at + by); + }; + const remove = async (id: string): Promise => { + const keys = shots().map((s) => s.id); + const at = keys.indexOf(id); + await store.act(SHOT_CMD.remove, { id }); + selected.delete(id); + const next = shots()[Math.min(at, store.shots.length - 1)]; + if (next) rowFor(next.id)?.focus(); + update(); + }; + const duplicate = async (id: string): Promise => { + const before = new Set(store.shots.map((s) => s.id)); + const reply = await store.act(SHOT_CMD.duplicate, { id }); + const made = createdString(reply) || store.shots.find((s) => !before.has(s.id))?.id || ''; + if (!made) return; + selected.clear(); + selected.add(made); + update(); + rowFor(made)?.focus(); + }; + menu.root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-act]'); + const id = menuFor; + if (!b || !id || b.disabled) return; + const act = b.dataset.act; + if (act === 'up' || act === 'down') { nudge(id, act === 'up' ? -1 : 1); return; } + menu.close(); + if (act === 'rename') rename(id); + else if (act === 'recapture') void store.act(SHOT_CMD.update, { id }); + else if (act === 'duplicate') void duplicate(id); + else if (act === 'remove') void remove(id); + }); + menu.root.addEventListener('change', (e) => { + const box = (e.target as HTMLElement).closest('input[data-flag]'); + const s = byId(menuFor); + if (!box || !s) return; + const flag = box.dataset.flag as IncludeKey; + const next = { ...store.shown(`shot.include.${s.id}`, s.include), [flag]: box.checked }; + store.hold(`shot.include.${s.id}`, next); + void store.act(SHOT_CMD.set, { id: s.id, include: { [flag]: box.checked } }); + }); let pendingTimer: number | undefined; let adding = false; @@ -122,7 +220,11 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): ${glyph('current', 14)} + `); + const more = q(row, '.fsh-shots-more'); + setAttr(more, 'aria-label', t('Shot options')); + setTitle(more, t('Shot options')); setAttr(q(row, '.fsh-shots-mark'), 'aria-label', t('Current')); const input = q(row, '.fsh-shots-name-input'); setAttr(input, 'aria-label', t('Shot name')); @@ -144,6 +246,7 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): setText(empty, msg); setHidden(empty, msg === ''); action(addBtn, 'Add shot', ws.canRun(SHOT_CMD.add) && !adding, ws.why(SHOT_CMD.add)); + paintMenu(); }; const rowOf = (target: EventTarget | null): HTMLElement | null => { @@ -174,6 +277,7 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): const id = row?.dataset.key; if (!row || !id) return; if ((e.target as HTMLElement).closest('.fsh-shots-apply')) { void apply(id); return; } + if ((e.target as HTMLElement).closest('.fsh-shots-more')) { openMenu(id, q(row, '.fsh-shots-more')); return; } row.focus(); pick(id, e); }); @@ -186,11 +290,17 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): const row = rowOf(e.target); const id = row?.dataset.key; if (!row || !id || e.target !== row) return; - if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + if ((e.key === 'ArrowDown' || e.key === 'ArrowUp') && e.altKey) { + nudge(id, e.key === 'ArrowUp' ? -1 : 1); + } else if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { const next = (e.key === 'ArrowDown' ? row.nextElementSibling : row.previousElementSibling) as HTMLElement | null; if (next?.dataset.key) { next.focus(); pick(next.dataset.key, e); } } else if (e.key === 'F2') { rename(id); + } else if (e.key === 'Delete' || e.key === 'Backspace') { + if (ws.canRun(SHOT_CMD.remove)) void remove(id); + } else if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) { + openMenu(id, q(row, '.fsh-shots-more')); } else if (e.key === 'Enter') { void apply(id); } else if (e.key === ' ') { @@ -207,6 +317,6 @@ export function mountShots(host: HTMLElement, ws: Workspace, store: ShotsStore): return { update, add, - dispose: () => { window.clearTimeout(pendingTimer); }, + dispose: () => { window.clearTimeout(pendingTimer); menu.dispose(); }, }; } From e07c8890c0a852c466cfbc2bbef25f30d0aeabb8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Thu, 3 Dec 2026 15:49:52 -0500 Subject: [PATCH 101/471] feat(shots): reorder shots by dragging the grip A small sortable helper marks the drop place with an inset line (no layout change) and answers the final index; the page holds the new order until shot.move's listing agrees. Ran npx tsc --noEmit. --- frontend/src/ui/shots/shots.ts | 8 ++- frontend/src/ui/shots/sortable.ts | 102 ++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 frontend/src/ui/shots/sortable.ts diff --git a/frontend/src/ui/shots/shots.ts b/frontend/src/ui/shots/shots.ts index 67dd0485..7beaa703 100644 --- a/frontend/src/ui/shots/shots.ts +++ b/frontend/src/ui/shots/shots.ts @@ -6,6 +6,7 @@ import { glyph } from './glyphs'; import { createdString, INCLUDE_KEYS, INCLUDE_LABELS, SHOT_CMD, type Include, type IncludeKey, type ShotView } from './model'; import { ShotsPopover } from './popover'; import { inlineName, type InlineName } from './rename'; +import { sortable } from './sortable'; import type { ShotsStore } from './store'; const PENDING_MS = 6000; @@ -313,10 +314,15 @@ ${INCLUDE_KEYS.map((k) => `