Skip to main content

brep_instructions/
player.rs

1//! The interactive HTML player: a trusted template and its data format, kept
2//! apart.
3//!
4//! * [`TEMPLATE`] (`player/player.html`) is code: one script block, one style
5//!   block, no inline event handlers, and it never puts data into the page as
6//!   markup (text goes in as text, pictures only as `data:image/…` or same-site
7//!   `/api/tools/…` URLs). A server serves it under its own content security
8//!   policy with a per-response nonce ([`served_html`]).
9//! * [`PlayerData`] is data: the steps flat in reading order, each with its
10//!   parent's id and depth, the meshes deduplicated per part, a node per
11//!   occurrence with its matrix, and per step what is placed, what is being
12//!   added, the insertion offsets and the camera. A server stores it per
13//!   instructions revision and the template fetches it. Data written before
14//!   the step tree (schema 1: chapters of steps) reads as a flat list.
15//! * Beside the steps the data carries the assembly's occurrence tree
16//!   ([`PlayerComponent`], one row per placed component with its thumbnail
17//!   and details), which the page's Model tab shows as an expandable tree
18//!   over the model with every part's visibility its own, and its Parts tab
19//!   as one card per part with the steps that use it; and per step the PMI
20//!   its view shows ([`PlayerPmi`]: dimensions, notes, balloons, leaders,
21//!   laid out by the same `pmi_present` the viewport, the sheets and the 3D
22//!   PDF use), drawn over the parts.
23//! * The offline copy is the same template with the data inlined
24//!   ([`offline_html`]): one self-contained `.html`.
25
26use crate::edit;
27use crate::model::{Instructions, Target, ToolUse};
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, HashMap};
30
31/// The player template.
32pub const TEMPLATE: &str = include_str!("../player/player.html");
33
34/// The player data's schema version.
35pub const DATA_SCHEMA: u32 = 2;
36
37/// The two player modes.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "lowercase")]
40pub enum Mode {
41    /// Touch-first, with a step checklist and per-step sign-off.
42    #[default]
43    Shop,
44    /// Pictures first, minimal text.
45    Customer,
46}
47
48impl Mode {
49    pub fn parse(text: &str) -> Option<Self> {
50        match text {
51            "shop" => Some(Self::Shop),
52            "customer" => Some(Self::Customer),
53            _ => None,
54        }
55    }
56
57    pub fn as_str(self) -> &'static str {
58        match self {
59            Self::Shop => "shop",
60            Self::Customer => "customer",
61        }
62    }
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[serde(rename_all = "camelCase")]
67pub struct PlayerData {
68    pub schema: u32,
69    pub title: String,
70    #[serde(default)]
71    pub subtitle: String,
72    pub target: Target,
73    /// Every step in reading order (a step's children before it).
74    pub steps: Vec<PlayerStep>,
75    /// Distinct tools, in first-use order.
76    #[serde(default)]
77    pub tools: Vec<ToolUse>,
78    /// A picture per tool of the library (by `toolId`): the server's own
79    /// `/api/tools/<id>/picture` as built, which the page the PLM serves
80    /// loads same-site; the offline page carries only `data:image` pictures
81    /// ([`PlayerData::inline_tool_pictures`]), the rest dropped.
82    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
83    pub tool_pictures: BTreeMap<String, String>,
84    pub meshes: Vec<PlayerMesh>,
85    pub nodes: Vec<PlayerNode>,
86    /// The assembly's occurrence tree, depth first (a component before its
87    /// children): the Model tab's tree and the Parts tab's cards. Absent from
88    /// data made before the tree was carried, and from a motion study's.
89    #[serde(default, skip_serializing_if = "Vec::is_empty")]
90    pub assembly: Vec<PlayerComponent>,
91    /// A motion study's baked frames: with no chapters the page is the study's
92    /// player (a timeline over the frames); a step may carry one too (its
93    /// motion). Absent from instructions made before motion existed.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub motion: Option<Motion>,
96}
97
98/// A motion study baked for the player: every frame's poses, in the order
99/// they play. Keyed by OCCURRENCE id (a node's `occurrence` is its solid's
100/// scene name, `ACOMP2:Part`, under the occurrence), so the same JSON is also
101/// what a document keeps as a study's published `motion`.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase")]
104pub struct Motion {
105    pub fps: u32,
106    /// Seconds.
107    pub duration: f64,
108    pub frames: Vec<MotionFrame>,
109}
110
111/// One frame: the occurrences whose pose differs from the document, each as
112/// the delta over its document pose (column-major 4×4, applied over the
113/// node's own matrix: `model = pose × node.matrix`); the occurrences a
114/// visibility clip hides; opacities (0..1) a transparency clip sets; the
115/// camera when a camera clip drives it (absolute: eye, target, up, and the
116/// projection); whether parts interfere, and which.
117#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
118#[serde(rename_all = "camelCase")]
119pub struct MotionFrame {
120    pub time: f64,
121    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
122    pub poses: std::collections::BTreeMap<String, [f64; 16]>,
123    #[serde(default, skip_serializing_if = "Vec::is_empty")]
124    pub hidden: Vec<String>,
125    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
126    pub opacity: std::collections::BTreeMap<String, f64>,
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub camera: Option<Camera>,
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub clashing: Vec<String>,
131}
132
133impl MotionFrame {
134    /// Whether parts interfere at this frame.
135    pub fn clash(&self) -> bool {
136        !self.clashing.is_empty()
137    }
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase")]
142pub struct PlayerStep {
143    pub id: String,
144    /// 1-based, in reading order.
145    pub number: usize,
146    /// The parent step's id; none at the top level.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub parent: Option<String>,
149    /// 0 at the top level.
150    #[serde(default)]
151    pub depth: usize,
152    pub title: String,
153    #[serde(default)]
154    pub notes: String,
155    pub adds: Vec<PlayerAdd>,
156    #[serde(default)]
157    pub tools: Vec<ToolUse>,
158    /// `12 N·m`.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub torque: Option<String>,
161    #[serde(default)]
162    pub callouts: Vec<PlayerCallout>,
163    pub signoff: bool,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub camera: Option<Camera>,
166    /// Node indices drawn ghosted.
167    pub placed: Vec<usize>,
168    /// Node indices highlighted.
169    pub adding: Vec<usize>,
170    /// Where an adding node starts its insertion motion.
171    #[serde(default)]
172    pub insertion: Vec<Insertion>,
173    /// The step view's explode poses: a matrix per posed node, applied after
174    /// the node's own matrix (world space), as the step's pictures pose it.
175    #[serde(default, skip_serializing_if = "Vec::is_empty")]
176    pub poses: Vec<Pose>,
177    /// The PMI the step's view shows, drawn over the parts.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub pmi: Option<PlayerPmi>,
180    /// A rendered picture of the step (PNG data URL), for customer mode and
181    /// for viewers without WebGL.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub image: Option<String>,
184    /// A motion study's published motion attached to the step: played in
185    /// place of the insertion animation, keyed by the scene's occurrences
186    /// (the study's keys under the wrapper).
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub motion: Option<Motion>,
189}
190
191#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
192#[serde(rename_all = "camelCase")]
193pub struct PlayerAdd {
194    /// The PLM part id, or the name ([`crate::model::Add::part`]).
195    pub part: String,
196    /// The display name (what the page shows; `part` when absent).
197    #[serde(default)]
198    pub name: String,
199    #[serde(default)]
200    pub find_number: String,
201    pub quantity: usize,
202    /// The occurrences, so shop mode can ask for one serial per unit.
203    pub occurrences: Vec<String>,
204    #[serde(default)]
205    pub serial_tracked: bool,
206    #[serde(default)]
207    pub subassembly: bool,
208    /// The part's thumbnail (PNG data URL).
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub thumbnail: Option<String>,
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "camelCase")]
215pub struct PlayerCallout {
216    pub kind: crate::model::CalloutKind,
217    pub text: String,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222pub struct Camera {
223    pub eye: [f64; 3],
224    pub target: [f64; 3],
225    pub up: [f64; 3],
226    /// Perspective field of view in degrees; `None` = orthographic.
227    #[serde(default, skip_serializing_if = "Option::is_none")]
228    pub fov_deg: Option<f64>,
229    /// Orthographic half height, in model units.
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub half_height: Option<f64>,
232}
233
234#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
235#[serde(rename_all = "camelCase")]
236pub struct Insertion {
237    pub node: usize,
238    pub offset: [f64; 3],
239}
240
241/// A posed node of a step: its view's explode pose as a column-major 4×4.
242#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct Pose {
245    pub node: usize,
246    pub matrix: [f64; 16],
247}
248
249/// A step view's PMI as the page draws it: every enabled, resolved
250/// annotation of the view (not its explode or hide rows) laid out in world
251/// space, sized as the viewport sized it when the view was saved. Text is
252/// stroked with the PMI font, so the page needs no font of its own. Arrays
253/// are little-endian base64 like a mesh's.
254#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
255#[serde(rename_all = "camelCase")]
256pub struct PlayerPmi {
257    /// f32 xyz pairs: dimension, extension and leader lines, frames and the
258    /// stroked text, as line segments.
259    pub lines: String,
260    /// f32 xyz triples: the filled arrowheads, as triangles.
261    #[serde(default, skip_serializing_if = "String::is_empty")]
262    pub arrows: String,
263    /// How many annotations are drawn.
264    pub annotations: usize,
265    /// Each drawn annotation's text, in the view's order (for a reader
266    /// without WebGL and for automation).
267    #[serde(default, skip_serializing_if = "Vec::is_empty")]
268    pub texts: Vec<String>,
269}
270
271impl PlayerPmi {
272    /// The drawing of `annotations` annotations from their polylines (each
273    /// at least two points; every polyline becomes its consecutive segments)
274    /// and arrowhead triangles. `None` when there is nothing to draw.
275    pub fn new(polylines: &[Vec<[f64; 3]>], arrows: &[[[f64; 3]; 3]], annotations: usize, texts: Vec<String>) -> Option<Self> {
276        let mut segments: Vec<f32> = Vec::new();
277        for line in polylines {
278            for pair in line.windows(2) {
279                segments.extend(pair[0].iter().chain(&pair[1]).map(|&v| v as f32));
280            }
281        }
282        let triangles: Vec<f32> = arrows.iter().flatten().flatten().map(|&v| v as f32).collect();
283        if segments.is_empty() && triangles.is_empty() {
284            return None;
285        }
286        Some(Self {
287            lines: encode_f32(&segments),
288            arrows: if triangles.is_empty() { String::new() } else { encode_f32(&triangles) },
289            annotations,
290            texts,
291        })
292    }
293}
294
295/// One placed component of the assembly: a row of the Model tab's tree and,
296/// with the other rows of its part, a card of the Parts tab.
297#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
298#[serde(rename_all = "camelCase")]
299pub struct PlayerComponent {
300    /// The occurrence path (`ACOMP1:ACOMP3`): a node belongs to the deepest
301    /// component whose path its occurrence starts with (then `:`).
302    pub path: String,
303    /// The parent component's path; none at the top of the assembly.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub parent: Option<String>,
306    /// 0 at the top of the assembly.
307    #[serde(default)]
308    pub depth: usize,
309    /// The part's name.
310    pub name: String,
311    /// What a step's add names the part by: its PLM id, or its name.
312    pub part: String,
313    /// The PLM part id when the part was placed from a PLM revision.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub part_id: Option<String>,
316    #[serde(default)]
317    pub find_number: String,
318    #[serde(default)]
319    pub subassembly: bool,
320    #[serde(default)]
321    pub fastener: bool,
322    #[serde(default)]
323    pub serial_tracked: bool,
324    #[serde(default)]
325    pub grounded: bool,
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub torque: Option<String>,
328    /// The part's attributes as `[name, value]` text pairs.
329    #[serde(default, skip_serializing_if = "Vec::is_empty")]
330    pub attributes: Vec<(String, String)>,
331    /// The part's thumbnail (PNG data URL); every row of one part carries
332    /// the same.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub thumbnail: Option<String>,
335}
336
337impl PlayerComponent {
338    /// One row per component of `root` and its sub-assemblies, depth first.
339    /// Thumbnails are filled by [`PlayerData::build`] from the scene's.
340    pub fn rows(root: &crate::wizard::Level) -> Vec<Self> {
341        let mut out = Vec::new();
342        fn walk(level: &crate::wizard::Level, parent: Option<&str>, depth: usize, out: &mut Vec<PlayerComponent>) {
343            for c in &level.components {
344                out.push(PlayerComponent {
345                    path: c.path.clone(),
346                    parent: parent.map(str::to_string),
347                    depth,
348                    name: c.part.clone(),
349                    part: c.part_key().to_string(),
350                    part_id: c.part_id.clone(),
351                    find_number: c.find_number.clone(),
352                    subassembly: c.children.is_some(),
353                    fastener: c.fastener,
354                    serial_tracked: c.serial_tracked,
355                    grounded: c.grounded,
356                    torque: c.torque.clone(),
357                    attributes: c.attributes.clone(),
358                    thumbnail: None,
359                });
360                if let Some(children) = &c.children {
361                    walk(children, Some(&c.path), depth + 1, out);
362                }
363            }
364        }
365        walk(root, None, 0, &mut out);
366        out
367    }
368}
369
370/// One triangle mesh, shared by every node of the same part. Arrays are
371/// little-endian and base64-encoded.
372#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
373#[serde(rename_all = "camelCase")]
374pub struct PlayerMesh {
375    pub id: String,
376    /// f32 xyz.
377    pub positions: String,
378    /// f32 xyz, one per position.
379    pub normals: String,
380    /// u32 triangle indices.
381    pub indices: String,
382    /// f32 xyz pairs: the solid's display edges as line segments, drawn over
383    /// the faces as the viewport draws them. Absent from data written before
384    /// edges were carried.
385    #[serde(default, skip_serializing_if = "String::is_empty")]
386    pub edges: String,
387}
388
389impl PlayerMesh {
390    pub fn new(id: &str, positions: &[f32], normals: &[f32], indices: &[u32]) -> Self {
391        Self { id: id.into(), positions: encode_f32(positions), normals: encode_f32(normals), indices: encode_u32(indices), edges: String::new() }
392    }
393
394    /// The same mesh with its edges, given as polylines (each at least two
395    /// points): every polyline becomes its consecutive segments.
396    /// Take the mesh back through `placement` (a rigid column-major 4×4): the
397    /// vertices through its inverse, the normals and edges through the
398    /// rotation's transpose, so the mesh reads in the part's own frame.
399    fn localise(&mut self, placement: &[f64; 16]) {
400        let m = placement;
401        let r = |p: [f32; 3]| -> [f32; 3] {
402            // Rᵀ · p: rows of R are the matrix's columns' first three entries.
403            let p = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
404            [
405                (m[0] * p[0] + m[1] * p[1] + m[2] * p[2]) as f32,
406                (m[4] * p[0] + m[5] * p[1] + m[6] * p[2]) as f32,
407                (m[8] * p[0] + m[9] * p[1] + m[10] * p[2]) as f32,
408            ]
409        };
410        let back = |p: [f32; 3]| -> [f32; 3] { r([p[0] - m[12] as f32, p[1] - m[13] as f32, p[2] - m[14] as f32]) };
411        let map = |text: &str, f: &dyn Fn([f32; 3]) -> [f32; 3]| -> String {
412            let values = decode_f32(text);
413            let mapped: Vec<f32> = values.chunks_exact(3).flat_map(|p| f([p[0], p[1], p[2]])).collect();
414            encode_f32(&mapped)
415        };
416        self.positions = map(&self.positions, &back);
417        self.normals = map(&self.normals, &r);
418        if !self.edges.is_empty() {
419            self.edges = map(&self.edges, &back);
420        }
421    }
422
423    pub fn with_edges(mut self, polylines: &[Vec<[f32; 3]>]) -> Self {
424        let mut segments: Vec<f32> = Vec::new();
425        for line in polylines {
426            for pair in line.windows(2) {
427                segments.extend_from_slice(&pair[0]);
428                segments.extend_from_slice(&pair[1]);
429            }
430        }
431        self.edges = if segments.is_empty() { String::new() } else { encode_f32(&segments) };
432        self
433    }
434}
435
436/// One drawn solid of one occurrence.
437#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
438#[serde(rename_all = "camelCase")]
439pub struct PlayerNode {
440    /// The occurrence path the solid belongs to.
441    pub occurrence: String,
442    /// Index into `meshes`.
443    pub mesh: usize,
444    /// Column-major 4 × 4 placement.
445    pub matrix: [f64; 16],
446    /// sRGB colour, 0..1.
447    pub color: [f32; 3],
448}
449
450/// What the caller supplies beside the block: the meshes and nodes of the
451/// assembly as placed, each step's camera and picture, and part thumbnails.
452#[derive(Debug, Clone, Default)]
453pub struct Scene {
454    pub meshes: Vec<PlayerMesh>,
455    pub nodes: Vec<PlayerNode>,
456    pub cameras: HashMap<String, Camera>,
457    pub step_images: HashMap<String, String>,
458    pub thumbnails: HashMap<String, String>,
459    /// Each step's explode poses, by step id.
460    pub poses: HashMap<String, Vec<Pose>>,
461    /// Each step's view PMI, by step id.
462    pub pmi: HashMap<String, PlayerPmi>,
463    /// The assembly's occurrence tree ([`PlayerComponent::rows`]); each
464    /// row's thumbnail is taken from `thumbnails` by its part.
465    pub assembly: Vec<PlayerComponent>,
466    /// The wrapper occurrence the instructions place the assembly under
467    /// (`ACOMP1`): a step's motion, keyed by the assembly's own occurrences,
468    /// is re-keyed under it. Empty when the nodes are the assembly's own.
469    pub wrapper: String,
470}
471
472/// The tolerance of a rigid fit, as a share of the mesh's extent.
473const RIGID_FIT_TOLERANCE: f64 = 1e-4;
474
475impl Scene {
476    /// One mesh per part. `keys` is one key per node (its part and member)
477    /// and `placements` one optional placement per node (column-major, the
478    /// engine's pose of the occurrence in the world). Among the nodes of one
479    /// key, the first is the reference:
480    ///
481    /// * with placements, its mesh is made part-local (its vertices taken back
482    ///   through its placement, normals through the rotation) and every placed
483    ///   node of the key shares it, each carrying its own placement as its
484    ///   matrix, whatever that copy's own tessellation was;
485    /// * without, a node whose mesh is the same tessellation as the reference's
486    ///   moved rigidly shares it and carries the rigid move, decided by the
487    ///   vertices themselves (the same index order and count, every vertex
488    ///   within `RIGID_FIT_TOLERANCE` of the fit), so a mirrored or
489    ///   re-tessellated copy keeps its own.
490    ///
491    /// Meshes left unreferenced are dropped and the rest renumbered.
492    pub fn share_meshes(&mut self, keys: &[String], placements: &[Option<[f64; 16]>]) {
493        let decoded: Vec<Vec<[f64; 3]>> = self.meshes.iter().map(|mesh| decode_f32(&mesh.positions).chunks(3).map(|p| [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])]).collect()).collect();
494        let placement = |i: usize| placements.get(i).copied().flatten();
495        let mut first_by_key: HashMap<&str, usize> = HashMap::new();
496        let mut shared: Vec<Option<(usize, [f64; 16])>> = vec![None; self.nodes.len()];
497        let mut localised: Vec<Option<[f64; 16]>> = vec![None; self.nodes.len()];
498        for (i, node) in self.nodes.iter().enumerate() {
499            let Some(key) = keys.get(i) else { continue };
500            match first_by_key.get(key.as_str()) {
501                None => {
502                    first_by_key.insert(key, i);
503                    if let Some(at) = placement(i) {
504                        localised[i] = Some(at);
505                    }
506                }
507                Some(&reference) => {
508                    let rm = self.nodes[reference].mesh;
509                    match (placement(reference), placement(i)) {
510                        (Some(_), Some(at)) => shared[i] = Some((rm, at)),
511                        _ => {
512                            let cm = node.mesh;
513                            if rm != cm && self.meshes[rm].indices == self.meshes[cm].indices {
514                                if let Some(matrix) = rigid_fit(&decoded[rm], &decoded[cm]) {
515                                    shared[i] = Some((rm, matrix));
516                                }
517                            }
518                        }
519                    }
520                }
521            }
522        }
523        for (i, at) in localised.iter().enumerate() {
524            if let Some(at) = at {
525                let mesh = self.nodes[i].mesh;
526                self.meshes[mesh].localise(at);
527                self.nodes[i].matrix = *at;
528            }
529        }
530        for (i, found) in shared.iter().enumerate() {
531            if let Some((mesh, matrix)) = found {
532                self.nodes[i].mesh = *mesh;
533                self.nodes[i].matrix = *matrix;
534            }
535        }
536        let used: Vec<bool> = (0..self.meshes.len()).map(|m| self.nodes.iter().any(|n| n.mesh == m)).collect();
537        let mut renumbered = vec![0usize; self.meshes.len()];
538        let mut next = 0;
539        for (m, keep) in used.iter().enumerate() {
540            if *keep {
541                renumbered[m] = next;
542                next += 1;
543            }
544        }
545        let meshes = std::mem::take(&mut self.meshes);
546        self.meshes = meshes.into_iter().enumerate().filter(|(m, _)| used[*m]).map(|(_, mesh)| mesh).collect();
547        for node in &mut self.nodes {
548            node.mesh = renumbered[node.mesh];
549        }
550    }
551}
552
553/// The rigid move (a proper rotation and a translation, column-major 4×4)
554/// taking every point of `a` onto the point of `b` with the same index, or
555/// `None` when there is none within tolerance (a different shape, a mirror,
556/// or too few points to fix a frame).
557fn rigid_fit(a: &[[f64; 3]], b: &[[f64; 3]]) -> Option<[f64; 16]> {
558    if a.len() != b.len() || a.len() < 3 {
559        return None;
560    }
561    let sub = |p: [f64; 3], q: [f64; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
562    let dot = |p: [f64; 3], q: [f64; 3]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
563    let cross = |p: [f64; 3], q: [f64; 3]| [p[1] * q[2] - p[2] * q[1], p[2] * q[0] - p[0] * q[2], p[0] * q[1] - p[1] * q[0]];
564    let norm = |p: [f64; 3]| dot(p, p).sqrt();
565    let scale = |p: [f64; 3], k: f64| [p[0] * k, p[1] * k, p[2] * k];
566    // Three points that fix a frame: the farthest from the first, then the
567    // farthest from that line.
568    let i0 = 0;
569    let i1 = (0..a.len()).max_by(|&i, &j| norm(sub(a[i], a[i0])).partial_cmp(&norm(sub(a[j], a[i0]))).unwrap_or(std::cmp::Ordering::Equal))?;
570    let axis = sub(a[i1], a[i0]);
571    let extent = norm(axis);
572    if extent <= 0.0 {
573        return None;
574    }
575    let off_line = |i: usize| norm(cross(axis, sub(a[i], a[i0]))) / extent;
576    let i2 = (0..a.len()).max_by(|&i, &j| off_line(i).partial_cmp(&off_line(j)).unwrap_or(std::cmp::Ordering::Equal))?;
577    let tolerance = RIGID_FIT_TOLERANCE * extent.max(1e-9);
578    if off_line(i2) <= tolerance {
579        return None;
580    }
581    let frame = |p: &[[f64; 3]]| -> Option<[[f64; 3]; 3]> {
582        let u = sub(p[i1], p[i0]);
583        let u = scale(u, 1.0 / norm(u));
584        let v0 = sub(p[i2], p[i0]);
585        let v = sub(v0, scale(u, dot(v0, u)));
586        let lv = norm(v);
587        if lv <= 0.0 {
588            return None;
589        }
590        let v = scale(v, 1.0 / lv);
591        Some([u, v, cross(u, v)])
592    };
593    let (fa, fb) = (frame(a)?, frame(b)?);
594    // R = Fb · Faᵀ: column k of R = Σ_j fb[j] * fa[j][k].
595    let mut r = [[0.0f64; 3]; 3];
596    for col in 0..3 {
597        for row in 0..3 {
598            r[col][row] = (0..3).map(|j| fb[j][row] * fa[j][col]).sum();
599        }
600    }
601    let apply = |p: [f64; 3]| [
602        r[0][0] * p[0] + r[1][0] * p[1] + r[2][0] * p[2],
603        r[0][1] * p[0] + r[1][1] * p[1] + r[2][1] * p[2],
604        r[0][2] * p[0] + r[1][2] * p[1] + r[2][2] * p[2],
605    ];
606    let t = sub(b[i0], apply(a[i0]));
607    for (p, q) in a.iter().zip(b) {
608        let moved = apply(*p);
609        if norm(sub([moved[0] + t[0], moved[1] + t[1], moved[2] + t[2]], *q)) > tolerance {
610            return None;
611        }
612    }
613    Some([
614        r[0][0], r[0][1], r[0][2], 0.0,
615        r[1][0], r[1][1], r[1][2], 0.0,
616        r[2][0], r[2][1], r[2][2], 0.0,
617        t[0], t[1], t[2], 1.0,
618    ])
619}
620
621impl Motion {
622    /// The same motion with every occurrence key put under `wrapper`
623    /// (`ACOMP2` → `ACOMP1:ACOMP2`); unchanged when `wrapper` is empty.
624    pub fn under(&self, wrapper: &str) -> Motion {
625        if wrapper.is_empty() {
626            return self.clone();
627        }
628        let key = |k: &str| format!("{wrapper}:{k}");
629        let frames = self
630            .frames
631            .iter()
632            .map(|frame| MotionFrame {
633                time: frame.time,
634                poses: frame.poses.iter().map(|(k, v)| (key(k), *v)).collect(),
635                hidden: frame.hidden.iter().map(|k| key(k)).collect(),
636                opacity: frame.opacity.iter().map(|(k, v)| (key(k), *v)).collect(),
637                camera: frame.camera.clone(),
638                clashing: frame.clashing.iter().map(|k| key(k)).collect(),
639            })
640            .collect();
641        Motion { fps: self.fps, duration: self.duration, frames }
642    }
643}
644
645/// A step's attached motion (the study's published JSON, `{study,
646/// assemblySignature}` beside the frames) re-keyed under the wrapper; a
647/// value that is not a motion is refused like a node naming a missing mesh.
648fn step_motion(step: &crate::model::Step, wrapper: &str) -> Result<Option<Motion>, String> {
649    let Some(value) = &step.motion else { return Ok(None) };
650    let motion: Motion = serde_json::from_value(value.clone()).map_err(|e| format!("step '{}': its motion is not a motion study's: {e}", step.id))?;
651    if motion.frames.is_empty() {
652        return Err(format!("step '{}': its motion has no frames", step.id));
653    }
654    Ok(Some(motion.under(wrapper)))
655}
656
657impl PlayerData {
658    /// The player data of `block` over `scene`.
659    pub fn build(block: &Instructions, scene: Scene) -> Result<Self, String> {
660        for (i, node) in scene.nodes.iter().enumerate() {
661            if node.mesh >= scene.meshes.len() {
662                return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
663            }
664        }
665        let occurrences: Vec<String> = scene.nodes.iter().map(|n| n.occurrence.clone()).collect();
666        let mut steps = Vec::new();
667        for (number, (depth, step)) in block.steps().enumerate() {
668            let number = number + 1;
669            let parent = block.parent_id(&step.id).flatten().map(str::to_string);
670            {
671                let presentation = edit::presentation(block, &step.id, &occurrences)?;
672                let index_of = |paths: &[String]| -> Vec<usize> {
673                    let set: std::collections::HashSet<&str> = paths.iter().map(String::as_str).collect();
674                    occurrences.iter().enumerate().filter(|(_, o)| set.contains(o.as_str())).map(|(i, _)| i).collect()
675                };
676                let adding = index_of(&presentation.adding);
677                let insertion = adding
678                    .iter()
679                    .filter_map(|&node| {
680                        let path = &occurrences[node];
681                        step.arrows
682                            .iter()
683                            .find(|a| path == &a.occurrence || (path.starts_with(&a.occurrence) && path[a.occurrence.len()..].starts_with(':')))
684                            .map(|a| Insertion { node, offset: a.start_offset() })
685                    })
686                    .collect();
687                steps.push(PlayerStep {
688                    id: step.id.clone(),
689                    number,
690                    parent,
691                    depth,
692                    title: step.title.clone(),
693                    notes: step.notes.clone(),
694                    adds: step
695                        .adds
696                        .iter()
697                        .map(|a| PlayerAdd {
698                            part: a.part.clone(),
699                            name: a.display_name().to_string(),
700                            find_number: a.find_number.clone(),
701                            quantity: a.quantity(),
702                            occurrences: a.occurrences.clone(),
703                            serial_tracked: a.serial_tracked,
704                            subassembly: a.subassembly,
705                            thumbnail: scene.thumbnails.get(&a.part).cloned(),
706                        })
707                        .collect(),
708                    tools: step.tools.clone(),
709                    torque: step.torque.as_ref().map(|t| t.text()),
710                    callouts: step.callouts.iter().map(|c| PlayerCallout { kind: c.kind, text: c.text.clone() }).collect(),
711                    signoff: step.signoff.required,
712                    camera: scene.cameras.get(&step.id).cloned(),
713                    placed: index_of(&presentation.placed),
714                    adding,
715                    insertion,
716                    poses: scene.poses.get(&step.id).cloned().unwrap_or_default(),
717                    pmi: scene.pmi.get(&step.id).cloned(),
718                    image: scene.step_images.get(&step.id).cloned(),
719                    motion: step_motion(step, &scene.wrapper)?,
720                });
721            }
722        }
723        let title = if block.front.title.is_empty() { block.target.name.clone() } else { block.front.title.clone() };
724        let mut assembly = scene.assembly;
725        for row in &mut assembly {
726            if row.thumbnail.is_none() {
727                row.thumbnail = scene.thumbnails.get(&row.part).cloned();
728            }
729        }
730        Ok(Self {
731            schema: DATA_SCHEMA,
732            title,
733            subtitle: block.front.subtitle.clone(),
734            target: block.target.clone(),
735            steps,
736            tool_pictures: block
737                .tools_list()
738                .iter()
739                .filter_map(|(tool, _)| tool.tool_id.as_deref())
740                .filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
741                .map(|id| (id.to_string(), format!("/api/tools/{id}/picture")))
742                .collect(),
743            tools: block.tools_list().into_iter().map(|(t, _)| t).collect(),
744            meshes: scene.meshes,
745            nodes: scene.nodes,
746            assembly,
747            motion: None,
748        })
749    }
750
751    /// Put the fetched tool pictures in: for each tool with a picture entry,
752    /// `fetched[id]` as `Some((media type, bytes))` becomes a `data:image`
753    /// URL when the type is one the page shows (PNG, JPEG, WebP) and the
754    /// bytes are within [`TOOL_PICTURE_MAX_BYTES`]; any other entry (not
755    /// fetched, no picture, another type, too large) is dropped, so an
756    /// offline page never carries a picture it cannot load. Returns how many
757    /// were put in.
758    pub fn inline_tool_pictures(&mut self, fetched: &BTreeMap<String, Option<(String, Vec<u8>)>>) -> usize {
759        let mut inlined = 0;
760        let pictures = std::mem::take(&mut self.tool_pictures);
761        for (id, url) in pictures {
762            if url.starts_with("data:image/") {
763                self.tool_pictures.insert(id, url);
764                inlined += 1;
765                continue;
766            }
767            let Some(Some((media, bytes))) = fetched.get(&id) else { continue };
768            let media = media.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
769            if !matches!(media.as_str(), "image/png" | "image/jpeg" | "image/webp") || bytes.len() > TOOL_PICTURE_MAX_BYTES {
770                continue;
771            }
772            self.tool_pictures.insert(id, format!("data:{media};base64,{}", base64(bytes)));
773            inlined += 1;
774        }
775        inlined
776    }
777
778    /// A motion study's player: no steps, the scene's meshes and nodes, and
779    /// the study's frames as `motion`. `title` is the study's name.
780    pub fn motion_study(title: &str, subtitle: &str, target: Target, scene: Scene, motion: Motion) -> Result<Self, String> {
781        for (i, node) in scene.nodes.iter().enumerate() {
782            if node.mesh >= scene.meshes.len() {
783                return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
784            }
785        }
786        if motion.frames.is_empty() {
787            return Err("a motion study's player needs at least one frame".into());
788        }
789        Ok(Self {
790            schema: DATA_SCHEMA,
791            title: title.to_string(),
792            subtitle: subtitle.to_string(),
793            target,
794            steps: Vec::new(),
795            tools: Vec::new(),
796            tool_pictures: BTreeMap::new(),
797            meshes: scene.meshes,
798            nodes: scene.nodes,
799            assembly: Vec::new(),
800            motion: Some(motion),
801        })
802    }
803
804    pub fn to_json(&self) -> String {
805        serde_json::to_string(self).expect("player data serializes")
806    }
807
808    /// Read the data, schema 1 (chapters of steps) included: its steps become
809    /// one flat list, every step at the top.
810    pub fn from_json(text: &str) -> Result<Self, String> {
811        let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("player data: {e}"))?;
812        let schema = value.get("schema").and_then(serde_json::Value::as_u64).unwrap_or(0);
813        if schema == 0 || schema > u64::from(DATA_SCHEMA) {
814            return Err(format!("player data schema {schema} is not supported"));
815        }
816        if schema == 1 {
817            if let Some(object) = value.as_object_mut() {
818                let chapters = object.remove("chapters").and_then(|c| c.as_array().cloned()).unwrap_or_default();
819                if !object.contains_key("steps") {
820                    let steps: Vec<serde_json::Value> =
821                        chapters.into_iter().flat_map(|c| c.get("steps").and_then(|s| s.as_array().cloned()).unwrap_or_default()).collect();
822                    object.insert("steps".into(), serde_json::Value::Array(steps));
823                }
824                object.insert("schema".into(), serde_json::Value::from(DATA_SCHEMA));
825            }
826        }
827        serde_json::from_value(value).map_err(|e| format!("player data: {e}"))
828    }
829}
830
831/// How the template finds its data and what it may do.
832#[derive(Debug, Clone, PartialEq, Serialize)]
833#[serde(rename_all = "camelCase")]
834struct Config<'a> {
835    mode: &'a str,
836    /// Where to fetch the data; `None` = inlined.
837    #[serde(skip_serializing_if = "Option::is_none")]
838    data_url: Option<&'a str>,
839    /// The job whose steps shop mode signs off; `None` = a local checklist.
840    #[serde(skip_serializing_if = "Option::is_none")]
841    job: Option<&'a str>,
842}
843
844/// The self-contained offline copy: the template with `data` inlined. Shop
845/// mode keeps a local checklist (no server to sign off to).
846pub fn offline_html(data: &PlayerData, mode: Mode) -> String {
847    let config = Config { mode: mode.as_str(), data_url: None, job: None };
848    // An offline page loads no `/api/tools/…` picture: only the inlined ones go.
849    let json = if data.tool_pictures.values().all(|url| url.starts_with("data:image/")) {
850        data.to_json()
851    } else {
852        let mut data = data.clone();
853        data.tool_pictures.retain(|_, url| url.starts_with("data:image/"));
854        data.to_json()
855    };
856    fill(None, &serde_json::to_string(&config).unwrap(), &json)
857}
858
859/// The largest tool picture an offline page inlines, in bytes.
860pub const TOOL_PICTURE_MAX_BYTES: usize = 1024 * 1024;
861
862/// The template as a server serves it: `nonce` goes on the script and style
863/// blocks, the page fetches its data from `data_url` (same origin), and in shop
864/// mode with a `job` its sign-offs go to that job.
865pub fn served_html(nonce: &str, data_url: &str, mode: Mode, job: Option<&str>) -> Result<String, String> {
866    if nonce.is_empty() || !nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=_-".contains(&b)) {
867        return Err("the nonce must be base64 or base64url text".into());
868    }
869    if !data_url.starts_with('/') || data_url.starts_with("//") {
870        return Err("the data URL must be a same-origin path".into());
871    }
872    let job = job.filter(|_| mode == Mode::Shop);
873    let config = Config { mode: mode.as_str(), data_url: Some(data_url), job };
874    Ok(fill(Some(nonce), &serde_json::to_string(&config).unwrap(), "null"))
875}
876
877fn fill(nonce: Option<&str>, config: &str, data: &str) -> String {
878    let nonce_attribute = nonce.map(|n| format!(" nonce=\"{n}\"")).unwrap_or_default();
879    TEMPLATE
880        .replace("{{NONCE}}", &nonce_attribute)
881        .replace("{{CONFIG}}", &script_json(config))
882        .replace("{{DATA}}", &script_json(data))
883}
884
885/// JSON made safe inside a `<script type="application/json">` block: no `<`,
886/// `>` or `&` (so no `</script>` and no comment openers), and no U+2028/9.
887pub fn script_json(json: &str) -> String {
888    let mut out = String::with_capacity(json.len());
889    for ch in json.chars() {
890        match ch {
891            '<' => out.push_str("\\u003c"),
892            '>' => out.push_str("\\u003e"),
893            '&' => out.push_str("\\u0026"),
894            '\u{2028}' => out.push_str("\\u2028"),
895            '\u{2029}' => out.push_str("\\u2029"),
896            _ => out.push(ch),
897        }
898    }
899    out
900}
901
902const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
903
904/// Standard base64 with padding.
905pub fn base64(bytes: &[u8]) -> String {
906    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
907    for chunk in bytes.chunks(3) {
908        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
909        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
910        out.push(BASE64[(n >> 18) as usize & 63] as char);
911        out.push(BASE64[(n >> 12) as usize & 63] as char);
912        out.push(if chunk.len() > 1 { BASE64[(n >> 6) as usize & 63] as char } else { '=' });
913        out.push(if chunk.len() > 2 { BASE64[n as usize & 63] as char } else { '=' });
914    }
915    out
916}
917
918/// Standard base64 back to bytes: padding (at most two `=`) only at the end.
919/// `None` for any other character, so a corrupt string is never read as the
920/// prefix before its first bad character.
921pub fn unbase64(text: &str) -> Option<Vec<u8>> {
922    let value = |c: u8| BASE64.iter().position(|&b| b == c);
923    let body = text.strip_suffix("==").or_else(|| text.strip_suffix('=')).unwrap_or(text);
924    let mut out = Vec::with_capacity(text.len() / 4 * 3);
925    let mut acc: u32 = 0;
926    let mut bits = 0;
927    for c in body.bytes() {
928        let v = value(c)?;
929        acc = (acc << 6) | v as u32;
930        bits += 6;
931        if bits >= 8 {
932            bits -= 8;
933            out.push((acc >> bits) as u8);
934            acc &= (1 << bits) - 1;
935        }
936    }
937    Some(out)
938}
939
940/// The f32 values an [`encode_f32`] string carries; none for a string that is
941/// not base64 (never a short read of its good prefix).
942pub fn decode_f32(text: &str) -> Vec<f32> {
943    unbase64(text).unwrap_or_default().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
944}
945
946pub fn encode_f32(values: &[f32]) -> String {
947    base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
948}
949
950pub fn encode_u32(values: &[u32]) -> String {
951    base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
952}
953
954/// A PNG as a data URL, the only picture form the player shows from data.
955pub fn png_data_url(png: &[u8]) -> String {
956    format!("data:image/png;base64,{}", base64(png))
957}
958