Skip to main content

machine_winder/
lib.rs

1//! A winder and unwinder with a dancer, as in film, paper and foil converting: a web runs from an unwind roll down
2//! over a dancer roller and up to a rewind roll, at a line speed, under a tension. Both rolls are centre-driven, each by
3//! a servo motor through a gearbox of ratio i; the dancer is a roller on a vertical slide, pushed down by a pneumatic
4//! cylinder (its force the tension setpoint, `dancer`), and its position is the measured value of the tension loop.
5//!
6//! The tool axis is the line position L (m): the web wound onto the rewind roll since it was empty, which is the web
7//! paid out by the unwind roll since it was full when the dancer stands in the middle. So L = 0 has the unwind full and
8//! the rewind on its core, L = the roll's capacity the other way round, and every pose is a pair of radii. The axis runs
9//! over a stretch of the roll (`roll.run_from_m`, `roll.run_m`): a run takes metres of a roll of hundreds.
10//!
11//! Rolls: a roll of web of thickness h on a core of radius r_c gains h per turn, so its radius is linear in its angle
12//! (an Archimedean spiral), r = r_c + h phi / (2 pi) for the rewind and r = r_f - h phi / (2 pi) for the unwind, and
13//! r^2 = r_c^2 + h s / pi with s the web on it: s(phi) = phi (r_c + r) / 2. Its inertia is the web's, a thick-walled
14//! cylinder, 1/2 rho w pi (r^4 - r_c^4), plus core and shaft, plus the motor's rotor and the gearbox's input through
15//! the ratio, i^2 J_m: the reflected inertia changes over a run by r^4, the torque for a tension by r.
16//!
17//! A roll that gains or loses web at its surface, where the web moves with the roll's surface, gets no torque from the
18//! web's mass flow: J dw/dt = sum of the torques (not d(J w)/dt). Unwind: J_u w_u' = i (tau_u - friction) + T1 r_u;
19//! rewind: J_r w_r' = i (tau_r - friction) - T2 r_r. Kinetic energy is carried from one roll to the other with the
20//! web (1/2 lambda v^3 per second each way, lambda = rho w h), booked with the web's transport (`power.web_transport`).
21//!
22//! The web (effects.web_stretch): two spans, unwind to dancer and dancer to rewind, of length L_k0 + y (y the dancer's
23//! travel down from the middle; each span is vertical, so both lengthen by y), each holding M_k of web unstretched.
24//! Its tension T = EA (L / M - 1) while L > M, plus the material damping EA tau dE/dt, and 0 while slack. The web
25//! carries its strain from span to span: what leaves a span leaves at its strain, so
26//!   dM1/dt = v_u / (1 + eps_0) - v_d / (1 + eps_1),   dM2/dt = v_d / (1 + eps_1) - v_r / (1 + eps_2),
27//! eps_0 the strain the unwind roll was wound at (`roll.wound_tension_n`), v_d the dancer roller's surface speed, and
28//! upwind in the other direction (backwards the rewind gives off web at the tension setpoint's strain). To first order
29//! in the strains this is the span equation L dT2/dt = EA (v2 - v1) + v1 T1 - v2 T2 plus EA dL/dt; the form here keeps
30//! the web's length exactly: what leaves the unwind arrives at the rewind plus what the spans store. The span's
31//! length change with the rolls' radii (the web leaves each roll over a fixed idler, not drawn) is left out, and the
32//! web's own mass in the spans.
33//!
34//! The dancer roller turns with the web (no slip) with its own inertia and bearing drag: J_d w_d' = R (T2 - T1) -
35//! drag; the dancer's slide carries it with its mass, its friction and its stops (effects.hard_stops):
36//! m y'' = F_cyl - k_air y + m g - T1 - T2 - friction. The cylinder's force is set so that it holds the tension
37//! setpoint, F_cyl = 2 T_set - m g (the dancer's own weight taken off, as dancer controls do), with the taper
38//! T_set(r) = T0 (1 - k (1 - r_c / r)) over the rewind's radius (effects.tension_taper).
39//!
40//! The rigid model (effects.web_stretch off): the web does not stretch, so the dancer stands at half of what the unwind
41//! paid out more than the rewind took up, y = (s_u - s_r) / 2, and the roller turns at (v_u + v_r) / (2 R); the two
42//! tensions follow from the dancer's and the roller's balance (`Winder::eval`).
43//!
44//! Control, as such drives are run, with the controller's own loops: both motors follow the line position by
45//! electronic gearing (the inverse kinematics: the angles of the line position at the radii computed from the wound
46//! length, so the speed setpoint is i v / r), with the tension's torque and the roll's inertia fed forward
47//! (T r / i and J(r) w' / i plus the rotor's, `feedforward_torque_moving`). The dancer's position loop (`dancer.position
48//! _loop`), a PI as a winder's technology controller runs it, trims the unwind: its speed trim, integrated, is web the
49//! unwind pays out beyond the line position, which `inverse` adds to the unwind's wound length, so the unwind runs on
50//! the line speed over its radius plus the trim, its radius following the web it gave, and its position loop holds the
51//! integral of that. Of a state the line position is the mean of the two rolls' (`tool_state`), the unwind's less the
52//! trim: in the rigid model the web's travel at the dancer roller.
53//!
54//! Gearboxes: rigid, with their efficiency (effects.gearbox_efficiency), no-load drag (effects.gearbox_drag) and, with
55//! effects.thermal_feedback, both at their temperature; each motor has a holding brake (effects.holding_brake) that keeps
56//! the roll, and with it the tension, while the drives are off.
57
58use sim_components::mech::{GearDrag, Gearbox, HoldingBrake, ThermalFeedback};
59use sim_core::{
60    AxisInfo, Config, ConfigError, ENERGY_PARTS, FrameMomentum, LOSS_PREFIX, Label, Machine, MachineEntry, Mode,
61    MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
62};
63use std::f64::consts::{PI, TAU};
64
65pub static ENTRY: MachineEntry = MachineEntry {
66    id: "winder",
67    key: "machine-winder",
68    default_config: include_str!("../default.toml"),
69    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
70    build,
71    suite_configs,
72};
73
74const G: f64 = 9.80665;
75/// Below this power a gearbox's efficiency fades out, so a gearbox at rest has no torque step (as `mech::Gearbox`).
76const EFFICIENCY_FADE_W: f64 = 0.5;
77
78/// Effects that take energy out or put it in; the standard suite runs with them off. The taper changes the cylinder's
79/// force with the rewind's radius, which puts energy in or takes it out.
80pub const LOSSY_EFFECTS: [&str; 6] =
81    ["motor_friction", "gearbox_efficiency", "gearbox_drag", "dancer_friction", "web_damping", "tension_taper"];
82
83fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
84    sim_components::base::mount(cfg, Box::new(Winder::new(cfg)?))
85}
86
87/// The default config with every loss switched off.
88pub fn lossless_config() -> Config {
89    let mut cfg = ENTRY.config();
90    for effect in LOSSY_EFFECTS {
91        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
92    }
93    cfg.set_text("dancer.stop_damping_n_s_m = 0.0").unwrap();
94    cfg
95}
96
97/// Loss-free rigid and elastic models, with and without the weight on the dancer (payload), run in the middle of the roll
98/// (`on_the_roll`). There the two radii are equal: under the constant holding torques of the suite's runs the tension
99/// stays where the unwind was wound, and the web carries no energy in or out (`power.web_transport`). At the roll's start
100/// the radii grow apart over the run, the tension the torques hold drifts off the wound tension, and the strain the web
101/// carries in and out is the energy the elastic runs lose there (0.36 % of what the pulse puts in over the 10 s, as
102/// `power.web_transport` books it, which the loss budget of the default config closes).
103fn suite_configs() -> Vec<Config> {
104    [(false, true), (false, false), (true, true), (true, false)]
105        .into_iter()
106        .map(|(elastic, payload)| {
107            let mut cfg = lossless_config();
108            cfg.set_text(&format!("effects.web_stretch = {elastic}")).unwrap();
109            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
110            on_the_roll(&mut cfg, 633.0);
111            cfg
112        })
113        .collect()
114}
115
116/// `cfg` with its axis over the 20 m of the roll from `from` on, its start 7 m in and its cycle 3 m forward and back as
117/// shipped.
118pub fn on_the_roll(cfg: &mut Config, from: f64) {
119    let (start, end) = (from + 7.0, from + 10.0);
120    cfg.set_text(&format!("roll.run_from_m = {from:?}")).unwrap();
121    cfg.set_text("roll.run_m = 20.0").unwrap();
122    cfg.set_text(&format!("start.pose = [{start:?}]")).unwrap();
123    cfg.set_text(&format!(
124        "cycle.segment = [{{ target = [{end:?}], dwell_s = 0.3, payload = false }}, \
125         {{ target = [{start:?}], dwell_s = 0.3, payload = true }}]"
126    ))
127    .unwrap();
128}
129
130/// A roll of web: core, full radius, the web's thickness, density times width and the inertia of core and shaft.
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct Roll {
133    pub core: f64,
134    pub full: f64,
135    pub thickness: f64,
136    /// rho w, kg/m^2 (per metre of radius and of length: the web's mass per area of its cross-section is rho).
137    pub density_width: f64,
138    pub core_inertia: f64,
139}
140
141impl Roll {
142    /// The radius with `wound` metres of web on the core: r^2 = r_c^2 + h s / pi.
143    pub fn radius(&self, wound: f64) -> f64 {
144        (self.core * self.core + self.thickness * wound / PI).max(0.0).sqrt()
145    }
146    /// The web a full roll holds, m: pi (r_f^2 - r_c^2) / h.
147    pub fn capacity(&self) -> f64 {
148        PI * (self.full * self.full - self.core * self.core) / self.thickness
149    }
150    /// The web's mass on the roll at radius `r`, kg: rho w pi (r^2 - r_c^2).
151    pub fn web_mass(&self, r: f64) -> f64 {
152        let r = r.max(self.core);
153        self.density_width * PI * (r * r - self.core * self.core)
154    }
155    /// The roll's inertia about its axis at radius `r`: the web, 1/2 rho w pi (r^4 - r_c^4), plus core and shaft.
156    pub fn inertia(&self, r: f64) -> f64 {
157        let r = r.max(self.core);
158        0.5 * self.density_width * PI * (r.powi(4) - self.core.powi(4)) + self.core_inertia
159    }
160    /// dJ/dr = 2 pi rho w r^3 (0 inside the core).
161    fn inertia_slope(&self, r: f64) -> f64 {
162        if r > self.core { TAU * self.density_width * r.powi(3) } else { 0.0 }
163    }
164}
165
166/// Coulomb (smoothed by tanh), viscous: [level, viscous, smoothing speed]; all zero with its effect off.
167#[derive(Debug, Clone, Copy, Default, PartialEq)]
168struct Friction([f64; 3]);
169
170impl Friction {
171    fn from_config(cfg: &Config, on: bool, keys: [&str; 3]) -> Result<Self, ConfigError> {
172        let smoothing = cfg.positive(keys[2])?;
173        if !on {
174            return Ok(Self([0.0, 0.0, smoothing]));
175        }
176        Ok(Self([cfg.non_negative(keys[0])?, cfg.non_negative(keys[1])?, smoothing]))
177    }
178    /// The force or torque opposing a positive speed.
179    fn at(&self, speed: f64) -> f64 {
180        let [c, b, s] = self.0;
181        c * (speed / s).tanh() + b * speed
182    }
183}
184
185/// What `Winder::eval` works out of a state: kinematics, the web's tensions, the rates and the forces.
186#[derive(Debug, Clone, Copy, Default)]
187pub struct Eval {
188    /// Radii, roll speeds (rad/s), surface speeds and inertias at the rolls (web, core, rotor through the ratio),
189    /// unwind first.
190    pub r: [f64; 2],
191    pub w: [f64; 2],
192    pub v: [f64; 2],
193    pub j: [f64; 2],
194    /// The dancer's travel down from the middle, its speed, and its roller's speed (rad/s).
195    pub y: f64,
196    pub vy: f64,
197    pub wd: f64,
198    /// The spans' tensions (unwind to dancer, dancer to rewind), the spring's share of them, their strains, their
199    /// lengths, the web they hold and its rate (the elastic model; the rigid one has the tensions alone).
200    pub t: [f64; 2],
201    pub spring: [f64; 2],
202    pub strain: [f64; 2],
203    pub length: [f64; 2],
204    pub material: [f64; 2],
205    pub material_rate: [f64; 2],
206    /// The web crossing into span 1 from the unwind, from span 1 to span 2 over the roller, and out of span 2 onto the
207    /// rewind, m/s unstretched (the elastic model).
208    pub flow: [f64; 3],
209    /// The rolls' angular accelerations, the dancer's and its roller's.
210    pub acc: [f64; 2],
211    pub ydd: f64,
212    pub wdd: f64,
213    /// Shaft friction, holding brake and the gearbox's drag at each motor (N m, opposing its speed), the drag alone, the
214    /// rate of each brake's deflection, the dancer slide's friction (N) and its roller's (N m).
215    pub shaft: [f64; 2],
216    pub drag: [f64; 2],
217    pub brake_rate: [f64; 2],
218    /// Each gearbox's factor on what it passes (`Winder::loss_factor`) and the torque at its input, N m.
219    pub factor: [f64; 2],
220    pub gear_input: [f64; 2],
221    pub slide: f64,
222    pub roller: f64,
223    /// The stops' force on the dancer (N, along y), their stored energy and their loss.
224    pub stop: [f64; 3],
225    /// The cylinder's force setpoint and its force at the dancer's travel (less the air spring's k y).
226    pub cylinder: f64,
227    pub load: f64,
228}
229
230pub struct Winder {
231    pub roll: Roll,
232    pub ratio: f64,
233    /// Each gearbox's efficiency now (1 with effects.gearbox_efficiency off; with effects.thermal_feedback at its
234    /// temperature), its no-load running torque (effects.gearbox_drag) and its lubricant's viscosity over the reference.
235    pub efficiency: [f64; 2],
236    drag: GearDrag,
237    oil: [f64; 2],
238    thermal: Option<ThermalFeedback>,
239    /// Motor rotor and gearbox input, kg m^2 at the motor.
240    pub j_rotor: f64,
241    pub ea: f64,
242    /// The web's width, m (drawn).
243    pub width: f64,
244    /// The web's material damping time constant (0 with effects.web_damping off), s.
245    pub damping_time: f64,
246    /// The tension setpoint at the rewind's core, N, and the taper k (0 with effects.tension_taper off).
247    pub tension: f64,
248    pub taper: f64,
249    /// The strain the unwind roll was wound at.
250    pub wound_strain: f64,
251    pub spans: [f64; 2],
252    pub dancer_mass: f64,
253    pub payload: f64,
254    pub attached: bool,
255    pub roller_radius: f64,
256    pub roller_inertia: f64,
257    pub air_spring: f64,
258    pub stroke: f64,
259    slide_friction: Friction,
260    roller_friction: Friction,
261    motor_friction: Friction,
262    /// The motors' holding brakes, engaged while the drives are off (`set_brake_engaged`).
263    brake: HoldingBrake,
264    /// Stops at +-stroke (effects.hard_stops): stiffness and damping; stiffness 0 without.
265    stop: [f64; 2],
266    pub g: f64,
267    pub elastic: bool,
268    /// The dancer's position loop: on, Kp (1/s), Tn (s), the most it trims (m/s), and its state: the web it has had the
269    /// unwind pay out beyond the line position (m), the integrator (m/s), the trim of the last step (m/s).
270    position_loop: bool,
271    trim_gains: [f64; 3],
272    pub trim_length: f64,
273    trim_integral: f64,
274    pub trim_speed: f64,
275    drives_off: bool,
276    /// An obstacle's push on the dancer, down along its travel y (`Machine::set_tool_force`), N, held until changed.
277    obstacle: f64,
278    /// Limits of the own verdicts: web's highest and lowest tension, dancer travel, inertia ratio, the motor's peak
279    /// torque, its rated torque and its highest speed.
280    limits: [f64; 7],
281    axes: [AxisInfo; 1],
282    motors: [MotorInfo; 2],
283}
284
285// Elastic state: [phi_u, phi_r, y, w_u, w_r, v_y, w_d, M1, M2, slack, brake_u, brake_r]: roll angles (rad, unwind in
286// its paying-out sense), the dancer's travel, the speeds, the dancer roller's speed, the web in each span (m
287// unstretched), the seconds a span has spent slack, and the holding brakes' deflections.
288const N_ELASTIC: usize = 12;
289// Rigid state: [phi_u, phi_r, w_u, w_r, brake_u, brake_r].
290const N_RIGID: usize = 6;
291/// The rolls by motor, for signal ids.
292const ROLLS: [&str; 2] = ["unwind", "rewind"];
293
294impl Winder {
295    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
296        let on = |effect: &str| cfg.bool(&format!("effects.{effect}"));
297        let (thickness, width) = (cfg.positive("web.thickness_m")?, cfg.positive("web.width_m")?);
298        let roll = Roll {
299            core: cfg.positive("roll.core_radius_m")?,
300            full: cfg.positive("roll.full_radius_m")?,
301            thickness,
302            density_width: cfg.positive("web.density_kg_m3")? * width,
303            core_inertia: cfg.non_negative("roll.core_inertia_kgm2")?,
304        };
305        if roll.full <= roll.core {
306            return Err(ConfigError::Invalid("roll.full_radius_m".into()));
307        }
308        let ea = cfg.positive("web.modulus_pa")? * thickness * width;
309        let taper = cfg.non_negative("web.taper")?;
310        if taper >= 1.0 {
311            return Err(ConfigError::Invalid("web.taper".into()));
312        }
313        let stroke = cfg.positive("dancer.stroke_m")?;
314        let (kp, tn) = (cfg.non_negative("dancer.trim_kp_1_s")?, cfg.positive("dancer.trim_tn_s")?);
315        let thermal = ThermalFeedback::from_config(cfg)?;
316        // What a catalogue gearbox writes beside its ratio: checked, not used (the gearboxes are rigid here).
317        cfg.positive("gearbox.stiffness_nm_rad")?;
318        cfg.non_negative("gearbox.backlash_rad")?;
319        // The stretch of the roll the axis runs over: from where on the roll, how long.
320        let (from, run) = (cfg.non_negative("roll.run_from_m")?, cfg.positive("roll.run_m")?);
321        if from + run > roll.capacity() {
322            return Err(ConfigError::Invalid("roll.run_m".into()));
323        }
324        let get = |what: &str, rate: &str| cfg.positive(&format!("axis.web.max_{what}_m_{rate}"));
325        let rating = |key: &str| cfg.f64(key).unwrap_or(f64::INFINITY);
326        Ok(Self {
327            roll,
328            ratio: cfg.positive("gearbox.ratio")?,
329            // The teeth's efficiency (the catalogue's less what the drag takes, `Gearbox::configured_efficiency`); with
330            // the temperature feedback that at ambient.
331            efficiency: [thermal.as_ref().map_or(Gearbox::configured_efficiency(cfg)?, |t| t.gearbox_efficiency(0.0));
332                2],
333            drag: GearDrag::from_config(cfg)?,
334            oil: [thermal.as_ref().map_or(1.0, |t| t.viscosity_factor(0.0)); 2],
335            thermal,
336            j_rotor: cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?,
337            ea,
338            width,
339            damping_time: if on("web_damping")? { cfg.non_negative("web.damping_time_s")? } else { 0.0 },
340            tension: cfg.positive("web.tension_n")?,
341            taper: if on("tension_taper")? { taper } else { 0.0 },
342            wound_strain: cfg.non_negative("roll.wound_tension_n")? / ea,
343            spans: [cfg.positive("span.unwind_m")?, cfg.positive("span.rewind_m")?],
344            dancer_mass: cfg.positive("mass.dancer_kg")?,
345            payload: if on("payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
346            attached: true,
347            roller_radius: cfg.positive("dancer.roller_radius_m")?,
348            roller_inertia: cfg.positive("dancer.roller_inertia_kgm2")?,
349            air_spring: cfg.non_negative("dancer.air_spring_n_m")?,
350            stroke,
351            slide_friction: Friction::from_config(
352                cfg,
353                on("dancer_friction")?,
354                ["dancer.friction_coulomb_n", "dancer.friction_viscous_n_s_m", "dancer.friction_smoothing_m_s"],
355            )?,
356            roller_friction: Friction::from_config(
357                cfg,
358                on("dancer_friction")?,
359                [
360                    "dancer.roller_friction_coulomb_nm",
361                    "dancer.roller_friction_viscous_nm_s_rad",
362                    "dancer.roller_friction_smoothing_rad_s",
363                ],
364            )?,
365            motor_friction: Friction::from_config(
366                cfg,
367                on("motor_friction")?,
368                ["motor.friction_coulomb_nm", "motor.friction_viscous_nm_s_rad", "motor.friction_smoothing_rad_s"],
369            )?,
370            brake: HoldingBrake::from_config(
371                cfg,
372                cfg.positive("motor.rotor_inertia_kgm2")? + cfg.non_negative("gearbox.inertia_at_input_kgm2")?,
373            )?,
374            stop: if on("hard_stops")? {
375                [cfg.positive("dancer.stop_stiffness_n_m")?, cfg.non_negative("dancer.stop_damping_n_s_m")?]
376            } else {
377                [0.0, 0.0]
378            },
379            g: if on("gravity")? { G } else { 0.0 },
380            elastic: on("web_stretch")?,
381            position_loop: cfg.bool("dancer.position_loop")?,
382            trim_gains: [kp, tn, cfg.non_negative("dancer.trim_max_m_s")?],
383            trim_length: 0.0,
384            trim_integral: 0.0,
385            trim_speed: 0.0,
386            drives_off: false,
387            obstacle: 0.0,
388            limits: [
389                rating("ratings.web_max_tension_n"),
390                rating("ratings.web_min_tension_n"),
391                rating("ratings.dancer_max_travel_m"),
392                rating("ratings.max_inertia_ratio"),
393                cfg.positive("drive.peak_torque_nm")?,
394                cfg.positive("drive.rated_torque_nm")?,
395                if cfg.get("drive.max_speed_rad_s").is_ok() {
396                    cfg.positive("drive.max_speed_rad_s")?
397                } else {
398                    cfg.positive("drive.no_load_speed_rad_s")?
399                },
400            ],
401            axes: [AxisInfo {
402                id: "web",
403                key: "axis-web",
404                unit: "m",
405                min: from,
406                max: from + run,
407                max_vel: get("velocity", "s")?,
408                max_acc: get("acceleration", "s2")?,
409                max_jerk: get("jerk", "s3")?,
410            }],
411            motors: [MotorInfo { id: "unwind", key: "motor-unwind" }, MotorInfo { id: "rewind", key: "motor-rewind" }],
412        })
413    }
414
415    /// The dancer with what it carries.
416    pub fn dancer_total_mass(&self) -> f64 {
417        self.dancer_mass + if self.attached { self.payload } else { 0.0 }
418    }
419
420    /// Radii at the line position `l`: the unwind with the capacity less `l` on its core, the rewind with `l`.
421    pub fn radii_at(&self, l: f64) -> [f64; 2] {
422        let c = &self.roll;
423        let h = c.thickness * l / PI;
424        [(c.full * c.full - h).max(c.core * c.core).sqrt(), (c.core * c.core + h).max(0.0).sqrt()]
425    }
426    /// The roll angles at the line position `l` with the dancer in the middle: s = phi (r0 + r) / 2 solved for phi.
427    pub fn angles_at(&self, l: f64) -> [f64; 2] {
428        let [ru, rr] = self.radii_at(l);
429        [2.0 * l / (self.roll.full + ru), 2.0 * l / (self.roll.core + rr)]
430    }
431    /// The unwind's radius at its angle (paid out from full) and the rewind's at its angle (wound from the core).
432    pub fn unwind_radius(&self, phi: f64) -> f64 {
433        (self.roll.full - self.roll.thickness * phi / TAU).max(self.roll.core)
434    }
435    pub fn rewind_radius(&self, phi: f64) -> f64 {
436        (self.roll.core + self.roll.thickness * phi / TAU).max(self.roll.core)
437    }
438    /// The web the unwind has paid out at its angle, and the rewind wound up at its, m: phi (r0 + r) / 2.
439    pub fn paid_out(&self, phi: f64) -> f64 {
440        0.5 * phi * (self.roll.full + self.unwind_radius(phi))
441    }
442    pub fn wound_up(&self, phi: f64) -> f64 {
443        0.5 * phi * (self.roll.core + self.rewind_radius(phi))
444    }
445    /// A roll's inertia at radius `r` as its motor turns it, at the roll: roll plus i^2 J_rotor.
446    pub fn roll_inertia(&self, r: f64) -> f64 {
447        self.roll.inertia(r) + self.ratio * self.ratio * self.j_rotor
448    }
449
450    /// The tension setpoint at the rewind's radius: T0 (1 - k (1 - r_c / r)).
451    pub fn tension_setpoint(&self, r_rewind: f64) -> f64 {
452        self.tension * (1.0 - self.taper * (1.0 - self.roll.core / r_rewind.max(self.roll.core)))
453    }
454    /// The cylinder's force setpoint for that tension: 2 T - m g, the dancer's weight taken off.
455    pub fn cylinder_force(&self, r_rewind: f64) -> f64 {
456        2.0 * self.tension_setpoint(r_rewind) - self.dancer_total_mass() * self.g
457    }
458
459    /// The stops' force on the dancer along y, their stored energy and their loss power.
460    fn stop(&self, y: f64, vy: f64) -> [f64; 3] {
461        let [k, c] = self.stop;
462        let depth = y.abs() - self.stroke;
463        if k == 0.0 || depth <= 0.0 {
464            return [0.0; 3];
465        }
466        let (side, rate) = (y.signum(), y.signum() * vy);
467        let push = (k * depth + c * rate).max(0.0);
468        [-side * push, 0.5 * k * depth * depth, (push - k * depth) * rate]
469    }
470
471    /// The motor torque that turns roll `k` (0 unwind, 1 rewind) at radius `r` so that its surface runs at `v` and
472    /// speeds up by `a`, against the web's tension `tension`: tau = (J(r) w' -+ T r) / i, w' = (a -+ h w^2 / (2 pi)) / r
473    /// (the radius shrinks on the unwind, grows on the rewind, so at a steady line speed the unwind speeds up).
474    pub fn roll_torque(&self, k: usize, r: f64, v: f64, a: f64, tension: f64) -> f64 {
475        let w = v / r;
476        let (sign, growth) = if k == 0 { (-1.0, -1.0) } else { (1.0, 1.0) };
477        let acc = (a - growth * self.roll.thickness * w * w / TAU) / r;
478        (self.roll_inertia(r) * acc + sign * tension * r) / self.ratio
479    }
480
481    /// The two spans' tensions of the rigid model at rest for the line's acceleration `a`: the roller's inertia takes
482    /// J_d a / R^2 between them, the dancer at rest their sum 2 T_set: T_set -+ J_d a / (2 R^2).
483    pub fn rigid_span_tensions(&self, l: f64, a: f64) -> [f64; 2] {
484        let t = self.tension_setpoint(self.radii_at(l)[1]);
485        let d = self.roller_inertia * a / (2.0 * self.roller_radius * self.roller_radius);
486        [t - d, t + d]
487    }
488
489    /// Everything of a state (see `Eval`).
490    pub fn eval(&self, s: &[f64], torque: &[f64]) -> Eval {
491        let (h, i, rd) = (self.roll.thickness, self.ratio, self.roller_radius);
492        let mut e = Eval::default();
493        let (phi, w) = if self.elastic { ([s[0], s[1]], [s[3], s[4]]) } else { ([s[0], s[1]], [s[2], s[3]]) };
494        e.r = [self.unwind_radius(phi[0]), self.rewind_radius(phi[1])];
495        e.w = w;
496        e.v = [e.r[0] * w[0], e.r[1] * w[1]];
497        e.j = e.r.map(|r| self.roll_inertia(r));
498        if self.elastic {
499            (e.y, e.vy, e.wd) = (s[2], s[5], s[6]);
500        } else {
501            e.y = 0.5 * (self.paid_out(phi[0]) - self.wound_up(phi[1]));
502            e.vy = 0.5 * (e.v[0] - e.v[1]);
503            e.wd = 0.5 * (e.v[0] + e.v[1]) / rd;
504        }
505        // The shaft's friction and, while the drives are off, its holding brake on its deflection.
506        let first_brake = if self.elastic { N_ELASTIC - 2 } else { N_RIGID - 2 };
507        for k in 0..2 {
508            let (brake, rate) = self.brake.torque(self.drives_off, i * w[k], s[first_brake + k]);
509            e.drag[k] = self.drag.torque(i * w[k], self.oil[k]);
510            (e.shaft[k], e.brake_rate[k]) = (self.motor_friction.at(i * w[k]) + brake + e.drag[k], rate);
511        }
512        let drive: [f64; 2] = std::array::from_fn(|k| i * (torque[k] - e.shaft[k]));
513        e.slide = self.slide_friction.at(e.vy);
514        e.roller = self.roller_friction.at(e.wd);
515        e.stop = self.stop(e.y, e.vy);
516        e.cylinder = self.cylinder_force(e.r[1]);
517        e.load = e.cylinder - self.air_spring * e.y;
518        let m = self.dancer_total_mass();
519        // What pushes the dancer down but the web: an obstacle's push on it among the rest.
520        let push = e.load + m * self.g - e.slide + e.stop[0] + self.obstacle;
521        if self.elastic {
522            let vd = rd * e.wd;
523            for k in 0..2 {
524                e.length[k] = self.spans[k] + e.y;
525                e.material[k] = s[7 + k];
526                e.strain[k] = e.length[k] / e.material[k] - 1.0;
527            }
528            let taut = e.strain.map(|x| x.max(0.0));
529            // The web crossing each boundary at the strain of the side it comes from.
530            let back = self.tension_setpoint(e.r[1]) / self.ea;
531            let flow = |v: f64, ahead: f64, behind: f64| v / (1.0 + if v >= 0.0 { ahead } else { behind });
532            let q = [flow(e.v[0], self.wound_strain, taut[0]), flow(vd, taut[0], taut[1]), flow(e.v[1], taut[1], back)];
533            e.material_rate = [q[0] - q[1], q[1] - q[2]];
534            e.flow = q;
535            for k in 0..2 {
536                let rate = (e.vy - (1.0 + e.strain[k]) * e.material_rate[k]) / e.material[k];
537                if e.strain[k] > 0.0 {
538                    e.spring[k] = self.ea * e.strain[k];
539                    e.t[k] = (e.spring[k] + self.ea * self.damping_time * rate).max(0.0);
540                }
541            }
542            let web = [e.t[0] * e.r[0], -e.t[1] * e.r[1]];
543            // The gearbox's loss factor of the torque going in, which depends on the roll's acceleration it gives, at its
544            // fixed point (`mech::settled_loss`), then the roll with it.
545            for k in 0..2 {
546                let acc = |factor: f64| (factor * drive[k] + web[k]) / self.geared_inertia(e.r[k], factor);
547                [e.factor[k]] = sim_components::mech::settled_loss([1.0], |&[factor]| {
548                    [self.loss_factor(k, torque[k] - e.shaft[k] - self.j_rotor * i * acc(factor), w[k])]
549                });
550                e.acc[k] = acc(e.factor[k]);
551            }
552            e.ydd = (push - e.t[0] - e.t[1]) / m;
553            e.wdd = (rd * (e.t[1] - e.t[0]) - e.roller) / self.roller_inertia;
554        } else {
555            // a_u = b_u + k_u T1, a_r = b_r - k_r T2 (the surfaces' accelerations), y'' = (a_u - a_r) / 2 and
556            // R w_d' = (a_u + a_r) / 2 into the dancer's and the roller's balance: two equations in T1 and T2. Solved
557            // with the gearboxes' loss factors at the torques the solution passes (to the fixed point, from loss-free).
558            let rate = [-h * w[0] * w[0] / TAU, h * w[1] * w[1] / TAU];
559            let (md, jd) = (0.5 * m, self.roller_inertia / (2.0 * rd * rd));
560            let solve = |factor: [f64; 2]| {
561                let j: [f64; 2] = std::array::from_fn(|k| self.geared_inertia(e.r[k], factor[k]));
562                let kk = [e.r[0] * e.r[0] / j[0], e.r[1] * e.r[1] / j[1]];
563                let b =
564                    [e.r[0] * factor[0] * drive[0] / j[0] + rate[0], e.r[1] * factor[1] * drive[1] / j[1] + rate[1]];
565                let (a11, a12, b1) = (1.0 + md * kk[0], 1.0 + md * kk[1], push - md * (b[0] - b[1]));
566                let (a21, a22, b2) = (1.0 + jd * kk[0], -(1.0 + jd * kk[1]), -e.roller / rd - jd * (b[0] + b[1]));
567                let det = a11 * a22 - a12 * a21;
568                let t = [(b1 * a22 - a12 * b2) / det, (a11 * b2 - a21 * b1) / det];
569                let acc =
570                    [(factor[0] * drive[0] + t[0] * e.r[0]) / j[0], (factor[1] * drive[1] - t[1] * e.r[1]) / j[1]];
571                let surface = [b[0] + kk[0] * t[0], b[1] - kk[1] * t[1]];
572                (t, acc, surface)
573            };
574            // The loss factors at their fixed point, as above.
575            e.factor = sim_components::mech::settled_loss([1.0; 2], |factor| {
576                let (_, acc, _) = solve(*factor);
577                std::array::from_fn(|k| self.loss_factor(k, torque[k] - e.shaft[k] - self.j_rotor * i * acc[k], w[k]))
578            });
579            let (t, acc, surface) = solve(e.factor);
580            (e.t, e.spring, e.acc) = (t, t, acc);
581            e.ydd = 0.5 * (surface[0] - surface[1]);
582            e.wdd = 0.5 * (surface[0] + surface[1]) / rd;
583        }
584        e.gear_input = std::array::from_fn(|k| torque[k] - e.shaft[k] - self.j_rotor * i * e.acc[k]);
585        e
586    }
587
588    /// Gearbox `k`'s factor on the torque `input` at its input while the roll turns at `w`: its efficiency while the
589    /// motor drives, 1 / efficiency while the roll drives the motor back, faded smoothly through zero power
590    /// (eta^tanh(P / 0.5 W)), as the other machines' gearboxes (`mech::Gearbox::loss_factor`).
591    fn loss_factor(&self, k: usize, input: f64, w: f64) -> f64 {
592        if self.efficiency[k] == 1.0 {
593            return 1.0;
594        }
595        self.efficiency[k].powf((input * self.ratio * w / EFFICIENCY_FADE_W).tanh())
596    }
597    /// What the roll's angular acceleration meets with the gearbox's loss factor `factor`: J_roll + factor i^2 J_m, the
598    /// rotor's own inertia seen through the gearbox as its torque is.
599    fn geared_inertia(&self, r: f64, factor: f64) -> f64 {
600        self.roll.inertia(r) + factor * self.ratio * self.ratio * self.j_rotor
601    }
602
603    /// The line's speed and acceleration: the rewind's surface, d(r w)/dt = r w' + (h w / 2 pi) w.
604    fn line(&self, e: &Eval) -> (f64, f64) {
605        let w = e.w[1];
606        (e.v[1], e.r[1] * e.acc[1] + self.roll.thickness * w * w / TAU)
607    }
608
609    /// Kinetic, potential and elastic energy (see `ENERGY_PARTS`): rolls with rotors, dancer and roller; the dancer's
610    /// weight and the cylinder (its force setpoint as it is now, and the air spring); the web's spans and the stops.
611    fn energy_parts(&self, e: &Eval) -> [f64; 3] {
612        let m = self.dancer_total_mass();
613        let kinetic = 0.5 * (e.j[0] * e.w[0] * e.w[0] + e.j[1] * e.w[1] * e.w[1])
614            + 0.5 * m * e.vy * e.vy
615            + 0.5 * self.roller_inertia * e.wd * e.wd;
616        let potential = -(m * self.g + e.cylinder) * e.y + 0.5 * self.air_spring * e.y * e.y;
617        let web: f64 = (0..2)
618            .filter(|&k| self.elastic && e.length[k] > e.material[k])
619            .map(|k| self.ea * (e.length[k] - e.material[k]).powi(2) / (2.0 * e.material[k]))
620            .sum();
621        [kinetic, potential, web + e.stop[1]]
622    }
623
624    /// The loss powers in the order of `effect_infos`: each motor's shaft, the dancer's slide and roller, the web's
625    /// damping, the stops, what the web carries in and out of the machine's energy, the cylinder's taper.
626    ///
627    /// The web's transport is the balance of what the tensions do on the bodies, what the spans store and what the
628    /// damping takes: P = -(1/2 J_u' w_u^2 + 1/2 J_r' w_r^2) - P_bodies - dU/dt - P_damping, which is the kinetic energy
629    /// the web carries from roll to roll (1/2 lambda (v_u^3 - v_r^3)) and the strain energy it brings into the spans and
630    /// takes out of them (T v (eps_in - eps) to first order, nothing where the strains are equal). The cylinder's power
631    /// is dF/dt y: the setpoint changes with the rewind's radius, and the potential with it.
632    fn losses(&self, e: &Eval) -> [f64; 9] {
633        let (i, rd, h) = (self.ratio, self.roller_radius, self.roll.thickness);
634        // The gearbox's drag acts on the rotor with the shaft's friction, but its loss is the gearbox's.
635        let shaft = [0, 1].map(|k| (e.shaft[k] - e.drag[k]) * i * e.w[k]);
636        // What goes into a gearbox less what comes out: (1 - factor) times the input's power, either way positive.
637        let gearbox = [0, 1].map(|k| ((1.0 - e.factor[k]) * e.gear_input[k] + e.drag[k]) * i * e.w[k]);
638        let dancer = e.slide * e.vy + e.roller * e.wd;
639        let growth = [-h * e.w[0] / TAU, h * e.w[1] / TAU];
640        let mass_flow: f64 = (0..2).map(|k| 0.5 * self.roll.inertia_slope(e.r[k]) * growth[k] * e.w[k] * e.w[k]).sum();
641        let bodies = e.t[0] * e.v[0] - e.t[1] * e.v[1] + rd * e.wd * (e.t[1] - e.t[0]) - (e.t[0] + e.t[1]) * e.vy;
642        let (mut stored, mut damping) = (0.0, 0.0);
643        if self.elastic {
644            for k in 0..2 {
645                stored += e.spring[k] * (e.vy - (1.0 + 0.5 * e.strain[k]) * e.material_rate[k]);
646                damping += (e.t[k] - e.spring[k]) * (e.vy - (1.0 + e.strain[k]) * e.material_rate[k]);
647            }
648        }
649        let r = e.r[1].max(self.roll.core);
650        let slope = -2.0 * self.tension * self.taper * self.roll.core / (r * r);
651        let cylinder = if e.r[1] > self.roll.core { slope * growth[1] * e.y } else { 0.0 };
652        [
653            shaft[0],
654            shaft[1],
655            gearbox[0],
656            gearbox[1],
657            dancer,
658            damping,
659            e.stop[2],
660            -mass_flow - bodies - stored - damping,
661            cylinder,
662        ]
663    }
664
665    /// The radii a roll has at its two ends: [full, core].
666    fn ends(&self) -> [f64; 2] {
667        [self.roll.full, self.roll.core]
668    }
669
670    /// The inertia ratio at roll radius `r`: what the motor sees of roll, core and shaft over rotor and gearbox input.
671    pub fn inertia_ratio(&self, r: f64) -> f64 {
672        self.roll.inertia(r) / (self.ratio * self.ratio * self.j_rotor)
673    }
674
675    /// The figures the own verdicts judge, from the line's speed `v`, its acceleration `a` and the spans' tensions `t`
676    /// at the rewind's radius `r_rewind`: per motor its torque at the full roll and at the core (`roll_torque`), its
677    /// speed at the core i v / r_c, the tension's torque at the full roll T r_f / i, and the inertia ratio at the full
678    /// roll. The tension at a roll's end is the setpoint there (with the taper: the rewind at its core while the unwind is
679    /// full, and full while the unwind is on its core) plus what the span's tension is off its setpoint now.
680    pub fn end_figures(&self, v: f64, a: f64, t: [f64; 2], r_rewind: f64) -> [[f64; 5]; 2] {
681        let now = self.tension_setpoint(r_rewind);
682        let [full, core] = self.ends();
683        std::array::from_fn(|k| {
684            // The rewind's radius when roll k is full and when it is on its core.
685            let rewind = if k == 0 { [core, full] } else { [full, core] };
686            let tension = rewind.map(|r| self.tension_setpoint(r) + t[k] - now);
687            [
688                self.roll_torque(k, full, v, a, tension[0]),
689                self.roll_torque(k, core, v, a, tension[1]),
690                self.ratio * v / core,
691                tension[0] * full / self.ratio,
692                self.inertia_ratio(full),
693            ]
694        })
695    }
696
697    /// The lowest tension's shortfall: the web's minimum tension over the lower span's (above 1: below the minimum; a
698    /// slack span counts as 1e9).
699    fn slack_ratio(&self, t: [f64; 2]) -> f64 {
700        let low = t[0].min(t[1]);
701        if low > 0.0 { (self.limits[1] / low).min(1e9) } else { 1e9 }
702    }
703
704    /// Every own check, whether or not the config rates it (`rating_checks` leaves out those it does not): the web's
705    /// highest tension, its lowest (as the minimum over it, at most 1), the dancer's travel, and per motor the inertia
706    /// ratio at the full roll, its torque at the full roll and at the core against its peak torque, its speed at the core
707    /// against its highest speed, and the tension's torque at the full roll against its rated torque.
708    fn all_checks(&self) -> Vec<RatingCheck> {
709        let check = |check: &'static str, signal: String, motor: Option<usize>, limit: f64| RatingCheck {
710            check,
711            signal,
712            motor,
713            limit,
714            life: false,
715        };
716        let [tension, minimum, travel, ratio, peak, rated, speed] = self.limits;
717        let mut out = vec![
718            check("web-tension", "web.tension_peak".into(), None, tension),
719            check("web-slack", "web.slack_ratio".into(), None, if minimum.is_finite() { 1.0 } else { minimum }),
720            check("dancer-travel", "dancer.position".into(), None, travel),
721        ];
722        for (k, roll) in ROLLS.iter().enumerate() {
723            out.extend([
724                check("inertia-ratio", format!("{roll}.inertia_ratio_at_full"), Some(k), ratio),
725                check("torque-at-full-roll", format!("{roll}.torque_at_full"), Some(k), peak),
726                check("torque-at-core", format!("{roll}.torque_at_core"), Some(k), peak),
727                check("speed-at-core", format!("{roll}.speed_at_core"), Some(k), speed),
728                check("tension-torque-at-full-roll", format!("{roll}.tension_torque_at_full"), Some(k), rated),
729            ]);
730        }
731        out
732    }
733
734    /// The dancer at its travel `y`, as `scene` draws it: its roller, its slide, the weight on it while it carries one, and
735    /// its cylinder below.
736    fn dancer_parts(&self, y: f64) -> Vec<Part> {
737        let (width, rd) = (self.width, self.roller_radius);
738        let depth = 0.5 * (self.spans[0] + self.spans[1]) + y;
739        let mut parts = Vec::with_capacity(4);
740        if self.attached && self.payload > 0.0 {
741            parts.push(Part::new(
742                "payload",
743                Shape::Box { size: [0.08, 0.05, 0.05] },
744                [0.0, 0.5 * width + 0.04, -depth + 0.09],
745                [0.2, 0.7, 0.3],
746            ));
747        }
748        parts.extend([
749            Part::new(
750                "dancer-roller",
751                Shape::Cylinder { radius: rd, length: width + 0.02 },
752                [0.0, 0.0, -depth],
753                [0.62, 0.64, 0.68],
754            ),
755            Part::new(
756                "dancer-slide",
757                Shape::Box { size: [0.06, 0.04, 0.12] },
758                [0.0, 0.5 * width + 0.04, -depth],
759                [0.2, 0.22, 0.26],
760            ),
761            Part::new(
762                "dancer-cylinder",
763                Shape::Segment { to: [0.0, 0.5 * width + 0.04, -depth - 0.35], width: 0.05 },
764                [0.0, 0.5 * width + 0.04, -depth - 0.06],
765                [0.3, 0.45, 0.7],
766            ),
767        ]);
768        parts
769    }
770
771    /// The signal list of `effect_signals`.
772    fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
773        for motor in &self.motors {
774            out.extend(TORQUE_PARTS.map(|part| {
775                SignalInfo::new(
776                    format!("motor.{}.torque_{part}", motor.id),
777                    motor.key,
778                    &format!("quantity-torque-{part}"),
779                    "N m",
780                )
781            }));
782        }
783        let gearbox = if self.ratio == 1.0 { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
784        let powers = [
785            ("shaft_unwind", "motor-unwind", "quantity-shaft-friction-power"),
786            ("shaft_rewind", "motor-rewind", "quantity-shaft-friction-power"),
787            ("gearbox_unwind", "motor-unwind", gearbox),
788            ("gearbox_rewind", "motor-rewind", gearbox),
789            ("dancer", "group-dancer", "quantity-friction-power"),
790            ("web_damping", "group-web", "quantity-damping-power"),
791            ("dancer_stops", "group-dancer", "quantity-damping-power"),
792            ("web_transport", "group-web", "quantity-web-transport-power"),
793            ("cylinder", "group-dancer", "quantity-cylinder-power"),
794        ];
795        out.extend(
796            powers.map(|(id, owner, quantity)| SignalInfo::new(format!("{LOSS_PREFIX}{id}"), owner, quantity, "W")),
797        );
798        out.extend(ENERGY_PARTS.map(|part| {
799            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
800        }));
801    }
802}
803
804impl Machine for Winder {
805    fn axes(&self) -> &[AxisInfo] {
806        &self.axes
807    }
808    fn motors(&self) -> &[MotorInfo] {
809        &self.motors
810    }
811
812    /// The line position's roll angles through the ratio, each at the radius of its wound length: the rewind's the line
813    /// position, the unwind's the line position plus the web the dancer's trim has had it pay out more.
814    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
815        motors[0] = self.ratio * self.angles_at(tool[0] + self.trim_length)[0];
816        motors[1] = self.ratio * self.angles_at(tool[0])[1];
817    }
818    /// The line position from the motors' angles, as `tool_state` takes it from the rolls'.
819    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
820        let (u, r) = (motors[0] / self.ratio, motors[1] / self.ratio);
821        tool[0] = 0.5 * (self.paid_out(u) - self.trim_length + self.wound_up(r));
822    }
823
824    fn state_len(&self) -> usize {
825        if self.elastic { N_ELASTIC } else { N_RIGID }
826    }
827
828    /// At rest at the line position, the dancer in the middle and each span at the tension setpoint: M = L / (1 + T / EA);
829    /// the motors hold the tension's torque, -T r_u / i on the unwind and T r_r / i on the rewind.
830    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
831        let l = tool[0];
832        let ([u, r], [ru, rr]) = (self.angles_at(l), self.radii_at(l));
833        let t = self.tension_setpoint(rr);
834        *state = if self.elastic {
835            let m = self.spans.map(|span| span / (1.0 + t / self.ea));
836            vec![u, r, 0.0, 0.0, 0.0, 0.0, 0.0, m[0], m[1], 0.0, 0.0, 0.0]
837        } else {
838            vec![u, r, 0.0, 0.0, 0.0, 0.0]
839        };
840        torque[0] = -t * ru / self.ratio;
841        torque[1] = t * rr / self.ratio;
842    }
843
844    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
845        let e = self.eval(s, torque);
846        if self.elastic {
847            let slack = if e.t.iter().any(|t| *t <= 0.0) { 1.0 } else { 0.0 };
848            out.copy_from_slice(&[
849                e.w[0],
850                e.w[1],
851                e.vy,
852                e.acc[0],
853                e.acc[1],
854                e.ydd,
855                e.wdd,
856                e.material_rate[0],
857                e.material_rate[1],
858                slack,
859                e.brake_rate[0],
860                e.brake_rate[1],
861            ]);
862        } else {
863            out.copy_from_slice(&[e.w[0], e.w[1], e.acc[0], e.acc[1], e.brake_rate[0], e.brake_rate[1]]);
864        }
865    }
866
867    /// The line position the rolls stand at: the mean of the web the unwind has paid out, less what the dancer's trim had
868    /// it pay out more, and the web the rewind has wound up; with the dancer in the middle both. In the rigid model the
869    /// web's travel at the dancer roller, (s_u + s_r) / 2.
870    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
871        let w = if self.elastic { [s[3], s[4]] } else { [s[2], s[3]] };
872        pos[0] = 0.5 * (self.paid_out(s[0]) - self.trim_length + self.wound_up(s[1]));
873        vel[0] = 0.5 * (self.unwind_radius(s[0]) * w[0] - self.trim_speed + self.rewind_radius(s[1]) * w[1]);
874    }
875    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
876        let (phi, v) = ([s[0], s[1]], vel[0]);
877        let w = [v / self.unwind_radius(phi[0]), v / self.rewind_radius(phi[1])];
878        if self.elastic {
879            (s[3], s[4], s[5], s[6]) = (w[0], w[1], 0.0, v / self.roller_radius);
880        } else {
881            (s[2], s[3]) = (w[0], w[1]);
882        }
883    }
884    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
885        let w = if self.elastic { [s[3], s[4]] } else { [s[2], s[3]] };
886        for k in 0..2 {
887            pos[k] = self.ratio * s[k];
888            vel[k] = self.ratio * w[k];
889        }
890    }
891
892    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
893        self.feedforward_torque_moving(pos, &[0.0], acc, out);
894    }
895    /// The tension's torque and the inertia compensation at the radii of the line position (`roll_torque`), the
896    /// spans' tensions those of the rigid model at rest (`rigid_span_tensions`).
897    fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
898        let (r, t) = (self.radii_at(pos[0]), self.rigid_span_tensions(pos[0], acc[0]));
899        for k in 0..2 {
900            out[k] = self.roll_torque(k, r[k], vel[0], acc[0], t[k]);
901        }
902    }
903    /// The rigid model's inverse dynamics at motor angles, speeds and accelerations of their own: the dancer then moves
904    /// at half the surfaces' difference, and the two tensions follow from its balance and the roller's.
905    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
906        let (i, h, rd) = (self.ratio, self.roll.thickness, self.roller_radius);
907        let phi = [angle[0] / i, angle[1] / i];
908        let (w, wdot) = ([speed[0] / i, speed[1] / i], [acc[0] / i, acc[1] / i]);
909        let r = [self.unwind_radius(phi[0]), self.rewind_radius(phi[1])];
910        let v = [r[0] * w[0], r[1] * w[1]];
911        let a = [r[0] * wdot[0] - h * w[0] * w[0] / TAU, r[1] * wdot[1] + h * w[1] * w[1] / TAU];
912        let y = 0.5 * (self.paid_out(phi[0]) - self.wound_up(phi[1]));
913        let vy = 0.5 * (v[0] - v[1]);
914        let m = self.dancer_total_mass();
915        let push = self.cylinder_force(r[1]) - self.air_spring * y + m * self.g + self.stop(y, vy)[0];
916        let sum = push - m * 0.5 * (a[0] - a[1]);
917        let diff = self.roller_inertia * 0.5 * (a[0] + a[1]) / (rd * rd);
918        let t = [0.5 * (sum - diff), 0.5 * (sum + diff)];
919        out[0] = (self.roll_inertia(r[0]) * wdot[0] - t[0] * r[0]) / i;
920        out[1] = (self.roll_inertia(r[1]) * wdot[1] + t[1] * r[1]) / i;
921    }
922
923    /// The motors' shaft friction and the gearboxes' drag at their speeds, and the dancer roller's drag through the web:
924    /// it takes R (T2 - T1),
925    /// so T1 = T - drag / (2 R) and T2 = T + drag / (2 R), r / i of each at the motors.
926    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
927        let (r, v, rd) = (self.radii_at(pos[0]), vel[0], self.roller_radius);
928        let drag = self.roller_friction.at(v / rd);
929        for k in 0..2 {
930            let speed = self.ratio * v / r[k];
931            out[k] = self.motor_friction.at(speed)
932                + self.drag.torque(speed, self.oil[k])
933                + drag * r[k] / (2.0 * rd * self.ratio);
934        }
935    }
936    /// The roller's drag of `steady_friction` as Coulomb and viscous parts; the motors' shafts are their own.
937    fn rigid_friction(&self, pos: &[f64], dir: &[f64], out: &mut Vec<[f64; 2]>) {
938        let (r, rd) = (self.radii_at(pos[0]), self.roller_radius);
939        let [c, b, _] = self.roller_friction.0;
940        for rk in r {
941            let share = rk / (2.0 * rd * self.ratio);
942            out.push([c * dir[0].signum() * share, b * dir[0] / rd * share]);
943        }
944    }
945    /// The own checks in the rigid model (`rating_checks`): the spans' tensions of `rigid_span_tensions`, the figures
946    /// at the rolls' ends, and no dancer travel (the rigid model holds it in the middle): NaN.
947    fn rigid_checks(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut Vec<f64>) {
948        let t = self.rigid_span_tensions(pos[0], acc[0]);
949        let mut all = vec![t[0].max(t[1]), self.slack_ratio(t), f64::NAN];
950        for f in self.end_figures(vel[0], acc[0], t, self.radii_at(pos[0])[1]) {
951            all.extend([f[4], f[0], f[1], f[2], f[3]]);
952        }
953        // In the order of `rating_checks`, which leaves out a check whose rating the config has none of.
954        out.extend(self.all_checks().iter().zip(all).filter(|(c, _)| c.limit.is_finite()).map(|(_, v)| v));
955    }
956
957    fn energy(&self, s: &[f64]) -> f64 {
958        self.energy_parts(&self.eval(s, &[0.0, 0.0])).iter().sum()
959    }
960
961    /// What moves and can hit an obstacle: the dancer's slide and the weight on it, as `scene` draws them (the rolls turn
962    /// in place).
963    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
964        let y = self.eval(s, &[0.0, 0.0]).y;
965        sim_core::scene::scene_boxes(&self.dancer_parts(y), &["dancer-slide", "payload"])
966    }
967
968    fn set_payload_attached(&mut self, attached: bool) {
969        self.attached = attached;
970    }
971    fn set_brake_engaged(&mut self, engaged: bool) {
972        self.drives_off = engaged;
973    }
974    /// What can touch is the dancer (`collision_bodies`), which the web holds and no motor moves: the push acts on its
975    /// travel y, in the dancer's balance; its power is the crash row.
976    fn set_tool_force(&mut self, force: &[f64]) -> bool {
977        self.obstacle = force[0];
978        true
979    }
980    fn contact_axes(&self) -> usize {
981        1
982    }
983    /// The dancer's travel y (down) and its rate, as `eval` takes them.
984    fn contact_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
985        if self.elastic {
986            (pos[0], vel[0]) = (s[2], s[5]);
987        } else {
988            let r = [self.unwind_radius(s[0]), self.rewind_radius(s[1])];
989            pos[0] = 0.5 * (self.paid_out(s[0]) - self.wound_up(s[1]));
990            vel[0] = 0.5 * (r[0] * s[2] - r[1] * s[3]);
991        }
992    }
993    /// The dancer at travel `at`: in the rigid model the unwind turned on by the web that takes (2 dy at its radius).
994    fn contact_placed(&self, s: &[f64], at: &[f64], out: &mut Vec<f64>) {
995        out.clear();
996        out.extend_from_slice(s);
997        if self.elastic {
998            out[2] = at[0];
999        } else {
1000            let y = 0.5 * (self.paid_out(s[0]) - self.wound_up(s[1]));
1001            out[0] += 2.0 * (at[0] - y) / self.unwind_radius(s[0]);
1002        }
1003    }
1004
1005    /// The dancer's position loop, every base step while the drives are on: the trim v = -(Kp e + integral), e the
1006    /// dancer's travel from the middle (down: too much web between the rolls, so the unwind slows), held to the most it
1007    /// may trim, the integrator Kp / Tn e (held while the trim is at its limit); the unwind's setpoint moves on by
1008    /// i v / r_u. While the drives are off the trim tracks what the rolls stand at: the web the unwind paid out more than
1009    /// the rewind took up (the dancer's travel, two spans of it), so that enabled again both motors' setpoints are where
1010    /// they stand. Before 15 November 2026 a re-enable after a coast set both rolls to the mean of the two, yanked them
1011    /// by the dancer's travel and tripped a weak DC link again.
1012    fn after_step(&mut self, s: &mut [f64], dt: f64) {
1013        if self.drives_off {
1014            (self.trim_speed, self.trim_integral) = (0.0, 0.0);
1015            self.trim_length = self.paid_out(s[0]) - self.wound_up(s[1]);
1016            return;
1017        }
1018        if !self.position_loop {
1019            self.trim_speed = 0.0;
1020            return;
1021        }
1022        let e = self.eval(s, &[0.0, 0.0]);
1023        let [kp, tn, most] = self.trim_gains;
1024        let wanted = -(kp * e.y + self.trim_integral);
1025        self.trim_speed = wanted.clamp(-most, most);
1026        if self.trim_speed == wanted {
1027            self.trim_integral += kp / tn * e.y * dt;
1028        }
1029        self.trim_length += self.trim_speed * dt;
1030    }
1031    fn memory(&self) -> Vec<f64> {
1032        vec![self.trim_length, self.trim_integral, self.trim_speed]
1033    }
1034    fn set_memory(&mut self, memory: &[f64]) {
1035        (self.trim_length, self.trim_integral, self.trim_speed) = (memory[0], memory[1], memory[2]);
1036    }
1037
1038    /// The dancer on the web with the rolls held: the two spans and the air spring, k = EA / L1 + EA / L2 + k_air, on the
1039    /// dancer and what it carries, f = sqrt(k / m) / (2 pi), damped by the web's material damping (EA tau / L each) and
1040    /// the slide's viscous friction; and the roller turning on the spans, one stretching as the other gives,
1041    /// k = R^2 (EA / L1 + EA / L2) on J_d. The dancer in the middle; none in the rigid model.
1042    fn modes(&self, _tool_pose: &[f64]) -> Vec<Mode> {
1043        if !self.elastic {
1044            return Vec::new();
1045        }
1046        let web = self.ea / self.spans[0] + self.ea / self.spans[1];
1047        let m = self.dancer_total_mass();
1048        let (k, c) = (web + self.air_spring, web * self.damping_time + self.slide_friction.0[1]);
1049        let w = (k / m).sqrt();
1050        let rd = self.roller_radius;
1051        let (kr, cr) = (rd * rd * web, rd * rd * web * self.damping_time + self.roller_friction.0[1]);
1052        let wr = (kr / self.roller_inertia).sqrt();
1053        let mut modes = vec![
1054            Mode { hz: w / TAU, damping: c / (2.0 * m * w) },
1055            Mode { hz: wr / TAU, damping: cr / (2.0 * self.roller_inertia * wr) },
1056        ];
1057        modes.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1058        modes
1059    }
1060    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1061        self.modes(tool_pose).first().map(|m| m.hz)
1062    }
1063
1064    /// In the frame of the scene, the rolls' axes along y at z = 0: the dancer and what it carries moving along z (down
1065    /// as y grows), the rolls with their rotors and the roller spinning about y. The web's weight moving from one roll
1066    /// to the other over the run is left out (minutes, not a vibration).
1067    fn frame_momentum(&self, s: &[f64]) -> Option<FrameMomentum> {
1068        use sim_components::base::{add_point, add_spin};
1069        let e = self.eval(s, &[0.0, 0.0]);
1070        let mut f = FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1071        let depth = 0.5 * (self.spans[0] + self.spans[1]);
1072        add_point(&mut f, self.dancer_total_mass(), [0.0, 0.0, -depth - e.y], [0.0, 0.0, -e.vy]);
1073        let rotor = self.ratio * self.ratio * self.j_rotor;
1074        // Both rolls turn clockwise seen from the front (about -y) as the line runs forward; the roller the other way.
1075        for k in 0..2 {
1076            add_spin(&mut f, [0.0, -1.0, 0.0], e.j[k] - rotor + self.ratio * self.j_rotor, e.w[k]);
1077        }
1078        add_spin(&mut f, [0.0, 1.0, 0.0], self.roller_inertia, e.wd);
1079        Some(f)
1080    }
1081
1082    fn rating_checks(&self) -> Vec<RatingCheck> {
1083        self.all_checks().into_iter().filter(|c| c.limit.is_finite()).collect()
1084    }
1085
1086    /// With effects.thermal_feedback: each gearbox's efficiency and its lubricant's viscosity (its drag) at its rise, in the
1087    /// order of `thermal_parts`.
1088    fn set_part_temperatures(&mut self, rises: &[f64]) {
1089        let Some(law) = &self.thermal else { return };
1090        for (k, rise) in rises.iter().enumerate().take(2) {
1091            (self.efficiency[k], self.oil[k]) = (law.gearbox_efficiency(*rise), law.viscosity_factor(*rise));
1092        }
1093    }
1094
1095    /// The two gearboxes, which warm with their losses (`power.gearbox_<motor>`) with effects.part_heating or
1096    /// effects.thermal_feedback; none where the ratio is 1 (a coupling).
1097    fn thermal_parts(&self) -> Vec<ThermalPart> {
1098        if self.ratio == 1.0 {
1099            return Vec::new();
1100        }
1101        [("gearbox_unwind", "motor-unwind", 0), ("gearbox_rewind", "motor-rewind", 1)]
1102            .map(|(id, owner_key, scene_index)| ThermalPart {
1103                id,
1104                kind: "gearbox",
1105                owner_key,
1106                scene_part: "gearbox",
1107                scene_index,
1108            })
1109            .into()
1110    }
1111
1112    fn signal_infos(&self) -> Vec<SignalInfo> {
1113        let mut out: Vec<SignalInfo> = [
1114            ("web.span.1.tension", "web-span-1", "quantity-tension", "N"),
1115            ("web.span.2.tension", "web-span-2", "quantity-tension", "N"),
1116            ("web.tension_peak", "group-web", "quantity-tension-peak", "N"),
1117            ("web.slack_ratio", "group-web", "quantity-slack-ratio", ""),
1118            ("web.tension_setpoint", "group-web", "quantity-tension-setpoint", "N"),
1119            ("web.slack_time", "group-web", "quantity-web-slack-time", "s"),
1120            ("dancer.position", "group-dancer", "quantity-position", "m"),
1121            ("dancer.speed", "group-dancer", "quantity-speed", "m/s"),
1122            ("dancer.load_force", "group-dancer", "quantity-cylinder-force", "N"),
1123            ("dancer.trim_speed", "group-dancer", "quantity-trim-speed", "m/s"),
1124            ("rewind.radius_from_speeds", "motor-rewind", "quantity-radius-from-speeds", "m"),
1125            ("gearbox.unwind.output_torque", "motor-unwind", "quantity-gearbox-torque", "N m"),
1126            ("gearbox.rewind.output_torque", "motor-rewind", "quantity-gearbox-torque", "N m"),
1127        ]
1128        .into_iter()
1129        .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
1130        .collect();
1131        for (roll, motor) in ROLLS.iter().zip(&self.motors) {
1132            for (what, quantity, unit) in [
1133                ("radius", "quantity-radius", "m"),
1134                ("inertia_ratio", "quantity-inertia-ratio", ""),
1135                ("inertia_ratio_at_full", "quantity-inertia-ratio-at-full", ""),
1136                ("torque_at_full", "quantity-torque-at-full", "N m"),
1137                ("torque_at_core", "quantity-torque-at-core", "N m"),
1138                ("speed_at_core", "quantity-speed-at-core", "rad/s"),
1139                ("tension_torque_at_full", "quantity-tension-torque-at-full", "N m"),
1140            ] {
1141                out.push(SignalInfo::new(format!("{roll}.{what}"), motor.key, quantity, unit));
1142            }
1143        }
1144        self.effect_infos(&mut out);
1145        out
1146    }
1147
1148    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1149        let e = self.eval(s, torque);
1150        let (v, a) = self.line(&e);
1151        // The rewind's radius as a drive works it out from the speeds: the unwind's radius times its speed over the
1152        // rewind's (equal surface speeds), where the rewind turns.
1153        let from_speeds = if e.w[1].abs() > 1e-9 { e.r[0] * e.w[0] / e.w[1] } else { e.r[1] };
1154        out.extend([
1155            e.t[0],
1156            e.t[1],
1157            e.t[0].max(e.t[1]),
1158            self.slack_ratio(e.t),
1159            self.tension_setpoint(e.r[1]),
1160            if self.elastic { s[9] } else { 0.0 },
1161            e.y,
1162            e.vy,
1163            e.load,
1164            self.trim_speed,
1165            from_speeds,
1166        ]);
1167        // What each gearbox passes on to its roll: its factor times the ratio times the torque at its input.
1168        out.extend((0..2).map(|k| e.factor[k] * self.ratio * e.gear_input[k]));
1169        let figures = self.end_figures(v, a, e.t, e.r[1]);
1170        for k in 0..2 {
1171            let [full, core, speed, tension, ratio] = figures[k];
1172            out.extend([e.r[k], self.inertia_ratio(e.r[k]), ratio, full, core, speed, tension]);
1173        }
1174    }
1175
1176    /// Per motor: inertia J w' / i (roll, core and rotor), no gravity (the dancer's weight is taken off by its cylinder),
1177    /// its shaft friction and its gearbox's loss at the rotor ((1 - factor) times its input torque), and the rest (the
1178    /// web's tension); the losses; the energy parts.
1179    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1180        let e = self.eval(s, torque);
1181        for k in 0..2 {
1182            let gearbox = (1.0 - e.factor[k]) * e.gear_input[k];
1183            let parts = [e.j[k] * e.acc[k] / self.ratio, 0.0, e.shaft[k] + gearbox];
1184            out.extend(parts);
1185            out.push(torque[k] - parts.iter().sum::<f64>());
1186        }
1187        out.extend(self.losses(&e));
1188        out.extend(self.energy_parts(&e));
1189    }
1190    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1191        out.extend(self.losses(&self.eval(s, torque)));
1192    }
1193
1194    /// Seen from the front: the unwind roll on the left, the rewind on the right, their motors behind them, the dancer's
1195    /// roller below in the middle on its slide with the cylinder under it, and the web from roll to roller to roll,
1196    /// shaded by its tension against the setpoint.
1197    fn scene(&self, s: &[f64], out: &mut Scene) {
1198        let e = self.eval(s, &[0.0, 0.0]);
1199        let (x, width, rd) = (0.35, self.width, self.roller_radius);
1200        let depth = 0.5 * (self.spans[0] + self.spans[1]) + e.y;
1201        let phi = [s[0], s[1]];
1202        out.labels.clear();
1203        out.parts.clear();
1204        let grey = [0.62, 0.64, 0.68];
1205        let (mut angle, mut speed) = ([0.0; 2], [0.0; 2]);
1206        self.motor_state(s, &mut angle, &mut speed);
1207        out.parts.push(Part::new("frame", Shape::Box { size: [1.2, 0.04, 0.06] }, [0.0, 0.3, 0.25], grey));
1208        for (k, centre) in [-x, x].into_iter().enumerate() {
1209            let turn = -phi[k];
1210            out.parts.extend([
1211                Part::new(
1212                    "roll",
1213                    Shape::Cylinder { radius: e.r[k], length: width },
1214                    [centre, 0.0, 0.0],
1215                    [0.85, 0.82, 0.7],
1216                ),
1217                Part::new(
1218                    "core",
1219                    Shape::Cylinder { radius: self.roll.core, length: width + 0.04 },
1220                    [centre, 0.0, 0.0],
1221                    [0.55, 0.4, 0.25],
1222                ),
1223                Part::new(
1224                    "roll-spoke",
1225                    Shape::Box { size: [1.8 * self.roll.core, 0.004, 0.2 * self.roll.core] },
1226                    [centre, -0.5 * width - 0.03, 0.0],
1227                    [0.1, 0.1, 0.1],
1228                )
1229                .turned(turn),
1230                Part::new("gearbox", Shape::Box { size: [0.09, 0.09, 0.09] }, [centre, 0.5 * width + 0.1, 0.0], grey),
1231                Part::new(
1232                    sim_core::scene::MOTOR_PART,
1233                    Shape::Box { size: [0.1, 0.16, 0.1] },
1234                    [centre, 0.5 * width + 0.23, 0.0],
1235                    [0.9, 0.45, 0.1],
1236                ),
1237                // The motor shaft's bar, at the motor's far end, turning with it.
1238                Part::new(
1239                    "rotor-bar",
1240                    Shape::Box { size: [0.08, 0.004, 0.015] },
1241                    [centre, 0.5 * width + 0.315, 0.0],
1242                    [0.1, 0.1, 0.1],
1243                )
1244                .turned(-angle[k]),
1245            ]);
1246        }
1247        out.parts.extend(self.dancer_parts(e.y));
1248        let set = self.tension_setpoint(e.r[1]).max(1.0);
1249        let shade = e.t.map(|t| ((t - set) / set).clamp(-1.0, 1.0) as f32);
1250        let spans = [([-x + e.r[0], 0.0], [-rd, -depth], shade[0]), ([rd, -depth], [x - e.r[1], 0.0], shade[1])];
1251        for (from, to, shade) in spans {
1252            out.parts.push(
1253                Part::new(
1254                    "web",
1255                    Shape::Segment { to: [to[0], 0.0, to[1]], width },
1256                    [from[0], 0.0, from[1]],
1257                    sim_core::scene::BELT_COLOR,
1258                )
1259                .highlighted(shade),
1260            );
1261        }
1262        for (k, centre) in [-x, x].into_iter().enumerate() {
1263            out.labels.push(Label {
1264                pos: [centre, 0.0, self.roll.full + 0.08],
1265                owner_key: self.motors[k].key,
1266                value: speed[k] * 60.0 / TAU,
1267                unit_key: "unit-rpm",
1268                decimals: 0,
1269            });
1270        }
1271        out.labels.extend([
1272            Label { pos: [0.15, 0.0, -depth], owner_key: "group-dancer", value: e.y, unit_key: "unit-m", decimals: 4 },
1273            Label {
1274                pos: [0.0, 0.0, 0.25],
1275                owner_key: "group-web",
1276                value: e.t[0].max(e.t[1]),
1277                unit_key: "unit-n",
1278                decimals: 1,
1279            },
1280        ]);
1281    }
1282}
1283
1284#[cfg(test)]
1285mod tests;