Skip to main content

sim_wasm/
lib.rs

1//! The simulator in the browser: core, machines and analysis built for `wasm32-unknown-unknown`, behind a few C-ABI
2//! functions that take and give UTF-8 text. `web/index.html` loads the module and runs a sizing check with it.
3//!
4//! The page writes a request into memory from `alloc`, calls `call(kind, ptr, len)` and reads the answer, JSON, from
5//! `out_ptr()` and `out_len()`. `call` returns 0 when the answer is a result and 1 when it is `{"error": "..."}`.
6//!
7//! | kind | request lines                                        | answer                                            |
8//! | ---- | ---------------------------------------------------- | ------------------------------------------------- |
9//! | 0    | language                                             | `[{"id", "name", "file"}]`, every machine         |
10//! | 1    | machine id                                           | `{"config"}`, the machine's default config (TOML) |
11//! | 2    | machine id, language and options, a config (TOML)    | the run's load per motor and its verdicts         |
12//! | 3    | machine id, language and options, a config (TOML)    | `{"dt_s", "centre", "radius", "motors", "sample"}`: the 3D view starts |
13//! | 4    | file name, language, then a machine file (TOML)      | `{"id", "name", "config"}`: the machine to use as an id |
14//! | 5    | machine id, language and options, a config (TOML)    | `{"motor", "points"}`: frequency response of one motor |
15//! | 6    | machine id, language, a config, `---`, a trace (CSV) | `{"rows", "advice"}`: masses and friction fitted to the trace |
16//! | 7    | language, then translation keys, one a line          | `{key: text}`: the page's texts and those keys    |
17//! | 8    | machine id, language, a config (TOML)                | `{"params", "parts"}`: the values the page's form edits |
18//! | 9    | machine id, language, a config, `---`, `path = value` lines | `{"config", "changed", "compact"}`: the values set in the config's own text |
19//! | 10   | machine id, language, a config (TOML)                | `{"step_s", "time", "signals", "motors"}`: the scopes of one pass of the cycle |
20//!
21//! An empty config is the machine's default one. Parts the config names (`[parts]`) come from the built-in catalogue,
22//! as in every front end. WebAssembly starts no threads, so analyses that share the processors natively run one after
23//! another here.
24//!
25//! Options follow the language on its line, separated by spaces: `path` runs the path (format: `sim_components::path`)
26//! that follows the config after a line `---` instead of the cycle, timed within the axis limits or with
27//! `time-optimal` as fast as the motors allow (kinds 2 and 3); `motor=K`, `from=HZ`, `to=HZ`, `count=N` and
28//! `amplitude=NM` set the sweep of kind 5 as `sim-cli sweep` takes them. A line `---` is never part of a TOML config.
29//!
30//! Machines: the registered ones by their id, the machine files of `machines/` built into the module as
31//! `file:<name>.toml`, and a file the page hands in (kind 4) as `upload:<name>`.
32//!
33//! The 3D view: kind 3 sets the machine at its start pose and starts its cycle or path; `centre` and `radius` are the
34//! sphere round its scene there, to fit the camera to. Then the page calls `frame(seconds)`, which runs the simulation
35//! on by that many seconds and returns where `frame_len()` 32-bit floats lie, no JSON: a head of `HEAD` floats
36//! (`time_s`, `cycle_s`, the tool's x, y, z, the number of parts, of obstacles and of samples; NaN for what is not
37//! known yet), `RECORD` floats per part and per obstacle, as `record` lays them out, and `sample` floats per sample as
38//! `Player::sample` lays them out: the plots' and the trail's data since the last frame. A request that is not a
39//! finite time from 0 to `MAX_FRAME_S` is refused: `frame` returns null and the error is the answer at `out_ptr`.
40
41use sim_components::analysis::{
42    SWEEP_POINTS, analyse_cycle_with, analyse_trajectory_with, default_sweep_amplitude, frequency_sweep, log_spaced,
43    verdicts,
44};
45use sim_components::{Command, Sim, load_config};
46use sim_core::scene::{Obstacle, Part, Scene, Shape, part_color};
47use sim_core::{Config, MachineEntry, Translations};
48use sim_machines::{LANGUAGES, MACHINES, find, translations};
49use std::cell::RefCell;
50use std::fmt::Write;
51
52/// Floats in front of the parts in a frame.
53pub const HEAD: usize = 8;
54/// Floats per part in a frame.
55pub const RECORD: usize = 20;
56/// The mesh number of an obstacle: a cube drawn see-through.
57pub const OBSTACLE_MESH: f32 = 2.0;
58/// The most simulated time one `frame` runs, s: more is refused rather than left to hang the page.
59pub const MAX_FRAME_S: f64 = 60.0;
60/// Floats of a sample in front of its motors: time, the tool's x, y, z, and its distance from the plan.
61pub const SAMPLE_HEAD: usize = 5;
62/// Signals per motor in a sample, each as its lowest and highest value over the sample: torque, torque command,
63/// speed, speed command, following error.
64pub const MOTOR_SIGNALS: usize = 5;
65/// How long a sample spans, s: the plots get every peak, as the lowest and highest value within it.
66pub const SAMPLE_S: f64 = 1e-3;
67
68/// The verdicts' labels are the app's: one translation source for every front end.
69static CHECK_LABELS: &[(&str, &str)] =
70    &[("en", include_str!("../../sim-app/i18n/en.ftl")), ("de", include_str!("../../sim-app/i18n/de.ftl"))];
71
72/// The page's own texts; kind 7 hands them out.
73static PAGE_TEXTS: &[(&str, &str)] = &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))];
74
75/// The machine files shipped in `machines/`, built in so that the page needs no third file.
76static SHIPPED: &[(&str, &str)] = &[
77    ("corexy.toml", include_str!("../../../machines/corexy.toml")),
78    ("h-bot.toml", include_str!("../../../machines/h-bot.toml")),
79    ("planar-delta.toml", include_str!("../../../machines/planar-delta.toml")),
80    ("rack-gantry.toml", include_str!("../../../machines/rack-gantry.toml")),
81    ("screw-portal.toml", include_str!("../../../machines/screw-portal.toml")),
82    ("single-axis.toml", include_str!("../../../machines/single-axis.toml")),
83    ("t-gantry.toml", include_str!("../../../machines/t-gantry.toml")),
84    ("xyz-portal.toml", include_str!("../../../machines/xyz-portal.toml")),
85];
86
87thread_local! {
88    /// The machine files read so far, by the id the page uses for them.
89    static FILES: RefCell<Vec<(String, &'static MachineEntry)>> = const { RefCell::new(Vec::new()) };
90}
91
92thread_local! {
93    static OUT: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
94}
95
96/// Room for a request of `len` bytes, which the caller writes and hands to `call`; `call` frees it.
97#[unsafe(no_mangle)]
98pub extern "C" fn alloc(len: usize) -> *mut u8 {
99    let mut buffer = Vec::<u8>::with_capacity(len.max(1));
100    let ptr = buffer.as_mut_ptr();
101    std::mem::forget(buffer);
102    ptr
103}
104
105/// Where the last answer is.
106#[unsafe(no_mangle)]
107pub extern "C" fn out_ptr() -> *const u8 {
108    OUT.with(|o| o.borrow().as_ptr())
109}
110
111/// How long the last answer is, in bytes.
112#[unsafe(no_mangle)]
113pub extern "C" fn out_len() -> usize {
114    OUT.with(|o| o.borrow().len())
115}
116
117/// # Safety
118/// `ptr` comes from `alloc(len)` and holds `len` bytes written by the caller; it is not used afterwards.
119#[unsafe(no_mangle)]
120pub unsafe extern "C" fn call(kind: u32, ptr: *mut u8, len: usize) -> u32 {
121    let request = unsafe { Vec::from_raw_parts(ptr, len, len.max(1)) };
122    let (answer, code) = match handle(kind, &String::from_utf8_lossy(&request)) {
123        Ok(json) => (json, 0),
124        Err(message) => (format!("{{\"error\":{}}}", quote(&message)), 1),
125    };
126    OUT.with(|o| *o.borrow_mut() = answer.into_bytes());
127    code
128}
129
130/// The answer to a request as `call` gets it, or the message of why there is none.
131pub fn handle(kind: u32, request: &str) -> Result<String, String> {
132    let r = Request::parse(request);
133    match kind {
134        0 => Ok(list(language(r.id))),
135        1 => Ok(format!("{{\"config\":{}}}", quote(machine(r.id, "en")?.default_config))),
136        2 => size(&r),
137        3 => play(&r),
138        4 => upload(r.id, r.lang, r.config),
139        5 => sweep(&r),
140        6 => fit(&r),
141        7 => Ok(texts(language(r.id), request.lines().skip(1))),
142        8 => form(&r),
143        9 => apply(&r),
144        10 => scopes(&r),
145        _ => Err(format!("unknown request kind: {kind}")),
146    }
147}
148
149/// A request's lines: the machine, the language with options after it, the config, and after a line `---` the text
150/// the options name (a path, a trace).
151struct Request<'a> {
152    id: &'a str,
153    lang: &'static str,
154    options: Vec<&'a str>,
155    config: &'a str,
156    extra: &'a str,
157}
158
159impl<'a> Request<'a> {
160    fn parse(request: &'a str) -> Self {
161        let mut lines = request.splitn(3, '\n');
162        let (id, second, rest) =
163            (lines.next().unwrap_or("").trim(), lines.next().unwrap_or(""), lines.next().unwrap_or(""));
164        let mut words = second.split_whitespace();
165        let lang = language(words.next().unwrap_or(""));
166        let (config, extra) = match rest.strip_prefix("---\n").or(rest.strip_prefix("---\r\n")) {
167            Some(extra) => ("", extra),
168            None => rest.split_once("\n---\n").or(rest.split_once("\n---\r\n")).unwrap_or((rest, "")),
169        };
170        Request { id, lang, options: words.collect(), config, extra }
171    }
172
173    fn flag(&self, name: &str) -> bool {
174        self.options.contains(&name)
175    }
176
177    /// The number of an option `name=value`; `default` without it.
178    fn number(&self, name: &str, default: f64) -> Result<f64, String> {
179        let prefix = format!("{name}=");
180        match self.options.iter().find_map(|o| o.strip_prefix(prefix.as_str())) {
181            None => Ok(default),
182            Some(v) => v.parse::<f64>().ok().filter(|v| v.is_finite()).ok_or_else(|| format!("{name}={v}")),
183        }
184    }
185}
186
187/// A machine by the id the page uses: a registered one, a machine file of `machines/` (read the first time it is
188/// asked for) or one the page handed in.
189fn machine(id: &str, lang: &str) -> Result<&'static MachineEntry, String> {
190    if let Some(entry) = find(id) {
191        return Ok(entry);
192    }
193    if let Some(entry) = FILES.with(|f| f.borrow().iter().find(|(k, _)| k == id).map(|(_, e)| *e)) {
194        return Ok(entry);
195    }
196    match id.strip_prefix("file:").and_then(|name| SHIPPED.iter().find(|(f, _)| *f == name)) {
197        Some((name, text)) => read_file(id, name, lang, text),
198        None => Err(format!("unknown machine: {id}")),
199    }
200}
201
202/// A machine file read and checked as `sim_machines::load_file` checks a file (TOML, or JSON by the extension of
203/// `name`), kept under `id`. An error names the file and the line (a JSON file: the key alone).
204fn read_file(id: &str, name: &str, lang: &str, text: &str) -> Result<&'static MachineEntry, String> {
205    let known: Vec<Config> = MACHINES.iter().map(|m| m.config()).collect();
206    let json = name.to_ascii_lowercase().ends_with(".json");
207    let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
208    let tr = translations(lang, MACHINES[0]);
209    let converted = if json {
210        sim_machines::json_to_toml(text).map_err(|e| tr.tr_arg(e.key(), e.detail()))?
211    } else {
212        text.to_string()
213    };
214    let entry = sim_netlist::from_text(&converted, !json, stem, &known).map_err(|(e, line)| {
215        let at = line.map_or(String::new(), |line| format!(":{line}"));
216        tr.tr_arg(e.key(), &format!("{name}{at}: {}", e.detail()))
217    })?;
218    FILES.with(|f| {
219        let mut files = f.borrow_mut();
220        files.retain(|(k, _)| k != id);
221        files.push((id.to_string(), entry));
222    });
223    Ok(entry)
224}
225
226/// A machine file the page hands in (kind 4), TOML or JSON by its file name's extension; one of the same name before is
227/// replaced.
228fn upload(name: &str, lang: &str, text: &str) -> Result<String, String> {
229    let name = if name.is_empty() { "machine.toml" } else { name };
230    let id = format!("upload:{name}");
231    let entry = read_file(&id, name, lang, text)?;
232    Ok(format!(
233        "{{\"id\":{},\"name\":{},\"config\":{}}}",
234        quote(&id),
235        quote(translations(lang, entry).tr(entry.key)),
236        quote(entry.default_config)
237    ))
238}
239
240/// The machine, its translations with the checks' labels, and the config of the request, read and resolved.
241fn configured(r: &Request) -> Result<(&'static MachineEntry, Translations, Config), String> {
242    let entry = machine(r.id, r.lang)?;
243    let mut tr = translations(r.lang, entry);
244    CHECK_LABELS.iter().chain(PAGE_TEXTS).filter(|(l, _)| *l == r.lang).for_each(|(_, t)| tr.add(t));
245    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
246    let cfg: Config =
247        if r.config.trim().is_empty() { entry.config() } else { load_config(entry, r.config).map_err(refused)? };
248    let cfg = sim_components::catalog::resolve(entry, &cfg).map_err(refused)?;
249    Ok((entry, tr, cfg))
250}
251
252/// The poses at times of the request's path (option `path`), planned from where `sim` stands, with what the planned
253/// path is off the given one, mm, as `sim-cli` warns of it; `None` without the option.
254fn planned_path(r: &Request, sim: &Sim, tr: &Translations) -> Result<Option<(Vec<(f64, Vec<f64>)>, f64)>, String> {
255    if !r.flag("path") {
256        return Ok(None);
257    }
258    let pieces = sim_components::path::parse(r.extra).map_err(|line| tr.tr_arg("web-path-unreadable", &line))?;
259    if pieces.is_empty() {
260        return Err(tr.tr("web-path-empty").to_string());
261    }
262    let optimal = r.flag("time-optimal");
263    let refused = |e: sim_components::CommandError| tr.tr(e.key).to_string();
264    let deviation = sim.path_deviation(&pieces, optimal).map_err(refused)?;
265    Ok(Some((sim.plan_path(&pieces, optimal).map_err(refused)?, deviation * 1e3)))
266}
267
268/// The machine of the 3D view: its simulation, the frame it hands the page, and the cycle passes it has seen.
269struct Player {
270    sim: Sim,
271    scene: Scene,
272    frame: Vec<f32>,
273    passes: u64,
274    /// When the latest pass began, once one has been seen to begin.
275    pass_began: Option<f64>,
276    /// How long the latest whole pass took, s; NaN before one has run.
277    cycle_s: f64,
278    /// Base steps per sample, and how many of the sample being gathered have run.
279    every: u64,
280    gathered: u64,
281    /// The sample being gathered: per motor and signal the lowest and highest value so far.
282    range: Vec<f32>,
283    /// The samples since the last frame, `sample_len` floats each.
284    samples: Vec<f32>,
285    /// The motors' angles and speeds, room kept from one step to the next.
286    angle: Vec<f64>,
287    speed: Vec<f64>,
288}
289
290thread_local! {
291    static PLAYER: RefCell<Option<Player>> = const { RefCell::new(None) };
292}
293
294/// Floats per sample for a machine of `motors` motors.
295pub fn sample_len(motors: usize) -> usize {
296    SAMPLE_HEAD + 2 * MOTOR_SIGNALS * motors
297}
298
299/// Sets up the 3D view (kind 3): the machine at rest at its start pose, its cycle or its path commanded.
300fn play(r: &Request) -> Result<String, String> {
301    let (entry, tr, cfg) = configured(r)?;
302    let mut sim = Sim::new(entry, &cfg).map_err(|e| tr.tr_arg(e.key(), e.detail()))?;
303    let command = match planned_path(r, &sim, &tr)? {
304        Some((points, _)) => Command::Trajectory(points),
305        None => Command::StartCycle,
306    };
307    sim.command(command).map_err(|e| tr.tr(e.key).to_string())?;
308    let motors = sim.machine.motors().to_vec();
309    let mut player = Player {
310        passes: sim.control.cycle_passes(),
311        every: ((SAMPLE_S / sim.dt).round() as u64).max(1),
312        gathered: 0,
313        range: Vec::new(),
314        samples: Vec::new(),
315        angle: vec![0.0; motors.len()],
316        speed: vec![0.0; motors.len()],
317        sim,
318        scene: Scene::default(),
319        frame: Vec::new(),
320        pass_began: None,
321        cycle_s: f64::NAN,
322    };
323    player.advance(0.0);
324    let drawn = (player.frame[5] + player.frame[6]) as usize * RECORD;
325    let (lo, hi) = bounds(&player.frame[HEAD..HEAD + drawn]);
326    let centre: [f32; 3] = std::array::from_fn(|i| (lo[i] + hi[i]) / 2.0);
327    let radius = (0..3).map(|i| (hi[i] - lo[i]).powi(2)).sum::<f32>().sqrt() / 2.0;
328    let names: Vec<String> =
329        motors.iter().map(|m| format!("{{\"id\":{},\"name\":{}}}", quote(m.id), quote(tr.tr(m.key)))).collect();
330    let json = format!(
331        "{{\"dt_s\":{},\"centre\":[{},{},{}],\"radius\":{},\"motors\":[{}],\"sample\":{}}}",
332        number(player.sim.dt),
333        number(centre[0].into()),
334        number(centre[1].into()),
335        number(centre[2].into()),
336        number(radius.into()),
337        names.join(","),
338        sample_len(motors.len())
339    );
340    PLAYER.with(|p| *p.borrow_mut() = Some(player));
341    Ok(json)
342}
343
344impl Player {
345    /// Runs on by `seconds` (whole base steps) and writes the frame.
346    fn advance(&mut self, seconds: f64) {
347        self.samples.clear();
348        for _ in 0..(seconds / self.sim.dt).round() as u64 {
349            self.sim.step();
350            // The controller counts the passes, as `analyse_cycle` does: from one count to the next is a pass.
351            let passes = self.sim.control.cycle_passes();
352            if passes != self.passes {
353                let now = self.sim.time();
354                if let Some(began) = self.pass_began {
355                    self.cycle_s = now - began;
356                }
357                (self.passes, self.pass_began) = (passes, Some(now));
358            }
359            self.sample();
360        }
361        self.scene = Scene::default();
362        self.sim.scene(&mut self.scene);
363        let tool = self.scene.tool.map_or([f32::NAN; 3], |p| p.map(|v| v as f32));
364        self.frame.clear();
365        let samples = self.samples.len() / sample_len(self.speed.len());
366        let (parts, obstacles) = (self.scene.parts.len(), self.scene.obstacles.len());
367        let head = [self.sim.time(), self.cycle_s, tool[0].into(), tool[1].into(), tool[2].into()];
368        self.frame.extend(head.map(|v| v as f32));
369        self.frame.extend([parts, obstacles, samples].map(|n| n as f32));
370        self.scene.parts.iter().for_each(|part| record(part, &mut self.frame));
371        self.scene.obstacles.iter().for_each(|o| record_obstacle(o, &mut self.frame));
372        self.frame.extend_from_slice(&self.samples);
373    }
374
375    /// Takes this base step's motor signals into the sample being gathered, and closes the sample after `every`
376    /// steps: `SAMPLE_HEAD` floats (time, the tool's x, y, z in the scene, its distance from where the plan has it then,
377    /// m; NaN where the machine has no mapping), then per motor the lowest and highest torque, torque command (N m),
378    /// speed, speed command (rad/s) and following error (rad) over the sample.
379    fn sample(&mut self) {
380        let sim = &self.sim;
381        sim.machine.motor_state(&sim.state, &mut self.angle, &mut self.speed);
382        if self.gathered == 0 {
383            self.range.clear();
384            self.range.resize(2 * MOTOR_SIGNALS * self.speed.len(), f32::NAN);
385        }
386        for (k, d) in sim.control.drives.iter().enumerate() {
387            let values = [d.torque, d.torque_command, self.speed[k], d.speed_command, d.following_error];
388            for (i, v) in values.into_iter().enumerate() {
389                let at = 2 * (MOTOR_SIGNALS * k + i);
390                // NaN loses to any number in `min` and `max`: the first value starts the range.
391                self.range[at] = self.range[at].min(v as f32);
392                self.range[at + 1] = self.range[at + 1].max(v as f32);
393            }
394        }
395        self.gathered += 1;
396        if self.gathered < self.every {
397            return;
398        }
399        self.gathered = 0;
400        let tool = sim.tool_point();
401        let planned = sim.machine.scene_point(&sim.control.set_pos);
402        let gap = match (tool, planned) {
403            (Some(t), Some(p)) => (0..3).map(|i| (t[i] - p[i]).powi(2)).sum::<f64>().sqrt(),
404            _ => f64::NAN,
405        };
406        let tool = tool.unwrap_or([f64::NAN; 3]);
407        self.samples.extend([sim.time(), tool[0], tool[1], tool[2], gap].map(|v| v as f32));
408        self.samples.extend_from_slice(&self.range);
409    }
410}
411
412/// An obstacle as the page draws it, `RECORD` floats as `record` lays them out: mesh `OBSTACLE_MESH` (the unit cube,
413/// drawn see-through), stretched to the obstacle's box, grey, or red while a part of the machine touches it.
414pub fn record_obstacle(obstacle: &Obstacle, out: &mut Vec<f32>) {
415    let (c, s) = (obstacle.aabb.centre, obstacle.aabb.size.map(|v| v.abs().max(1e-6)));
416    out.push(OBSTACLE_MESH);
417    out.extend([s[0], 0.0, 0.0, 0.0, 0.0, s[1], 0.0, 0.0, 0.0, 0.0, s[2], 0.0].map(|v| v as f32));
418    out.extend([c[0] as f32, c[1] as f32, c[2] as f32, 1.0]);
419    out.extend(if obstacle.contact { [0.9, 0.15, 0.1] } else { [0.55, 0.57, 0.62] });
420}
421
422/// One part as the page draws it, `RECORD` floats: the mesh (0 a cube of side 1, 1 a cylinder of diameter and length
423/// 1 along y, both centred on the origin; turned as `Part::flat` says), the matrix that takes the mesh to the part in scene coordinates (4 × 4,
424/// column by column, as WebGL takes it), and the colour (`part_color`, red, green, blue in 0..1).
425/// A segment is a cube stretched from `pos` to `to`, `width` wide in the depth (y) and 4 mm thick, as in sim-app.
426pub fn record(part: &Part, out: &mut Vec<f32>) {
427    // Sizes are drawn as their size, whatever the sign, and never flat, so that the shader can invert the matrix.
428    let size = |v: f64| v.abs().max(1e-6);
429    let (mesh, columns, at) = match &part.shape {
430        Shape::Box { size: s } => {
431            let (sin, cos) = part.angle.sin_cos();
432            // The angle turns from +x towards +z, about y.
433            let x = [cos, 0.0, sin].map(|v| v * size(s[0]));
434            let z = [-sin, 0.0, cos].map(|v| v * size(s[2]));
435            (0.0, [x, [0.0, size(s[1]), 0.0], z], part.pos)
436        }
437        Shape::Cylinder { radius, length } => {
438            let d = size(2.0 * radius);
439            (1.0, [[d, 0.0, 0.0], [0.0, size(*length), 0.0], [0.0, 0.0, d]], part.pos)
440        }
441        Shape::Segment { to, width } => {
442            let along: [f64; 3] = std::array::from_fn(|i| to[i] - part.pos[i]);
443            let norm = along.iter().map(|v| v * v).sum::<f64>().sqrt();
444            let length = size(norm);
445            // A segment of no length (an arm's last link where the flange sits at its last joint) has no direction: it
446            // lies along x, so that its width and thickness keep theirs and the matrix stays invertible.
447            let u = if norm > 0.0 { along.map(|v| v / norm) } else { [1.0, 0.0, 0.0] };
448            // The depth axis, or x for a segment along the depth, made square to the segment.
449            let near = if u[1].abs() > 0.99 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
450            let dot = (0..3).map(|i| near[i] * u[i]).sum::<f64>();
451            let w: [f64; 3] = std::array::from_fn(|i| near[i] - dot * u[i]);
452            let w_len = w.iter().map(|v| v * v).sum::<f64>().sqrt();
453            let w = w.map(|v| v / w_len);
454            let n = [u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]];
455            let mid = std::array::from_fn(|i| part.pos[i] + along[i] / 2.0);
456            (0.0, [u.map(|v| v * length), w.map(|v| v * size(*width)), n.map(|v| v * 0.004)], mid)
457        }
458    };
459    // A segment is never flat (`Part::flat`), so this turns only boxes and cylinders.
460    let columns = columns.map(|c| part.oriented(c));
461    out.push(mesh);
462    for c in columns {
463        out.extend([c[0] as f32, c[1] as f32, c[2] as f32, 0.0]);
464    }
465    out.extend([at[0] as f32, at[1] as f32, at[2] as f32, 1.0]);
466    out.extend(part_color(part.color, part.highlight, part.heat));
467}
468
469/// The box with edges along the axes round every part of `records` (`RECORD` floats each): lowest and highest corner.
470pub fn bounds(records: &[f32]) -> ([f32; 3], [f32; 3]) {
471    let (mut lo, mut hi) = ([f32::INFINITY; 3], [f32::NEG_INFINITY; 3]);
472    for r in records.as_chunks::<RECORD>().0 {
473        for i in 0..3 {
474            // The mesh fits in the unit cube; that cube's corners reach half of each column out from its centre.
475            let half = (r[1 + i].abs() + r[5 + i].abs() + r[9 + i].abs()) / 2.0;
476            lo[i] = lo[i].min(r[13 + i] - half);
477            hi[i] = hi[i].max(r[13 + i] + half);
478        }
479    }
480    (lo, hi)
481}
482
483/// Runs the 3D view's machine on by `seconds` and returns its frame (see the module's documentation); null before
484/// kind 3 has set one up, and null with the error as the answer at `out_ptr` for a time that is not finite, below 0
485/// or over `MAX_FRAME_S` (an infinite one ran the steps' count to the largest integer and hung the page).
486#[unsafe(no_mangle)]
487pub extern "C" fn frame(seconds: f64) -> *const f32 {
488    if !(0.0..=MAX_FRAME_S).contains(&seconds) {
489        let error = format!("{{\"error\":{}}}", quote(&format!("frame: {seconds} s is not from 0 to {MAX_FRAME_S} s")));
490        OUT.with(|o| *o.borrow_mut() = error.into_bytes());
491        return std::ptr::null();
492    }
493    PLAYER.with(|p| {
494        p.borrow_mut().as_mut().map_or(std::ptr::null(), |player| {
495            player.advance(seconds);
496            player.frame.as_ptr()
497        })
498    })
499}
500
501/// How many floats the last frame has.
502#[unsafe(no_mangle)]
503pub extern "C" fn frame_len() -> usize {
504    PLAYER.with(|p| p.borrow().as_ref().map_or(0, |player| player.frame.len()))
505}
506
507fn language(asked: &str) -> &'static str {
508    LANGUAGES.iter().copied().find(|l| *l == asked).unwrap_or("en")
509}
510
511/// The registered machines, then the machine files of `machines/` and those the page handed in (`"file": true`).
512fn list(lang: &str) -> String {
513    let mut rows: Vec<String> = MACHINES
514        .iter()
515        .map(|m| {
516            format!("{{\"id\":{},\"name\":{},\"file\":false}}", quote(m.id), quote(translations(lang, m).tr(m.key)))
517        })
518        .collect();
519    let shipped = SHIPPED.iter().map(|(name, _)| (format!("file:{name}"), name.to_string()));
520    let uploaded = FILES.with(|f| {
521        let files = f.borrow();
522        let ids: Vec<String> = files.iter().map(|(id, _)| id.clone()).filter(|id| id.starts_with("upload:")).collect();
523        ids.into_iter().map(|id| (id.clone(), id["upload:".len()..].to_string())).collect::<Vec<_>>()
524    });
525    for (id, name) in shipped.chain(uploaded) {
526        rows.push(format!("{{\"id\":{},\"name\":{},\"file\":true}}", quote(&id), quote(&name)));
527    }
528    format!("[{}]", rows.join(","))
529}
530
531/// The page's texts (`i18n/*.ftl` of this crate) in `lang`, and those of `keys` from the simulator's translations
532/// and the app's (axis, quantity and check names), as one JSON object.
533fn texts<'a>(lang: &str, keys: impl Iterator<Item = &'a str>) -> String {
534    let mut tr = translations(lang, MACHINES[0]);
535    CHECK_LABELS.iter().chain(PAGE_TEXTS).filter(|(l, _)| *l == lang).for_each(|(_, t)| tr.add(t));
536    let own = PAGE_TEXTS[0].1.lines().filter_map(|l| l.split_once(" = ").map(|(k, _)| k.trim()));
537    let keys: Vec<&str> =
538        own.filter(|k| !k.starts_with('#')).chain(keys.map(str::trim).filter(|k| !k.is_empty())).collect();
539    let rows: Vec<String> = keys.iter().map(|k| format!("{}:{}", quote(k), quote(tr.tr(k)))).collect();
540    format!("{{{}}}", rows.join(","))
541}
542
543/// The cycle of the config, one pass measured by `analyse_cycle`, or the path of the request run through by
544/// `analyse_trajectory`, and judged as `sim-cli verdicts` judges it; per motor every column of `sim-cli analyze`, with
545/// the operating points and the torque-speed curve. The column names are fixed: a motor's `torque_unit` and
546/// `speed_unit` say what its `*_torque_nm` and `peak_speed_rad_s` hold (N m and rad/s, on a linear motor N and m/s).
547fn size(r: &Request) -> Result<String, String> {
548    let (entry, tr, cfg) = configured(r)?;
549    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
550    let mut sim = Sim::new(entry, &cfg).map_err(refused)?;
551    let motors = sim.machine.motors().to_vec();
552    let infos = sim.signal_infos();
553    let unit_of = |motor: &str, signal: &str, rotary: &str| {
554        let id = format!("motor.{motor}.{signal}");
555        infos.iter().find(|s| s.id == id).map_or(rotary, |s| s.unit.as_str()).to_string()
556    };
557    let mut warnings: Vec<String> = sim
558        .limit_violations
559        .iter()
560        .map(|v| tr.tr_arg(v.key, &format!("{}: {:.4} > {:.4}", tr.tr(motors[v.motor].key), v.needed, v.allowed)))
561        .collect();
562    let path = planned_path(r, &sim, &tr)?;
563    let load = match path {
564        Some((points, deviation)) => {
565            // As `sim-cli`: not below what the figure can show.
566            let shown = format!("{deviation:.4}");
567            if shown != "0.0000" {
568                warnings.push(tr.tr_arg("path-deviation", &shown));
569            }
570            analyse_trajectory_with(&mut sim, points, false)
571        }
572        None => analyse_cycle_with(&mut sim, false),
573    }
574    .map_err(|e| tr.tr(e.key).to_string())?;
575    let judged = verdicts(&cfg, &load).map_err(refused)?;
576    let or_null = |v: Option<f64>| v.map_or("null".to_string(), number);
577    let belt = load.belt_tension;
578    let machine_wide = [
579        ("belt_tension_min_n", belt.map(|b| b.0)),
580        ("belt_tension_max_n", belt.map(|b| b.1)),
581        ("path_error_peak_m", Some(load.path_error_peak)),
582        ("path_error_rms_m", Some(load.path_error_rms)),
583        ("tracking_error_peak_m", Some(load.tracking_error_peak)),
584        ("dwell_error_peak_m", Some(load.dwell_error_peak)),
585        ("belt_slack_time_s", load.belt_slack_time),
586        ("radial_load_peak_n", load.radial_load_peak),
587        ("guide_load_peak_n", load.guide_load.map(|g| g.0)),
588        ("guide_life_km", sim_components::analysis::guide_life_km(&cfg, &load)),
589        ("guide_life_h", sim_components::analysis::guide_life_h(&cfg, &load)),
590        // effects.thermal_warm_start: the largest change of a rise over the measured pass, K; null from cold.
591        ("warm_start_change_k", load.warm_start.map(|w| w.change)),
592    ];
593    let machine_wide: Vec<String> = machine_wide.iter().map(|(k, v)| format!("{}:{}", quote(k), or_null(*v))).collect();
594    let warnings: Vec<String> = warnings.iter().map(|w| quote(w)).collect();
595    let mut json = format!(
596        "{{\"machine\":{},\"cycle_s\":{},\"tripped\":{},\"warnings\":[{}],{},\"motors\":[",
597        quote(entry.id),
598        number(load.duration),
599        load.tripped,
600        warnings.join(","),
601        machine_wide.join(",")
602    );
603    for (k, (motor, m)) in motors.iter().zip(&load.motors).enumerate() {
604        let columns = [
605            ("peak_torque_nm", Some(m.peak_torque)),
606            ("rms_torque_nm", Some(m.rms_torque)),
607            ("peak_speed_rad_s", Some(m.peak_speed)),
608            ("utilisation", Some(m.utilisation)),
609            ("thermal_utilisation", Some(m.thermal_utilisation)),
610            ("rms_current_a", Some(m.rms_current)),
611            ("peak_current_a", Some(m.peak_current)),
612            ("winding_rise_k", Some(m.winding_rise)),
613            ("housing_rise_k", Some(m.housing_rise)),
614            ("drive_overload", Some(m.drive_overload)),
615            ("energy_in_j", Some(m.energy_in)),
616            ("energy_regenerated_j", Some(m.energy_regenerated)),
617            ("peak_regenerated_power_w", Some(m.peak_regenerated_power)),
618            ("largest_regeneration_j", Some(m.largest_regeneration)),
619            ("cubic_mean_torque_nm", Some(m.cubic_mean_torque)),
620            ("braking_resistor_energy_j", Some(m.resistor_energy)),
621            ("braking_resistor_mean_power_w", Some(m.resistor_energy / load.duration)),
622            ("dc_link_peak_voltage_v", Some(m.peak_dc_link_voltage)),
623            ("mains_energy_j", Some(m.mains_energy)),
624            ("pulley_bearing_life_h", sim_components::analysis::pulley_bearing_life_h(&cfg, m)),
625            ("gearbox_life_h", sim_components::analysis::gearbox_life_h(&cfg, m)),
626            ("belt_tooth_utilisation", sim_components::analysis::belt_tooth_utilisation(&cfg, m).map_err(refused)?),
627            ("gearbox_gearing_life_h", sim_components::analysis::gearbox_gearing_life_h(&cfg, m)),
628            ("motor_bearing_life_h", sim_components::analysis::motor_bearing_life_h(&cfg, m)),
629        ];
630        let _ = write!(
631            json,
632            "{}{{\"id\":{},\"name\":{},\"torque_unit\":{},\"speed_unit\":{}",
633            if k == 0 { "" } else { "," },
634            quote(motor.id),
635            quote(tr.tr(motor.key)),
636            quote(&unit_of(motor.id, "torque", "N m")),
637            quote(&unit_of(motor.id, "speed", "rad/s"))
638        );
639        for (key, value) in columns {
640            let _ = write!(json, ",{}:{}", quote(key), or_null(value));
641        }
642        let pair = |(s, t): (f64, f64)| format!("[{},{}]", number(s), number(t));
643        let points: Vec<String> = m.points.iter().copied().map(pair).collect();
644        let (curve, s1) = torque_speed_curve(sim.control.drive_params_of(k));
645        let (curve, s1): (Vec<String>, Vec<String>) =
646            (curve.into_iter().map(pair).collect(), s1.into_iter().map(pair).collect());
647        let _ = write!(
648            json,
649            ",\"points\":[{}],\"curve\":[{}],\"s1\":[{}]}}",
650            points.join(","),
651            curve.join(","),
652            s1.join(",")
653        );
654    }
655    json.push_str("],\"verdicts\":[");
656    for (i, v) in judged.iter().enumerate() {
657        let _ =
658            write!(
659                json,
660                "{}{{\"check\":{},\"label\":{},\"motor\":{},\"value\":{},\"limit\":{},\"margin\":{},\"ok\":{}}}",
661                if i == 0 { "" } else { "," },
662                quote(v.check),
663                quote(tr.tr(&sim_components::report::check_key(
664                    v.check,
665                    v.motor.is_some_and(|k| sim.machine.motor_linear(k))
666                ))),
667                v.motor.map_or("null".into(), |k| quote(motors[k].id)),
668                number(v.value),
669                number(v.limit),
670                // As the sizing report has it: the share of the limit left, 1 - value / limit (limit / value for a check
671                // that must stay above its limit); null where there is none (0 of an at-least check).
672                number(1.0 - sim_components::analysis::utilisation(v)),
673                v.ok
674            );
675    }
676    json.push_str("]}");
677    Ok(json)
678}
679
680/// The torque-speed curve of a motor's drive (`DriveParams::torque_curve`) as an outline of (speed rad/s, torque N m):
681/// the highest torque from the no-load speed backwards to the no-load speed forwards, then the lowest torque back,
682/// at the curve's corners and 40 speeds between (a field-weakened curve bends). And the continuous (S1) rating as the
683/// app and the motor-s1 verdict have it (`charts::torque_speed`): its line for positive torque, then the one for
684/// negative torque back, closed.
685pub fn torque_speed_curve(drive: &sim_components::drive::DriveParams) -> (Vec<(f64, f64)>, Vec<(f64, f64)>) {
686    let (top, rated) = (drive.no_load_speed, drive.rated_speed);
687    let mut speeds: Vec<f64> = (0..=40).map(|i| top * (i as f64 / 20.0 - 1.0)).chain([-rated, 0.0, rated]).collect();
688    speeds.sort_by(f64::total_cmp);
689    speeds.dedup();
690    let high = speeds.iter().map(|&s| (s, drive.torque_curve(s).1));
691    let curve = high.chain(speeds.iter().rev().map(|&s| (s, drive.torque_curve(s).0))).collect();
692    let [high, low] = sim_components::charts::torque_speed(drive, drive.bus_voltage).s1;
693    let s1: Vec<(f64, f64)> = high.iter().chain(low.iter().rev()).chain(high.first()).map(|p| (p[0], p[1])).collect();
694    (curve, s1)
695}
696
697/// The frequency response from one motor's torque to its speed (kind 5), as `sim-cli sweep` gives it. On a linear
698/// motor `amplitude_nm` is a force in N and the gain is in (m/s)/N.
699fn sweep(r: &Request) -> Result<String, String> {
700    let (entry, tr, cfg) = configured(r)?;
701    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
702    let motor = r.number("motor", 0.0)?;
703    let count = r.number("count", SWEEP_POINTS as f64)?;
704    if motor < 0.0 || motor.fract() != 0.0 || !(2.0..=1000.0).contains(&count) {
705        return Err(format!("motor={motor} count={count}"));
706    }
707    let frequencies = log_spaced(r.number("from", 5.0)?, r.number("to", 500.0)?, count as usize);
708    let amplitude = r.number("amplitude", default_sweep_amplitude(entry, &cfg).map_err(refused)?)?;
709    let points = frequency_sweep(entry, &cfg, motor as usize, &frequencies, amplitude).map_err(refused)?;
710    let rows: Vec<String> = points
711        .iter()
712        .map(|p| format!("[{},{},{}]", number(p.frequency), number(p.gain), number(p.phase_deg)))
713        .collect();
714    Ok(format!("{{\"motor\":{motor},\"amplitude_nm\":{},\"points\":[{}]}}", number(amplitude), rows.join(",")))
715}
716
717/// What the fit (kind 6) is given after the request's `---`: the trace, then a mapping file for a vendor export, then a
718/// measured sweep, split by lines of `%%%`; an empty part is none.
719const FIT_PARTS: &str = "\n%%%\n";
720
721/// Masses and friction fitted to a measured trace (kind 6), as `sim-cli fit` fits them: the trace in the simulator's own
722/// columns, or a vendor export through its mapping file (`import`); per axis on a machine whose axes are its motors'
723/// (`fit_rigid`), else per joint (`fit_joints`). With the option `stiffness` also the factor on the stiffness at the key
724/// `stiffness-key=` (the belts' by default) from the trace's own moves (`fit_move_stiffness`); with a sweep (options
725/// `motor=`, `amplitude=` as kind 5) the load's resonance (`fit_sweep`). Rows of quantity, of, config, fitted and
726/// standard error, and the advice translated.
727fn fit(r: &Request) -> Result<String, String> {
728    use sim_components::identify::{
729        BELT_STIFFNESS_KEY, fit_joints, fit_move_stiffness, fit_rigid, fit_sweep, parse_sweep,
730    };
731    let (entry, tr, cfg) = configured(r)?;
732    let refused = |e: sim_components::trace::TraceError| tr.tr_arg(e.key, &e.detail);
733    let machine = (entry.build)(&cfg).map_err(|e| tr.tr_arg(e.key(), e.detail()))?;
734    let parts: Vec<&str> = r.extra.split(FIT_PARTS).map(str::trim).collect();
735    let part = |i: usize| parts.get(i).copied().filter(|p| !p.is_empty());
736    if part(0).is_none() && part(2).is_none() {
737        return Err(tr.tr("web-fit-nothing").to_string());
738    }
739    let (mut rows, mut advice, mut units) = (Vec::new(), Vec::new(), Vec::new());
740    let row = |q: &str, of: &str, config: f64, fitted: f64, error: f64| {
741        format!("[{},{},{},{},{}]", quote(q), quote(of), number(config), number(fitted), number(error))
742    };
743    let trace = match part(0) {
744        None => None,
745        Some(text) => Some(match part(1) {
746            Some(map) => {
747                use sim_components::import::{Mapping, import};
748                let imported = import(text, &Mapping::parse(map).map_err(refused)?).map_err(refused)?;
749                let motors = machine.motors().len();
750                if motors != 0 && imported.trace.motors.len() != motors {
751                    let detail = format!("{} [[motor]] for {motors} motors", imported.trace.motors.len());
752                    return Err(tr.tr_arg("error-import-map", &detail));
753                }
754                advice.extend(imported.notes.iter().map(|(key, detail)| tr.tr_arg(key, detail)));
755                imported.trace
756            }
757            None => sim_components::trace::Trace::parse(text, machine.motors()).map_err(refused)?,
758        }),
759    };
760    if let Some(trace) = &trace {
761        if sim_components::trace::per_axis_fit(machine.as_ref()) {
762            for (axis, fit) in machine.axes().iter().zip(fit_rigid(entry, &cfg, trace).map_err(refused)?) {
763                let Some(fit) = fit else {
764                    advice.push(tr.tr_arg("fit-axis-skipped", axis.id));
765                    continue;
766                };
767                let names = ["moved_mass_kg", "viscous_friction_n_s_m", "coulomb_friction_n", "constant_force_n"];
768                for (q, name) in names.iter().enumerate() {
769                    rows.push(row(name, axis.id, fit.config[q], fit.fitted[q], fit.error[q]));
770                    units.push(quote(fit.units[q]));
771                }
772                // As `sim-cli fit` writes them: the friction beyond its sliding level, a payload picked or dropped.
773                for d in &fit.details {
774                    rows.push(row(d.quantity, axis.id, d.config, d.fitted, d.error));
775                    units.push(quote(""));
776                }
777                for (time, time_error, change, error) in &fit.payload_steps {
778                    rows.push(row("payload_step_s", axis.id, f64::NAN, *time, *time_error));
779                    units.push(quote("s"));
780                    rows.push(row("payload_factor_change", axis.id, 0.0, *change, *error));
781                    units.push(quote(""));
782                }
783                advice.extend(fit.advice(axis.id).iter().map(|(key, detail)| tr.tr_arg(key, detail)));
784            }
785        } else {
786            match fit_joints(entry, &cfg, trace).map_err(refused)? {
787                Some(fit) => {
788                    rows.extend(fit.values.iter().map(|v| row(v.quantity, &v.of, v.config, v.fitted, v.error)));
789                    units.extend(fit.values.iter().map(|_| quote("")));
790                    advice.extend(fit.advice().iter().map(|(key, detail)| tr.tr_arg(key, detail)));
791                }
792                None => advice.push(tr.tr("fit-joints-skipped").to_string()),
793            }
794        }
795        if r.flag("stiffness") {
796            let key = r.options.iter().find_map(|o| o.strip_prefix("stiffness-key=")).unwrap_or(BELT_STIFFNESS_KEY);
797            let fit = fit_move_stiffness(entry, &cfg, trace, key).map_err(refused)?;
798            rows.push(row("stiffness_factor", key, 1.0, fit.factor, fit.error));
799            rows.push(row("ringing_rms_nm", key, f64::NAN, fit.ringing, f64::NAN));
800            rows.push(row("ringing_left_rms_nm", key, f64::NAN, fit.residual, f64::NAN));
801            units.extend(["", "", ""].map(quote));
802            let (key, detail) = fit.advice();
803            advice.push(tr.tr_arg(key, &detail));
804        }
805    }
806    if let Some(text) = part(2) {
807        let measured = parse_sweep(text).map_err(refused)?;
808        let motor = r.number("motor", 0.0)?;
809        if motor < 0.0 || motor.fract() != 0.0 || motor as usize >= machine.motors().len() {
810            return Err(format!("motor={motor}"));
811        }
812        let from_config = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
813        let amplitude = r.number("amplitude", default_sweep_amplitude(entry, &cfg).map_err(from_config)?)?;
814        let fit = fit_sweep(entry, &cfg, motor as usize, &measured, amplitude)
815            .map_err(from_config)?
816            .ok_or_else(|| tr.tr("fit-no-resonance").to_string())?;
817        let id = machine.motors()[motor as usize].id;
818        rows.push(row("resonance_hz", id, fit.config.frequency, fit.fitted.frequency, fit.fitted.frequency_error));
819        rows.push(row("resonance_damping", id, fit.config.damping, fit.fitted.damping, f64::NAN));
820        units.extend(["Hz", ""].map(quote));
821        let (key, detail) = fit.advice();
822        advice.push(tr.tr_arg(key, &detail));
823    }
824    let advice: Vec<String> = advice.iter().map(|a| quote(a)).collect();
825    // `units`: the unit of each row's values, in the order of `rows` (empty for a joint value, which has none of its own).
826    Ok(format!("{{\"rows\":[{}],\"advice\":[{}],\"units\":[{}]}}", rows.join(","), advice.join(","), units.join(",")))
827}
828
829/// The values of the page's form (kind 8): every number of the config but the effect switches and the bounds, with
830/// its label (`param-<key>` and `group-<table>`, as the app's parameter panel), and the `[parts]` names with what the
831/// catalogue offers for each: the supplies, the motors of the config's supply, the gearboxes that fit its motor, the
832/// drives of its supply and the belt axes. Booleans, arrays and the other names are edited in the TOML.
833fn form(r: &Request) -> Result<String, String> {
834    use sim_components::catalog::{self, PART_KEYS, SUPPLIES};
835    let entry = machine(r.id, r.lang)?;
836    let tr = translations(r.lang, entry);
837    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
838    let cfg =
839        if r.config.trim().is_empty() { entry.config() } else { load_config(entry, r.config).map_err(refused)? };
840    let mut params = Vec::new();
841    for (path, value) in cfg.leaves() {
842        let Some((table, leaf)) = path.rsplit_once('.') else { continue };
843        let skipped = table == "effects" || table == "bounds" || table.starts_with("bounds.");
844        if skipped || !(value.is_float() || value.is_integer()) {
845            continue;
846        }
847        params.push(format!(
848            "{{\"path\":{},\"group\":{},\"label\":{},\"value\":{}}}",
849            quote(&path),
850            quote(tr.tr(&format!("group-{}", table.replace('.', "-")))),
851            quote(tr.tr(&format!("param-{leaf}"))),
852            quote(&value.to_string())
853        ));
854    }
855    let named = |key: &str| cfg.get(&format!("parts.{key}")).ok().and_then(|v| v.as_str()).unwrap_or("").to_string();
856    let (supply, motor) = (named("motor_supply"), named("motor"));
857    let mut parts = Vec::new();
858    for key in PART_KEYS {
859        if cfg.get(&format!("parts.{key}")).is_err() {
860            continue;
861        }
862        let options: Vec<String> = match key {
863            "motor_supply" => SUPPLIES.iter().map(|s| s.to_string()).collect(),
864            "motor" => catalog::motor_articles_for(&supply).into_iter().map(String::from).collect(),
865            "gearbox" if !motor.is_empty() => catalog::gearboxes_for_motor(&motor, ""),
866            "drive" => catalog::drives_for(&supply).into_iter().map(|d| d.0.to_string()).collect(),
867            "axis" => catalog::axis_names(),
868            _ => Vec::new(),
869        };
870        let options: Vec<String> = options.iter().map(|o| quote(o)).collect();
871        parts.push(format!(
872            "{{\"key\":{},\"value\":{},\"options\":[{}]}}",
873            quote(key),
874            quote(&named(key)),
875            options.join(",")
876        ));
877    }
878    Ok(format!("{{\"params\":[{}],\"parts\":[{}]}}", params.join(","), parts.join(",")))
879}
880
881/// The page's changes set in its config (kind 9): each `path = value` line after `---` (TOML syntax; an unknown key or
882/// another type refused, as `Config::set_text` refuses them) written over the value's own text, so that the comments
883/// and the layout stay. Answers the text, every value that differs from the machine's default config as such a line
884/// (what a share link carries), and whether those lines on the default config give this config back (`compact`: a
885/// changed array, such as a cycle segment, is not among them, so the link then carries the whole text).
886fn apply(r: &Request) -> Result<String, String> {
887    let entry = machine(r.id, r.lang)?;
888    let tr = translations(r.lang, entry);
889    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
890    let text = if r.config.trim().is_empty() { entry.default_config } else { r.config };
891    let mut cfg = Config::parse(text).map_err(refused)?;
892    for line in r.extra.lines().filter(|l| !l.trim().is_empty()) {
893        sim_components::set_config_text(entry, &mut cfg, line).map_err(refused)?;
894    }
895    let text = edited(text, &cfg).map_err(refused)?;
896    let default = entry.config();
897    let changed: Vec<String> = cfg
898        .leaves()
899        .into_iter()
900        .filter(|(path, value)| default.get(path).ok() != Some(value))
901        .map(|(path, value)| format!("{path} = {value}"))
902        .collect();
903    let mut rebuilt = default;
904    let compact = changed.iter().all(|line| rebuilt.set_text(line).is_ok()) && rebuilt == cfg;
905    let changed: Vec<String> = changed.iter().map(|c| quote(c)).collect();
906    Ok(format!("{{\"config\":{},\"changed\":[{}],\"compact\":{compact}}}", quote(&text), changed.join(",")))
907}
908
909/// `text` with every value that `cfg` has changed written in place, so that its comments and layout stay; where that
910/// does not give `cfg` back (an array was changed, a value is not where the text has it), `cfg` written plainly.
911/// The app saves a config over its file the same way (`sim-app` `saved_text`).
912fn edited(text: &str, cfg: &Config) -> Result<String, sim_core::ConfigError> {
913    use toml::Value;
914    let plain = cfg.to_text()?;
915    let (Ok(doc), Ok(old)) = (toml_edit::Document::parse(text), Config::parse(text)) else { return Ok(plain) };
916    let mut edits = Vec::new();
917    for (path, value) in cfg.leaves() {
918        if old.get(&path).ok() == Some(&value) {
919            continue;
920        }
921        let new = match value {
922            Value::Float(x) => toml_edit::Value::from(x),
923            Value::Integer(n) => toml_edit::Value::from(n),
924            Value::Boolean(on) => toml_edit::Value::from(on),
925            Value::String(name) => toml_edit::Value::from(name),
926            _ => return Ok(plain),
927        };
928        // The span is the value's own text: the comment behind it stays.
929        let span = path
930            .split('.')
931            .try_fold(doc.as_item(), |item, key| item.get(key))
932            .and_then(toml_edit::Item::as_value)
933            .and_then(toml_edit::Value::span);
934        let Some(span) = span else { return Ok(plain) };
935        edits.push((span, new.to_string()));
936    }
937    edits.sort_by_key(|(span, _)| std::cmp::Reverse(span.start));
938    let mut kept = text.to_string();
939    for (span, new) in edits {
940        kept.replace_range(span, new.trim());
941    }
942    Ok(if Config::parse(&kept).as_ref() == Ok(cfg) { kept } else { plain })
943}
944
945/// The signals of the scopes (kind 10), per motor, by the end of their id `motor.<id>.<signal>`.
946pub const SCOPE_SIGNALS: [&str; 6] = ["angle", "speed", "torque", "current", "following_error", "winding_temperature"];
947/// The most rows a scope answer has: one a millisecond up to a pass of 30 s.
948pub const SCOPE_ROWS: usize = 30_000;
949
950/// A path's run (`Command::Trajectory`, from rest) with 0.3 s of rest after its end as the sizing check gives it, every
951/// signal once a millisecond, the time counted from the start: the rows `record_cycle` gives for the cycle.
952fn record_path(sim: &mut Sim, points: Vec<(f64, Vec<f64>)>) -> Result<Vec<Vec<f64>>, sim_components::CommandError> {
953    let end = points.last().map_or(0.0, |p| p.0) + 0.3;
954    sim.command(Command::Trajectory(points))?;
955    let every = ((1e-3 / sim.dt).round() as u64).max(1);
956    let (first, start) = (sim.step, sim.time());
957    let (mut rows, mut sample) = (Vec::new(), Vec::new());
958    // A tripped drive never finishes the path.
959    while sim.time() - start < end && sim.control.enabled() {
960        sim.step();
961        if (sim.step - first).is_multiple_of(every) {
962            sim.sample(&mut sample);
963            sample[0] = (sim.step - first) as f64 * sim.dt;
964            rows.push(sample.clone());
965        }
966    }
967    Ok(rows)
968}
969
970/// One pass of the configured cycle, once a millisecond, as `sim-cli compare` records it (`record_cycle`: the second
971/// pass, the time from its start), or with the option `path` the run of the request's path (`record_path`): per motor
972/// its angle, speed, torque, current, following error and winding temperature rise. A longer pass keeps every n-th row,
973/// `SCOPE_ROWS` at most. Numbers to 6 significant digits.
974fn scopes(r: &Request) -> Result<String, String> {
975    let (entry, tr, cfg) = configured(r)?;
976    let refused = |e: sim_core::ConfigError| tr.tr_arg(e.key(), e.detail());
977    let mut sim = Sim::new(entry, &cfg).map_err(refused)?;
978    let signals = sim.signal_infos();
979    let motors = sim.machine.motors().to_vec();
980    let rows = match planned_path(r, &sim, &tr)? {
981        Some((points, _)) => record_path(&mut sim, points).map_err(|e| tr.tr(e.key).to_string())?,
982        None => sim_components::analysis::record_cycle(entry, &cfg).map_err(refused)?,
983    };
984    let every = rows.len().div_ceil(SCOPE_ROWS).max(1);
985    let rows: Vec<&Vec<f64>> = rows.iter().step_by(every).collect();
986    let column = |id: String| signals.iter().position(|s| s.id == id);
987    let series = |c: Option<usize>| -> String {
988        let values: Vec<String> = rows.iter().map(|row| c.map_or("null".into(), |c| short(row[c]))).collect();
989        format!("[{}]", values.join(","))
990    };
991    // The label is the first motor's; each unit is listed per motor (a rotary and a linear motor may share a machine).
992    let head = SCOPE_SIGNALS.map(|name| {
993        let info = motors.first().and_then(|m| column(format!("motor.{}.{name}", m.id))).map(|c| &signals[c]);
994        let (key, unit) = info.map_or((name.to_string(), ""), |s| (s.quantity_key.clone(), s.unit.as_str()));
995        let units: Vec<String> = motors
996            .iter()
997            .map(|m| quote(column(format!("motor.{}.{name}", m.id)).map_or("", |c| signals[c].unit.as_str())))
998            .collect();
999        format!(
1000            "{{\"id\":{},\"label\":{},\"unit\":{},\"units\":[{}]}}",
1001            quote(name),
1002            quote(tr.tr(&key)),
1003            quote(unit),
1004            units.join(",")
1005        )
1006    });
1007    let mut json = format!(
1008        "{{\"step_s\":{},\"time\":{},\"signals\":[{}],\"motors\":[",
1009        number(1e-3 * every as f64),
1010        series(Some(0)),
1011        head.join(",")
1012    );
1013    for (k, m) in motors.iter().enumerate() {
1014        let data = SCOPE_SIGNALS.map(|name| series(column(format!("motor.{}.{name}", m.id))));
1015        let _ = write!(
1016            json,
1017            "{}{{\"id\":{},\"name\":{},\"data\":[{}]}}",
1018            if k == 0 { "" } else { "," },
1019            quote(m.id),
1020            quote(tr.tr(m.key)),
1021            data.join(",")
1022        );
1023    }
1024    json.push_str("]}");
1025    Ok(json)
1026}
1027
1028/// A number to 6 significant digits, `null` where it is not finite: the scopes' rows, a third the size of `number`'s.
1029fn short(v: f64) -> String {
1030    if v.is_finite() { format!("{v:.5e}") } else { "null".into() }
1031}
1032
1033/// JSON has no NaN or infinity: those are `null`.
1034fn number(v: f64) -> String {
1035    if v.is_finite() { format!("{v:?}") } else { "null".into() }
1036}
1037
1038fn quote(text: &str) -> String {
1039    let mut out = String::with_capacity(text.len() + 2);
1040    out.push('"');
1041    for c in text.chars() {
1042        match c {
1043            '"' => out.push_str("\\\""),
1044            '\\' => out.push_str("\\\\"),
1045            '\n' => out.push_str("\\n"),
1046            '\r' => out.push_str("\\r"),
1047            '\t' => out.push_str("\\t"),
1048            c if (c as u32) < 0x20 => {
1049                let _ = write!(out, "\\u{:04x}", c as u32);
1050            }
1051            c => out.push(c),
1052        }
1053    }
1054    out.push('"');
1055    out
1056}