1use super::interference::{displays_pierce, overlaps, posed_bbox};
40use super::pmi_section::{clip_display_all, side_of_all, Side};
41use super::{component_move::now_ms, EngineState};
42use crate::camera::Aabb;
43use crate::scene::SolidDisplay;
44use brep_kernel::{PmiCamera, PmiProjection};
45use brep_simulation::model::Study;
46use brep_simulation::sample::SectionSample;
47use brep_simulation::FrameSample;
48use serde_json::{json, Map, Value};
49use std::collections::{BTreeMap, HashMap};
50
51const BAKE_BUDGET_MS: f64 = 12.0;
54
55#[derive(Debug, Clone, PartialEq)]
58pub struct BakedFrame {
59 pub poses: BTreeMap<String, [f64; 16]>,
60 pub failed: bool,
62 pub clashes: Vec<(String, String)>,
66}
67
68pub(super) const IDENTITY: [f64; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
70
71const CLASH_TINT: [f32; 3] = [0.92, 0.25, 0.2];
73
74#[derive(Debug)]
77pub struct SimulationPlayback {
78 pub study: String,
79 baked_study: Study,
82 revision: u64,
83 base: HashMap<String, f64>,
85 pub frames: Vec<BakedFrame>,
86 total: usize,
87 reference: Map<String, Value>,
89 pub time: f64,
91 pub playing: bool,
92 pub looping: bool,
93 shown: Option<usize>,
95 wanted: Option<usize>,
97 originals: HashMap<String, SolidDisplay>,
99 applied: HashMap<String, [f64; 16]>,
101 pub error: Option<String>,
103 participants: Vec<(String, Vec<String>)>,
106 tinted: Vec<String>,
108 hidden: Vec<String>,
110 translucent: Vec<String>,
112 sectioned: Vec<String>,
115 camera_before: Option<PmiCamera>,
118 shown_sample: Option<FrameSample>,
120}
121
122impl SimulationPlayback {
123 pub(crate) fn baked_study(&self) -> &Study {
125 &self.baked_study
126 }
127
128 pub(crate) fn revision(&self) -> u64 {
130 self.revision
131 }
132
133 pub(crate) fn base(&self) -> &HashMap<String, f64> {
135 &self.base
136 }
137
138 pub(crate) fn original(&self, name: &str) -> Option<&SolidDisplay> {
140 self.originals.get(name)
141 }
142}
143
144impl EngineState {
145 pub(crate) fn simulation_playback(&self) -> Option<&SimulationPlayback> {
147 self.simulation_play.as_ref()
148 }
149
150 pub fn simulation_bake_all(&mut self, study: Option<&str>) -> Result<String, String> {
154 let id = self.simulation_prepare(study)?;
155 if let Some(play) = self.simulation_play.as_mut() {
156 play.playing = false;
157 }
158 if !self.ensure_assembly_session() {
159 return Err(super::ASSEMBLY_SESSION_PENDING.into());
160 }
161 let mut guard = 0usize;
162 while self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) {
163 guard += 1;
164 if guard > 1_000_000 {
165 return Err("the bake did not finish".into());
166 }
167 self.simulation_bake_next();
168 }
169 Ok(id)
170 }
171
172 pub(super) fn simulation_keep_bake_through_publish(&mut self, study: &str, motion: Value) {
176 let revision = self.history.revision();
177 if let Some(play) = self.simulation_play.as_mut().filter(|play| play.study == study) {
178 play.baked_study.motion = Some(motion);
179 play.revision = revision;
180 }
181 }
182
183 pub fn simulation_play(&mut self, study: Option<&str>, looping: Option<bool>) -> Result<String, String> {
187 let id = self.simulation_prepare(study)?;
188 let play = self.simulation_play.as_mut().expect("prepared");
189 if let Some(looping) = looping {
190 play.looping = looping;
191 }
192 if play.time >= play.baked_study.duration - 1e-9 {
193 play.time = 0.0;
194 }
195 play.playing = true;
196 play.wanted = Some(play.baked_study.frame_at(play.time));
197 Ok(id)
198 }
199
200 pub fn simulation_pause(&mut self) {
202 if let Some(play) = self.simulation_play.as_mut() {
203 play.playing = false;
204 }
205 }
206
207 pub fn simulation_stop(&mut self) {
210 self.simulation_restore_displays();
211 if let Some(play) = self.simulation_play.as_mut() {
212 play.playing = false;
213 play.time = 0.0;
214 play.wanted = None;
215 }
216 }
217
218 pub fn simulation_seek(&mut self, study: Option<&str>, time: f64) -> Result<(), String> {
221 if !time.is_finite() {
222 return Err("seek: the time is not a number".into());
223 }
224 self.simulation_prepare(study)?;
225 let play = self.simulation_play.as_mut().expect("prepared");
226 play.playing = false;
227 play.time = time.clamp(0.0, play.baked_study.duration);
228 play.wanted = Some(play.baked_study.frame_at(play.time));
229 self.simulation_show_wanted();
230 Ok(())
231 }
232
233 pub fn simulation_set_looping(&mut self, study: Option<&str>, looping: bool) -> Result<(), String> {
235 self.simulation_prepare(study)?;
236 self.simulation_play.as_mut().expect("prepared").looping = looping;
237 Ok(())
238 }
239
240 pub fn simulation_playing_or_shown(&self) -> bool {
242 self.simulation_play.as_ref().is_some_and(|play| play.playing || play.shown.is_some())
243 }
244
245 fn simulation_prepare(&mut self, study: Option<&str>) -> Result<String, String> {
248 let block = self.simulation()?.ok_or("no study yet: New study starts one")?;
249 let study = match study {
250 Some(id) => block.study(id).ok_or_else(|| format!("no study '{id}'"))?,
251 None => block.active_study().ok_or("no study yet: New study starts one")?,
252 }
253 .clone();
254 let revision = self.history.revision();
255 let current = self
256 .simulation_play
257 .as_ref()
258 .is_some_and(|play| play.study == study.id && play.revision == revision && play.baked_study == study);
259 if current {
260 return Ok(study.id);
261 }
262 self.simulation_restore_displays();
266 if self.pmi_active_view.is_some() {
267 self.pmi_deactivate_view();
268 }
269 let previous = self.simulation_play.take();
270 let (time, looping) = previous
271 .filter(|play| play.study == study.id)
272 .map_or((0.0, false), |play| (play.time.min(study.duration), play.looping));
273 let base = self.simulation_motor_mates().into_iter().map(|mate| (mate.id, mate.value)).collect();
274 let participants = if study.interference.enabled { self.interference_participants() } else { Vec::new() };
275 let total = study.frame_count();
276 let id = study.id.clone();
277 self.simulation_play = Some(SimulationPlayback {
278 study: id.clone(),
279 baked_study: study,
280 revision,
281 base,
282 frames: Vec::with_capacity(total),
283 total,
284 reference: Map::new(),
285 time,
286 playing: false,
287 looping,
288 shown: None,
289 wanted: None,
290 originals: HashMap::new(),
291 applied: HashMap::new(),
292 error: None,
293 participants,
294 tinted: Vec::new(),
295 hidden: Vec::new(),
296 translucent: Vec::new(),
297 sectioned: Vec::new(),
298 camera_before: None,
299 shown_sample: None,
300 });
301 Ok(id)
302 }
303
304 pub fn simulation_tick(&mut self, dt: f64) -> bool {
308 let Some(play) = self.simulation_play.as_ref() else { return false };
309 if play.revision != self.history.revision() {
311 let (study, time, playing, looping) = (play.study.clone(), play.time, play.playing, play.looping);
312 self.simulation_restore_displays();
313 self.simulation_play = None;
314 if self.simulation_prepare(Some(&study)).is_err() {
315 return false;
316 }
317 let play = self.simulation_play.as_mut().expect("prepared");
318 play.time = time.min(play.baked_study.duration);
319 play.playing = playing;
320 play.looping = looping;
321 play.wanted = Some(play.baked_study.frame_at(play.time));
322 }
323 let start = now_ms();
324 let mut ready = true;
325 if self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) {
326 ready = self.ensure_assembly_session();
331 }
332 while ready && self.simulation_play.as_ref().is_some_and(|play| play.frames.len() < play.total) && now_ms() - start < BAKE_BUDGET_MS {
333 self.simulation_bake_next();
334 }
335 let play = self.simulation_play.as_mut().expect("checked above");
336 if play.playing {
337 let duration = play.baked_study.duration;
338 play.time += dt.max(0.0);
339 if play.time >= duration - 1e-9 {
340 if play.looping {
341 play.time = (play.time % duration).max(0.0);
342 } else {
343 play.time = duration;
344 play.playing = false;
345 }
346 }
347 let baked = play.frames.len();
349 if play.baked_study.frame_at(play.time) >= baked {
350 play.time = play.baked_study.frame_time(baked.saturating_sub(1));
351 if baked == 0 {
352 play.time = 0.0;
353 }
354 }
355 play.wanted = Some(play.baked_study.frame_at(play.time));
356 }
357 self.simulation_show_wanted();
358 let play = self.simulation_play.as_ref().expect("checked above");
359 play.playing || play.frames.len() < play.total
360 }
361
362 pub(super) fn simulation_bake_next(&mut self) {
365 let Some(play) = self.simulation_play.as_mut() else { return };
366 let index = play.frames.len();
367 if index >= play.total {
368 return;
369 }
370 let time = play.baked_study.frame_time(index);
371 let base = &play.base;
372 let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
373 let mut overrides = Map::new();
374 for (id, mate) in &sample.mates {
375 let mut change = Map::new();
376 if let Some(value) = mate.value {
377 change.insert("value".into(), json!(value));
378 }
379 if let Some(enabled) = mate.enabled {
380 change.insert("enabled".into(), json!(enabled));
381 }
382 overrides.insert(id.clone(), Value::Object(change));
383 }
384 let request = json!({ "overrides": overrides, "reference": play.reference });
385 let (poses, failed): (BTreeMap<String, [f64; 16]>, bool) = match brep_kernel::assembly_frame_solve_impl(&request.to_string()) {
386 Ok(reply) => {
387 let reply: Value = serde_json::from_str(&reply).unwrap_or(Value::Null);
388 let poses_json = reply.get("poses").and_then(Value::as_object).cloned().unwrap_or_default();
389 let poses = poses_json.iter().map(|(id, pose)| (id.clone(), crate::pipeline::pose_params_to_transform(pose))).collect();
390 play.reference = poses_json;
391 (poses, false)
392 }
393 Err(error) => {
394 let poses = play.frames.last().map(|frame| frame.poses.clone()).unwrap_or_default();
395 play.error = Some(format!("frame {index} ({time:.3} s): {error}"));
396 (poses, true)
397 }
398 };
399 let participants = std::mem::take(&mut play.participants);
402 let previous = play.frames.last().cloned();
403 let clashes = if participants.is_empty() { Vec::new() } else { self.simulation_frame_clashes(&participants, &poses, previous.as_ref()) };
404 let Some(play) = self.simulation_play.as_mut() else { return };
405 play.participants = participants;
406 play.frames.push(BakedFrame { poses, failed, clashes });
407 }
408
409 fn simulation_frame_clashes(&self, participants: &[(String, Vec<String>)], poses: &BTreeMap<String, [f64; 16]>, previous: Option<&BakedFrame>) -> Vec<(String, String)> {
418 let originals = self.simulation_play.as_ref().map(|play| &play.originals);
419 let display_of = |name: &String| -> Option<&SolidDisplay> { originals.and_then(|originals| originals.get(name)).or_else(|| self.scene.solid(name)) };
420 let delta_of = |occ: &str| -> [f64; 16] {
421 let top = occ.split(':').next().unwrap_or(occ);
422 let (key, world) = match poses.get(occ) {
423 Some(world) => (occ, world),
424 None => match poses.get(top) {
425 Some(world) => (top, world),
426 None => return IDENTITY,
427 },
428 };
429 match self.occurrence_document_matrix(key) {
430 Some(document) => mat_mul(world, &rigid_inverse(&document)),
431 None => IDENTITY,
432 }
433 };
434 let mut posed: Vec<(&str, [f64; 16], Aabb, &[String])> = Vec::new();
435 for (occ, solids) in participants {
436 let delta = delta_of(occ);
437 let mut bbox = Aabb::empty();
438 for name in solids {
439 if let Some(solid) = display_of(name) {
440 bbox.union(&posed_bbox(&solid.bbox, &delta));
441 }
442 }
443 if !bbox.is_empty() {
444 posed.push((occ.as_str(), delta, bbox, solids.as_slice()));
445 }
446 }
447 let same_as_previous = |occ: &str, prev: &BakedFrame| {
448 let top = occ.split(':').next().unwrap_or(occ);
449 poses.get(occ) == prev.poses.get(occ) && poses.get(top) == prev.poses.get(top)
450 };
451 let mut clashes = Vec::new();
452 for i in 0..posed.len() {
453 for j in i + 1..posed.len() {
454 if !overlaps(&posed[i].2, &posed[j].2) {
455 continue;
456 }
457 let pair = (posed[i].0.to_string(), posed[j].0.to_string());
458 if let Some(prev) = previous {
459 if same_as_previous(&pair.0, prev) && same_as_previous(&pair.1, prev) {
460 if prev.clashes.contains(&pair) {
461 clashes.push(pair);
462 }
463 continue;
464 }
465 }
466 let hit = posed[i].3.iter().filter_map(display_of).any(|a| posed[j].3.iter().filter_map(display_of).any(|b| displays_pierce(a, &posed[i].1, b, &posed[j].1)));
467 if hit {
468 clashes.push(pair);
469 }
470 }
471 }
472 clashes
473 }
474
475 fn simulation_show_wanted(&mut self) {
477 let Some(play) = self.simulation_play.as_ref() else { return };
478 let Some(wanted) = play.wanted else { return };
479 if wanted >= play.frames.len() || play.shown == Some(wanted) {
480 return;
481 }
482 self.simulation_pose_frame(wanted);
483 }
484
485 pub(crate) fn simulation_frame_worlds(&self, index: usize) -> Option<BTreeMap<String, [f64; 16]>> {
492 let play = self.simulation_play.as_ref()?;
493 let frame = play.frames.get(index)?;
494 let mut worlds = frame.poses.clone();
495 let time = play.baked_study.frame_time(index);
496 let base = &play.base;
497 let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
498 for explode in &sample.explode {
499 let Some(view) = self.exploded_views().into_iter().find(|view| view.id == explode.view) else { continue };
500 let steps: Vec<_> = view.steps.iter().filter(|step| step.enabled).collect();
501 let count = steps.len() as f64;
502 for (k, step) in steps.iter().enumerate() {
503 let fraction = (explode.progress * count - k as f64).clamp(0.0, 1.0);
504 if fraction <= 0.0 {
505 continue;
506 }
507 for target in &step.targets {
508 let Some(world) = worlds.get(target).copied().or_else(|| self.occurrence_document_matrix(target)) else { continue };
509 let mut shift = IDENTITY;
510 for axis in 0..3 {
511 shift[axis * 4 + 3] = step.translate[axis] * fraction;
512 }
513 worlds.insert(target.clone(), mat_mul(&shift, &world));
514 }
515 }
516 }
517 Some(worlds)
518 }
519
520 fn simulation_pose_frame(&mut self, index: usize) {
524 let Some(play) = self.simulation_play.as_ref() else { return };
525 if index >= play.frames.len() {
526 return;
527 }
528 let time = play.baked_study.frame_time(index);
529 let base = play.base.clone();
530 let sample = play.baked_study.sample(time, &|id| base.get(id).copied());
531 let Some(worlds) = self.simulation_frame_worlds(index) else { return };
532 let Some(play) = self.simulation_play.as_ref() else { return };
533 let frame = worlds;
534 let gone: Vec<String> = play.applied.keys().filter(|id| !frame.contains_key(*id)).cloned().collect();
536 self.simulation_unsection();
537 let Some(_) = self.simulation_play.as_ref() else { return };
538 let mut changed = false;
539 for id in gone {
540 self.simulation_pose_occurrence(&id, None);
541 changed = true;
542 }
543 for (id, world) in &frame {
544 let Some(document) = self.occurrence_document_matrix(id) else { continue };
545 let shown = self.simulation_play.as_ref().and_then(|play| play.applied.get(id).copied()).unwrap_or(document);
546 if same_matrix(&shown, world) {
547 continue;
548 }
549 if same_matrix(world, &document) {
550 self.simulation_pose_occurrence(id, None);
552 } else {
553 let delta = mat_mul(world, &rigid_inverse(&document));
554 self.simulation_pose_occurrence(id, Some((delta, *world)));
555 }
556 changed = true;
557 }
558 if let Some(play) = self.simulation_play.as_mut() {
559 play.shown = Some(index);
560 }
561 if changed {
562 self.dirty = true;
563 }
564 self.simulation_apply_section(sample.section.as_ref());
565 self.simulation_tint_clashes(index);
566 self.simulation_apply_hidden(&sample.hidden);
567 self.simulation_apply_opacity(&sample.opacity);
568 if let Some(camera) = &sample.camera {
569 self.simulation_apply_camera(&camera.from, &camera.to, camera.t);
570 }
571 if let Some(play) = self.simulation_play.as_mut() {
572 play.shown_sample = Some(sample);
573 }
574 }
575
576 fn simulation_unsection(&mut self) {
580 let Some(play) = self.simulation_play.as_mut() else { return };
581 let sectioned = std::mem::take(&mut play.sectioned);
582 if sectioned.is_empty() {
583 return;
584 }
585 let applied: Vec<(String, [f64; 16])> = play.applied.iter().map(|(id, world)| (id.clone(), *world)).collect();
586 let mut reposed: Vec<String> = Vec::new();
587 for name in §ioned {
588 if let (Some(original), Some(display)) = (play.originals.get(name), self.scene.solid_mut(name)) {
589 *display = original.clone();
590 }
591 if let Some((id, _)) = applied.iter().filter(|(id, _)| name.starts_with(&format!("{id}:"))).max_by_key(|(id, _)| id.len()) {
593 if !reposed.contains(id) {
594 reposed.push(id.clone());
595 }
596 }
597 }
598 for id in reposed {
599 let Some(world) = applied.iter().find(|(key, _)| *key == id).map(|(_, world)| *world) else { continue };
600 let Some(document) = self.occurrence_document_matrix(&id) else { continue };
601 self.simulation_pose_occurrence(&id, Some((mat_mul(&world, &rigid_inverse(&document)), world)));
602 }
603 self.dirty = true;
604 }
605
606 fn simulation_apply_section(&mut self, section: Option<&SectionSample>) {
611 let Some(section) = section else { return };
612 let state = self.pmi_state_shared();
613 let Some(view) = state.find_view(§ion.view) else { return };
614 let report = self.pmi_report.as_ref().and_then(|report| report.view(§ion.view));
615 let planes: Vec<([f64; 3], [f64; 3])> = view
616 .section_planes_in(report)
617 .into_iter()
618 .map(|(point, normal)| (std::array::from_fn(|i| point[i] + normal[i] * section.offset), normal))
619 .collect();
620 if planes.is_empty() {
621 return;
622 }
623 let exclude = view.display.section.clone();
624 let names: Vec<(String, Side)> = self
625 .scene
626 .solids()
627 .iter()
628 .filter(|solid| solid.visible)
629 .map(|solid| (solid.name.clone(), if exclude.as_ref().is_some_and(|cut| cut.excludes(&solid.name)) { Side::Kept } else { side_of_all(solid, &planes) }))
630 .collect();
631 let mut sectioned = Vec::new();
632 for (name, side) in names {
633 if side == Side::Kept {
634 continue;
635 }
636 let Some(display) = self.scene.solid(&name).cloned() else { continue };
637 if let Some(play) = self.simulation_play.as_mut() {
638 play.originals.entry(name.clone()).or_insert(display);
639 }
640 if let Some(display) = self.scene.solid_mut(&name) {
641 match side {
642 Side::Removed => display.visible = false,
643 Side::Cut => clip_display_all(display, &planes),
644 Side::Kept => {}
645 }
646 display.revision = crate::scene::next_revision();
647 }
648 sectioned.push(name);
649 }
650 if let Some(play) = self.simulation_play.as_mut() {
651 play.sectioned = sectioned;
652 }
653 self.dirty = true;
654 }
655
656 fn simulation_apply_opacity(&mut self, opacity: &BTreeMap<String, f64>) {
659 let mut want: Vec<(String, f32)> = Vec::new();
660 for (id, value) in opacity {
661 for name in self.simulation_occurrence_solids(id) {
662 want.push((name, value.clamp(0.0, 1.0) as f32));
663 }
664 }
665 want.sort_by(|a, b| a.0.cmp(&b.0));
666 want.dedup_by(|a, b| a.0 == b.0);
667 let Some(play) = self.simulation_play.as_ref() else { return };
668 let previous = play.translucent.clone();
669 let mut changed = false;
670 for name in previous.iter().filter(|name| !want.iter().any(|(n, _)| n == *name)) {
671 let opacity = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.opacity);
672 if let (Some(opacity), Some(display)) = (opacity, self.scene.solid_mut(name)) {
673 if display.opacity != opacity {
674 display.opacity = opacity;
675 display.revision = crate::scene::next_revision();
676 changed = true;
677 }
678 }
679 }
680 for (name, value) in &want {
681 let Some(display) = self.scene.solid(name).cloned() else { continue };
682 if let Some(play) = self.simulation_play.as_mut() {
683 play.originals.entry(name.clone()).or_insert(display);
684 }
685 if let Some(display) = self.scene.solid_mut(name) {
686 if display.opacity != Some(*value) {
687 display.opacity = Some(*value);
688 display.revision = crate::scene::next_revision();
689 changed = true;
690 }
691 }
692 }
693 if let Some(play) = self.simulation_play.as_mut() {
694 play.translucent = want.into_iter().map(|(name, _)| name).collect();
695 }
696 if changed {
697 self.dirty = true;
698 }
699 }
700
701 fn simulation_occurrence_solids(&self, id: &str) -> Vec<String> {
704 if id.contains(':') {
705 let prefix = format!("{id}:");
706 self.scene.solids().iter().filter(|solid| solid.name.starts_with(&prefix)).map(|solid| solid.name.clone()).collect()
707 } else {
708 self.member_solid_names(id)
709 }
710 }
711
712 fn simulation_apply_hidden(&mut self, occurrences: &[String]) {
716 let mut want: Vec<String> = occurrences.iter().flat_map(|id| self.simulation_occurrence_solids(id)).collect();
717 want.sort();
718 want.dedup();
719 let Some(play) = self.simulation_play.as_ref() else { return };
720 let previous = play.hidden.clone();
721 let mut changed = false;
722 for name in previous.iter().filter(|name| !want.contains(name)) {
723 let visible = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.visible);
724 if let (Some(visible), Some(display)) = (visible, self.scene.solid_mut(name)) {
725 if display.visible != visible {
726 display.visible = visible;
727 changed = true;
728 }
729 }
730 }
731 for name in &want {
732 let Some(display) = self.scene.solid(name).cloned() else { continue };
733 if let Some(play) = self.simulation_play.as_mut() {
734 play.originals.entry(name.clone()).or_insert(display);
735 }
736 if let Some(display) = self.scene.solid_mut(name) {
737 if display.visible {
738 display.visible = false;
739 changed = true;
740 }
741 }
742 }
743 if let Some(play) = self.simulation_play.as_mut() {
744 play.hidden = want;
745 }
746 if changed {
747 self.dirty = true;
748 }
749 }
750
751 fn simulation_apply_camera(&mut self, from: &str, to: &str, t: f64) {
756 let Some(camera) = self.simulation_camera_between(from, to, t) else { return };
757 let standing = self.snapshot_camera();
758 if let Some(play) = self.simulation_play.as_mut() {
759 if play.camera_before.is_none() {
760 play.camera_before = Some(standing);
761 }
762 }
763 self.simulation_apply_pmi_camera(&camera);
764 }
765
766 pub(crate) fn simulation_camera_between(&self, from: &str, to: &str, t: f64) -> Option<PmiCamera> {
770 let state = self.pmi_state_shared();
771 let a = state.find_view(from).and_then(|v| v.camera.clone())?;
772 let b = state.find_view(to).and_then(|v| v.camera.clone())?;
773 let t = t.clamp(0.0, 1.0);
774 let lerp = |p: [f64; 3], q: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| p[i] + (q[i] - p[i]) * t) };
775 let scale_of = |camera: &PmiCamera| match camera.projection {
776 PmiProjection::Orthographic { half_height } => half_height,
777 PmiProjection::Perspective { fov_y_deg } => fov_y_deg,
778 };
779 let orthographic = |camera: &PmiCamera| matches!(camera.projection, PmiProjection::Orthographic { .. });
780 let same_kind = orthographic(&a) == orthographic(&b);
781 let (ortho, scale) = if same_kind {
782 (orthographic(&a), scale_of(&a) + (scale_of(&b) - scale_of(&a)) * t)
783 } else if t < 0.5 {
784 (orthographic(&a), scale_of(&a))
785 } else {
786 (orthographic(&b), scale_of(&b))
787 };
788 Some(PmiCamera {
789 eye: lerp(a.eye, b.eye),
790 target: lerp(a.target, b.target),
791 up: lerp(a.up, b.up),
792 projection: if ortho { PmiProjection::Orthographic { half_height: scale } } else { PmiProjection::Perspective { fov_y_deg: scale } },
793 viewport: a.viewport,
794 })
795 }
796
797 fn simulation_apply_pmi_camera(&mut self, camera: &PmiCamera) {
799 let (kind, scale) = match camera.projection {
800 PmiProjection::Orthographic { half_height } => ("orthographic", half_height),
801 PmiProjection::Perspective { fov_y_deg } => ("perspective", fov_y_deg),
802 };
803 let json = json!({ "kind": kind, "eye": camera.eye, "target": camera.target, "up": camera.up, "scale": scale }).to_string();
804 if self.apply_camera_state_json(&json).is_ok() {
805 self.controls_sync_after_camera_apply();
806 }
807 }
808
809 fn simulation_tint_clashes(&mut self, index: usize) {
814 let Some(play) = self.simulation_play.as_ref() else { return };
815 let Some(frame) = play.frames.get(index) else { return };
816 let mut want: Vec<String> = Vec::new();
817 for (a, b) in &frame.clashes {
818 for occ in [a, b] {
819 if let Some((_, solids)) = play.participants.iter().find(|(id, _)| id == occ) {
820 want.extend(solids.iter().cloned());
821 }
822 }
823 }
824 want.sort();
825 want.dedup();
826 let previous = play.tinted.clone();
827 let mut changed = false;
828 for name in previous.iter().filter(|name| !want.contains(name)) {
829 let color = self.simulation_play.as_ref().and_then(|play| play.originals.get(name)).map(|original| original.color_override);
830 if let (Some(color), Some(display)) = (color, self.scene.solid_mut(name)) {
831 if display.color_override != color {
832 display.color_override = color;
833 display.revision = crate::scene::next_revision();
834 changed = true;
835 }
836 }
837 }
838 for name in &want {
839 let Some(display) = self.scene.solid(name).cloned() else { continue };
842 if let Some(play) = self.simulation_play.as_mut() {
843 play.originals.entry(name.clone()).or_insert(display);
844 }
845 if let Some(display) = self.scene.solid_mut(name) {
846 if display.color_override != Some(CLASH_TINT) {
847 display.color_override = Some(CLASH_TINT);
848 display.revision = crate::scene::next_revision();
850 changed = true;
851 }
852 }
853 }
854 if let Some(play) = self.simulation_play.as_mut() {
855 play.tinted = want;
856 }
857 if changed {
858 self.dirty = true;
859 }
860 }
861
862 fn simulation_pose_occurrence(&mut self, id: &str, pose: Option<([f64; 16], [f64; 16])>) {
868 let names: Vec<String> = if id.contains(':') {
869 let prefix = format!("{id}:");
870 self.scene.solids().iter().filter(|solid| solid.name.starts_with(&prefix)).map(|solid| solid.name.clone()).collect()
871 } else {
872 self.member_solid_names(id)
873 };
874 let Some(play) = self.simulation_play.as_mut() else { return };
875 for name in names {
876 let Some(display) = self.scene.solid(&name) else { continue };
877 let original = play.originals.entry(name.clone()).or_insert_with(|| display.clone()).clone();
878 if let Some(display) = self.scene.solid_mut(&name) {
879 *display = original;
880 if let Some((delta, _)) = &pose {
881 pose_display_by_matrix(display, delta);
882 }
883 }
884 }
885 let nested = format!("{id}:");
886 play.applied.retain(|key, _| !key.starts_with(&nested));
887 match pose {
888 Some((_, world)) => {
889 play.applied.insert(id.to_string(), world);
890 }
891 None => {
892 play.applied.remove(id);
893 }
894 }
895 }
896
897 pub(super) fn occurrence_document_matrix(&self, id: &str) -> Option<[f64; 16]> {
901 let (top, rest) = match id.split_once(':') {
902 Some((top, rest)) => (top, Some(rest)),
903 None => (id, None),
904 };
905 let record = self.assembly_components().iter().find(|record| record.id == top)?;
906 match rest {
907 None => Some(record.transform),
908 Some(rest) => Some(mat_mul(&record.transform, record.nested_poses.get(rest)?)),
909 }
910 }
911
912 pub(crate) fn simulation_restore_displays(&mut self) {
916 let Some(play) = self.simulation_play.as_mut() else { return };
917 play.applied.clear();
918 play.tinted.clear();
919 play.hidden.clear();
920 play.translucent.clear();
921 play.sectioned.clear();
922 play.shown_sample = None;
923 let camera_before = play.camera_before.take();
924 let originals = std::mem::take(&mut play.originals);
925 if let Some(camera) = camera_before {
926 self.simulation_apply_pmi_camera(&camera);
927 }
928 let Some(play) = self.simulation_play.as_mut() else { return };
929 if let Some(shown) = play.shown.take() {
930 play.wanted.get_or_insert(shown);
931 }
932 if originals.is_empty() {
933 return;
934 }
935 for (name, original) in originals {
936 if let Some(display) = self.scene.solid_mut(&name) {
937 *display = original;
938 }
939 }
940 self.dirty = true;
941 }
942
943 pub(crate) fn simulation_after_apply(&mut self) {
947 let Some(play) = self.simulation_play.as_ref() else { return };
948 if play.revision == self.history.revision() {
949 self.simulation_show_wanted();
950 }
951 }
952
953 pub fn simulation_forget_playback(&mut self) {
956 self.simulation_restore_displays();
957 self.simulation_play = None;
958 }
959
960 pub fn simulation_playback_json(&self) -> Value {
973 let Some(play) = self.simulation_play.as_ref() else { return Value::Null };
974 let failed: Vec<usize> = play.frames.iter().enumerate().filter(|(_, frame)| frame.failed).map(|(index, _)| index).collect();
975 let poses: BTreeMap<&str, Value> = play
976 .applied
977 .iter()
978 .map(|(id, world)| (id.as_str(), brep_kernel::transform_to_pose_params(&brep_kernel::AffineTransform { elements: *world })))
979 .collect();
980 json!({
981 "study": play.study,
982 "time": play.time,
983 "playheadFrame": play.baked_study.frame_at(play.time),
984 "shown": play.shown,
985 "baked": play.frames.len(),
986 "total": play.total,
987 "playing": play.playing,
988 "looping": play.looping,
989 "failed": failed,
990 "error": play.error,
991 "poses": poses,
992 "interference": play.baked_study.interference.enabled,
993 "clashes": play.frames.iter().enumerate().filter(|(_, frame)| !frame.clashes.is_empty()).map(|(index, _)| index).collect::<Vec<usize>>(),
994 "shownClashes": play.shown.and_then(|index| play.frames.get(index)).map(|frame| frame.clashes.clone()).unwrap_or_default(),
995 "hidden": play.shown_sample.as_ref().map(|sample| sample.hidden.clone()).unwrap_or_default(),
996 "explode": play.shown_sample.as_ref().map(|sample| sample.explode.iter().map(|e| json!({ "view": e.view, "progress": e.progress })).collect::<Vec<Value>>()).unwrap_or_default(),
997 "camera": play.shown_sample.as_ref().and_then(|sample| sample.camera.as_ref()).map(|c| json!({ "from": c.from, "to": c.to, "t": c.t })),
998 "cameraHeld": play.camera_before.is_some(),
999 "opacity": play.shown_sample.as_ref().map(|sample| sample.opacity.clone()).unwrap_or_default(),
1000 "section": play.shown_sample.as_ref().and_then(|sample| sample.section.as_ref()).map(|s| json!({ "view": s.view, "offset": s.offset })),
1001 })
1002 }
1003}
1004
1005pub(super) use crate::geometry3d::mat4_mul_row_major as mat_mul;
1007
1008pub(super) use crate::geometry3d::mat4_rigid_inverse as rigid_inverse;
1010
1011pub(super) fn same_matrix(a: &[f64; 16], b: &[f64; 16]) -> bool {
1013 a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-9)
1014}
1015
1016use crate::view::mat4_mul_column_major;
1018
1019fn pose_display_by_matrix(display: &mut SolidDisplay, m: &[f64; 16]) {
1024 let column_major: [f32; 16] = std::array::from_fn(|k| {
1025 let (col, row) = (k / 4, k % 4);
1026 m[row * 4 + col] as f32
1027 });
1028 display.pose = if display.shape_revision == 0 {
1029 Some(column_major)
1030 } else {
1031 display.pose.map(|before| mat4_mul_column_major(&column_major, &before))
1032 };
1033 if display.shape_revision == 0 {
1034 display.shape_revision = display.revision;
1035 }
1036 display.revision = crate::scene::next_revision();
1037 let point = |p: [f64; 3]| -> [f64; 3] {
1038 std::array::from_fn(|i| m[i * 4] * p[0] + m[i * 4 + 1] * p[1] + m[i * 4 + 2] * p[2] + m[i * 4 + 3])
1039 };
1040 let vector = |v: [f64; 3]| -> [f64; 3] { std::array::from_fn(|i| m[i * 4] * v[0] + m[i * 4 + 1] * v[1] + m[i * 4 + 2] * v[2]) };
1041 let mut bbox = crate::camera::Aabb::empty();
1042 for position in &mut display.mesh.positions {
1043 let posed = point(position.map(f64::from));
1044 *position = posed.map(|v| v as f32);
1045 bbox.expand(posed);
1046 }
1047 for normal in &mut display.mesh.normals {
1048 let rotated = vector(normal.map(f64::from));
1049 let length = rotated.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-20);
1050 *normal = rotated.map(|v| (v / length) as f32);
1051 }
1052 for edge in &mut display.edges {
1053 for p in &mut edge.polyline {
1054 let posed = point(p.map(f64::from));
1055 *p = posed.map(|v| v as f32);
1056 bbox.expand(posed);
1057 }
1058 }
1059 for vertex in &mut display.vertices {
1060 vertex.position = point(vertex.position);
1061 bbox.expand(vertex.position);
1062 }
1063 if !bbox.is_empty() {
1064 display.bbox = bbox;
1065 }
1066}