1use crate::edit;
27use crate::model::{Instructions, Style, Target, ToolUse};
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, HashMap};
30
31pub const TEMPLATE: &str = include_str!("../player/player.html");
33
34pub const DATA_SCHEMA: u32 = 2;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
39#[serde(rename_all = "lowercase")]
40pub enum Mode {
41 #[default]
43 Shop,
44 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 pub steps: Vec<PlayerStep>,
75 #[serde(default)]
77 pub tools: Vec<ToolUse>,
78 #[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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
90 pub assembly: Vec<PlayerComponent>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub motion: Option<Motion>,
96 #[serde(default = "Style::saved_before_styles")]
100 pub style: Style,
101 #[serde(default, skip_serializing_if = "String::is_empty")]
106 pub record_key: String,
107}
108
109pub fn record_key(block: &Instructions) -> String {
114 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
117 for byte in serde_json::to_string(block).unwrap_or_default().bytes() {
118 hash ^= u64::from(byte);
119 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
120 }
121 format!("{hash:016x}")
122}
123
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129#[serde(rename_all = "camelCase")]
130pub struct Motion {
131 pub fps: u32,
132 pub duration: f64,
134 pub frames: Vec<MotionFrame>,
135}
136
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
144#[serde(rename_all = "camelCase")]
145pub struct MotionFrame {
146 pub time: f64,
147 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
148 pub poses: std::collections::BTreeMap<String, [f64; 16]>,
149 #[serde(default, skip_serializing_if = "Vec::is_empty")]
150 pub hidden: Vec<String>,
151 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
152 pub opacity: std::collections::BTreeMap<String, f64>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub camera: Option<Camera>,
155 #[serde(default, skip_serializing_if = "Vec::is_empty")]
156 pub clashing: Vec<String>,
157}
158
159impl MotionFrame {
160 pub fn clash(&self) -> bool {
162 !self.clashing.is_empty()
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
167#[serde(rename_all = "camelCase")]
168pub struct PlayerStep {
169 pub id: String,
170 pub number: usize,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub parent: Option<String>,
175 #[serde(default)]
177 pub depth: usize,
178 pub title: String,
179 #[serde(default)]
180 pub notes: String,
181 pub adds: Vec<PlayerAdd>,
182 #[serde(default)]
183 pub tools: Vec<ToolUse>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub torque: Option<String>,
187 #[serde(default)]
188 pub callouts: Vec<PlayerCallout>,
189 pub signoff: bool,
190 #[serde(default, skip_serializing_if = "Vec::is_empty")]
192 pub fields: Vec<crate::fields::StepField>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub camera: Option<Camera>,
195 pub placed: Vec<usize>,
197 pub adding: Vec<usize>,
199 #[serde(default)]
201 pub insertion: Vec<Insertion>,
202 #[serde(default, skip_serializing_if = "Vec::is_empty")]
205 pub poses: Vec<Pose>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub pmi: Option<PlayerPmi>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub image: Option<String>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
217 pub motion: Option<Motion>,
218}
219
220#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
221#[serde(rename_all = "camelCase")]
222pub struct PlayerAdd {
223 pub part: String,
225 #[serde(default)]
227 pub name: String,
228 #[serde(default)]
229 pub find_number: String,
230 pub quantity: usize,
231 pub occurrences: Vec<String>,
233 #[serde(default)]
234 pub serial_tracked: bool,
235 #[serde(default)]
236 pub subassembly: bool,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub thumbnail: Option<String>,
240}
241
242#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
243#[serde(rename_all = "camelCase")]
244pub struct PlayerCallout {
245 pub kind: crate::model::CalloutKind,
246 pub text: String,
247}
248
249#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
250#[serde(rename_all = "camelCase")]
251pub struct Camera {
252 pub eye: [f64; 3],
253 pub target: [f64; 3],
254 pub up: [f64; 3],
255 #[serde(default, skip_serializing_if = "Option::is_none")]
257 pub fov_deg: Option<f64>,
258 #[serde(default, skip_serializing_if = "Option::is_none")]
260 pub half_height: Option<f64>,
261}
262
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265pub struct Insertion {
266 pub node: usize,
267 pub offset: [f64; 3],
268 #[serde(default)]
272 pub arrow: usize,
273}
274
275#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
277#[serde(rename_all = "camelCase")]
278pub struct Pose {
279 pub node: usize,
280 pub matrix: [f64; 16],
281}
282
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
289#[serde(rename_all = "camelCase")]
290pub struct PlayerPmi {
291 pub lines: String,
294 #[serde(default, skip_serializing_if = "String::is_empty")]
296 pub arrows: String,
297 pub annotations: usize,
299 #[serde(default, skip_serializing_if = "Vec::is_empty")]
302 pub texts: Vec<String>,
303}
304
305impl PlayerPmi {
306 pub fn new(polylines: &[Vec<[f64; 3]>], arrows: &[[[f64; 3]; 3]], annotations: usize, texts: Vec<String>) -> Option<Self> {
310 let mut segments: Vec<f32> = Vec::new();
311 for line in polylines {
312 for pair in line.windows(2) {
313 segments.extend(pair[0].iter().chain(&pair[1]).map(|&v| v as f32));
314 }
315 }
316 let triangles: Vec<f32> = arrows.iter().flatten().flatten().map(|&v| v as f32).collect();
317 if segments.is_empty() && triangles.is_empty() {
318 return None;
319 }
320 Some(Self {
321 lines: encode_f32(&segments),
322 arrows: if triangles.is_empty() { String::new() } else { encode_f32(&triangles) },
323 annotations,
324 texts,
325 })
326 }
327}
328
329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333pub struct PlayerComponent {
334 pub path: String,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
339 pub parent: Option<String>,
340 #[serde(default)]
342 pub depth: usize,
343 pub name: String,
345 pub part: String,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub part_id: Option<String>,
350 #[serde(default)]
351 pub find_number: String,
352 #[serde(default)]
353 pub subassembly: bool,
354 #[serde(default)]
355 pub fastener: bool,
356 #[serde(default)]
357 pub serial_tracked: bool,
358 #[serde(default)]
359 pub grounded: bool,
360 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub torque: Option<String>,
362 #[serde(default, skip_serializing_if = "Vec::is_empty")]
364 pub attributes: Vec<(String, String)>,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
368 pub thumbnail: Option<String>,
369}
370
371impl PlayerComponent {
372 pub fn rows(root: &crate::wizard::Level) -> Vec<Self> {
375 let mut out = Vec::new();
376 fn walk(level: &crate::wizard::Level, parent: Option<&str>, depth: usize, out: &mut Vec<PlayerComponent>) {
377 for c in &level.components {
378 out.push(PlayerComponent {
379 path: c.path.clone(),
380 parent: parent.map(str::to_string),
381 depth,
382 name: c.part.clone(),
383 part: c.part_key().to_string(),
384 part_id: c.part_id.clone(),
385 find_number: c.find_number.clone(),
386 subassembly: c.children.is_some(),
387 fastener: c.fastener,
388 serial_tracked: c.serial_tracked,
389 grounded: c.grounded,
390 torque: c.torque.clone(),
391 attributes: c.attributes.clone(),
392 thumbnail: None,
393 });
394 if let Some(children) = &c.children {
395 walk(children, Some(&c.path), depth + 1, out);
396 }
397 }
398 }
399 walk(root, None, 0, &mut out);
400 out
401 }
402}
403
404#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
407#[serde(rename_all = "camelCase")]
408pub struct PlayerMesh {
409 pub id: String,
410 pub positions: String,
412 pub normals: String,
414 pub indices: String,
416 #[serde(default, skip_serializing_if = "String::is_empty")]
420 pub edges: String,
421}
422
423impl PlayerMesh {
424 pub fn new(id: &str, positions: &[f32], normals: &[f32], indices: &[u32]) -> Self {
425 Self { id: id.into(), positions: encode_f32(positions), normals: encode_f32(normals), indices: encode_u32(indices), edges: String::new() }
426 }
427
428 fn localise(&mut self, placement: &[f64; 16]) {
434 let m = placement;
435 let r = |p: [f32; 3]| -> [f32; 3] {
436 let p = [f64::from(p[0]), f64::from(p[1]), f64::from(p[2])];
438 [
439 (m[0] * p[0] + m[1] * p[1] + m[2] * p[2]) as f32,
440 (m[4] * p[0] + m[5] * p[1] + m[6] * p[2]) as f32,
441 (m[8] * p[0] + m[9] * p[1] + m[10] * p[2]) as f32,
442 ]
443 };
444 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]) };
445 let map = |text: &str, f: &dyn Fn([f32; 3]) -> [f32; 3]| -> String {
446 let values = decode_f32(text);
447 let mapped: Vec<f32> = values.chunks_exact(3).flat_map(|p| f([p[0], p[1], p[2]])).collect();
448 encode_f32(&mapped)
449 };
450 self.positions = map(&self.positions, &back);
451 self.normals = map(&self.normals, &r);
452 if !self.edges.is_empty() {
453 self.edges = map(&self.edges, &back);
454 }
455 }
456
457 pub fn with_edges(mut self, polylines: &[Vec<[f32; 3]>]) -> Self {
458 let mut segments: Vec<f32> = Vec::new();
459 for line in polylines {
460 for pair in line.windows(2) {
461 segments.extend_from_slice(&pair[0]);
462 segments.extend_from_slice(&pair[1]);
463 }
464 }
465 self.edges = if segments.is_empty() { String::new() } else { encode_f32(&segments) };
466 self
467 }
468}
469
470#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
472#[serde(rename_all = "camelCase")]
473pub struct PlayerNode {
474 pub occurrence: String,
476 pub mesh: usize,
478 pub matrix: [f64; 16],
480 pub color: [f32; 3],
482}
483
484#[derive(Debug, Clone, Default)]
487pub struct Scene {
488 pub meshes: Vec<PlayerMesh>,
489 pub nodes: Vec<PlayerNode>,
490 pub cameras: HashMap<String, Camera>,
491 pub step_images: HashMap<String, String>,
492 pub thumbnails: HashMap<String, String>,
493 pub poses: HashMap<String, Vec<Pose>>,
495 pub pmi: HashMap<String, PlayerPmi>,
497 pub arrows: HashMap<String, Vec<crate::model::Arrow>>,
501 pub assembly: Vec<PlayerComponent>,
504 pub wrapper: String,
508}
509
510const RIGID_FIT_TOLERANCE: f64 = 1e-4;
512
513impl Scene {
514 pub fn share_meshes(&mut self, keys: &[String], placements: &[Option<[f64; 16]>]) {
531 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();
532 let placement = |i: usize| placements.get(i).copied().flatten();
533 let mut first_by_key: HashMap<&str, usize> = HashMap::new();
534 let mut shared: Vec<Option<(usize, [f64; 16])>> = vec![None; self.nodes.len()];
535 let mut localised: Vec<Option<[f64; 16]>> = vec![None; self.nodes.len()];
536 for (i, node) in self.nodes.iter().enumerate() {
537 let Some(key) = keys.get(i) else { continue };
538 match first_by_key.get(key.as_str()) {
539 None => {
540 first_by_key.insert(key, i);
541 if let Some(at) = placement(i) {
542 localised[i] = Some(at);
543 }
544 }
545 Some(&reference) => {
546 let rm = self.nodes[reference].mesh;
547 match (placement(reference), placement(i)) {
548 (Some(_), Some(at)) => shared[i] = Some((rm, at)),
549 _ => {
550 let cm = node.mesh;
551 if rm != cm && self.meshes[rm].indices == self.meshes[cm].indices {
552 if let Some(matrix) = rigid_fit(&decoded[rm], &decoded[cm]) {
553 shared[i] = Some((rm, matrix));
554 }
555 }
556 }
557 }
558 }
559 }
560 }
561 for (i, at) in localised.iter().enumerate() {
562 if let Some(at) = at {
563 let mesh = self.nodes[i].mesh;
564 self.meshes[mesh].localise(at);
565 self.nodes[i].matrix = *at;
566 }
567 }
568 for (i, found) in shared.iter().enumerate() {
569 if let Some((mesh, matrix)) = found {
570 self.nodes[i].mesh = *mesh;
571 self.nodes[i].matrix = *matrix;
572 }
573 }
574 let used: Vec<bool> = (0..self.meshes.len()).map(|m| self.nodes.iter().any(|n| n.mesh == m)).collect();
575 let mut renumbered = vec![0usize; self.meshes.len()];
576 let mut next = 0;
577 for (m, keep) in used.iter().enumerate() {
578 if *keep {
579 renumbered[m] = next;
580 next += 1;
581 }
582 }
583 let meshes = std::mem::take(&mut self.meshes);
584 self.meshes = meshes.into_iter().enumerate().filter(|(m, _)| used[*m]).map(|(_, mesh)| mesh).collect();
585 for node in &mut self.nodes {
586 node.mesh = renumbered[node.mesh];
587 }
588 }
589}
590
591fn rigid_fit(a: &[[f64; 3]], b: &[[f64; 3]]) -> Option<[f64; 16]> {
596 if a.len() != b.len() || a.len() < 3 {
597 return None;
598 }
599 let sub = |p: [f64; 3], q: [f64; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
600 let dot = |p: [f64; 3], q: [f64; 3]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
601 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]];
602 let norm = |p: [f64; 3]| dot(p, p).sqrt();
603 let scale = |p: [f64; 3], k: f64| [p[0] * k, p[1] * k, p[2] * k];
604 let i0 = 0;
607 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))?;
608 let axis = sub(a[i1], a[i0]);
609 let extent = norm(axis);
610 if extent <= 0.0 {
611 return None;
612 }
613 let off_line = |i: usize| norm(cross(axis, sub(a[i], a[i0]))) / extent;
614 let i2 = (0..a.len()).max_by(|&i, &j| off_line(i).partial_cmp(&off_line(j)).unwrap_or(std::cmp::Ordering::Equal))?;
615 let tolerance = RIGID_FIT_TOLERANCE * extent.max(1e-9);
616 if off_line(i2) <= tolerance {
617 return None;
618 }
619 let frame = |p: &[[f64; 3]]| -> Option<[[f64; 3]; 3]> {
620 let u = sub(p[i1], p[i0]);
621 let u = scale(u, 1.0 / norm(u));
622 let v0 = sub(p[i2], p[i0]);
623 let v = sub(v0, scale(u, dot(v0, u)));
624 let lv = norm(v);
625 if lv <= 0.0 {
626 return None;
627 }
628 let v = scale(v, 1.0 / lv);
629 Some([u, v, cross(u, v)])
630 };
631 let (fa, fb) = (frame(a)?, frame(b)?);
632 let mut r = [[0.0f64; 3]; 3];
634 for col in 0..3 {
635 for row in 0..3 {
636 r[col][row] = (0..3).map(|j| fb[j][row] * fa[j][col]).sum();
637 }
638 }
639 let apply = |p: [f64; 3]| [
640 r[0][0] * p[0] + r[1][0] * p[1] + r[2][0] * p[2],
641 r[0][1] * p[0] + r[1][1] * p[1] + r[2][1] * p[2],
642 r[0][2] * p[0] + r[1][2] * p[1] + r[2][2] * p[2],
643 ];
644 let t = sub(b[i0], apply(a[i0]));
645 for (p, q) in a.iter().zip(b) {
646 let moved = apply(*p);
647 if norm(sub([moved[0] + t[0], moved[1] + t[1], moved[2] + t[2]], *q)) > tolerance {
648 return None;
649 }
650 }
651 Some([
652 r[0][0], r[0][1], r[0][2], 0.0,
653 r[1][0], r[1][1], r[1][2], 0.0,
654 r[2][0], r[2][1], r[2][2], 0.0,
655 t[0], t[1], t[2], 1.0,
656 ])
657}
658
659impl Motion {
660 pub fn under(&self, wrapper: &str) -> Motion {
663 if wrapper.is_empty() {
664 return self.clone();
665 }
666 let key = |k: &str| format!("{wrapper}:{k}");
667 let frames = self
668 .frames
669 .iter()
670 .map(|frame| MotionFrame {
671 time: frame.time,
672 poses: frame.poses.iter().map(|(k, v)| (key(k), *v)).collect(),
673 hidden: frame.hidden.iter().map(|k| key(k)).collect(),
674 opacity: frame.opacity.iter().map(|(k, v)| (key(k), *v)).collect(),
675 camera: frame.camera.clone(),
676 clashing: frame.clashing.iter().map(|k| key(k)).collect(),
677 })
678 .collect();
679 Motion { fps: self.fps, duration: self.duration, frames }
680 }
681}
682
683fn step_motion(step: &crate::model::Step, wrapper: &str) -> Result<Option<Motion>, String> {
687 let Some(value) = &step.motion else { return Ok(None) };
688 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))?;
689 if motion.frames.is_empty() {
690 return Err(format!("step '{}': its motion has no frames", step.id));
691 }
692 Ok(Some(motion.under(wrapper)))
693}
694
695impl PlayerData {
696 pub fn build(block: &Instructions, scene: Scene) -> Result<Self, String> {
698 for (i, node) in scene.nodes.iter().enumerate() {
699 if node.mesh >= scene.meshes.len() {
700 return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
701 }
702 }
703 let occurrences: Vec<String> = scene.nodes.iter().map(|n| n.occurrence.clone()).collect();
704 let mut steps = Vec::new();
705 for (number, (depth, step)) in block.steps().enumerate() {
706 let number = number + 1;
707 let parent = block.parent_id(&step.id).flatten().map(str::to_string);
708 {
709 let presentation = edit::presentation(block, &step.id, &occurrences)?;
710 let index_of = |paths: &[String]| -> Vec<usize> {
711 let set: std::collections::HashSet<&str> = paths.iter().map(String::as_str).collect();
712 occurrences.iter().enumerate().filter(|(_, o)| set.contains(o.as_str())).map(|(i, _)| i).collect()
713 };
714 let adding = index_of(&presentation.adding);
715 let arrows = scene.arrows.get(&step.id).unwrap_or(&step.arrows);
716 let insertion = adding
717 .iter()
718 .filter_map(|&node| {
719 let path = &occurrences[node];
720 arrows
721 .iter()
722 .enumerate()
723 .find(|(_, a)| path == &a.occurrence || (path.starts_with(&a.occurrence) && path[a.occurrence.len()..].starts_with(':')))
724 .map(|(arrow, a)| Insertion { node, offset: a.start_offset(), arrow })
725 })
726 .collect();
727 steps.push(PlayerStep {
728 id: step.id.clone(),
729 number,
730 parent,
731 depth,
732 title: step.title.clone(),
733 notes: step.notes.clone(),
734 adds: step
735 .adds
736 .iter()
737 .map(|a| PlayerAdd {
738 part: a.part.clone(),
739 name: a.display_name().to_string(),
740 find_number: a.find_number.clone(),
741 quantity: a.quantity(),
742 occurrences: a.occurrences.clone(),
743 serial_tracked: a.serial_tracked,
744 subassembly: a.subassembly,
745 thumbnail: scene.thumbnails.get(&a.part).cloned(),
746 })
747 .collect(),
748 tools: step.tools.clone(),
749 torque: step.torque.as_ref().map(|t| t.text()),
750 callouts: step.callouts.iter().map(|c| PlayerCallout { kind: c.kind, text: c.text.clone() }).collect(),
751 signoff: step.signoff.required,
752 fields: step.fields.clone(),
753 camera: scene.cameras.get(&step.id).cloned(),
754 placed: index_of(&presentation.placed),
755 adding,
756 insertion,
757 poses: scene.poses.get(&step.id).cloned().unwrap_or_default(),
758 pmi: scene.pmi.get(&step.id).cloned(),
759 image: scene.step_images.get(&step.id).cloned(),
760 motion: step_motion(step, &scene.wrapper)?,
761 });
762 }
763 }
764 let title = if block.front.title.is_empty() { block.target.name.clone() } else { block.front.title.clone() };
765 let mut assembly = scene.assembly;
766 for row in &mut assembly {
767 if row.thumbnail.is_none() {
768 row.thumbnail = scene.thumbnails.get(&row.part).cloned();
769 }
770 }
771 Ok(Self {
772 schema: DATA_SCHEMA,
773 title,
774 subtitle: block.front.subtitle.clone(),
775 target: block.target.clone(),
776 steps,
777 tool_pictures: block
778 .tools_list()
779 .iter()
780 .filter_map(|(tool, _)| tool.tool_id.as_deref())
781 .filter(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-'))
782 .map(|id| (id.to_string(), format!("/api/tools/{id}/picture")))
783 .collect(),
784 tools: block.tools_list().into_iter().map(|(t, _)| t).collect(),
785 meshes: scene.meshes,
786 nodes: scene.nodes,
787 assembly,
788 motion: None,
789 style: block.template.style,
790 record_key: record_key(block),
791 })
792 }
793
794 pub fn inline_tool_pictures(&mut self, fetched: &BTreeMap<String, Option<(String, Vec<u8>)>>) -> usize {
802 let mut inlined = 0;
803 let pictures = std::mem::take(&mut self.tool_pictures);
804 for (id, url) in pictures {
805 if url.starts_with("data:image/") {
806 self.tool_pictures.insert(id, url);
807 inlined += 1;
808 continue;
809 }
810 let Some(Some((media, bytes))) = fetched.get(&id) else { continue };
811 let media = media.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
812 if !matches!(media.as_str(), "image/png" | "image/jpeg" | "image/webp") || bytes.len() > TOOL_PICTURE_MAX_BYTES {
813 continue;
814 }
815 self.tool_pictures.insert(id, format!("data:{media};base64,{}", base64(bytes)));
816 inlined += 1;
817 }
818 inlined
819 }
820
821 pub fn motion_study(title: &str, subtitle: &str, target: Target, scene: Scene, motion: Motion) -> Result<Self, String> {
824 for (i, node) in scene.nodes.iter().enumerate() {
825 if node.mesh >= scene.meshes.len() {
826 return Err(format!("node {i} names mesh {} of {}", node.mesh, scene.meshes.len()));
827 }
828 }
829 if motion.frames.is_empty() {
830 return Err("a motion study's player needs at least one frame".into());
831 }
832 Ok(Self {
833 schema: DATA_SCHEMA,
834 title: title.to_string(),
835 subtitle: subtitle.to_string(),
836 target,
837 steps: Vec::new(),
838 tools: Vec::new(),
839 tool_pictures: BTreeMap::new(),
840 meshes: scene.meshes,
841 nodes: scene.nodes,
842 assembly: Vec::new(),
843 motion: Some(motion),
844 style: Style::Shaded,
845 record_key: String::new(),
846 })
847 }
848
849 pub fn to_json(&self) -> String {
850 serde_json::to_string(self).expect("player data serializes")
851 }
852
853 pub fn from_json(text: &str) -> Result<Self, String> {
856 let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("player data: {e}"))?;
857 let schema = value.get("schema").and_then(serde_json::Value::as_u64).unwrap_or(0);
858 if schema == 0 || schema > u64::from(DATA_SCHEMA) {
859 return Err(format!("player data schema {schema} is not supported"));
860 }
861 if schema == 1 {
862 if let Some(object) = value.as_object_mut() {
863 let chapters = object.remove("chapters").and_then(|c| c.as_array().cloned()).unwrap_or_default();
864 if !object.contains_key("steps") {
865 let steps: Vec<serde_json::Value> =
866 chapters.into_iter().flat_map(|c| c.get("steps").and_then(|s| s.as_array().cloned()).unwrap_or_default()).collect();
867 object.insert("steps".into(), serde_json::Value::Array(steps));
868 }
869 object.insert("schema".into(), serde_json::Value::from(DATA_SCHEMA));
870 }
871 }
872 serde_json::from_value(value).map_err(|e| format!("player data: {e}"))
873 }
874}
875
876#[derive(Debug, Clone, PartialEq, Serialize)]
878#[serde(rename_all = "camelCase")]
879struct Config<'a> {
880 mode: &'a str,
881 #[serde(skip_serializing_if = "Option::is_none")]
883 data_url: Option<&'a str>,
884 #[serde(skip_serializing_if = "Option::is_none")]
886 job: Option<&'a str>,
887}
888
889pub fn offline_html(data: &PlayerData, mode: Mode) -> String {
892 let config = Config { mode: mode.as_str(), data_url: None, job: None };
893 let json = if data.tool_pictures.values().all(|url| url.starts_with("data:image/")) {
895 data.to_json()
896 } else {
897 let mut data = data.clone();
898 data.tool_pictures.retain(|_, url| url.starts_with("data:image/"));
899 data.to_json()
900 };
901 fill(None, &serde_json::to_string(&config).unwrap(), &json)
902}
903
904pub const TOOL_PICTURE_MAX_BYTES: usize = 1024 * 1024;
906
907pub fn served_html(nonce: &str, data_url: &str, mode: Mode, job: Option<&str>) -> Result<String, String> {
911 if nonce.is_empty() || !nonce.bytes().all(|b| b.is_ascii_alphanumeric() || b"+/=_-".contains(&b)) {
912 return Err("the nonce must be base64 or base64url text".into());
913 }
914 if !data_url.starts_with('/') || data_url.starts_with("//") {
915 return Err("the data URL must be a same-origin path".into());
916 }
917 let job = job.filter(|_| mode == Mode::Shop);
918 let config = Config { mode: mode.as_str(), data_url: Some(data_url), job };
919 Ok(fill(Some(nonce), &serde_json::to_string(&config).unwrap(), "null"))
920}
921
922fn fill(nonce: Option<&str>, config: &str, data: &str) -> String {
923 let nonce_attribute = nonce.map(|n| format!(" nonce=\"{n}\"")).unwrap_or_default();
924 TEMPLATE
925 .replace("{{NONCE}}", &nonce_attribute)
926 .replace("{{CONFIG}}", &script_json(config))
927 .replace("{{DATA}}", &script_json(data))
928}
929
930pub fn script_json(json: &str) -> String {
933 let mut out = String::with_capacity(json.len());
934 for ch in json.chars() {
935 match ch {
936 '<' => out.push_str("\\u003c"),
937 '>' => out.push_str("\\u003e"),
938 '&' => out.push_str("\\u0026"),
939 '\u{2028}' => out.push_str("\\u2028"),
940 '\u{2029}' => out.push_str("\\u2029"),
941 _ => out.push(ch),
942 }
943 }
944 out
945}
946
947const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
948
949pub fn base64(bytes: &[u8]) -> String {
951 let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
952 for chunk in bytes.chunks(3) {
953 let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
954 let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
955 out.push(BASE64[(n >> 18) as usize & 63] as char);
956 out.push(BASE64[(n >> 12) as usize & 63] as char);
957 out.push(if chunk.len() > 1 { BASE64[(n >> 6) as usize & 63] as char } else { '=' });
958 out.push(if chunk.len() > 2 { BASE64[n as usize & 63] as char } else { '=' });
959 }
960 out
961}
962
963pub fn unbase64(text: &str) -> Option<Vec<u8>> {
967 let value = |c: u8| BASE64.iter().position(|&b| b == c);
968 let body = text.strip_suffix("==").or_else(|| text.strip_suffix('=')).unwrap_or(text);
969 let mut out = Vec::with_capacity(text.len() / 4 * 3);
970 let mut acc: u32 = 0;
971 let mut bits = 0;
972 for c in body.bytes() {
973 let v = value(c)?;
974 acc = (acc << 6) | v as u32;
975 bits += 6;
976 if bits >= 8 {
977 bits -= 8;
978 out.push((acc >> bits) as u8);
979 acc &= (1 << bits) - 1;
980 }
981 }
982 Some(out)
983}
984
985pub fn decode_f32(text: &str) -> Vec<f32> {
988 unbase64(text).unwrap_or_default().chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()
989}
990
991pub fn encode_f32(values: &[f32]) -> String {
992 base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
993}
994
995pub fn encode_u32(values: &[u32]) -> String {
996 base64(&values.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>())
997}
998
999pub fn png_data_url(png: &[u8]) -> String {
1001 format!("data:image/png;base64,{}", base64(png))
1002}
1003