Skip to main content

brep_app/panels/
cam_sim.rs

1//! The CAM simulation player (lane C17, rows 2-3): a section of the CAM pane
2//! that loads a setup's generated operations into a program, plays it
3//! against the stock (C7's Z-dexel for 3-axis streams, the tri-dexel when a
4//! tool axis tilts), draws the stock, the tool at the scrub position and the
5//! collision / gouge markers in the viewport, compares the stock with the
6//! part (deviation colour map with a legend), reads the cycle time, stops at
7//! a collision when asked, and exports the simulated stock as STL.
8//!
9//! The simulation advances on the UI thread in bounded chunks per frame
10//! (`budget_per_frame` motions) so the pane stays responsive; the runner
11//! Command/Reply that moves it to the worker is requested from C1.
12
13use crate::ui_kit;
14use std::collections::{BTreeMap, BTreeSet, HashMap};
15
16use brep_cam::collision::{simulate_checked, simulate_checked_on_machine, CollisionOptions};
17use brep_cam::cutter::ToolProfile;
18use brep_cam::model::{Bounds3, Machine, Point3, RigidTransform, Setup, Stock};
19use brep_cam::kinematics::post::{resolve_program, ResolveOptions};
20use brep_cam::kinematics::Chain;
21use brep_cam::multiaxis::sim::{
22    check_machine, DriverOptions, MachineCheckOptions, Player, PlayState, Position, RangeCutter, SimDriver, StockModel, Timeline, TriDexel,
23    TriDexelOptions,
24};
25use brep_render::runner::{CamSimJob, CamSimRequest};
26use brep_cam::program::{assemble, OperationInput, ProgramInput, SetupInput};
27use brep_cam::stock::resolve_stock;
28use brep_cam::stock_sim::mesh::StockMesh;
29use brep_cam::stock_sim::removal::RemovalOptions;
30use brep_cam::stock_sim::{DexelGrid, DexelOptions};
31use brep_cam::verify::{deviation_map, DeviationMap, DeviationOptions};
32use brep_cam::stock_sim::remaining::{remaining_stock_mesh, RemainingStockMesh};
33use brep_cam::{BruteForceIndex, Cutter, MeshBuilder, MeshSnapshot, NullSink, Runner, Tolerance, TreeIndex, TreeOptions};
34use brep_render::cam_sim::{marks_group, remaining_group, remaining_legend, stock_group, stock_stl, tool_group, Marker, MARKS_GROUP, STOCK_GROUP, TOOL_GROUP};
35use brep_render::engine_state::EngineState;
36use egui;
37use serde_json::{json, Value};
38
39use crate::automation::hit_keys::HitKeyDoc;
40use crate::document::cam::CamDocument;
41use crate::panels::file::{SaveBody, SaveRequest};
42
43/// One operation's range in the program with its cutter.
44#[derive(Clone, Debug)]
45pub struct RangeTool {
46    pub operation: String,
47    pub first: usize,
48    pub count: usize,
49    pub cutter: Option<Cutter>,
50    pub profile: Option<ToolProfile>,
51    pub turning: Option<brep_cam::multiaxis::sim::player::TurningRange>,
52    /// The operation's tolerance: the remaining-stock bands' edge.
53    pub tolerance: f64,
54}
55
56/// A loaded simulation.
57pub struct SimSession {
58    pub setup: String,
59    pub player: Player,
60    pub driver: SimDriver,
61    pub ranges: Vec<RangeTool>,
62    pub to_model: RigidTransform,
63    /// Collision and gouge markers found by C7's checked simulation (3-axis
64    /// streams) at load, with the motions they belong to.
65    pub marks: Vec<Marker>,
66    pub collision_motions: BTreeSet<usize>,
67    /// Every collision found: (motion index in the program, part or body, against).
68    pub collisions: Vec<(usize, String, String)>,
69    /// The ranges with their cutters, as the stepping function takes them.
70    pub range_cutters: Vec<RangeCutter>,
71    /// The stock as loaded (the runner's Load and a reload after a lost session).
72    load_stock: StockModel,
73    /// The machine the session simulates on (sent with the runner's Load).
74    sim_machine: Option<Machine>,
75    /// `Some` when the background runner holds the stock (C17b); `None`
76    /// simulates inline on the UI thread in bounded chunks.
77    pub remote: Option<RemoteSim>,
78    pub multi_axis: bool,
79    /// The part in machine coordinates (deviation).
80    pub part: Option<MeshSnapshot>,
81    pub deviation: Option<DeviationMap>,
82    pub legend: Option<Value>,
83    mesh: StockMesh,
84    mesh_version: Option<u64>,
85    /// The part's index, built once for the remaining-stock overlay.
86    part_index: Option<TreeIndex>,
87    /// The stock coloured by remaining material (C7's remaining_stock_mesh),
88    /// for the stock version and tolerance in `remaining_key`.
89    pub remaining: Option<RemainingStockMesh>,
90    remaining_key: Option<(u64, u64)>,
91    /// Distinguishes sessions in the overlay's stock key (versions restart at 0).
92    epoch: u64,
93}
94
95static NEXT_EPOCH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
96
97/// Remaining-stock band edge when an operation has no usable tolerance.
98pub const DEFAULT_TOLERANCE: f64 = 0.05;
99
100/// The runner-side session's bookkeeping on the main side.
101#[derive(Debug, Default)]
102pub struct RemoteSim {
103    pub session: u64,
104    seq: u64,
105    /// The chunk on the runner: (seq, target).
106    pub in_flight: Option<(u64, usize)>,
107    /// Sequence numbers whose replies are dropped (cancelled chunks).
108    dropped: BTreeSet<u64>,
109    /// The runner acknowledged the Load.
110    pub loaded: bool,
111    /// Chunks submitted and replies accepted (for the state blob).
112    pub submitted: u64,
113    pub accepted: u64,
114    pub cancelled: u64,
115    /// The runner refused a chunk: the player stops here with the reason and
116    /// submits nothing more until the simulation is loaded again. (It used to
117    /// resubmit the refused chunk every frame and never catch up.)
118    pub failed: Option<String>,
119}
120
121static NEXT_SESSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
122
123impl SimSession {
124    /// The stock mesh for the driver's current version (rebuilt on change).
125    pub fn mesh(&mut self) -> &StockMesh {
126        if self.mesh_version != Some(self.driver.version) {
127            self.mesh = self.driver.stock.mesh();
128            self.mesh_version = Some(self.driver.version);
129        }
130        &self.mesh
131    }
132
133    /// The range (and its tool) a motion belongs to.
134    pub fn range_of(&self, motion: usize) -> Option<&RangeTool> {
135        self.ranges.iter().find(|r| motion >= r.first && motion < r.first + r.count)
136    }
137
138    /// Whether the stock shows the player's completed count with nothing
139    /// in flight.
140    pub fn caught_up(&self) -> bool {
141        self.driver.applied == self.player.completed() && self.remote.as_ref().map_or(true, |r| r.in_flight.is_none() && r.loaded)
142    }
143
144    /// Bring the stock toward the player's completed count: inline, at most
145    /// `budget` motions now; on the runner, fold landed replies and submit
146    /// the next chunk of at most `chunk` motions. `true` while not caught up.
147    pub fn drive(&mut self, state: &mut EngineState, budget: usize, chunk: usize) -> Result<bool, String> {
148        let target = self.player.completed();
149        let tolerance = Tolerance::default();
150        let Some(remote) = self.remote.as_mut() else {
151            if self.driver.applied != target {
152                self.driver
153                    .advance_ranges(&self.player.timeline, &self.range_cutters, target, budget, &tolerance, &mut |_| true)
154                    .map_err(|e| e.to_string())?;
155            }
156            return Ok(self.driver.applied != target);
157        };
158        let _ = state.cam_sim_poll_progress();
159        if let Some(failed) = &remote.failed {
160            return Err(failed.clone());
161        }
162        while let Some(reply) = state.cam_sim_poll() {
163            if reply.session != remote.session || remote.dropped.remove(&reply.seq) || remote.in_flight.map(|f| f.0) != Some(reply.seq) {
164                continue;
165            }
166            remote.in_flight = None;
167            if let Some(error) = reply.error {
168                if error.contains("no simulation session") {
169                    // The runner lost the session (a worker restart): load again.
170                    remote.loaded = false;
171                    continue;
172                }
173                remote.failed = Some(error.clone());
174                self.player.pause();
175                return Err(error);
176            }
177            remote.accepted += 1;
178            remote.loaded = true;
179            let d = &mut self.driver;
180            d.applied = reply.applied;
181            d.version = reply.version;
182            d.removed_volume = reply.removed_volume;
183            d.unsupported = reply.unsupported;
184            d.warnings = reply.warnings;
185            if let Some(stock) = reply.stock {
186                d.stock = stock;
187                self.mesh_version = None;
188            }
189        }
190        if remote.in_flight.is_none() {
191            remote.seq += 1;
192            let seq = remote.seq;
193            let request = if !remote.loaded {
194                Some(CamSimRequest::Load {
195                    timeline: self.player.timeline.clone(),
196                    stock: self.load_stock.clone(),
197                    ranges: self.range_cutters.clone(),
198                    options: self.driver.options.clone(),
199                    machine: self.sim_machine.clone(),
200                })
201            } else if self.driver.applied != target {
202                Some(CamSimRequest::Advance { target, budget: chunk, stock: true, known_version: self.driver.version })
203            } else {
204                None
205            };
206            if let Some(request) = request {
207                if let CamSimRequest::Load { .. } = &request {
208                    // The view restarts from the loaded stock.
209                    self.driver.stock = self.load_stock.clone();
210                    self.driver.applied = 0;
211                    self.driver.version = 0;
212                    self.driver.removed_volume = 0.0;
213                    self.driver.unsupported.clear();
214                    self.driver.warnings.clear();
215                    self.mesh_version = None;
216                }
217                if state.cam_sim_submit(CamSimJob { session: remote.session, seq, request }) {
218                    remote.in_flight = Some((seq, target));
219                    remote.submitted += 1;
220                } else {
221                    return Err("the runner refused the simulation command".into());
222                }
223            }
224        }
225        Ok(!self.caught_up())
226    }
227
228    /// Stop simulating: the chunk in flight is cancelled (between two
229    /// motions on the native thread) and its reply dropped; the stock stays
230    /// the last accepted one and the transport pauses there.
231    pub fn cancel(&mut self, state: &mut EngineState) -> bool {
232        let mut stopped = false;
233        if let Some(remote) = self.remote.as_mut() {
234            if let Some((seq, _)) = remote.in_flight.take() {
235                state.cam_sim_cancel();
236                remote.dropped.insert(seq);
237                remote.cancelled += 1;
238                stopped = true;
239            }
240        }
241        let applied = self.driver.applied;
242        if self.player.completed() != applied || stopped {
243            self.player.pause();
244            self.player.position = if applied == 0 { Position { motion: 0, fraction: 0.0 } } else { Position { motion: applied - 1, fraction: 1.0 } };
245            stopped = true;
246        }
247        stopped
248    }
249
250    /// Compare the stock with the part: the deviation map and its legend.
251    pub fn compare(&mut self, options: &DeviationOptions, scale: f64) -> Result<(), String> {
252        let part = self.part.as_ref().ok_or("no part mesh: the setup's target bodies are not on screen")?;
253        let grid = match &self.driver.stock {
254            StockModel::Dexel(g) => g.clone(),
255            StockModel::TriDexel(t) => t.to_dexel_grid(),
256            StockModel::Turning(t) => t.view.clone(),
257        };
258        let index = BruteForceIndex::build(part);
259        let map = deviation_map(&grid, part, &index, options);
260        self.legend = Some(brep_render::cam_sim::deviation_legend(&map, scale));
261        if let StockModel::Turning(stock)=&self.driver.stock {
262            use brep_cam::planar::{Region,Loop};
263            let tol=Tolerance::default();
264            if !options.tolerance.is_finite() || options.tolerance<=0. {return Err("turning deviation tolerance must be positive".into());}
265            let (target_min,target_max)=stock.target.bounds();let (_,stock_max)=stock.section.bounds();
266            let domain=Region::new(vec![Loop::rectangle(brep_cam::Point2::new(0.,target_min.y),brep_cam::Point2::new(stock_max.x.max(target_max.x)+1.,stock_max.y.max(target_max.y)+1.))],&tol).map_err(|e|e.to_string())?;
267            let machined=stock.section.intersection(&domain,&tol).map_err(|e|e.to_string())?;
268            let rear=stock.section.difference(&domain,&tol).map_err(|e|e.to_string())?;
269            let missing=stock.target.difference(&machined,&tol).map_err(|e|e.to_string())?;
270            let excess=machined.difference(&stock.target,&tol).map_err(|e|e.to_string())?;
271            let outer=stock.target.offset(options.tolerance,&tol).map_err(|e|e.to_string())?;
272            let inner=stock.target.offset(-options.tolerance,&tol).map_err(|e|e.to_string())?;
273            let within=machined.difference(&outer,&tol).map_err(|e|e.to_string())?.is_empty() && inner.difference(&machined,&tol).map_err(|e|e.to_string())?.is_empty();
274            let rear_volume=brep_cam::turning::sim::StockState::new(rear,tol).map_err(|e|e.to_string())?.volume();
275            self.legend.as_mut().unwrap()["axial"]=json!({"withinTolerance":within,"tolerance":options.tolerance,"machinedFromZ":target_min.y,"machinedExcessArea":excess.area(),"machinedMissingArea":missing.area(),"rearRemainingVolume":rear_volume,"totalRemainingVolume":stock.volume(),"scope":"certified target meridian from its rear face forward; rear bar extension reported separately"});
276        }
277        self.deviation = Some(map);
278        Ok(())
279    }
280
281    /// The tolerance of the operation at the playback position.
282    pub fn tolerance_here(&self) -> f64 {
283        self.range_of(self.player.position.motion).map_or(DEFAULT_TOLERANCE, |r| r.tolerance)
284    }
285
286    /// Colour the stock as it stands by remaining material against the part
287    /// (C7's remaining_stock_mesh, band edges from the operation tolerance at
288    /// the playback position). Recomputed only when the stock version or the
289    /// tolerance changed; `true` when it was.
290    pub fn refresh_remaining(&mut self) -> Result<bool, String> {
291        let tolerance = self.tolerance_here();
292        let key = (self.driver.version, tolerance.to_bits());
293        if self.remaining_key == Some(key) {
294            return Ok(false);
295        }
296        let part = self.part.as_ref().ok_or("no part mesh: the setup's target bodies are not on screen")?;
297        let index = self.part_index.get_or_insert_with(|| TreeIndex::build(part, TreeOptions::default()));
298        let grid = match &self.driver.stock {
299            StockModel::Dexel(g) => g.clone(),
300            StockModel::TriDexel(t) => t.to_dexel_grid(),
301            StockModel::Turning(t) => t.view.clone(),
302        };
303        let options = DeviationOptions { tolerance, max_distance: 1_000.0 };
304        self.remaining = Some(remaining_stock_mesh(&grid, part, index, &options));
305        self.remaining_key = Some(key);
306        Ok(true)
307    }
308
309    /// JSON for `cam_sim_state`.
310    pub fn state_json(&self) -> Value {
311        let p = &self.player;
312        let op = p.timeline.operation_of(p.position.motion).map(|i| p.timeline.operations[i].operation.to_string());
313        json!({
314            "setup": self.setup,
315            "multiAxis": self.multi_axis,
316            "playing": p.state == PlayState::Playing,
317            "speed": p.speed,
318            "motion": p.position.motion,
319            "fraction": p.position.fraction,
320            "time": p.time(),
321            "totalSeconds": p.timeline.total_seconds,
322            "progress": p.progress(),
323            "motions": p.timeline.len(),
324            "completed": p.completed(),
325            "applied": self.driver.applied,
326            "caughtUp": self.caught_up(),
327            "runner": self.remote.as_ref().map(|r| json!({ "session": r.session, "loaded": r.loaded, "inFlight": r.in_flight.map(|f| f.1), "submitted": r.submitted, "accepted": r.accepted, "cancelled": r.cancelled, "failed": r.failed })),
328            "removedVolume": self.driver.removed_volume,
329            "stockVolume": self.driver.stock.volume(),
330            "unsupported": self.driver.unsupported,
331            "warnings": self.driver.warnings.len(),
332            "operation": op,
333            "operations": p.timeline.operations.iter().map(|r| json!({ "operation": r.operation.to_string(), "first": r.first, "count": r.count, "seconds": p.timeline.end_times.get(r.first + r.count.saturating_sub(1)).copied().unwrap_or(0.0) - p.timeline.start_time(r.first) })).collect::<Vec<_>>(),
334            "marks": self.marks.len(),
335            "collisionMotions": self.collision_motions.iter().collect::<Vec<_>>(),
336            "collisions": self.collisions.iter().map(|(m, p, a)| json!({ "motion": m, "part": p, "against": a })).collect::<Vec<_>>(),
337            "deviation": self.legend,
338            "stockVersion": self.driver.version,
339            "remaining": self.remaining.as_ref().map(|r| {
340                let mut legend = remaining_legend(r);
341                legend["stockVersion"] = json!(self.remaining_key.map(|k| k.0));
342                legend
343            }),
344        })
345    }
346}
347
348/// A target body's display mesh as a CAM snapshot in MODEL coordinates.
349fn snapshot_of_solids(state: &EngineState, names: &[String], tolerance: Tolerance) -> Option<MeshSnapshot> {
350    let mut builder = MeshBuilder::new(tolerance);
351    let mut any = false;
352    for name in names {
353        let Some(solid) = state.scene.solid(name) else { continue };
354        let mesh = &solid.mesh;
355        let positions: Vec<f64> = mesh.positions.iter().flat_map(|p| [p[0] as f64, p[1] as f64, p[2] as f64]).collect();
356        let max_face = mesh.face_ids.iter().copied().max().map_or(0, |m| m as usize + 1);
357        let face_names: Vec<String> = (0..max_face).map(|i| solid.faces.get(i).map(|f| f.name.clone()).unwrap_or_else(|| format!("f{i}"))).collect();
358        if builder.add_body_buffers(name, false, &positions, &mesh.indices, &mesh.face_ids, &face_names).is_ok() {
359            any = true;
360        }
361    }
362    if any {
363        Some(builder.finish())
364    } else {
365        None
366    }
367}
368
369/// Model-space bounds of the named solids on screen.
370fn bounds_of_solids(state: &EngineState, names: &[String]) -> Bounds3 {
371    let mut b = Bounds3::empty();
372    for name in names {
373        if let Some(solid) = state.scene.solid(name) {
374            for p in &solid.mesh.positions {
375                b.include(Point3::new(p[0] as f64, p[1] as f64, p[2] as f64));
376            }
377        }
378    }
379    b
380}
381
382/// Build the session for `setup_id` (or the setup of the first generated
383/// operation) from the engine's generation results.
384///
385/// `toolpaths` replaces an operation's generated toolpath for the session
386/// (by operation id; an operation with one needs no generation result).
387pub fn build_session(
388    state: &EngineState,
389    doc: &CamDocument,
390    setup_id: Option<&str>,
391    cell: f64,
392    machine: Option<&Machine>,
393    toolpaths: &BTreeMap<String, brep_cam::model::Toolpath>,
394) -> Result<SimSession, String> {
395    let toolpath_of = |id: &str| -> Option<brep_cam::model::Toolpath> {
396        toolpaths.get(id).cloned().or_else(|| state.cam.results.get(id).and_then(|r| r.toolpath.clone()))
397    };
398    let generated: Vec<&brep_cam::model::Operation> = doc
399        .operations
400        .iter()
401        .filter(|op| toolpaths.contains_key(op.id.as_str()) || state.cam.results.get(op.id.as_str()).map_or(false, |r| r.toolpath.is_some()))
402        .collect();
403    if generated.is_empty() {
404        return Err("nothing to simulate: generate an operation first".into());
405    }
406    let setup_id = match setup_id {
407        Some(id) => id.to_string(),
408        None => generated[0].setup.to_string(),
409    };
410    let setup: &Setup = doc.setup(&setup_id).ok_or_else(|| format!("no setup `{setup_id}`"))?;
411    let ops: Vec<&brep_cam::model::Operation> = generated.into_iter().filter(|op| op.setup.as_str() == setup_id).collect();
412    if ops.is_empty() {
413        return Err(format!("setup `{setup_id}` has no generated operation"));
414    }
415    let mut inputs = Vec::new();
416    let mut multi_axis = false;
417    for op in &ops {
418        let tool = doc.tool(op.tool.as_str()).ok_or_else(|| format!("operation `{}` names a missing tool", op.id))?;
419        let toolpath = toolpath_of(op.id.as_str()).ok_or_else(|| format!("operation `{}` has no toolpath", op.id))?;
420        if toolpath.motions.iter().any(|m| m.tool_axis.map_or(false, |a| a.normalized().map_or(false, |u| u.distance(Point3::Z) > 1e-9))) {
421            multi_axis = true;
422        }
423        inputs.push(OperationInput { operation: (*op).clone(), tool: tool.clone(), toolpath });
424    }
425    let turning_program=inputs.iter().any(|i|matches!(i.operation.strategy,brep_cam::Strategy::TurnFace(_)|brep_cam::Strategy::TurnProfile(_)));
426    let turning_machine=if turning_program {machine.cloned().or_else(||doc.setup_machine(&setup_id))}else{None};
427    let program = assemble(&ProgramInput { name: format!("sim-{setup_id}"), machine:turning_machine, setups: vec![SetupInput { setup: setup.clone(), operations: inputs }], ..Default::default() })
428        .map_err(|e| format!("program: {e}"))?;
429    // The machine the session checks: the one given to the player, else the
430    // setup's (C17c); its feeds and accelerations time the program.
431    let setup_machine = doc.setup_machine(&setup_id);
432    let machine = machine.cloned().or(setup_machine);
433    let machine = machine.as_ref();
434    let timeline = Timeline::from_program(&program, machine.unwrap_or(&Machine::default()));
435    // Ranges with their cutters.
436    let mut ranges = Vec::new();
437    let mut turning_target = None;
438    for (section, range) in program.sections.iter().zip(&timeline.operations) {
439        let tool = program.tools.iter().find(|t| t.id == section.tool).ok_or("program tool missing")?;
440        let tolerance = doc.operation(range.operation.as_str()).map(|o| o.tolerance).filter(|t| t.is_finite() && *t > 0.0).unwrap_or(DEFAULT_TOLERANCE);
441        if tool.kind == brep_cam::ToolKind::LatheInsert {
442            use brep_cam::planar::{Region,Loop,Segment};
443            let operation=doc.operation(section.operation.as_str()).ok_or("turning operation missing")?;
444            if !matches!(operation.strategy,brep_cam::Strategy::TurnFace(_)|brep_cam::Strategy::TurnProfile(_)) {return Err("axial simulation supports face/profile turning only".into());}
445            let certified=state.cam.results[section.operation.as_str()].turning_profile.as_ref().ok_or("turning result has no certified meridian; regenerate")?;
446            let target=Region::from_unoriented(certified.loops.iter().map(|lp|Loop::new(lp.iter().zip(lp.iter().cycle().skip(1)).take(lp.len()).filter(|(a,b)|a!=b).map(|(a,b)|Segment::line(brep_cam::Point2::new(a.x,a.z),brep_cam::Point2::new(b.x,b.z))).collect())).collect(),&Tolerance::default()).map_err(|e|e.to_string())?;
447            if turning_target.as_ref().is_some_and(|p|p!=&target) {return Err("turning ranges have different protected profiles".into());}
448            turning_target=Some(target.clone());
449            let protected=target.offset(-operation.tolerance,&Tolerance::default()).map_err(|e|e.to_string())?;
450            let geometry=tool.turning_geometry.as_ref().ok_or_else(||format!("tool {} has no insert geometry",tool.id))?;
451            if tool.holder.is_some() {return Err("turning simulation requires an explicit axial holder envelope; mill holder stacks are unsupported".into());}
452            let envelope=brep_cam::turning::envelope(tool,geometry,operation.tolerance*0.1).map_err(|e|e.to_string())?;
453            let stick=setup.turning_stick_out.ok_or("setup has no stick-out")?;
454            let stock=match setup.stock {brep_cam::Stock::Cylinder{base,axis,radius,height}=>brep_cam::StockCylinder{base:setup.model_to_machine.apply_point(base),axis:setup.model_to_machine.apply_vector(axis),radius,height},_=>return Err("turning simulation requires cylindrical stock".into())};
455            let chuck_z=brep_cam::turning::profile::bar_section(&stock,stick).map_err(|e|e.to_string())?.chuck_z;
456            let turning=brep_cam::multiaxis::sim::player::TurningRange{tool:tool.id.clone(),envelope,holders:Vec::new(),protected,chuck_z};
457            ranges.push(RangeTool{operation:range.operation.to_string(),first:range.first,count:range.count,cutter:None,profile:None,turning:Some(turning),tolerance});
458        } else {
459            let cutter = Cutter::from_tool(tool).map_err(|e| format!("tool `{}`: {e}", tool.id))?;
460            let profile = ToolProfile::new(&cutter, tool.holder.as_ref(), 0.01);
461            ranges.push(RangeTool { operation: range.operation.to_string(), first: range.first, count: range.count, cutter:Some(cutter), profile:Some(profile), turning:None, tolerance });
462        }
463    }
464    // Stock from the setup and the target bodies on screen.
465    let mut target_names: Vec<String> = setup.targets.iter().map(|t| t.solid.clone()).collect();
466    for op in &ops {
467        for s in &op.targets.target_solids {
468            if !target_names.contains(s) {
469                target_names.push(s.clone());
470            }
471        }
472    }
473    // The stock generation planned against: the setup's start as a generated
474    // operation's job resolved it from the bodies' f64 tessellation. The
475    // display mesh is f32, an ULP off at the stock's faces, and a carry grows
476    // that skin into a full-height wall the shank then "hits".
477    let start = ops.iter().find_map(|op| state.cam.results.get(op.id.as_str()).and_then(|r| r.setup_start.as_ref()));
478    let target_bounds = start.and_then(|s| s.target_bounds).unwrap_or_else(|| bounds_of_solids(state, &target_names));
479    let tolerance = Tolerance::default();
480    let from_solid = match &setup.stock {
481        Stock::FromSolid { solid } => snapshot_of_solids(state, std::slice::from_ref(solid), tolerance),
482        _ => None,
483    };
484    let resolved = resolve_stock(setup, &target_bounds, from_solid.as_ref()).map_err(|e| e.to_string())?;
485    let part = snapshot_of_solids(state, &target_names, tolerance).map(|m| brep_cam::mesh::to_machine(setup, &m));
486    // A setup continuing from another starts from that setup's simulated
487    // stock carried into this frame: the stock generation planned against
488    // (lane C7's job_stock, before this setup's first operation).
489    let carried = match &resolved {
490        brep_cam::ResolvedStock::Rest(_) if start.is_some_and(|s| s.carried.is_some()) => start.and_then(|s| s.carried.clone()),
491        brep_cam::ResolvedStock::Rest(_) => {
492            let mesh = part.as_ref().ok_or("the carried stock needs the target bodies on screen")?;
493            let previous = crate::panels::cam_generate::setup_history(state, doc, setup);
494            let own_machine = doc.setup_machine(setup.id.as_str());
495            let job = brep_cam::JobStock { setup, machine: own_machine.as_ref(), tools: &doc.tools, mesh,
496                fallback_targets: &target_names, earlier: &[], previous: &previous, tolerance };
497            let mut sink = NullSink;
498            let result = brep_cam::job_stock(&mut brep_cam::PreOpStockCache::new(previous.len() + 1), &job, &mut Runner::detached(&mut sink))
499                .map_err(|e| format!("carried stock from the previous setup: {e}"))?;
500            Some(result.stock.grid)
501        }
502        _ => None,
503    };
504    // An indexed or rotary stream cuts in the part frame through the
505    // machine's chain (C7's `*_on_machine`), which only the Z-dexel does.
506    let chain = brep_cam::multiaxis::sim::sim_chain(machine);
507    if brep_cam::multiaxis::sim::uses_rotary(&timeline.motions) {
508        multi_axis = false;
509    }
510    let stock = if let Some(target)=turning_target {
511        // A mill-turn setup turns, then live-mills the turned stock (the driver
512        // switches to its Z-dexel view); turning after milling cannot follow.
513        let first_milling=ranges.iter().filter(|r|r.turning.is_none()).map(|r|r.first).min();
514        if first_milling.is_some_and(|m|ranges.iter().any(|r|r.turning.is_some()&&r.first>m)) {return Err("turning after milling in one setup is not simulated: split the setup after the first milling operation".into());}
515        let brep_cam::ResolvedStock::Cylinder(cylinder)=&resolved else {return Err("turning simulation requires cylinder stock".into());};
516        let section=brep_cam::planar::Region::new(vec![brep_cam::planar::Loop::rectangle(brep_cam::Point2::new(0.,cylinder.base.z),brep_cam::Point2::new(cylinder.radius,cylinder.base.z+cylinder.height))],&tolerance).map_err(|e|e.to_string())?;
517        let view=DexelGrid::from_stock(&resolved,&DexelOptions{cell,..Default::default()},None,None).map_err(|e|e.to_string())?;
518        let mut axial=brep_cam::multiaxis::sim::player::TurningStock{section,target,view};axial.refresh_view();
519        StockModel::Turning(axial)
520    } else if let Some(grid) = carried {
521        if multi_axis {
522            StockModel::TriDexel(TriDexel::from_dexel(&grid, &TriDexelOptions { cell, ..Default::default() }).map_err(|e| format!("{e:?}"))?)
523        } else {
524            StockModel::Dexel(grid)
525        }
526    } else if multi_axis {
527        StockModel::TriDexel(TriDexel::from_stock(&resolved, &TriDexelOptions { cell, ..Default::default() }, None, None).map_err(|e| e.to_string())?)
528    } else {
529        StockModel::Dexel(DexelGrid::from_stock(&resolved, &DexelOptions { cell, ..Default::default() }, None, None).map_err(|e| format!("{e:?}"))?)
530    };
531    // Collision and gouge pre-pass (3-axis streams): C7's checked simulation
532    // per operation on a scratch grid.
533    let mut marks = Vec::new();
534    let mut collision_motions = BTreeSet::new();
535    let mut collisions: Vec<(usize, String, String)> = Vec::new();
536    if let StockModel::Dexel(grid) = &stock {
537        let mut scratch = grid.clone();
538        for r in &ranges {
539            let motions: Vec<brep_cam::model::Motion> = timeline.motions[r.first..r.first + r.count].to_vec();
540            let mut sink = NullSink;
541            let options = CollisionOptions { stop_at_first: false, ..Default::default() };
542            let mut runner = Runner::detached(&mut sink);
543            let checked = match &chain {
544                Some(chain) => simulate_checked_on_machine(&mut scratch, None, r.cutter.as_ref().unwrap(), r.profile.as_ref().unwrap(), &motions, &tolerance, &RemovalOptions::default(), &options, chain, &mut runner),
545                None => simulate_checked(&mut scratch, None, r.cutter.as_ref().unwrap(), r.profile.as_ref().unwrap(), &motions, &tolerance, &RemovalOptions::default(), &options, &mut runner),
546            }
547            .map_err(|_| "collision check cancelled".to_string())?;
548            for c in checked.collisions {
549                // The cutting part meeting material on a non-cutting move is a
550                // gouge; the shank or holder touching anything is a collision.
551                let gouge = matches!(c.part, brep_cam::CollisionPart::CuttingOnRapid);
552                marks.push(Marker { at: c.contact, gouge });
553                collision_motions.insert(r.first + c.motion_index);
554                collisions.push((r.first + c.motion_index, format!("{:?}", c.part), format!("{:?}", c.against)));
555            }
556        }
557    }
558    // Machine collision (C10c): the machine's link solids along the resolved
559    // motion, against each other and the stock as loaded. The first hit is
560    // marked (on the part, in setup coordinates) and joins the stop list.
561    let mut machine_notes = Vec::new();
562    if let Some(machine) = machine.filter(|m| !m.collision.is_empty()) {
563        // The same zero work offset generation and the removal use.
564        match Chain::from_machine(machine, Point3::ZERO) {
565            Ok(chain) => match resolve_program(&program, &chain, &ResolveOptions::default()) {
566                Ok(resolved) => {
567                    let tri = match &stock {
568                        StockModel::TriDexel(t) => Some(t.clone()),
569                        StockModel::Dexel(g) => TriDexel::from_dexel(g, &TriDexelOptions { cell, ..Default::default() }).ok(),
570                        StockModel::Turning(t) => TriDexel::from_dexel(&t.view, &TriDexelOptions { cell, ..Default::default() }).ok(),
571                    };
572                    let mut sink = NullSink;
573                    match check_machine(&chain, &machine.collision, &resolved.motions, tri.as_ref(), &MachineCheckOptions::default(), &mut Runner::detached(&mut sink)) {
574                        Ok(report) => {
575                            if let Some(hit) = report.first {
576                                let motion = resolved.motions[hit.block..].iter().find_map(|b| b.source).unwrap_or(hit.block);
577                                let on_part = chain.world_to_part(&hit.angles_deg, hit.point);
578                                marks.push(Marker { at: on_part, gouge: false });
579                                collision_motions.insert(motion);
580                                collisions.push((motion, hit.body.clone(), hit.against.clone()));
581                            }
582                        }
583                        Err(e) => machine_notes.push(format!("machine check: {e}")),
584                    }
585                }
586                Err(e) => machine_notes.push(format!("machine kinematics: {e}")),
587            },
588            Err(e) => machine_notes.push(format!("machine: {e}")),
589        }
590    }
591    let range_cutters: Vec<RangeCutter> = ranges.iter().map(|r| RangeCutter { first: r.first, count: r.count, cutter: r.cutter, profile: r.profile.clone(), turning:r.turning.clone() }).collect();
592    if matches!(&stock,StockModel::Turning(_)) {
593        let mut checked=SimDriver::new(stock.clone(),DriverOptions::default()).map_err(|e|e.to_string())?;
594        // The turning motions only: live milling after them is the player's.
595        let turned=range_cutters.iter().filter(|r|r.turning.is_none()).map(|r|r.first).min().unwrap_or(timeline.len());
596        checked.advance_ranges(&timeline,&range_cutters,turned,usize::MAX,&tolerance,&mut |_|true).map_err(|e|format!("turning checked replay: {e}"))?;
597    }
598    let load_stock = stock.clone();
599    let mut driver = SimDriver::new(stock, DriverOptions::default()).map_err(|e| e.to_string())?.with_chain(chain);
600    for note in machine_notes {
601        driver.warnings.push((0, brep_cam::model::Diagnostic::new("machine-check", note)));
602    }
603    Ok(SimSession {
604        setup: setup_id,
605        player: Player::new(timeline),
606        driver,
607        ranges,
608        to_model: setup.machine_to_model(),
609        marks,
610        collision_motions,
611        collisions,
612        range_cutters,
613        load_stock,
614        sim_machine: machine.cloned(),
615        remote: None,
616        multi_axis,
617        part,
618        deviation: None,
619        legend: None,
620        mesh: StockMesh::default(),
621        mesh_version: None,
622        part_index: None,
623        remaining: None,
624        remaining_key: None,
625        epoch: NEXT_EPOCH.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
626    })
627}
628
629/// How many frames' budgets one runner chunk may hold (see `pump`).
630const RUNNER_CHUNK_GROWTH: usize = 8;
631
632/// The pane section's state.
633pub struct CamSimPanel {
634    hits: HashMap<String, egui::Rect>,
635    pub session: Option<SimSession>,
636    pub speed: f64,
637    pub stop_at_collision: bool,
638    pub cell: f64,
639    pub budget_per_frame: usize,
640    /// `budget_per_frame` was set explicitly (`cam_sim_set budgetPerFrame`):
641    /// runner chunks are then exactly that size, never grown.
642    pub budget_pinned: bool,
643    pub show_deviation: bool,
644    /// Colour the stock by remaining material at the playback point.
645    pub show_remaining: bool,
646    /// Seconds since the remaining-stock overlay was last recomputed.
647    remaining_age: f64,
648    pub notice: Option<String>,
649    /// The stock, tool and marks groups last sent to the viewport.
650    overlay: [String; 3],
651    /// What the sent stock group was built from; the stock (the whole grid's
652    /// mesh) is rebuilt and resent only when it changes, never per frame for
653    /// a moving tool.
654    overlay_stock_key: Option<String>,
655    /// While the stock is catching up or playing, a newer stock version waits
656    /// until this time to be resent. A tri-dexel stock group is hundreds of
657    /// thousands of vertices and the viewport re-parses it, so resending it
658    /// for every 64-motion chunk made the redraw, not the simulation, set the
659    /// pace (about 0.85 s per chunk on the 4th-axis part). The stock is
660    /// always resent once the player settles.
661    overlay_stock_next: Option<web_time::Instant>,
662    /// Stock groups built (automation: `overlayStockBuilds`).
663    overlay_stock_builds: u64,
664    /// An export waiting for the shell's save door.
665    pub pending_save: Option<SaveRequest>,
666    /// `true` after a load so `cam_sim_state` can report the last error.
667    pub error: Option<String>,
668    /// The machine the next load checks collisions on (from `cam_sim_load`;
669    /// the setup dialog has no machine field yet).
670    pub machine: Option<Machine>,
671    /// Toolpaths that replace operations' generated ones (by operation id),
672    /// kept for later loads like `machine`.
673    pub toolpaths: BTreeMap<String, brep_cam::model::Toolpath>,
674    /// Simulate inline even when the runner can (tests, comparison).
675    pub force_inline: bool,
676}
677
678impl Default for CamSimPanel {
679    fn default() -> Self {
680        Self::new()
681    }
682}
683
684impl CamSimPanel {
685    pub fn new() -> Self {
686        Self {
687            hits: HashMap::new(),
688            session: None,
689            speed: 1.0,
690            stop_at_collision: true,
691            cell: 0.5,
692            budget_per_frame: 64,
693            budget_pinned: false,
694            show_deviation: false,
695            show_remaining: false,
696            remaining_age: 0.0,
697            notice: None,
698            overlay: Default::default(),
699            overlay_stock_key: None,
700            overlay_stock_next: None,
701            overlay_stock_builds: 0,
702            pending_save: None,
703            error: None,
704            machine: None,
705            toolpaths: BTreeMap::new(),
706            force_inline: false,
707        }
708    }
709
710    /// Load (or reload) the simulation of a setup.
711    pub fn load(&mut self, state: &mut EngineState, doc: &CamDocument, setup_id: Option<&str>) -> Result<(), String> {
712        if let Some(old) = self.session.as_mut() {
713            old.cancel(state);
714            if let Some(r) = &old.remote {
715                let _ = state.cam_sim_submit(CamSimJob { session: r.session, seq: u64::MAX, request: CamSimRequest::Drop });
716            }
717        }
718        match build_session(state, doc, setup_id, self.cell, self.machine.as_ref(), &self.toolpaths) {
719            Ok(mut s) => {
720                if !self.force_inline {
721                    // Probe the runner with the Load itself: a runner that
722                    // cannot simulate declines and the session stays inline.
723                    let session = NEXT_SESSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
724                    let mut remote = RemoteSim { session, ..Default::default() };
725                    remote.seq = 1;
726                    let load = CamSimRequest::Load {
727                        timeline: s.player.timeline.clone(),
728                        stock: s.load_stock.clone(),
729                        ranges: s.range_cutters.clone(),
730                        options: s.driver.options.clone(),
731                        machine: s.sim_machine.clone(),
732                    };
733                    if state.cam_sim_submit(CamSimJob { session, seq: 1, request: load }) {
734                        remote.in_flight = Some((1, 0));
735                        remote.submitted = 1;
736                        s.remote = Some(remote);
737                    }
738                }
739                s.player.set_speed(self.speed).ok();
740                s.player.stop_at_collision = self.stop_at_collision;
741                self.notice = Some(format!(
742                    "{} motions, {:.1} s, {}{}",
743                    s.player.timeline.len(),
744                    s.player.timeline.total_seconds,
745                    if matches!(&s.driver.stock, StockModel::Turning(_)) { "axisymmetric stock" } else if s.multi_axis { "tri-dexel stock" } else { "Z-dexel stock" },
746                    if s.marks.is_empty() { String::new() } else { format!(", {} collision marks", s.marks.len()) }
747                ));
748                self.session = Some(s);
749                self.error = None;
750                Ok(())
751            }
752            Err(e) => {
753                self.error = Some(e.clone());
754                self.notice = Some(e.clone());
755                Err(e)
756            }
757        }
758    }
759
760    pub fn unload(&mut self, state: &mut EngineState) {
761        if let Some(mut s) = self.session.take() {
762            s.cancel(state);
763            if let Some(r) = &s.remote {
764                let _ = state.cam_sim_submit(CamSimJob { session: r.session, seq: u64::MAX, request: CamSimRequest::Drop });
765            }
766        }
767        self.overlay = Default::default();
768        self.overlay_stock_key = None;
769    }
770
771    /// Stop simulating (see [`SimSession::cancel`]).
772    pub fn cancel(&mut self, state: &mut EngineState) -> bool {
773        let stopped = self.session.as_mut().map_or(false, |s| s.cancel(state));
774        if stopped {
775            self.notice = Some("simulation stopped: the stock shows the last finished motion".into());
776        }
777        stopped
778    }
779
780    /// Advance the transport by `dt` seconds and the stock toward it; `true`
781    /// when another frame is needed. The app calls it once per frame, drawn
782    /// or not: called from the pane, a simulation loaded while the CAM pane
783    /// was not drawn never read the runner's reply and never caught up.
784    pub fn pump(&mut self, state: &mut EngineState, dt: f64) -> bool {
785        let stop_at_collision = self.stop_at_collision;
786        let budget = self.budget_per_frame;
787        // The runner cuts a 64-motion chunk in tens of milliseconds and then
788        // waits for the next frame, so a long catch-up was paced by frames
789        // (about 0.4 s each on the thin wall), not by cutting. Off the UI
790        // thread a chunk may hold RUNNER_CHUNK_GROWTH frames' budgets; a Stop
791        // still cancels it between two motions natively, and the browser drops
792        // the chunk when it lands.
793        let chunk = if self.budget_pinned { budget } else { budget.saturating_mul(RUNNER_CHUNK_GROWTH) };
794        let Some(s) = self.session.as_mut() else { return false };
795        self.remaining_age += dt;
796        let before = s.player.position;
797        let moved = s.player.advance(dt);
798        if moved && stop_at_collision && s.player.state == PlayState::Playing {
799            // Pause at the first collision motion entered since the last frame.
800            let entered = (before.motion..=s.player.position.motion).find(|m| s.collision_motions.contains(m) && (*m > before.motion || before.fraction == 0.0));
801            if let Some(m) = entered {
802                s.player.pause();
803                s.player.position = brep_cam::multiaxis::sim::Position { motion: m, fraction: 0.0 };
804                self.notice = Some(format!("stopped at motion {m}: collision"));
805            }
806        }
807        match s.drive(state, budget, chunk) {
808            Ok(pending) => pending || s.player.state == PlayState::Playing,
809            Err(e) => {
810                self.notice = Some(e);
811                false
812            }
813        }
814    }
815
816    /// Push the viewport groups (stock, tool, marks) when they changed.
817    pub fn push_overlay(&mut self, state: &mut EngineState) {
818        // The remaining-stock colours follow the playback point: on every stock
819        // change while paused, at most twice a second while playing.
820        if self.show_remaining {
821            if let Some(s) = self.session.as_mut() {
822                let playing = s.player.state == PlayState::Playing;
823                if !playing || self.remaining_age >= 0.5 {
824                    match s.refresh_remaining() {
825                        Ok(true) => self.remaining_age = 0.0,
826                        Ok(false) => {}
827                        Err(e) => {
828                            self.notice = Some(e);
829                            self.show_remaining = false;
830                        }
831                    }
832                }
833            }
834        }
835        let show_remaining = self.show_remaining;
836        let mut built = None;
837        let groups = match self.session.as_mut() {
838            None => {
839                self.overlay_stock_key = None;
840                [STOCK_GROUP, TOOL_GROUP, MARKS_GROUP].map(|name| Some(json!({ "name": name }).to_string()))
841            }
842            Some(s) => {
843                let to_model = s.to_model;
844                let remaining = show_remaining && s.remaining.is_some();
845                let legend = if self.show_deviation { s.legend.as_ref().map(|l| l.to_string()) } else { None };
846                let look = format!("{}:{}:{:?}:{:?}", s.epoch, remaining, s.remaining_key, legend);
847                let key = format!("{look}:{}", s.driver.version);
848                // Only the stock version moved: hold it back while the player
849                // is still busy and the last resend's interval has not passed.
850                let settled = s.caught_up() && s.player.state != PlayState::Playing;
851                let held = !settled
852                    && self.overlay_stock_key.as_deref().is_some_and(|k| k.rsplit_once(':').map(|(l, _)| l) == Some(look.as_str()))
853                    && self.overlay_stock_next.is_some_and(|t| web_time::Instant::now() < t);
854                // An unchanged stock is neither copied nor compared: it is the
855                // whole grid's mesh (80 MB of JSON on a thin-wall part), and
856                // cloning it every frame cost about 0.1 s per frame.
857                let stock = if self.overlay_stock_key.as_deref() == Some(key.as_str()) || held {
858                    None
859                } else {
860                    built = Some(web_time::Instant::now());
861                    self.overlay_stock_builds += 1;
862                    self.overlay_stock_key = Some(key);
863                    match (&s.remaining, remaining) {
864                        (Some(r), true) => remaining_group(r, &to_model),
865                        _ => {
866                            let deviation = if self.show_deviation { s.deviation.clone() } else { None };
867                            let scale = s.legend.as_ref().and_then(|l| l["scale"].as_f64()).unwrap_or(1.0);
868                            stock_group(s.mesh(), &to_model, deviation.as_ref().map(|d| (d, scale)))
869                        }
870                    }
871                    .to_string()
872                    .into()
873                };
874                let tool = match (s.player.pose(), s.range_of(s.player.position.motion)) {
875                    (Some((tip, axis)), Some(r)) if r.profile.is_some() => tool_group(r.profile.as_ref().unwrap(), tip, axis, &to_model),
876                    _ => json!({ "name": TOOL_GROUP }),
877                };
878                [stock, Some(tool.to_string()), Some(marks_group(&s.marks, &to_model).to_string())]
879            }
880        };
881        // Groups are upserted by name: send only the ones that changed.
882        let changed: Vec<usize> = (0..3).filter(|&i| groups[i].as_ref().is_some_and(|g| *g != self.overlay[i])).collect();
883        if !changed.is_empty() {
884            let body: Vec<&str> = changed.iter().map(|&i| groups[i].as_deref().unwrap_or_default()).collect();
885            let _ = state.widgets.set_overlay_json(&format!("{{\"groups\":[{}]}}", body.join(",")));
886            state.dirty = true;
887            for (slot, group) in self.overlay.iter_mut().zip(groups) {
888                if let Some(group) = group {
889                    *slot = group;
890                }
891            }
892        }
893        if let Some(start) = built {
894            // The next mid-run resend waits at least twice what this one cost,
895            // so redrawing takes at most a third of the time.
896            let cost = start.elapsed();
897            self.overlay_stock_next = Some(web_time::Instant::now() + (cost * 2).max(web_time::Duration::from_millis(500)));
898        }
899    }
900
901    /// The simulated stock as STL text (model coordinates).
902    pub fn export_stl(&mut self) -> Option<String> {
903        let s = self.session.as_mut()?;
904        let to_model = s.to_model;
905        let name = format!("stock-{}", s.setup);
906        Some(stock_stl(s.mesh(), &to_model, &name))
907    }
908
909    pub fn state_json(&self) -> Value {
910        json!({
911            "loaded": self.session.is_some(),
912            "speed": self.speed,
913            "stopAtCollision": self.stop_at_collision,
914            "cell": self.cell,
915            "showDeviation": self.show_deviation,
916            "showRemaining": self.show_remaining,
917            "notice": self.notice,
918            "error": self.error,
919            "session": self.session.as_ref().map(|s| s.state_json()),
920            "overlayStockBuilds": self.overlay_stock_builds,
921        })
922    }
923
924    pub fn hits_json(&self) -> String {
925        crate::automation::hit_rects::hits_json(&self.hits)
926    }
927
928    /// The section's widget rects, merged into the CAM pane's blob.
929    pub fn hit_rects(&self) -> &HashMap<String, egui::Rect> {
930        &self.hits
931    }
932
933    pub fn clear_hits(&mut self) {
934        self.hits.clear();
935    }
936
937    /// The pane section.
938    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState, doc: &CamDocument, setup_hint: Option<&str>) {
939        self.hits.clear();
940        let header = egui::CollapsingHeader::new("Simulation").default_open(true).show(ui, |ui| {
941            ui.horizontal_wrapped(|ui| {
942                let load = ui.add(ui_kit::Button::new(if self.session.is_some() { "Reload" } else { "Load" })).on_hover_text("Simulate the generated operations of the selected setup");
943                self.hits.insert("cam:sim:load".into(), load.rect);
944                if load.clicked() {
945                    let _ = self.load(state, doc, setup_hint);
946                }
947                let busy = self.session.as_ref().map_or(false, |s| !s.caught_up());
948                let stop = ui_kit::button::add_enabled(ui, busy, ui_kit::Button::new("Stop")).on_hover_text("Stop simulating: keep the stock of the last finished motion");
949                self.hits.insert("cam:sim:cancel".into(), stop.rect);
950                if stop.clicked() {
951                    self.cancel(state);
952                }
953                let has = self.session.is_some();
954                let playing = self.session.as_ref().map_or(false, |s| s.player.state == PlayState::Playing);
955                let play = ui_kit::button::add_enabled(ui, has, ui_kit::Button::new(if playing { "Pause" } else { "Play" }));
956                self.hits.insert("cam:sim:play".into(), play.rect);
957                if play.clicked() {
958                    if let Some(s) = self.session.as_mut() {
959                        s.player.toggle();
960                    }
961                }
962                let back = ui_kit::button::add_enabled(ui, has, ui_kit::Button::new("|<"));
963                self.hits.insert("cam:sim:step:back".into(), back.rect);
964                if back.clicked() {
965                    if let Some(s) = self.session.as_mut() {
966                        s.player.step_back();
967                    }
968                }
969                let fwd = ui_kit::button::add_enabled(ui, has, ui_kit::Button::new(">|"));
970                self.hits.insert("cam:sim:step:forward".into(), fwd.rect);
971                if fwd.clicked() {
972                    if let Some(s) = self.session.as_mut() {
973                        s.player.step_forward();
974                    }
975                }
976            });
977            if let Some(s) = self.session.as_mut() {
978                let mut progress = s.player.progress();
979                let slider = ui.add(egui::Slider::new(&mut progress, 0.0..=1.0).show_value(false).text("scrub"));
980                self.hits.insert("cam:sim:scrub".into(), slider.rect);
981                if slider.changed() {
982                    s.player.pause();
983                    s.player.scrub(progress);
984                }
985                ui.horizontal_wrapped(|ui| {
986                    let mut speed = self.speed;
987                    let drag = ui.add(egui::DragValue::new(&mut speed).range(0.1..=100.0).speed(0.1).prefix("speed ×"));
988                    self.hits.insert("cam:sim:speed".into(), drag.rect);
989                    if drag.changed() && s.player.set_speed(speed).is_ok() {
990                        self.speed = speed;
991                    }
992                    let stop = ui_kit::checkbox(ui, &mut self.stop_at_collision, "stop at collision");
993                    self.hits.insert("cam:sim:stop".into(), stop.rect);
994                    s.player.stop_at_collision = self.stop_at_collision;
995                });
996                let op = s.player.timeline.operation_of(s.player.position.motion).map(|i| s.player.timeline.operations[i].operation.to_string()).unwrap_or_default();
997                let time = s.player.time();
998                let total = s.player.timeline.total_seconds;
999                let line = ui.label(format!(
1000                    "{op}  {:.1} s / {:.1} s  motion {}/{}  applied {}  removed {:.1}  {}",
1001                    time,
1002                    total,
1003                    s.player.position.motion + 1,
1004                    s.player.timeline.len(),
1005                    s.driver.applied,
1006                    s.driver.removed_volume,
1007                    if s.caught_up() { "" } else { "(simulating…)" }
1008                ));
1009                self.hits.insert("cam:sim:readout".into(), line.rect);
1010                if !s.marks.is_empty() {
1011                    ui_kit::status::error(ui, format!("{} collision / gouge marks (red points)", s.marks.len()));
1012                }
1013                if !s.driver.unsupported.is_empty() {
1014                    ui_kit::status::warn(ui, format!("{} tilted motions not cut by the Z-dexel", s.driver.unsupported.len()));
1015                }
1016                ui.horizontal_wrapped(|ui| {
1017                    let compare = ui.add(ui_kit::Button::new("Compare to part")).on_hover_text("Deviation of the simulated stock from the part: excess blue, gouge red");
1018                    self.hits.insert("cam:sim:deviation".into(), compare.rect);
1019                    if compare.clicked() {
1020                        match s.compare(&DeviationOptions::default(), 1.0) {
1021                            Ok(()) => self.show_deviation = true,
1022                            Err(e) => self.notice = Some(e),
1023                        }
1024                    }
1025                    let shown = ui.add_enabled(s.deviation.is_some(), egui::Checkbox::new(&mut self.show_deviation, "colour map"));
1026                    self.hits.insert("cam:sim:deviation:show".into(), shown.rect);
1027                    let remaining = ui
1028                        .add_enabled(s.part.is_some(), egui::Checkbox::new(&mut self.show_remaining, "Remaining stock"))
1029                        .on_hover_text("Colour the stock at the playback point by the material left over the part: red gouge, green within the operation tolerance, blue up to 10× it, yellow beyond");
1030                    self.hits.insert("cam:sim:remaining".into(), remaining.rect);
1031                    let export = ui.add(ui_kit::Button::new("Export stock (STL)"));
1032                    self.hits.insert("cam:sim:export".into(), export.rect);
1033                    if export.clicked() {
1034                        let name = format!("stock-{}.stl", s.setup);
1035                        let solid = format!("stock-{}", s.setup);
1036                        let to_model = s.to_model;
1037                        let stl = stock_stl(s.mesh(), &to_model, &solid);
1038                        self.pending_save = Some(SaveRequest { title: "Export the simulated stock".into(), file_name: name, body: SaveBody::Text(stl) });
1039                    }
1040                });
1041                if let (true, Some(r)) = (self.show_remaining, &s.remaining) {
1042                    let tol = r.tolerance;
1043                    let (_, _, gouge) = r.counts();
1044                    let line = ui.label(format!(
1045                        "remaining stock (mm): red < {:.3}  green ±{:.3}  blue ≤ {:.3}  yellow > {:.3}   max excess {:.3}{}",
1046                        -tol,
1047                        tol,
1048                        10.0 * tol,
1049                        10.0 * tol,
1050                        r.max.max(0.0),
1051                        if gouge > 0 { format!("   {gouge} gouged vertices") } else { String::new() }
1052                    ));
1053                    self.hits.insert("cam:sim:remaining:legend".into(), line.rect);
1054                }
1055                if let Some(legend) = &s.legend {
1056                    let line = ui.label(format!(
1057                        "deviation: min {:.3}  max {:.3}  tolerance ±{:.3}  (green within, blue excess, red gouge)",
1058                        legend["min"].as_f64().unwrap_or(0.0),
1059                        legend["max"].as_f64().unwrap_or(0.0),
1060                        legend["tolerance"].as_f64().unwrap_or(0.0)
1061                    ));
1062                    self.hits.insert("cam:sim:legend".into(), line.rect);
1063                }
1064            }
1065            if let Some(notice) = &self.notice {
1066                let label = ui.label(egui::RichText::new(notice).weak());
1067                self.hits.insert("cam:sim:notice".into(), label.rect);
1068            }
1069        });
1070        self.hits.insert("cam:sim:header".into(), header.header_response.rect);
1071        self.push_overlay(state);
1072    }
1073}
1074
1075pub static HIT_KEYS: &[HitKeyDoc] = &[
1076    HitKeyDoc { panel: "cam", prefix: "cam:sim:header", meaning: "the Simulation section's header", command: None },
1077    HitKeyDoc { panel: "cam", prefix: "cam:sim:load", meaning: "load (or reload) the simulation of the selected setup's generated operations", command: Some("cam_sim_load") },
1078    HitKeyDoc { panel: "cam", prefix: "cam:sim:cancel", meaning: "stop simulating: the stock keeps the last finished motion", command: Some("cam_sim_cancel") },
1079    HitKeyDoc { panel: "cam", prefix: "cam:sim:play", meaning: "play or pause the simulation", command: Some("cam_sim_play") },
1080    HitKeyDoc { panel: "cam", prefix: "cam:sim:step:back", meaning: "step to the start of the current (or previous) motion", command: Some("cam_sim_step") },
1081    HitKeyDoc { panel: "cam", prefix: "cam:sim:step:forward", meaning: "step to the end of the current (or next) motion", command: Some("cam_sim_step") },
1082    HitKeyDoc { panel: "cam", prefix: "cam:sim:scrub", meaning: "the scrub slider over the program's time", command: Some("cam_sim_scrub") },
1083    HitKeyDoc { panel: "cam", prefix: "cam:sim:speed", meaning: "playback speed relative to machining time", command: Some("cam_sim_set") },
1084    HitKeyDoc { panel: "cam", prefix: "cam:sim:stop", meaning: "pause when a collision motion is entered", command: Some("cam_sim_set") },
1085    HitKeyDoc { panel: "cam", prefix: "cam:sim:readout", meaning: "operation, time, motion, applied count and removed volume", command: Some("cam_sim_state") },
1086    HitKeyDoc { panel: "cam", prefix: "cam:sim:deviation", meaning: "compare the simulated stock with the part (deviation colour map)", command: Some("cam_sim_deviation") },
1087    HitKeyDoc { panel: "cam", prefix: "cam:sim:deviation:show", meaning: "show or hide the deviation colour map", command: Some("cam_sim_set") },
1088    HitKeyDoc { panel: "cam", prefix: "cam:sim:remaining", meaning: "colour the stock by remaining material at the playback point (bands from the operation tolerance)", command: Some("cam_sim_set") },
1089    HitKeyDoc { panel: "cam", prefix: "cam:sim:remaining:legend", meaning: "the remaining-stock legend: band edges in mm and the largest excess", command: Some("cam_sim_state") },
1090    HitKeyDoc { panel: "cam", prefix: "cam:sim:export", meaning: "export the simulated stock as STL through the save door", command: Some("cam_sim_export") },
1091    HitKeyDoc { panel: "cam", prefix: "cam:sim:legend", meaning: "the deviation legend", command: None },
1092    HitKeyDoc { panel: "cam", prefix: "cam:sim:notice", meaning: "what the last simulation action said", command: None },
1093];
1094