1use crate::ui_kit;
21use crate::automation::hit_keys::HitKeyDoc;
22use crate::form_view::{form_view, FormViewSpec};
23use brep_render::engine_state::{EngineState, MotorMate, RefSelectField, RefSelectTarget};
24use brep_render::features::form_fields_from_schema;
25use brep_simulation::forms::{self, FormChoices, MateChoice};
26use brep_simulation::model::{Clip, ClipBody, Drive, Study, FPS_RANGE, MAX_DURATION};
27use serde_json::{json, Value};
28use std::collections::{HashMap, HashSet};
29
30const DIALOG_HOVER_OWNER: &str = "simulation";
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum SimulationRequest {
36 NewStudy,
37 AddMotor,
38}
39
40const RULER_HEIGHT: f32 = 22.0;
42
43#[derive(Debug, Clone, PartialEq)]
46pub struct ExportRequest {
47 pub study: String,
48 pub format: String,
50 pub width: u32,
51 pub height: u32,
52 pub fps: u32,
53 pub path: String,
54}
55
56#[derive(Default)]
57pub struct SimulationPanel {
58 hits: HashMap<String, egui::Rect>,
59 request: Option<SimulationRequest>,
60 notice: Option<String>,
61 error: Option<String>,
62 in_workbench: bool,
64 export_format: String,
67 export_width: u32,
68 export_height: u32,
69 export_fps: u32,
70 export_path: String,
71 export: Option<ExportRequest>,
73 open: Option<String>,
76 hover: Option<String>,
78}
79
80enum Change {
82 Activate(String),
83 NewStudy,
84 AddMotor { study: String, mate: Option<String> },
85 Remove { study: String, item: Option<String> },
86 Patch { study: String, item: Option<String>, patch: Value, coalesce: Option<String> },
87 Play { study: String },
88 Pause,
89 Stop,
90 Loop { study: String, looping: bool },
91 Seek { study: String, time: f64 },
92 AddClip { study: String, kind: String },
93 Publish { study: String },
96 Open(Option<String>),
98 BeginRefSelect { clip: String, path: Vec<String>, label: String, filter: Vec<String>, multiple: bool, seed: Vec<String> },
100 FinishRefSelect,
102 RefSelectRemove(usize),
104}
105
106const CLIP_KINDS: [(&str, &str); 6] = [("suppress", "Disable a mate"), ("visibility", "Hide parts"), ("transparency", "Fade parts"), ("camera", "Camera path"), ("section", "Section"), ("explode", "Exploded view")];
108
109impl SimulationPanel {
110 pub fn new() -> Self {
111 Self::default()
112 }
113
114 pub fn request(&mut self, request: SimulationRequest) {
116 self.request = Some(request);
117 }
118
119 pub fn take_export(&mut self) -> Option<ExportRequest> {
122 self.export.take()
123 }
124
125 pub fn report(&mut self, result: Result<String, String>) {
127 match result {
128 Ok(notice) => {
129 self.notice = Some(notice);
130 self.error = None;
131 }
132 Err(error) => self.error = Some(error),
133 }
134 }
135
136 fn left_workbench(&mut self, in_workbench: bool) -> bool {
140 let left = self.in_workbench && !in_workbench;
141 self.in_workbench = in_workbench;
142 left
143 }
144
145 pub fn drive_playback(&mut self, engine: &mut EngineState, pane_shown: bool, dt: f64) -> bool {
157 if self.left_workbench(pane_shown) && engine.simulation_playing_or_shown() {
158 engine.simulation_stop();
159 }
160 pane_shown && engine.simulation_tick(dt)
161 }
162
163 pub fn hits_json(&self) -> String {
164 crate::automation::hit_rects::hits_json(&self.hits)
165 }
166
167 pub fn clear_hits(&mut self) {
170 self.hits.clear();
171 }
172
173 pub fn state_json(&self) -> String {
176 json!({ "notice": self.notice, "error": self.error, "open": self.open }).to_string()
177 }
178
179 pub fn show(&mut self, ui: &mut egui::Ui, engine: &mut EngineState) {
180 self.hits.clear();
181 self.hits.insert("panel:clip".into(), ui.clip_rect());
182 if !engine.simulation_available() {
183 ui.label("Open an assembly: a study drives its distance and angle mates as motors.");
184 return;
185 }
186 if let Some(request) = self.request.take() {
187 let study = engine.simulation().ok().flatten().and_then(|b| b.active_study().map(|s| s.id.clone()));
188 let change = match request {
189 SimulationRequest::NewStudy => Change::NewStudy,
190 SimulationRequest::AddMotor => Change::AddMotor { study: study.unwrap_or_default(), mate: None },
191 };
192 self.apply(change, engine);
193 }
194 let block = match engine.simulation() {
195 Ok(block) => block.unwrap_or_default(),
196 Err(error) => {
197 ui.colored_label(ui.visuals().error_fg_color, format!("The studies cannot be read: {error}"));
198 return;
199 }
200 };
201 if let Some(error) = &self.error {
202 let label = ui.colored_label(ui.visuals().error_fg_color, error);
203 self.hits.insert("simulation:error".into(), label.rect);
204 }
205 if let Some(notice) = &self.notice {
206 let label = ui.weak(notice);
207 self.hits.insert("simulation:notice".into(), label.rect);
208 }
209 let mut change = None;
210 let active = block.active_study().map(|s| s.id.clone());
211 ui.horizontal_wrapped(|ui| {
212 ui.label("Studies");
213 for study in &block.studies {
214 let row = ui.selectable_label(active.as_deref() == Some(study.id.as_str()), crate::theme::data(&study.name));
215 self.hits.insert(format!("simulation:study:{}", study.id), row.rect);
216 if row.clicked() && active.as_deref() != Some(study.id.as_str()) {
217 change = Some(Change::Activate(study.id.clone()));
218 }
219 }
220 let new = ui.add(ui_kit::Button::new("+ Study"));
221 self.hits.insert("simulation:new_study".into(), new.rect);
222 if new.clicked() {
223 change = Some(Change::NewStudy);
224 }
225 });
226 let Some(study) = block.active_study() else {
227 ui.weak("No study yet: + Study (or New study on the toolbar) starts one.");
228 if let Some(change) = change {
229 self.apply(change, engine);
230 }
231 return;
232 };
233 ui.separator();
234 self.study_fields(ui, study, &mut change);
235 let playback = engine.simulation_playback_json();
236 self.transport(ui, study, &playback, &mut change);
237 self.ruler(ui, study, &playback, &mut change);
238 ui.separator();
239 let mates = engine.simulation_motor_mates();
240 let pmi = engine.pmi_state();
241 let choices = FormChoices {
242 mates: mates.iter().map(|m| MateChoice { id: m.id.clone(), kind: m.kind.clone(), value: m.value }).collect(),
243 constraints: engine.simulation_constraint_ids(),
244 camera_views: pmi.views.iter().filter(|v| v.camera.is_some()).map(|v| v.id.clone()).collect(),
245 section_views: pmi.views.iter().filter(|v| v.display.section.is_some()).map(|v| v.id.clone()).collect(),
246 exploded_views: engine.exploded_views().into_iter().map(|v| v.id).collect(),
247 };
248 if self.open.as_deref().is_some_and(|id| !study.motors.iter().any(|m| m.id == id) && !study.clips.iter().any(|c| c.id == id)) {
250 self.open = None;
251 }
252 self.hover = None;
253 match self.open.clone() {
254 Some(open) => {
255 let picking = engine.ref_select_field().filter(|f| f.target == RefSelectTarget::Simulation && f.subject == open);
258 self.item_form(ui, study, &open, &choices, picking.as_ref(), &mut change);
259 }
260 None => {
261 self.motors(ui, study, &mates, &mut change);
262 ui.separator();
263 self.clips(ui, study, &mut change);
264 }
265 }
266 ui.separator();
267 self.export_row(ui, study);
268 if let Some(change) = change {
269 self.apply(change, engine);
270 }
271 if let Some(field) = engine.ref_select_field() {
274 if field.target == RefSelectTarget::Simulation && self.open.as_deref() == Some(field.subject.as_str()) {
275 engine.ref_select_claim();
276 }
277 }
278 let hover_changed = match &self.hover {
280 Some(name) => engine.hover_entity_by_name(DIALOG_HOVER_OWNER, name),
281 None => engine.dialog_hover_end(DIALOG_HOVER_OWNER),
282 };
283 if hover_changed {
284 ui.ctx().request_repaint();
285 }
286 }
287
288 fn export_row(&mut self, ui: &mut egui::Ui, study: &Study) {
291 if self.export_format.is_empty() {
292 self.export_format = "gif".into();
293 }
294 if self.export_width == 0 || self.export_height == 0 {
295 (self.export_width, self.export_height) = (960, 540);
296 }
297 if self.export_fps == 0 {
298 self.export_fps = study.fps;
299 }
300 ui.strong("Export");
301 ui.horizontal_wrapped(|ui| {
302 let mut format = self.export_format.clone();
303 let choices = [("gif".to_string(), "gif", "GIF"), ("mp4".to_string(), "mp4", "MP4"), ("html".to_string(), "html", "HTML")];
304 crate::form::enum_dropdown(ui, "simulation:export:format", &choices, &mut format, None, Some(&mut self.hits));
305 if format != self.export_format {
306 if self.export_path.ends_with(&format!(".{}", self.export_format)) {
308 self.export_path = format!("{}.{format}", self.export_path.trim_end_matches(&format!(".{}", self.export_format)));
309 }
310 self.export_format = format;
311 }
312 for (label, value, key) in [("width", &mut self.export_width, "simulation:export:width"), ("height", &mut self.export_height, "simulation:export:height")] {
313 ui.label(label);
314 let drag = ui.add(egui::DragValue::new(value).range(16..=4096).speed(8));
315 self.hits.insert(key.into(), drag.rect);
316 }
317 ui.label("fps");
318 let drag = ui.add(egui::DragValue::new(&mut self.export_fps).range(1..=120));
319 self.hits.insert("simulation:export:fps".into(), drag.rect);
320 });
321 ui.horizontal_wrapped(|ui| {
322 if self.export_path.is_empty() {
323 self.export_path = format!("{}.{}", study.name.trim().replace(' ', "-"), self.export_format);
324 }
325 ui.label("file");
326 let field = ui.add(egui::TextEdit::singleline(&mut self.export_path).desired_width(220.0));
327 self.hits.insert("simulation:export:path".into(), field.rect);
328 let run = ui.add(ui_kit::Button::new("Export"));
329 self.hits.insert("simulation:export:run".into(), run.rect);
330 if run.clicked() {
331 self.export = Some(ExportRequest {
332 study: study.id.clone(),
333 format: self.export_format.clone(),
334 width: self.export_width,
335 height: self.export_height,
336 fps: self.export_fps,
337 path: self.export_path.clone(),
338 });
339 self.notice = Some("Exporting…".into());
340 self.error = None;
341 }
342 });
343 }
344
345 fn clips(&mut self, ui: &mut egui::Ui, study: &Study, change: &mut Option<Change>) {
348 ui.strong("Clips");
349 if study.clips.is_empty() {
350 ui.weak("None: + Clip disables a mate, hides or fades parts, moves the camera, cuts a section or plays an exploded view over a span.");
351 }
352 for clip in &study.clips {
353 let key = format!("simulation:clip:{}", clip.id);
354 ui.horizontal_wrapped(|ui| {
355 let row = ui.selectable_label(false, crate::theme::data(clip_label(clip))).on_hover_text("Open the clip's fields");
356 self.hits.insert(key.clone(), row.rect);
357 if row.clicked() {
358 *change = Some(Change::Open(Some(clip.id.clone())));
359 }
360 ui.label(crate::theme::data(format!("{:.2}–{:.2} s", clip.from, clip.to)).weak());
361 let remove = ui.add(ui_kit::Button::new("Remove"));
362 self.hits.insert(format!("{key}:remove"), remove.rect);
363 if remove.clicked() {
364 *change = Some(Change::Remove { study: study.id.clone(), item: Some(clip.id.clone()) });
365 }
366 });
367 }
368 let mut kind = String::new();
369 let combo = egui::ComboBox::from_id_salt("simulation-add-clip").selected_text("+ Clip").show_ui(ui, |ui| {
370 for (id, label) in CLIP_KINDS {
371 let option = ui.selectable_value(&mut kind, id.to_string(), label);
372 self.hits.insert(format!("simulation:menuitem:clip_kind:{id}"), option.rect);
373 }
374 });
375 self.hits.insert("simulation:add_clip".into(), combo.response.rect);
376 if !kind.is_empty() {
377 *change = Some(Change::AddClip { study: study.id.clone(), kind });
378 }
379 }
380
381 fn item_form(&mut self, ui: &mut egui::Ui, study: &Study, open: &str, choices: &FormChoices, picking: Option<&RefSelectField>, change: &mut Option<Change>) {
386 let motor = study.motors.iter().find(|m| m.id == open);
387 let clip = study.clips.iter().find(|c| c.id == open);
388 let (title, subtitle, schema, mut params, hidden) = match (motor, clip) {
389 (Some(motor), _) => {
390 let params = forms::motor_params(motor);
391 let mate = choices.mates.iter().find(|m| m.id == motor.constraint).map_or_else(|| motor.constraint.clone(), |m| format!("{} ({})", m.id, m.kind));
392 (format!("Motor {}", motor.id), mate, forms::motor_schema(motor, choices), params.clone(), forms::motor_hidden(¶ms))
393 }
394 (None, Some(clip)) => {
395 let params = forms::clip_params(clip);
396 (format!("Clip {}", clip.id), forms::clip_title(clip).to_string(), forms::clip_schema(clip, choices), params.clone(), forms::clip_hidden(clip, ¶ms))
397 }
398 (None, None) => return,
399 };
400 let fields = form_fields_from_schema(&schema);
401 let hidden: HashSet<String> = hidden.into_iter().collect();
402 let spec = FormViewSpec {
403 title: &title,
404 subtitle: Some(subtitle.as_str()),
405 fields: &fields,
406 hidden: Some(&hidden),
407 banner: None,
408 trailing: None,
409 exit_label: "Return to list",
410 extra: None,
411 rollback: false,
412 hits_prefix: "simulation:item:",
413 read_only: None,
414 picking: picking.map(|f| crate::form::ActivePick { path: &f.path, names: &f.names }),
415 };
416 let before = params.clone();
417 let out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
418 self.hover = out.hovered_entity;
419 if let Some(activate) = out.ref_activate {
420 *change = Some(Change::BeginRefSelect { clip: open.to_string(), path: activate.path, label: activate.label, filter: activate.filter, multiple: activate.multiple, seed: activate.seed });
421 }
422 if let Some(index) = out.pick_remove {
423 *change = Some(Change::RefSelectRemove(index));
424 }
425 if out.pick_done {
426 *change = Some(Change::FinishRefSelect);
427 }
428 if out.exit_clicked {
429 *change = Some(Change::Open(None));
430 }
431 if out.changed {
432 let field = params
434 .as_object()
435 .into_iter()
436 .flatten()
437 .find(|(key, value)| before.get(key.as_str()) != Some(value))
438 .map(|(key, _)| key.clone())
439 .unwrap_or_default();
440 let patch = match (motor, clip) {
441 (Some(_), _) => forms::motor_patch(¶ms, choices),
442 (None, Some(clip)) => forms::clip_patch(clip, ¶ms),
443 (None, None) => return,
444 };
445 match patch {
446 Ok(patch) => *change = Some(Change::Patch { study: study.id.clone(), item: Some(open.to_string()), patch, coalesce: Some(format!("simulation:{}:{open}:{field}", study.id)) }),
447 Err(error) => self.error = Some(error),
448 }
449 }
450 }
451
452 fn study_fields(&mut self, ui: &mut egui::Ui, study: &Study, change: &mut Option<Change>) {
454 let id = study.id.clone();
455 ui.horizontal_wrapped(|ui| {
456 let mut name = study.name.clone();
457 let field = ui.add(egui::TextEdit::singleline(&mut name).desired_width(140.0));
458 self.hits.insert("simulation:field:name".into(), field.rect);
459 if field.changed() && !name.trim().is_empty() {
460 *change = Some(patch(&id, None, "name", json!(name.trim()), "name"));
461 }
462 ui.label("Duration");
463 let mut duration = study.duration;
464 let field = ui.add(egui::DragValue::new(&mut duration).range(0.1..=MAX_DURATION).speed(0.1).suffix(" s"));
465 self.hits.insert("simulation:field:duration".into(), field.rect);
466 if field.changed() {
467 *change = Some(patch(&id, None, "duration", json!(duration), "duration"));
468 }
469 let mut fps = study.fps;
470 let field = ui.add(egui::DragValue::new(&mut fps).range(*FPS_RANGE.start()..=*FPS_RANGE.end()).suffix(" fps"));
471 self.hits.insert("simulation:field:fps".into(), field.rect);
472 if field.changed() {
473 *change = Some(patch(&id, None, "fps", json!(fps), "fps"));
474 }
475 let delete = ui.add(ui_kit::Button::danger("Delete study"));
476 self.hits.insert("simulation:delete_study".into(), delete.rect);
477 if delete.clicked() {
478 *change = Some(Change::Remove { study: id.clone(), item: None });
479 }
480 });
481 }
482
483 fn transport(&mut self, ui: &mut egui::Ui, study: &Study, playback: &Value, change: &mut Option<Change>) {
485 let this_study = playback["study"].as_str() == Some(study.id.as_str());
486 let playing = this_study && playback["playing"] == true;
487 let looping = this_study && playback["looping"] == true;
488 let time = if this_study { playback["time"].as_f64().unwrap_or(0.0) } else { 0.0 };
489 ui.horizontal_wrapped(|ui| {
490 let play = ui.add(ui_kit::Button::new(if playing { "Pause" } else { "▶ Play" }));
491 self.hits.insert("simulation:play".into(), play.rect);
492 if play.clicked() {
493 *change = Some(if playing { Change::Pause } else { Change::Play { study: study.id.clone() } });
494 }
495 let stop = ui_kit::button::add_enabled(ui, this_study, ui_kit::Button::new("■ Stop"));
496 self.hits.insert("simulation:stop".into(), stop.rect);
497 if stop.clicked() {
498 *change = Some(Change::Stop);
499 }
500 let loop_button = ui.selectable_label(looping, "Loop");
501 self.hits.insert("simulation:loop".into(), loop_button.rect);
502 if loop_button.clicked() {
503 *change = Some(Change::Loop { study: study.id.clone(), looping: !looping });
504 }
505 let publish = ui.add(ui_kit::Button::new(if study.motion.is_some() { "Publish again" } else { "Publish" }))
506 .on_hover_text("Bake the study to the end and keep its motion with the assembly, for a manufacturing-instructions step to play");
507 self.hits.insert("simulation:publish".into(), publish.rect);
508 if publish.clicked() {
509 *change = Some(Change::Publish { study: study.id.clone() });
510 }
511 let frame = study.frame_at(time);
512 let readout = ui.monospace(format!("{time:.2} s frame {frame}/{}", study.frame_count().saturating_sub(1)));
513 self.hits.insert("simulation:time".into(), readout.rect);
514 if this_study {
515 let (baked, total) = (playback["baked"].as_f64().unwrap_or(0.0), playback["total"].as_f64().unwrap_or(1.0).max(1.0));
516 if baked < total {
517 let bar = ui.add(egui::ProgressBar::new((baked / total) as f32).desired_width(90.0).text(format!("baking {baked:.0}/{total:.0}")));
518 self.hits.insert("simulation:bake".into(), bar.rect);
519 }
520 if let Some(error) = playback["error"].as_str() {
521 let failed = playback["failed"].as_array().map_or(0, Vec::len);
522 let label = ui.colored_label(ui.visuals().warn_fg_color, format!("{failed} frame(s) the mates could not hold: {error}"));
523 self.hits.insert("simulation:failed".into(), label.rect);
524 }
525 }
526 let mut check = study.interference.enabled;
527 let box_ = ui_kit::checkbox(ui, &mut check, "Interference");
528 self.hits.insert("simulation:field:interference".into(), box_.rect);
529 if box_.changed() {
530 *change = Some(patch(&study.id, None, "interference", json!({ "enabled": check }), ""));
531 }
532 if this_study {
533 let clashing = playback["clashes"].as_array().map_or(0, Vec::len);
534 if clashing > 0 {
535 let shown: Vec<String> = playback["shownClashes"]
536 .as_array()
537 .into_iter()
538 .flatten()
539 .filter_map(|pair| Some(format!("{} ↔ {}", pair.get(0)?.as_str()?, pair.get(1)?.as_str()?)))
540 .collect();
541 let text = if shown.is_empty() {
542 format!("{clashing} frame(s) with interference")
543 } else {
544 format!("{clashing} frame(s) with interference; here: {}", shown.join(", "))
545 };
546 let label = ui.colored_label(ui.visuals().error_fg_color, text);
547 self.hits.insert("simulation:interference".into(), label.rect);
548 }
549 }
550 });
551 }
552
553 fn ruler(&mut self, ui: &mut egui::Ui, study: &Study, playback: &Value, change: &mut Option<Change>) {
559 let width = ui.available_width().max(120.0);
560 let (rect, response) = ui.allocate_exact_size(egui::vec2(width, RULER_HEIGHT), egui::Sense::click_and_drag());
561 self.hits.insert("simulation:ruler".into(), rect);
562 let painter = ui.painter_at(rect);
563 let visuals = ui.visuals();
564 let stroke = visuals.widgets.noninteractive.fg_stroke;
565 let x_of = |t: f64| rect.left() + rect.width() * (t / study.duration) as f32;
566 let this_study = playback["study"].as_str() == Some(study.id.as_str());
567 if this_study {
568 let baked = playback["baked"].as_u64().unwrap_or(0) as usize;
569 if baked > 0 {
570 let baked_to = study.frame_time(baked - 1);
571 painter.rect_filled(egui::Rect::from_min_max(rect.left_top(), egui::pos2(x_of(baked_to), rect.bottom())), 0.0, visuals.faint_bg_color);
572 }
573 for index in playback["clashes"].as_array().into_iter().flatten().filter_map(Value::as_u64) {
574 let x = x_of(study.frame_time(index as usize));
575 painter.line_segment([egui::pos2(x, rect.top() + 10.0), egui::pos2(x, rect.bottom())], egui::Stroke::new(2.0, visuals.error_fg_color));
576 }
577 for index in playback["failed"].as_array().into_iter().flatten().filter_map(Value::as_u64) {
578 let x = x_of(study.frame_time(index as usize));
579 painter.line_segment([egui::pos2(x, rect.top() + 4.0), egui::pos2(x, rect.bottom())], egui::Stroke::new(2.0, visuals.warn_fg_color));
580 }
581 }
582 painter.line_segment([rect.left_bottom(), rect.right_bottom()], stroke);
583 let step = if study.duration > 30.0 { 10.0 } else { 1.0 };
584 let mut t = 0.0;
585 while t <= study.duration + 1e-9 {
586 let x = x_of(t);
587 painter.line_segment([egui::pos2(x, rect.bottom() - 6.0), egui::pos2(x, rect.bottom())], stroke);
588 painter.text(egui::pos2(x + 2.0, rect.top()), egui::Align2::LEFT_TOP, format!("{t:.0}s"), egui::FontId::proportional(10.0), stroke.color);
589 t += step;
590 }
591 if this_study {
592 let x = x_of(playback["time"].as_f64().unwrap_or(0.0));
593 painter.line_segment([egui::pos2(x, rect.top()), egui::pos2(x, rect.bottom())], egui::Stroke::new(2.0, visuals.selection.stroke.color));
594 }
595 if response.is_pointer_button_down_on() || response.dragged() || response.clicked() {
596 if let Some(pointer) = response.interact_pointer_pos() {
597 let u = ((pointer.x - rect.left()) / rect.width()).clamp(0.0, 1.0) as f64;
598 *change = Some(Change::Seek { study: study.id.clone(), time: u * study.duration });
599 }
600 }
601 ui.weak(format!("{} frames at {} fps", study.frame_count(), study.fps));
602 }
603
604 fn motors(&mut self, ui: &mut egui::Ui, study: &Study, mates: &[MotorMate], change: &mut Option<Change>) {
607 ui.strong("Motors");
608 if study.motors.is_empty() {
609 ui.weak("None: + Motor drives a distance or angle mate.");
610 }
611 for motor in &study.motors {
612 let key = format!("simulation:motor:{}", motor.id);
613 let mate = mates.iter().find(|m| m.id == motor.constraint);
614 let unit = mate.map_or("/s", |m| m.rate_unit());
615 let label = match (&motor.drive, mate) {
616 (Drive::Speed { speed }, Some(m)) => format!("{} ({}) at {speed} {unit}", m.id, m.kind),
617 (Drive::Speed { speed }, None) => format!("{} (missing) at {speed} {unit}", motor.constraint),
618 (Drive::Profile { start, end, .. }, Some(m)) => format!("{} ({}) {start} → {end} {}", m.id, m.kind, unit.trim_end_matches("/s")),
619 (Drive::Profile { start, end, .. }, None) => format!("{} (missing) {start} → {end}", motor.constraint),
620 };
621 ui.horizontal_wrapped(|ui| {
622 let row = ui.selectable_label(false, crate::theme::data(label)).on_hover_text("Open the motor's fields");
623 self.hits.insert(key.clone(), row.rect);
624 if row.clicked() {
625 *change = Some(Change::Open(Some(motor.id.clone())));
626 }
627 ui.label(crate::theme::data(format!("{:.2}–{:.2} s", motor.from, motor.to)).weak());
628 let remove = ui.add(ui_kit::Button::new("Remove"));
629 self.hits.insert(format!("{key}:remove"), remove.rect);
630 if remove.clicked() {
631 *change = Some(Change::Remove { study: study.id.clone(), item: Some(motor.id.clone()) });
632 }
633 });
634 }
635 let add = ui_kit::button::add_enabled(ui, !mates.is_empty(), ui_kit::Button::new("+ Motor"));
636 self.hits.insert("simulation:add_motor".into(), add.rect);
637 if add.clicked() {
638 *change = Some(Change::AddMotor { study: study.id.clone(), mate: None });
639 }
640 }
641
642 fn apply(&mut self, change: Change, engine: &mut EngineState) {
643 self.notice = None;
644 self.error = None;
645 let result = match change {
646 Change::Activate(id) => engine.simulation_set_active(&id).map(|()| None),
647 Change::NewStudy => engine.simulation_add_study("").map(|id| Some(format!("New study {id}"))),
648 Change::AddMotor { study, mate } => {
649 let study = (!study.is_empty()).then_some(study);
650 engine.simulation_add_motor(study.as_deref(), mate.as_deref()).map(|(_, id)| {
651 self.open = Some(id.clone());
652 Some(format!("Motor {id} added"))
653 })
654 }
655 Change::Remove { study, item } => {
656 if item.is_some() && item == self.open && engine.ref_select_field().is_some_and(|f| f.target == RefSelectTarget::Simulation) {
658 engine.cancel_ref_select();
659 }
660 engine.simulation_remove(&study, item.as_deref()).map(|()| None)
661 }
662 Change::Patch { study, item, patch, coalesce } => engine.simulation_patch(&study, item.as_deref(), &patch, coalesce.as_deref()).map(|()| None),
663 Change::Play { study } => engine.simulation_play(Some(&study), None).map(|_| None),
664 Change::Pause => {
665 engine.simulation_pause();
666 Ok(None)
667 }
668 Change::Stop => {
669 engine.simulation_stop();
670 Ok(None)
671 }
672 Change::Loop { study, looping } => engine.simulation_set_looping(Some(&study), looping).map(|()| None),
673 Change::Seek { study, time } => engine.simulation_seek(Some(&study), time).map(|()| None),
674 Change::AddClip { study, kind } => engine.simulation_add_clip(Some(&study), &kind, None).map(|(_, id)| {
675 self.open = Some(id.clone());
676 Some(format!("Clip {id} added"))
677 }),
678 Change::Publish { study } => engine.simulation_publish(Some(&study)).map(|(_, frames)| Some(format!("Published: {frames} frames kept with the assembly"))),
679 Change::Open(item) => {
680 if item.is_none() && engine.ref_select_field().is_some_and(|f| f.target == RefSelectTarget::Simulation) {
682 engine.finish_ref_select();
683 }
684 self.open = item;
685 Ok(None)
686 }
687 Change::BeginRefSelect { clip, path, label, filter, multiple, seed } => {
688 if engine.ref_select_active() {
691 engine.finish_ref_select();
692 }
693 engine.begin_ref_select_for_simulation(&clip, path, label, filter, multiple, seed);
694 Ok(None)
695 }
696 Change::FinishRefSelect => {
697 engine.finish_ref_select();
698 Ok(None)
699 }
700 Change::RefSelectRemove(index) => {
701 engine.ref_select_remove(index);
702 Ok(None)
703 }
704 };
705 match result {
706 Ok(notice) => self.notice = notice,
707 Err(error) => self.error = Some(error),
708 }
709 }
710}
711
712fn clip_label(clip: &Clip) -> String {
714 match &clip.body {
715 ClipBody::Suppress { constraint } => format!("Disable {constraint}"),
716 ClipBody::Camera { views } => format!("Camera ({})", crate::panels::count(views.len(), "view", "views")),
717 ClipBody::Visibility { occurrences } => format!("Hide ({})", crate::panels::count(occurrences.len(), "part", "parts")),
718 ClipBody::Transparency { occurrences, .. } => format!("Transparency ({})", crate::panels::count(occurrences.len(), "part", "parts")),
719 ClipBody::Section { view, .. } => format!("Section {view}"),
720 ClipBody::Explode { collapse, .. } => if *collapse { "Collapse".to_string() } else { "Explode".to_string() },
721 }
722}
723
724fn patch(study: &str, item: Option<&str>, key: &str, value: Value, field: &str) -> Change {
726 let mut fields = serde_json::Map::new();
727 fields.insert(key.to_string(), value);
728 Change::Patch {
729 study: study.to_string(),
730 item: item.map(str::to_string),
731 patch: Value::Object(fields),
732 coalesce: (!field.is_empty()).then(|| format!("simulation:{study}:{field}")),
733 }
734}
735
736pub static HIT_KEYS: &[HitKeyDoc] = &[
737 HitKeyDoc { panel: "simulation", prefix: "panel:clip", meaning: "the visible region of the pane (scroll_into_view scrolls a simulation:* widget inside it)", command: None },
738 HitKeyDoc { panel: "simulation", prefix: "simulation:error", meaning: "why the last action was refused", command: None },
739 HitKeyDoc { panel: "simulation", prefix: "simulation:notice", meaning: "what the last action did", command: None },
740 HitKeyDoc { panel: "simulation", prefix: "simulation:study:", meaning: "a study's row, by study id: make it the active one", command: Some("simulation_update") },
741 HitKeyDoc { panel: "simulation", prefix: "simulation:new_study", meaning: "+ Study: a new study, made active", command: Some("simulation_new_study") },
742 HitKeyDoc { panel: "simulation", prefix: "simulation:delete_study", meaning: "delete the active study", command: Some("simulation_remove") },
743 HitKeyDoc { panel: "simulation", prefix: "simulation:field:", meaning: "the active study's name, duration and fps fields, and the Interference checkbox (check every frame for parts that collide)", command: Some("simulation_update") },
744 HitKeyDoc { panel: "simulation", prefix: "simulation:interference", meaning: "how many baked frames have interfering parts, and which pairs clash at the shown frame", command: Some("simulation_playback") },
745 HitKeyDoc { panel: "simulation", prefix: "simulation:play", meaning: "Play the active study from its playhead, or Pause while it plays", command: Some("simulation_play") },
746 HitKeyDoc { panel: "simulation", prefix: "simulation:stop", meaning: "Stop: every part back at its document pose, the playhead at 0", command: Some("simulation_stop") },
747 HitKeyDoc { panel: "simulation", prefix: "simulation:loop", meaning: "Loop: repeat the study at its end", command: Some("simulation_play") },
748 HitKeyDoc { panel: "simulation", prefix: "simulation:time", meaning: "the playhead's time and frame", command: Some("simulation_playback") },
749 HitKeyDoc { panel: "simulation", prefix: "simulation:bake", meaning: "the bake's progress bar, while frames are still being solved", command: Some("simulation_playback") },
750 HitKeyDoc { panel: "simulation", prefix: "simulation:failed", meaning: "how many frames the mates could not hold, and the last reason", command: Some("simulation_playback") },
751 HitKeyDoc { panel: "simulation", prefix: "simulation:ruler", meaning: "the active study's time ruler (red marks: frames with interference; amber: frames the mates could not hold): press or drag on it to scrub to a time", command: Some("simulation_seek") },
752 HitKeyDoc { panel: "simulation", prefix: "simulation:motor:", meaning: "a motor's row, by motor id: its label (the mate and the drive; click opens the motor's form) and remove", command: Some("simulation_update") },
753 HitKeyDoc { panel: "simulation", prefix: "simulation:add_motor", meaning: "+ Motor: a motor on the first distance or angle mate, the whole study long; its form opens", command: Some("simulation_add_motor") },
754 HitKeyDoc { panel: "simulation", prefix: "simulation:clip:", meaning: "a clip's row, by clip id: its label (click opens the clip's form) and remove", command: Some("simulation_update") },
755 HitKeyDoc { panel: "simulation", prefix: "simulation:add_clip", meaning: "+ Clip: the menu of clip kinds (suppress = Disable a mate, visibility, transparency, camera, section, explode), each added over the whole study on its natural target; its form opens", command: Some("simulation_add_clip") },
756 HitKeyDoc { panel: "simulation", prefix: "simulation:menuitem:clip_kind:", meaning: "+ Clip's entries, by kind", command: Some("simulation_add_clip") },
757 HitKeyDoc { panel: "simulation", prefix: "simulation:item:", meaning: "the open motor's or clip's form (the app's schema-driven dialog): form:feature (the title), form:return (back to the rows), field:<key> (a motor: constraint, from, to, mode, speed, shape, start, end, accel; a clip: from, to, and by kind constraint | occurrences | opacityFrom, opacityTo | view1..view4 | view, sweepEnabled, sweepFrom, sweepTo | view, collapse), field:<key>#<variant> (an open option menu's entries), field:occurrences#activate (Select, or Done while the pick runs), #line<i> and #x<i> (a picked part and its remove)", command: Some("simulation_update") },
758 HitKeyDoc { panel: "simulation", prefix: "simulation:publish", meaning: "Publish (or Publish again): bake the study to the end and write its motion into the assembly's simulation block, for a manufacturing-instructions step to attach", command: Some("simulation_publish") },
759 HitKeyDoc { panel: "simulation", prefix: "simulation:export:", meaning: "the Export row: format (GIF | MP4 | HTML), width, height, fps, the file path and run (a video renders every baked frame at that size; HTML writes the interactive player page)", command: Some("simulation_export") },
760 HitKeyDoc { panel: "simulation", prefix: "simulation:export:format#", meaning: "the export format dropdown's entries while open (#gif, #mp4, #html)", command: Some("simulation_export") },
761];
762
763pub fn state_json(engine: &EngineState, panel: &SimulationPanel) -> String {
765 let mut state = engine.simulation_state_json();
766 state["playback"] = engine.simulation_playback_json();
767 state["pane"] = serde_json::from_str(&panel.state_json()).unwrap_or(Value::Null);
768 state.to_string()
769}
770