1use super::{Document, Documents};
32use brep_render::{brep_kernel, camera::Aabb, engine_state::EngineState, scene::RenderScene};
33use serde_json::Value;
34
35type Matrix = [f64; 16];
36const IDENTITY: Matrix = [
37 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.,
38];
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum WorkPartMode {
43 InPlace,
45 NewTab,
47}
48
49pub(super) fn entry_at<'a>(document: &'a Value, names: &[String]) -> Option<&'a Value> {
51 let (last, parents) = names.split_last()?;
52 let mut owner = document;
53 for name in parents {
54 owner = &owner["partsLibrary"][name]["document"];
55 }
56 let entry = &owner["partsLibrary"][last];
57 entry.is_object().then_some(entry)
58}
59
60struct Pushed {
62 signature: String,
63 undo_top: Option<u64>,
66 capture: Option<(Vec<String>, brep_render::engine_state::replace_component::ReplaceCapture)>,
70}
71
72pub(super) struct WorkPart {
73 pub assembly_id: u64,
74 pub part_id: u64,
75 pub(super) hosted: Option<Box<Document>>,
77 name: String,
78 component_path: String,
79 part_path: Vec<String>,
80 source: Option<String>,
81 world: Matrix,
82 pushed: Vec<Pushed>,
85 redo: Vec<Pushed>,
87 seen: Option<(u64, u64)>,
89 context_seen: Option<(u64, u64)>,
92 problems: Vec<(String, String, String, String)>,
95 pushes: u64,
97 no_coalesce: bool,
101 error: Option<String>,
103 checkout: CheckoutOffer,
106}
107
108#[derive(Default)]
110enum CheckoutOffer {
111 #[default]
113 Unasked,
114 Asking { part: String, revision: String },
116 Running(crate::plm::PlmFuture<()>),
117 Done(Option<String>),
119}
120
121pub(super) fn resolve_occurrence(
125 root: &EngineState,
126 root_document: &Value,
127 component_path: &str,
128) -> Result<(Matrix, Vec<String>, Option<String>, Value), String> {
129 let mut document = root_document;
130 let mut world = IDENTITY;
131 let mut part_path = Vec::new();
132 let mut source = None;
133 let ids: Vec<&str> = component_path.split(':').collect();
134 let mut top: Option<&brep_render::pipeline::ComponentSnapshot> = None;
135 for (depth, &id) in ids.iter().enumerate() {
136 let feature = document["features"]
137 .as_array()
138 .and_then(|features| {
139 features.iter().find(|f| {
140 matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT"))
141 && f["inputParams"]["id"].as_str() == Some(id)
142 })
143 })
144 .ok_or_else(|| format!("component '{id}' is missing"))?;
145 let name = feature["inputParams"]["partName"]
146 .as_str()
147 .ok_or("component has no part name")?;
148 world = if depth == 0 {
155 let record = root
156 .assembly_components()
157 .iter()
158 .find(|c| c.id == id)
159 .ok_or("component is not present in the current assembly")?;
160 top = Some(record);
161 record.transform
162 } else {
163 match top.and_then(|record| Some((record, record.nested_poses.get(&ids[1..=depth].join(":"))?))) {
164 Some((record, solved)) => multiply(record.transform, *solved),
165 None => multiply(world, component_pose(document, &feature["inputParams"]["transform"])?),
166 }
167 };
168 part_path.push(name.to_string());
169 let entry = &document["partsLibrary"][name];
170 source = entry["sourceKey"]
171 .as_str()
172 .filter(|s| !s.is_empty() && !s.starts_with('@'))
173 .map(str::to_string);
174 document = &entry["document"];
175 if !document.is_object() {
176 return Err(format!("part '{name}' has no embedded document"));
177 }
178 }
179 Ok((world, part_path, source, document.clone()))
180}
181
182fn context_scene(host: &EngineState, component_path: &str, world: Matrix, previous: &RenderScene) -> RenderScene {
191 let inverse = inverse_rigid(world);
192 let prefix = format!("{component_path}:");
193 let frame = world
197 .iter()
198 .fold(0xcbf2_9ce4_8422_2325u64, |h, v| (h ^ v.to_bits()).wrapping_mul(0x100_0000_01b3));
199 let mut context = RenderScene::new();
200 for solid in host
201 .scene
202 .solids()
203 .iter()
204 .filter(|solid| solid.visible && !solid.name.starts_with(&prefix))
205 {
206 let mut ghost = solid.clone();
207 ghost.source_handle = 0;
208 ghost.revision = ((solid.revision ^ frame).wrapping_mul(0x9e37_79b9_7f4a_7c15)) | (1 << 63);
209 ghost.shape_revision = 0;
210 ghost.pose = None;
211 ghost.bbox = Aabb::empty();
212 for point in &mut ghost.mesh.positions {
213 let mapped = point_at(inverse, point.map(f64::from));
214 ghost.bbox.expand(mapped);
215 *point = mapped.map(|v| v as f32);
216 }
217 for normal in &mut ghost.mesh.normals {
218 *normal = vector_at(inverse, normal.map(f64::from)).map(|v| v as f32);
219 }
220 for edge in &mut ghost.edges {
223 for point in &mut edge.polyline {
224 *point = point_at(inverse, point.map(f64::from)).map(|v| v as f32);
225 }
226 }
227 ghost.vertices.clear();
228 if let Some(before) = previous.solid(&ghost.name) {
229 let fresh = ghost.revision;
230 ghost.revision = before.revision;
231 if ghost != *before {
232 ghost.revision = fresh;
233 }
234 }
235 context.insert_solid(ghost);
236 }
237 context
238}
239
240fn edit_key(engine: &EngineState) -> (u64, u64) {
241 (engine.applied_generation(), engine.history_revision())
242}
243
244impl Documents {
245 pub fn occurrence_part(&self, component_path: &str) -> Result<(String, Option<String>), String> {
249 let root = self.engine();
250 let document: Value = serde_json::from_str(&root.history_request_json()).map_err(|e| e.to_string())?;
251 let (_, names, source, _) = resolve_occurrence(root, &document, component_path)?;
252 Ok((names.last().cloned().unwrap_or_default(), source))
253 }
254
255 pub fn begin_work_part(&mut self, component_path: &str) -> Result<(), String> {
257 self.begin_work_part_as(component_path, WorkPartMode::InPlace)
258 }
259
260 pub fn begin_work_part_as(
261 &mut self,
262 component_path: &str,
263 mode: WorkPartMode,
264 ) -> Result<(), String> {
265 if self.work_part.is_some() {
266 let host = self.work_part.as_ref().map(|s| s.assembly_id);
268 self.finish_work_part()?;
269 if let Some(index) = host.and_then(|id| self.open.iter().position(|d| d.id() == id)) {
270 self.activate(index);
271 }
272 }
273 let root = &self.open[self.active].engine;
274 if root.run_pending()
275 || root.sketch_mode()
276 || root.sketch3d_mode()
277 || root.ref_select_active()
278 {
279 return Err("finish the current operation before choosing a Work part".into());
280 }
281 if !self.active().access().is_editable() {
282 return Err("the assembly is read-only".into());
283 }
284 let assembly_id = self.active_id();
285 let root_document: Value =
286 serde_json::from_str(&root.history_request_json()).map_err(|e| e.to_string())?;
287 let (world, part_path, source, document) =
288 resolve_occurrence(root, &root_document, component_path)?;
289 let context = context_scene(root, component_path, world, &RenderScene::new());
290 let inverse = inverse_rigid(world);
291 let mut camera = root.camera.clone();
292 camera.eye = point_at(inverse, camera.eye);
293 camera.target = point_at(inverse, camera.target);
294 camera.up = vector_at(inverse, camera.up);
295 let existing = source.as_deref().and_then(|name| self.index_of(name));
296 if existing == Some(self.active_index()) {
297 return Err("the component source refers to its assembly".into());
298 }
299 let load = |docs: &Documents| -> Result<Document, String> {
302 let mut engine = docs.spawn_engine();
303 engine.set_history_json(&document.to_string())?;
304 if document["workbench"].as_str().is_none() {
306 let is_assembly = document["features"].as_array().is_some_and(|features| {
307 features
308 .iter()
309 .any(|f| matches!(f["type"].as_str(), Some("ACOMP" | "ASSEMBLY COMPONENT")))
310 });
311 engine.settings.workbench =
312 if is_assembly { "assembly" } else { "modeling" }.into();
313 }
314 let mut doc = Document::new(engine);
315 doc.set_name(source.clone());
316 doc.mark_clean();
317 Ok(doc)
318 };
319 let (hosted, part_id) = match (mode, existing) {
320 (WorkPartMode::NewTab, Some(index)) => {
321 if !self.open[index].access().is_editable() {
322 return Err("the part is read-only".into());
323 }
324 let id = self.open[index].id();
325 self.activate(index);
326 (None, id)
327 }
328 (WorkPartMode::NewTab, None) => {
329 let doc = load(self).inspect_err(|_| self.install_active_library())?;
330 let id = doc.id();
331 self.open_document(doc);
332 (None, id)
333 }
334 (WorkPartMode::InPlace, _) => {
335 let doc = load(self).inspect_err(|_| self.install_active_library())?;
336 let id = doc.id();
337 (Some(Box::new(doc)), id)
338 }
339 };
340 let mut session = WorkPart {
341 assembly_id,
342 part_id,
343 hosted,
344 name: part_path.last().cloned().unwrap_or_default(),
345 component_path: component_path.into(),
346 part_path,
347 source,
348 world,
349 pushed: Vec::new(),
350 redo: Vec::new(),
351 seen: None,
352 context_seen: None,
353 problems: Vec::new(),
354 pushes: 0,
355 no_coalesce: false,
356 error: None,
357 checkout: CheckoutOffer::default(),
358 };
359 let host_key = edit_key(&self.open[self.active_host_index(&session)].engine);
360 session.context_seen = Some(host_key);
361 self.work_part = Some(session);
362 let part = self.work_engine_mut().expect("work part engine");
363 part.context_scene = context;
364 part.sync_context_highlight();
365 part.camera = camera;
366 part.clear_selection();
367 part.dirty = true;
368 let baseline = Pushed {
369 signature: super::signature(part),
370 undo_top: part.history.undo_top(),
371 capture: None,
372 };
373 let seen = edit_key(part);
374 let session = self.work_part.as_mut().unwrap();
375 session.pushed.push(baseline);
376 session.seen = Some(seen);
377 self.install_active_library();
378 Ok(())
379 }
380
381 fn active_host_index(&self, session: &WorkPart) -> usize {
382 self.open
383 .iter()
384 .position(|d| d.id() == session.assembly_id)
385 .unwrap_or(self.active)
386 }
387
388 pub(super) fn hosted(&self) -> Option<&Document> {
390 self.work_part.as_ref().and_then(|s| s.hosted.as_deref())
391 }
392
393 pub(super) fn hosted_mut(&mut self) -> Option<&mut Document> {
394 self.work_part.as_mut().and_then(|s| s.hosted.as_deref_mut())
395 }
396
397 fn work_engine_mut(&mut self) -> Option<&mut EngineState> {
398 let session = self.work_part.as_mut()?;
399 if let Some(doc) = session.hosted.as_deref_mut() {
400 return Some(&mut doc.engine);
401 }
402 let id = session.part_id;
403 self.open.iter_mut().find(|d| d.id() == id).map(|d| &mut d.engine)
404 }
405
406 fn work_engine(&self) -> Option<&EngineState> {
407 let session = self.work_part.as_ref()?;
408 if let Some(doc) = session.hosted.as_deref() {
409 return Some(&doc.engine);
410 }
411 self.open.iter().find(|d| d.id() == session.part_id).map(|d| &d.engine)
412 }
413
414 pub fn work_part_in_place(&self) -> bool {
416 self.hosted().is_some()
417 }
418
419 pub fn work_part_assembly(&self) -> Option<&EngineState> {
422 let session = self.work_part.as_ref()?;
423 self.open.iter().find(|d| d.id() == session.assembly_id).map(|d| &d.engine)
424 }
425
426 pub fn work_part_assembly_mut(&mut self) -> Option<&mut EngineState> {
427 let id = self.work_part.as_ref()?.assembly_id;
428 self.open.iter_mut().find(|d| d.id() == id).map(|d| &mut d.engine)
429 }
430
431 pub fn work_part_path(&self) -> Option<&str> {
433 self.work_part.as_ref().map(|s| s.component_path.as_str())
434 }
435
436 pub(super) fn sync_work_part(&mut self) {
439 let Some(session) = self.work_part.as_ref() else {
440 return;
441 };
442 let Some(host) = self.open.iter().position(|d| d.id() == session.assembly_id) else {
443 return;
444 };
445 let Some(part) = self.work_engine() else {
446 return;
447 };
448 let busy = part.run_pending()
449 || part.sketch_mode()
450 || part.sketch3d_mode()
451 || part.ref_select_active();
452 let key = edit_key(part);
453 if !busy && Some(key) != session.seen && !self.open[host].engine.run_pending() {
454 let _ = self.push_work_part(false);
457 }
458 self.refresh_context();
459 }
460
461 fn push_work_part(&mut self, force: bool) -> Result<(), String> {
464 let session = self.work_part.as_ref().ok_or("no Work part is active")?;
465 let host = self
466 .open
467 .iter()
468 .position(|d| d.id() == session.assembly_id)
469 .ok_or("assembly tab is missing")?;
470 if !force && self.open[host].engine.run_pending() {
471 return Ok(());
472 }
473 let part = self.work_engine().ok_or("part document is missing")?;
474 let key = edit_key(part);
475 let signature = super::signature(part);
476 let undo_top = part.history.undo_top();
477 let edited: Value =
478 serde_json::from_str(&part.history_request_json()).map_err(|e| e.to_string())?;
479 let session = self.work_part.as_mut().unwrap();
480 let previous_seen = session.seen;
481 session.seen = Some(key);
482 if session.pushed.last().is_some_and(|p| p.signature == signature) {
483 return Ok(());
484 }
485 let pushed_len = session.pushed.len();
486 if pushed_len >= 2 && session.pushed[pushed_len - 2].signature == signature {
488 let step = session.pushed.pop().unwrap();
489 session.redo.push(step);
490 self.open[host].engine.undo();
491 self.install_active_library();
492 self.work_part.as_mut().unwrap().context_seen = None;
493 return Ok(());
494 }
495 if session.redo.last().is_some_and(|p| p.signature == signature) {
497 let step = session.redo.pop().unwrap();
498 session.pushed.push(step);
499 self.open[host].engine.redo();
500 self.install_active_library();
501 self.work_part.as_mut().unwrap().context_seen = None;
502 return Ok(());
503 }
504 let replace = pushed_len >= 2
507 && undo_top.is_some()
508 && !session.no_coalesce
509 && session.pushed.last().is_some_and(|p| p.undo_top == undo_top);
510 if !self.open[host].access().is_editable() {
511 let session = self.work_part.as_mut().unwrap();
512 session.error = Some("the assembly is read-only; part edits are not applied".into());
513 return Err("the assembly is read-only".into());
514 }
515 super::install_library_of(&self.open[host]);
522 let ready = self.open[host].engine.assembly_session_ready();
523 self.install_active_library();
524 if !ready {
525 self.work_part.as_mut().unwrap().seen = previous_seen;
526 return if force { Err(brep_render::engine_state::ASSEMBLY_SESSION_PENDING.into()) } else { Ok(()) };
527 }
528 let session = self.work_part.as_mut().unwrap();
529 let reused = if replace { session.pushed.last().and_then(|p| p.capture.clone()) } else { None };
533 if replace {
534 if reused.is_some() {
535 self.open[host].engine.undo_before_edit();
536 } else {
537 self.open[host].engine.undo();
538 }
539 }
540 let path = session.part_path.clone();
541 let source = session.source.clone();
542 let mut assembly_document: Value =
543 serde_json::from_str(&self.open[host].engine.history_request_json())
544 .map_err(|e| e.to_string())?;
545 let mut notes = Vec::new();
546 let signatures_before = library_signatures(&assembly_document);
547 let result = refresh_parts(&mut assembly_document, &path, source.as_deref(), &edited, &mut notes)
548 .and_then(|changed| {
549 if changed {
550 Ok(())
551 } else {
552 Err("the assembly no longer holds this part's definition".to_string())
553 }
554 })
555 .and_then(|()| {
556 let after = library_signatures(&assembly_document);
560 let parts: Vec<String> =
561 after.iter().filter(|(name, sig)| signatures_before.get(*name) != Some(*sig)).map(|(name, _)| name.clone()).collect();
562 super::install_library_of(&self.open[host]);
567 let engine = &mut self.open[host].engine;
568 let capture = match reused {
569 Some((reused_parts, capture)) if reused_parts == parts => capture,
570 stale => {
571 if stale.is_some() {
574 engine.rebuild_current_history();
575 }
576 engine.capture_part_edit(&engine.components_of_parts(&parts))?
577 }
578 };
579 let kept = (parts.clone(), capture.clone());
580 engine.commit_part_edit(capture, assembly_document.clone(), &parts).map(|()| kept)
581 });
582 self.install_active_library();
583 let session = self.work_part.as_mut().unwrap();
584 match result {
585 Ok(capture) => {
586 if replace {
587 session.pushed.pop();
588 }
589 session.pushed.push(Pushed { signature, undo_top, capture: Some(capture) });
590 session.redo.clear();
591 session.no_coalesce = false;
592 session.pushes += 1;
593 session.error = None;
594 session.context_seen = None;
595 for note in notes {
596 self.open[host].engine.push_notice(format!("Work part: {note}"));
597 }
598 Ok(())
599 }
600 Err(error) => {
601 if replace {
602 self.open[host].engine.redo();
603 self.install_active_library();
604 }
605 let session = self.work_part.as_mut().unwrap();
606 if error == brep_render::engine_state::ASSEMBLY_SESSION_PENDING {
607 session.seen = previous_seen;
612 session.no_coalesce = true;
613 return if force { Err(error) } else { Ok(()) };
614 }
615 session.error = Some(error.clone());
616 Err(error)
617 }
618 }
619 }
620
621 pub fn work_part_settling(&self) -> bool {
625 if self.work_part_next.is_some() {
627 return true;
628 }
629 let Some(session) = self.work_part.as_ref() else {
630 return false;
631 };
632 let (Some(part), Some(host)) = (self.work_engine(), self.work_part_assembly()) else {
633 return false;
634 };
635 let editing = part.sketch_mode() || part.sketch3d_mode() || part.ref_select_active();
636 host.run_pending()
637 || (!editing && Some(edit_key(part)) != session.seen && session.error.is_none())
638 || session.context_seen != Some(edit_key(host))
639 }
640
641 pub fn work_part_modified_sources(&self) -> Vec<String> {
644 self.owned_modified_keys()
645 }
646
647 pub fn flush_work_part(&mut self) {
651 if self.work_part.is_some() {
652 let _ = self.push_work_part(true);
653 }
654 }
655
656 fn refresh_context(&mut self) {
658 let Some(session) = self.work_part.as_ref() else {
659 return;
660 };
661 let Some(host) = self.open.iter().position(|d| d.id() == session.assembly_id) else {
662 return;
663 };
664 let engine = &self.open[host].engine;
665 if engine.run_pending() || session.context_seen == Some(edit_key(engine)) {
666 return;
667 }
668 let key = edit_key(engine);
669 let world = serde_json::from_str::<Value>(&engine.history_request_json())
670 .ok()
671 .and_then(|document| resolve_occurrence(engine, &document, &session.component_path).ok())
672 .map(|(world, ..)| world)
673 .unwrap_or(session.world);
674 let previous = self.work_engine().map(|part| &part.context_scene);
675 let context = context_scene(engine, &session.component_path, world, previous.unwrap_or(&RenderScene::new()));
676 let mut statuses = self.open[host].engine.assembly_statuses_value();
677 let mut problems: Vec<(String, String, String, String)> = statuses
678 .as_array_mut()
679 .map(|rows| {
680 rows.iter()
681 .filter(|row| {
682 let status = row["status"].as_str().unwrap_or("");
683 row["enabled"].as_bool() != Some(false)
684 && !matches!(status, "satisfied" | "disabled" | "over" | "")
685 })
686 .map(|row| {
687 let text = |k: &str| row[k].as_str().unwrap_or("").to_string();
688 (text("id"), text("type"), text("status"), text("message"))
689 })
690 .collect()
691 })
692 .unwrap_or_default();
693 for held in self.open[host].engine.replace_unresolved().as_array().into_iter().flatten() {
696 let id = held["id"].as_str().unwrap_or("").to_string();
697 if !problems.iter().any(|(known, ..)| *known == id) {
698 let message = "held for Repair: the face or edge it used is gone".to_string();
699 problems.push((id, held["type"].as_str().unwrap_or("").to_string(), "held".into(), message));
700 }
701 }
702 let moved = world != session.world;
703 let session = self.work_part.as_mut().unwrap();
704 session.context_seen = Some(key);
705 session.problems = problems;
706 if moved {
707 let delta = multiply(inverse_rigid(world), session.world);
710 session.world = world;
711 if let Some(part) = self.work_engine_mut() {
712 part.camera.eye = point_at(delta, part.camera.eye);
713 part.camera.target = point_at(delta, part.camera.target);
714 part.camera.up = vector_at(delta, part.camera.up);
715 }
716 }
717 if let Some(part) = self.work_engine_mut() {
718 part.context_scene = context;
719 part.sync_context_highlight();
720 part.dirty = true;
721 }
722 }
723
724 pub(super) fn finish_work_part(&mut self) -> Result<(), String> {
726 let Some(session) = &self.work_part else {
727 return Ok(());
728 };
729 let assembly = self
730 .open
731 .iter()
732 .position(|d| d.id() == session.assembly_id)
733 .ok_or("assembly tab is missing")?;
734 if self.work_engine().is_none() {
735 self.work_part = None;
736 return Err("part document is missing".into());
737 }
738 {
739 let part = self.work_engine_mut().unwrap();
740 if part.ref_select_active() {
741 part.cancel_ref_select();
742 }
743 if part.sketch_mode() {
746 part.exit_sketch_mode(true);
747 }
748 if part.sketch3d_mode() {
749 part.exit_sketch3d_mode(true);
750 }
751 }
752 let part = self.work_engine().unwrap();
753 let changed = self
754 .work_part
755 .as_ref()
756 .and_then(|s| s.pushed.last())
757 .is_none_or(|p| p.signature != super::signature(part));
758 if changed {
759 if !self.open[assembly].access().is_editable() {
760 return Err("assembly is read-only; part edits remain open".into());
761 }
762 self.push_work_part(true).map_err(|error| {
763 format!("{error}; edits remain in the Work part")
764 })?;
765 }
766 let session = self.work_part.take().unwrap();
767 let world = session.world;
768 let camera = match &session.hosted {
769 Some(doc) => doc.engine.camera.clone(),
770 None => {
771 let part = self.open.iter_mut().find(|d| d.id() == session.part_id).unwrap();
772 part.engine.context_scene.clear();
773 part.engine.sync_context_highlight();
774 part.engine.dirty = true;
775 part.engine.camera.clone()
776 }
777 };
778 let host = &mut self.open[assembly].engine;
779 host.camera.eye = point_at(world, camera.eye);
780 host.camera.target = point_at(world, camera.target);
781 host.camera.up = vector_at(world, camera.up);
782 host.camera.projection = camera.projection;
783 host.dirty = true;
784 self.install_active_library();
785 Ok(())
786 }
787
788 pub fn work_part_up_to(&mut self, depth: usize) -> Result<(), String> {
794 let session = self.work_part.as_ref().ok_or("no Work part is active")?;
795 let ids: Vec<&str> = session.component_path.split(':').collect();
796 if depth >= ids.len() {
797 return Ok(());
798 }
799 let next = (
800 session.assembly_id,
801 ids[..depth].join(":"),
802 if session.hosted.is_some() { WorkPartMode::InPlace } else { WorkPartMode::NewTab },
803 );
804 self.return_to_assembly()?;
805 if depth > 0 {
806 self.work_part_next = Some(next);
807 self.begin_next_work_part();
808 }
809 Ok(())
810 }
811
812 pub fn work_part_up(&mut self) -> Result<(), String> {
814 let depth = self.work_part.as_ref().ok_or("no Work part is active")?.part_path.len();
815 self.work_part_up_to(depth.saturating_sub(1))
816 }
817
818 pub(super) fn begin_next_work_part(&mut self) {
822 let Some((assembly, _, _)) = &self.work_part_next else {
823 return;
824 };
825 if self.work_part.is_some() || self.active_id() != *assembly {
826 self.work_part_next = None;
827 return;
828 }
829 if self.engine().run_pending() {
830 return;
831 }
832 let (_, path, mode) = self.work_part_next.take().unwrap();
833 if let Err(error) = self.begin_work_part_as(&path, mode) {
834 self.engine_mut().push_notice(format!("Work part: {error}"));
835 }
836 }
837
838 pub fn return_to_assembly(&mut self) -> Result<(), String> {
839 let id = self
840 .work_part
841 .as_ref()
842 .ok_or("no Work part is active")?
843 .assembly_id;
844 self.finish_work_part()?;
845 let index = self
846 .open
847 .iter()
848 .position(|d| d.id() == id)
849 .ok_or("assembly tab is missing")?;
850 self.activate(index);
851 Ok(())
852 }
853
854 pub fn work_part_state(&self) -> Value {
856 let Some(s) = self.work_part.as_ref() else {
857 return Value::Null;
858 };
859 let assembly = self.work_part_assembly();
860 let part = self.work_engine();
861 let context: Value = assembly
867 .map(|engine| {
868 let fingerprint = engine.scene.solids().iter().fold(engine.scene.solids().len() as u64, |h, solid| {
869 (h ^ solid.revision ^ u64::from(solid.visible)).wrapping_mul(0x100_0000_01b3)
870 });
871 let key = (s.component_path.clone(), fingerprint);
872 if let Some((cached, value)) = self.work_part_context.borrow().as_ref() {
873 if *cached == key {
874 return value.clone();
875 }
876 }
877 let prefix = format!("{}:", s.component_path);
878 let map: serde_json::Map<String, Value> = engine
879 .scene
880 .solids()
881 .iter()
882 .filter(|solid| solid.visible && !solid.name.starts_with(&prefix))
883 .map(|solid| {
884 (solid.name.clone(), serde_json::json!({"min": solid.bbox.min, "max": solid.bbox.max}))
885 })
886 .collect();
887 let value = Value::Object(map);
888 *self.work_part_context.borrow_mut() = Some((key, value.clone()));
889 value
890 })
891 .unwrap_or_else(|| Value::Object(Default::default()));
892 let [r, g, b, _] = brep_render::render::WORK_PART_CONTEXT_RGBA;
893 let (shown, alpha) = part.map_or((true, 0.0), |engine| engine.context_display());
894 let style = serde_json::json!({"rgba": [r, g, b, alpha], "alpha": alpha, "shown": shown, "depthWrite": false, "dimmed": alpha < 1.0});
895 serde_json::json!({
896 "name": s.name,
897 "componentPath": s.component_path,
898 "partPath": s.part_path,
899 "mode": if s.hosted.is_some() { "inPlace" } else { "newTab" },
900 "contextSolids": part.map_or(0, |engine| engine.context_scene.solids().len()),
901 "contextSelectable": true,
902 "contextSelection": part.map_or(serde_json::Value::Null, |engine| engine.context_selection_json()),
903 "contextHover": part.map_or(serde_json::Value::Null, |engine| engine.context_hover_json()),
904 "contextStyle": style,
905 "context": context,
906 "modifiedSources": self.owned_modified_keys_of(s.assembly_id),
907 "assemblyId": s.assembly_id,
908 "partId": s.part_id,
909 "pushes": s.pushes,
910 "pending": assembly.is_some_and(EngineState::run_pending),
911 "undoSteps": s.pushed.len().saturating_sub(1),
912 "redoSteps": s.redo.len(),
913 "error": s.error,
914 "constraintProblems": s.problems.iter().map(|(id, ty, status, message)| {
915 serde_json::json!({"id": id, "type": ty, "status": status, "message": message})
916 }).collect::<Vec<_>>(),
917 })
918 }
919
920 fn offer_checkout(&mut self, ui: &mut eframe::egui::Ui, store: &dyn crate::store::ModelStore, hits: &mut Value) {
925 use eframe::egui;
926 let Some(session) = self.work_part.as_mut() else {
927 return;
928 };
929 if matches!(session.checkout, CheckoutOffer::Unasked) {
930 session.checkout = CheckoutOffer::Done(None);
931 let key = session.source.clone().unwrap_or_default();
932 if let (Some(_), Some((part, revision))) = (store.plm_client(), crate::plm::bom::revision_of_document(&key)) {
933 session.checkout = match store.plm_revision(&key) {
934 Some(entry) if entry.editable && entry.locked_by_me => CheckoutOffer::Done(None),
935 Some(entry) if !entry.editable => CheckoutOffer::Done(Some(format!(
936 "{key}: revision {} is {} — your edits stay in the assembly", entry.revision_label, entry.lifecycle
937 ))),
938 Some(entry) if entry.locked_by.is_some() => CheckoutOffer::Done(Some(format!(
939 "{key} is checked out by {} — your edits stay in the assembly", entry.locked_by.unwrap_or_default()
940 ))),
941 _ => CheckoutOffer::Asking { part, revision },
942 };
943 }
944 }
945 let name = session.name.clone();
946 match &mut session.checkout {
947 CheckoutOffer::Asking { part, revision } => {
948 let (part, revision) = (part.clone(), revision.clone());
949 let mut answer = None;
950 let modal = egui::Modal::new(egui::Id::new("brep-work-part-checkout")).show(ui.ctx(), |ui| {
951 ui.heading("Check out before editing?");
952 ui.label(format!("{name} is not checked out to you. Check it out now, so Save can write it?"));
953 ui.horizontal(|ui| {
954 let yes = ui.button("Check out");
955 hits["checkout:yes"] = serde_json::json!([yes.rect.min.x, yes.rect.min.y, yes.rect.width(), yes.rect.height()]);
956 if yes.clicked() || ui.input(|i| i.key_pressed(egui::Key::Enter)) {
957 answer = Some(true);
958 }
959 let no = ui.button("Not now");
960 hits["checkout:no"] = serde_json::json!([no.rect.min.x, no.rect.min.y, no.rect.width(), no.rect.height()]);
961 if no.clicked() {
962 answer = Some(false);
963 }
964 });
965 });
966 let answer = answer.or_else(|| modal.should_close().then_some(false));
967 match (answer, store.plm_client()) {
968 (Some(true), Some(client)) => {
969 use crate::panels::plm::PlmLifecycle;
970 session.checkout = CheckoutOffer::Running(client.checkout(&part, &revision));
971 }
972 (Some(_), _) => session.checkout = CheckoutOffer::Done(Some(format!("{name} is not checked out; Save will offer it"))),
973 (None, _) => {}
974 }
975 }
976 CheckoutOffer::Running(future) => {
977 let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
978 match std::future::Future::poll(future.as_mut(), &mut cx) {
979 std::task::Poll::Ready(Ok(())) => {
980 session.checkout = CheckoutOffer::Done(Some(format!("{name} is checked out to you")));
981 store.refresh_plm_index(&[session.source.clone().unwrap_or_default()], false);
982 }
983 std::task::Poll::Ready(Err(error)) => {
984 session.checkout = CheckoutOffer::Done(Some(format!("{name} could not be checked out: {error}")));
985 }
986 std::task::Poll::Pending => ui.ctx().request_repaint_after(std::time::Duration::from_millis(50)),
987 }
988 }
989 CheckoutOffer::Unasked | CheckoutOffer::Done(_) => {}
990 }
991 }
992
993 pub fn show_work_part_bar(&mut self, ui: &mut eframe::egui::Ui, store: &dyn crate::store::ModelStore) {
994 let state = crate::automation::registry::enabled().then(|| self.work_part_state());
996 let mut hits = serde_json::json!({});
997 self.offer_checkout(ui, store, &mut hits);
998 let modal = self.work_part.as_ref().is_some_and(|s| matches!(s.checkout, CheckoutOffer::Asking { .. }));
1002 if let Some(session) = &self.work_part {
1003 let assembly = self.open.iter().find(|d| d.id() == session.assembly_id).map_or_else(|| "assembly".into(), |d| d.title());
1006 let crumbs: Vec<String> = std::iter::once(assembly).chain(session.part_path.iter().cloned()).collect();
1007 let component_path = session.component_path.clone();
1008 let problems: Vec<String> = session
1009 .problems
1010 .iter()
1011 .map(|(id, ty, status, message)| {
1012 if message.is_empty() {
1013 format!("{id} ({ty}): {status}")
1014 } else {
1015 format!("{id} ({ty}): {status}, {message}")
1016 }
1017 })
1018 .collect();
1019 let error = session.error.clone();
1020 let checkout = match &session.checkout {
1021 CheckoutOffer::Done(line) => line.clone(),
1022 CheckoutOffer::Running(_) => Some("checking out…".into()),
1023 _ => None,
1024 };
1025 let modified: Vec<String> = self.owned_modified_keys_of(session.assembly_id);
1026 let context_part = self.work_engine().and_then(|engine| engine.context_selection().map(|c| c.solid.rsplit(':').next().unwrap_or(&c.solid).to_string()));
1027 let display = self.work_engine().map(|engine| engine.context_display());
1028 let mut new_display = display;
1029 let mut context_action: Option<bool> = None;
1031 let mut finish = false;
1032 let mut up_to: Option<usize> = None;
1034 eframe::egui::Frame::group(ui.style()).show(ui, |ui| {
1035 ui.horizontal_wrapped(|ui| {
1036 ui.label("Work part:");
1037 let last = crumbs.len() - 1;
1038 for (depth, crumb) in crumbs.iter().enumerate() {
1039 if depth > 0 {
1040 ui.weak("›");
1041 }
1042 if depth == last {
1043 ui.strong(crumb);
1044 continue;
1045 }
1046 let link = ui.link(crumb).on_hover_text(if depth == 0 {
1047 "Return to the assembly"
1048 } else {
1049 "Make this sub-assembly the Work part"
1050 });
1051 hits[format!("crumb:{depth}")] = serde_json::json!([link.rect.min.x, link.rect.min.y, link.rect.width(), link.rect.height()]);
1052 if link.clicked() {
1053 up_to = Some(depth);
1054 }
1055 }
1056 ui.weak(format!("({component_path})"));
1057 if last > 1 {
1059 let button = ui.button("Up").on_hover_text(format!("Make {} the Work part", crumbs[last - 1]));
1060 hits["up"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1061 if button.clicked() {
1062 up_to = Some(last - 1);
1063 }
1064 }
1065 let button = ui
1066 .button("Return to assembly")
1067 .on_hover_text("Make the assembly the work context again (Esc)");
1068 hits["return"] = serde_json::json!([
1069 button.rect.min.x,
1070 button.rect.min.y,
1071 button.rect.width(),
1072 button.rect.height()
1073 ]);
1074 finish = button.clicked();
1075 if let Some((shown, opacity)) = &mut new_display {
1078 let toggle = ui
1079 .checkbox(shown, "Show the rest of the assembly")
1080 .on_hover_text("Shown for reference; it updates as you edit. Hidden, it is neither drawn nor picked");
1081 hits["display:show"] = serde_json::json!([toggle.rect.min.x, toggle.rect.min.y, toggle.rect.width(), toggle.rect.height()]);
1082 ui.add_enabled_ui(*shown, |ui| {
1083 let slider = ui
1084 .add(eframe::egui::Slider::new(opacity, 0.05..=1.0).show_value(false))
1085 .on_hover_text("How solid the rest of the assembly looks");
1086 hits["display:opacity"] = serde_json::json!([slider.rect.min.x, slider.rect.min.y, slider.rect.width(), slider.rect.height()]);
1087 });
1088 }
1089 });
1090 if let Some(part) = &context_part {
1093 ui.horizontal_wrapped(|ui| {
1094 ui.label(format!("Face of {part}:"));
1095 let button = ui.button("Sketch on this face").on_hover_text(
1096 "A datum on this face (copied, not linked: it stays if that part moves), and a new sketch on it",
1097 );
1098 hits["context-sketch"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1099 if button.clicked() {
1100 context_action = Some(true);
1101 }
1102 let button = ui.button("Datum here").on_hover_text(
1103 "A datum on this face (copied, not linked: it stays if that part moves)",
1104 );
1105 hits["context-datum"] = serde_json::json!([button.rect.min.x, button.rect.min.y, button.rect.width(), button.rect.height()]);
1106 if button.clicked() {
1107 context_action = Some(false);
1108 }
1109 });
1110 }
1111 for problem in &problems {
1112 ui.colored_label(ui.visuals().warn_fg_color, format!("Constraint {problem}"));
1113 }
1114 if !modified.is_empty() {
1115 ui.weak(format!(
1116 "Modified with their own files (written when the assembly is saved): {}",
1117 modified.join(", ")
1118 ));
1119 }
1120 if let Some(error) = &error {
1121 ui.colored_label(ui.visuals().error_fg_color, format!("Not applied: {error}"));
1122 }
1123 if let Some(line) = &checkout {
1124 ui.weak(line);
1125 }
1126 });
1127 let escape = ui.input(|i| i.key_pressed(eframe::egui::Key::Escape))
1128 && ui.ctx().memory(|m| m.focused().is_none())
1129 && self.work_engine().is_some_and(|engine| {
1130 !engine.has_selection()
1131 && engine.context_selection().is_none()
1132 && !engine.sketch_mode()
1133 && !engine.sketch3d_mode()
1134 && !engine.ref_select_active()
1135 });
1136 if let (Some((shown, opacity)), true) = (new_display, new_display != display) {
1137 if let Some(engine) = self.work_engine_mut() {
1138 engine.set_context_display(shown, opacity);
1139 }
1140 }
1141 if let Some(sketch) = context_action {
1142 if let Some(engine) = self.work_engine_mut() {
1143 let made = if sketch { engine.sketch_on_context() } else { engine.datum_on_context() };
1144 if let Err(error) = made {
1145 engine.push_notice(format!("Work part: {error}"));
1146 }
1147 }
1148 }
1149 if finish || escape {
1150 if let Err(error) = self.return_to_assembly() {
1151 self.engine_mut().push_notice(format!("Work part: {error}"));
1152 }
1153 } else if let Some(depth) = up_to {
1154 if let Err(error) = self.work_part_up_to(depth) {
1155 self.engine_mut().push_notice(format!("Work part: {error}"));
1156 }
1157 }
1158 }
1159 if modal {
1160 if let Some(hits) = hits.as_object_mut() {
1161 hits.retain(|key, _| key.starts_with("checkout:"));
1162 }
1163 }
1164 if let Some(state) = state {
1165 crate::automation::registry::publish(
1166 "__brepWorkPart",
1167 "active Work part session: component path, part path, mode (inPlace|newTab), context render state, assembly context solids (assembly coordinates), pushes, undo coupling, constraint problems; null when inactive",
1168 &state.to_string(),
1169 );
1170 crate::automation::registry::publish(
1171 "__brepWorkPartHit",
1172 "Work part controls: return, crumb:<depth> (the breadcrumb: 0 the assembly, then each sub-assembly above the part), up (nested parts), and checkout:yes / checkout:no while the checkout offer is shown",
1173 &hits.to_string(),
1174 );
1175 }
1176 }
1177}
1178
1179fn library_signatures(document: &Value) -> std::collections::BTreeMap<String, String> {
1181 document["partsLibrary"]
1182 .as_object()
1183 .into_iter()
1184 .flatten()
1185 .map(|(name, entry)| (name.clone(), entry["sourceSignature"].as_str().unwrap_or_default().to_string()))
1186 .collect()
1187}
1188
1189pub(crate) fn refresh_parts(
1192 owner: &mut Value,
1193 path: &[String],
1194 source: Option<&str>,
1195 edited: &Value,
1196 notes: &mut Vec<String>,
1197) -> Result<bool, String> {
1198 let names: Vec<String> = owner["partsLibrary"]
1199 .as_object()
1200 .map(|entries| entries.keys().cloned().collect())
1201 .unwrap_or_default();
1202 let mut changed = false;
1203 for name in names {
1204 let entry = &owner["partsLibrary"][&name];
1205 let on_path = path.first() == Some(&name);
1206 let target = (on_path && path.len() == 1)
1207 || source.is_some_and(|s| entry["sourceKey"].as_str() == Some(s));
1208 let tail = if on_path { &path[1..] } else { &[] };
1209 if !target && !holds_part(&entry["document"], tail, source) {
1213 continue;
1214 }
1215 let mut child = entry["document"].clone();
1216 let updated = if target {
1217 child = edited.clone();
1218 true
1219 } else {
1220 refresh_parts(&mut child, tail, source, edited, notes)?
1221 };
1222 if updated {
1223 notes.extend(crate::panels::parts_library::refresh_library_entry_value(owner, &name, child)?);
1224 changed = true;
1225 }
1226 }
1227 Ok(changed)
1228}
1229
1230fn holds_part(owner: &Value, path: &[String], source: Option<&str>) -> bool {
1233 owner["partsLibrary"].as_object().into_iter().flatten().any(|(name, entry)| {
1234 let on_path = path.first() == Some(name);
1235 (on_path && path.len() == 1)
1236 || source.is_some_and(|s| entry["sourceKey"].as_str() == Some(s))
1237 || holds_part(&entry["document"], if on_path { &path[1..] } else { &[] }, source)
1238 })
1239}
1240
1241fn component_pose(document: &Value, transform: &Value) -> Result<Matrix, String> {
1242 let read = |field: &str| -> Result<[f64; 3], String> {
1243 let mut out = [0.; 3];
1244 for (i, key) in ["x", "y", "z"].iter().enumerate() {
1245 let value = if transform[field].is_object() {
1246 &transform[field][*key]
1247 } else {
1248 &transform[field][i]
1249 };
1250 out[i] = match value {
1251 Value::Null => 0.,
1252 Value::Number(n) => n.as_f64().ok_or("invalid component pose")?,
1253 Value::String(s) => brep_kernel::eval_expression(
1254 document["expressions"].as_str().unwrap_or(""),
1255 &document["configurator"],
1256 s,
1257 )?,
1258 _ => return Err("invalid component pose".into()),
1259 };
1260 if !out[i].is_finite() {
1261 return Err("non-finite component pose".into());
1262 }
1263 }
1264 Ok(out)
1265 };
1266 let t = read("translate")?;
1267 let r = read("rotateEulerDeg")?.map(f64::to_radians);
1268 let (a, b) = (r[0].cos(), r[0].sin());
1269 let (c, d) = (r[1].cos(), r[1].sin());
1270 let (e, f) = (r[2].cos(), r[2].sin());
1271 Ok([
1272 c * e,
1273 -c * f,
1274 d,
1275 t[0],
1276 a * f + b * e * d,
1277 a * e - b * f * d,
1278 -b * c,
1279 t[1],
1280 b * f - a * e * d,
1281 b * e + a * f * d,
1282 a * c,
1283 t[2],
1284 0.,
1285 0.,
1286 0.,
1287 1.,
1288 ])
1289}
1290fn multiply(a: Matrix, b: Matrix) -> Matrix {
1291 brep_render::geometry3d::mat4_mul_row_major(&a, &b)
1292}
1293fn inverse_rigid(m: Matrix) -> Matrix {
1294 brep_render::geometry3d::mat4_rigid_inverse(&m)
1295}
1296fn vector_at(m: Matrix, p: [f64; 3]) -> [f64; 3] {
1297 std::array::from_fn(|r| (0..3).map(|k| m[r * 4 + k] * p[k]).sum())
1298}
1299fn point_at(m: Matrix, p: [f64; 3]) -> [f64; 3] {
1300 let v = vector_at(m, p);
1301 std::array::from_fn(|r| v[r] + m[r * 4 + 3])
1302}
1303
1304pub static HIT_KEYS: &[crate::automation::hit_keys::HitKeyDoc] =
1305 &[crate::automation::hit_keys::HitKeyDoc {
1306 panel: "workpart",
1307 prefix: "return",
1308 meaning: "return to assembly and apply Work part edits",
1309 command: None,
1310 },
1311 crate::automation::hit_keys::HitKeyDoc {
1312 panel: "workpart",
1313 prefix: "checkout:",
1314 meaning: "the offer to check out a PLM part made the Work part: checkout:yes (default), checkout:no",
1315 command: None,
1316 },
1317 crate::automation::hit_keys::HitKeyDoc {
1318 panel: "workpart",
1319 prefix: "context-",
1320 meaning: "a face of another part selected (context): context-sketch (a datum on it, copied not linked, and a new sketch there), context-datum (the datum only)",
1321 command: None,
1322 },
1323 crate::automation::hit_keys::HitKeyDoc {
1324 panel: "workpart",
1325 prefix: "display:",
1326 meaning: "the rest of the assembly (context): display:show (show/hide it), display:opacity (its opacity slider)",
1327 command: None,
1328 },
1329 crate::automation::hit_keys::HitKeyDoc {
1330 panel: "workpart",
1331 prefix: "crumb:",
1332 meaning: "the Work part breadcrumb: crumb:0 returns to the assembly, crumb:<k> makes the k-th sub-assembly above the part the Work part",
1333 command: None,
1334 },
1335 crate::automation::hit_keys::HitKeyDoc {
1336 panel: "workpart",
1337 prefix: "up",
1338 meaning: "a nested Work part: make the sub-assembly holding it the Work part",
1339 command: None,
1340 }];
1341