diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 5b550a86..197e494e 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -2053,7 +2053,7 @@ impl IntentSession { /// unmodified default post: formats and independently decodes them with /// `formatter`, then runs the same checks. Returns the chunk, and the /// decoder's position and plane after it. - #[pyo3(signature=(events_json,formatter,position,units,plane,tool,cancel=None))] + #[pyo3(signature=(events_json,formatter,position,units,plane,tool,placed,cancel=None))] #[allow(clippy::too_many_arguments, clippy::type_complexity)] fn consume_default<'py>( &mut self, @@ -2064,8 +2064,14 @@ impl IntentSession { units: f64, plane: Option<&str>, tool: &str, + placed: (bool, bool, bool), cancel: Option>, - ) -> PyResult<(Bound<'py, PyBytes>, (f64, f64, f64), Option)> { + ) -> PyResult<( + Bound<'py, PyBytes>, + (f64, f64, f64), + Option, + (bool, bool, bool), + )> { use camlib::motion::{Event, Motion, MoveKind}; if !self.initial.is_empty() || events_json.len() > 512 * 1024 { return Err(PyValueError::new_err( @@ -2092,11 +2098,12 @@ impl IntentSession { .ok_or_else(|| PyValueError::new_err("invalid decoder plane")) }) .transpose()?; - let (blocks, decoded, end, plane) = formatter.format_decode( + let (blocks, decoded, end, plane, placed) = formatter.format_decode( &motions, [position.0, position.1, position.2], units, plane, + [placed.0, placed.1, placed.2], )?; let decoded: Vec> = motions .iter() @@ -2133,6 +2140,7 @@ impl IntentSession { PyBytes::new(py, &bytes), (end[0], end[1], end[2]), plane.map(|i| names[i].to_string()), + (placed[0], placed[1], placed[2]), )) } #[pyo3(signature=(lines_json,cancel=None))] @@ -2418,7 +2426,9 @@ impl DefaultMotionPost { } /// Blocks for each source motion and its decoded motion words (None when /// a linear block rounds to the current position), the decoded end - /// position and plane. `units` is the decoder's active unit scale. + /// position and plane, and which axes are still where the controller + /// placed them. `units` is the decoder's active unit scale; `placed` the + /// post's `_placed` before the batch. #[allow(clippy::type_complexity)] fn motions( &self, @@ -2426,11 +2436,13 @@ impl DefaultMotionPost { position: (f64, f64, f64), units: f64, plane: Option<&str>, + placed: (bool, bool, bool), ) -> PyResult<( Vec>, Vec)>>, (f64, f64, f64), Option, + (bool, bool, bool), )> { use camlib::motion::Curve; let names = ["xy", "xz", "yz"]; @@ -2444,8 +2456,13 @@ impl DefaultMotionPost { .ok_or_else(|| PyValueError::new_err("invalid decoder plane")) }) .transpose()?; - let (blocks, decoded, position, plane) = - self.format_decode(&motions, [position.0, position.1, position.2], units, plane)?; + let (blocks, decoded, position, plane, placed) = self.format_decode( + &motions, + [position.0, position.1, position.2], + units, + plane, + [placed.0, placed.1, placed.2], + )?; let point = |p: camlib::motion::Vec3| (p[0], p[1], p[2]); let words = decoded .into_iter() @@ -2483,13 +2500,16 @@ impl DefaultMotionPost { words, point(position), plane.map(|i| names[i].to_string()), + (placed[0], placed[1], placed[2]), )) } } impl DefaultMotionPost { /// Blocks for each source motion, its independently decoded curve, feed /// and rapid flag (None when a linear block rounds to the current - /// position), the decoded end position and plane index. + /// position), the decoded end position and plane index, and the axes + /// still where the controller placed them (`placed` on entry: the post's + /// `_placed`). #[allow(clippy::type_complexity)] fn format_decode( &self, @@ -2497,11 +2517,13 @@ impl DefaultMotionPost { position: camlib::motion::Vec3, units: f64, plane: Option, + placed: [bool; 3], ) -> PyResult<( Vec>, Vec, bool)>>, camlib::motion::Vec3, Option, + [bool; 3], )> { use camlib::motion::{Curve, MoveKind, Plane}; let names = ["xy", "xz", "yz"]; @@ -2515,6 +2537,7 @@ impl DefaultMotionPost { // against its source, so a missing code is refused. let mut selected = plane; let mut position = position; + let mut placed = placed; let declared = |code: &Option, effect: &str| { code.clone() .ok_or_else(|| PyValueError::new_err(format!("dialect does not declare {effect}"))) @@ -2598,6 +2621,7 @@ impl DefaultMotionPost { for &i in &axes { addresses.push_str(&self.axes[i]); values.push(e[i]); + placed[i] = false; } addresses.push_str(&self.centers[u]); addresses.push_str(&self.centers[v]); @@ -2615,13 +2639,29 @@ impl DefaultMotionPost { && (position[0] - end[0]).hypot(position[1] - end[1]) + 0.5 * self.unit * 10f64.powi(-(self.decimals as i32)) <= self.output_tolerance; - for &i in &axes { - addresses.push_str(&self.axes[i]); - values.push(if vertical && i < 2 { + let value = |i: usize| { + if vertical && i < 2 { position[i] } else { end[i] - }); + } + }; + // `GCodePost.on_motion`: an axis the controller placed that + // this move keeps gets no word (a word would command it + // through the actual work offset). A block left with no axis + // word is written whole: a bare G0 is no motion block. + let mut kept: Vec = axes + .iter() + .copied() + .filter(|&i| !(placed[i] && value(i) == position[i])) + .collect(); + if kept.is_empty() { + kept = axes.clone(); + } + for i in kept { + addresses.push_str(&self.axes[i]); + values.push(value(i)); + placed[i] = false; } } if let Some(f) = m.feed_mm_min { @@ -2679,7 +2719,7 @@ impl DefaultMotionPost { blocks.push(lines); decoded.push(result); } - Ok((blocks, decoded, position, plane)) + Ok((blocks, decoded, position, plane, placed)) } } diff --git a/docs/lnc-mill-post.md b/docs/lnc-mill-post.md index 3a62eb1e..7ac00cc4 100644 --- a/docs/lnc-mill-post.md +++ b/docs/lnc-mill-post.md @@ -128,7 +128,7 @@ M6 G1 G43 H7 Z3. F3000. M3 S12000 M8 -G1 X10. Y0. Z3. F1200. +G1 X10. Z3. F1200. G2 X20. Y0. I5. J0. F1200. ... M5 diff --git a/docs/posts.md b/docs/posts.md index fb847cc0..087db3c5 100644 --- a/docs/posts.md +++ b/docs/posts.md @@ -339,6 +339,56 @@ deviation of a posted arc includes the spiral: the start/end radius difference of the written words is added to the bound before it is compared with the posting tolerance. +## Axis words a straight move leaves out + +A straight move (G0/G1) leaves out the word of an axis it does not move +while that axis is still where the controller placed it itself (#367): + +- At the program start every axis is where the controller placed it (the + machine's start pose). +- A tool change whose declared mode moves axes to a machine position places + them again, from its change block (`M6`, or the `T` word with + `tool_change="direct_t"`/`"lathe_t"`): Z with + `tool_change_position_mode="z_home"`, every axis with `"table"`. + `"preserve_tip"` and `"preserve_spindle"` place none. +- An axis leaves that state with the first block that writes its word: a + move that changes it, an arc or helix (they always name their plane's + axes), a canned cycle, a tapping or threading block, or a block a + controller post writes itself (a FANUC `G1 G43 H.. Z..`, a Carvera + `G53 G0 Z-3`). A probing cycle leaves every axis written, since its macros + move axes their blocks need not name. + +An axis word commands the axis to that work coordinate through the +controller's *actual* work offset, even at the value it already has. Where +the controller placed the axis itself, the program's nominal offset and the +real one differ by the calibration interval, so the word would move the axis +by that error; at a travel limit, past it. A mill homed at X 0 and Y 0 (its +travel minimums) facing from its home pose writes + +``` +G0 Z10 +G0 X-24 Y-17.6 Z10 +``` + +and not `G0 X-250 Y-200 Z10` first, which LinuxCNC refuses as beyond the soft +limit when the real offset is 0.02 mm the other way. The word is left out +only when the value the block would write equals the controller's current +position exactly (the vertical-move rule above keeps the current XY, so a +move vertical in the plan qualifies), and never in a block that turns cutter +compensation on or off. A move that would keep no axis word at all (it moves +nothing) is written whole, since a bare `G0` is no motion block. Every decoder reads an absent word as the axis's +current position, and the machine check holds an axis no block has written +exactly at its declared position ([machine coverage](machine.md)), so the +first moves from a pose on a travel limit are checked inside it. Only the +blocks before each axis is first written change; the toolpaths do not. + +The default post (`GCodePost.on_motion`, and every controller post in +`examples/` built on it), the native default formatter and the Rust posts +(default, Haas NGC, Carvera) apply the rule alike. The state is +`self._placed` (one flag per work axis), kept by `PostProcessor._call` from +the blocks each hook writes; a post that writes its own straight-move blocks +can read it. + ## Writing your own post Subclass `GCodePost` and override the hooks you need. Each hook writes lines diff --git a/fixtures/posts/F0IMB1000.NC b/fixtures/posts/F0IMB1000.NC index a668b61e..f92fc589 100644 --- a/fixtures/posts/F0IMB1000.NC +++ b/fixtures/posts/F0IMB1000.NC @@ -17,7 +17,7 @@ M6 G1 G43 H7 Z3. F3000. M3 S12000 M8 -G1 X10. Y0. Z3. F1200. +G1 X10. Z3. F1200. M9 M5 G1 G49 Z63. F3000. diff --git a/fixtures/posts/LNC-MILL-ARCS.NC b/fixtures/posts/LNC-MILL-ARCS.NC index 90e4d2cc..65aab318 100644 --- a/fixtures/posts/LNC-MILL-ARCS.NC +++ b/fixtures/posts/LNC-MILL-ARCS.NC @@ -15,7 +15,7 @@ M6 G1 G43 H7 Z3. F3000. M3 S12000 M8 -G1 X10. Y0. Z3. F1200. +G1 X10. Z3. F1200. G2 X20. Y0. I5. J0. F1200. G18 G2 X25. Z8. K5. I0. F1200. diff --git a/fixtures/posts/rust/carvera-arcs.nc b/fixtures/posts/rust/carvera-arcs.nc index 21183380..30780a8f 100644 --- a/fixtures/posts/rust/carvera-arcs.nc +++ b/fixtures/posts/rust/carvera-arcs.nc @@ -11,7 +11,7 @@ T1 M6 M3 S12000 M400 M7 -G0 X6 Y13 Z14 +G0 X6 Y13 G1 X6 Y13 Z8 F150 G1 X6 Y16 Z8 F600 G2 X26 Y16 I10 J0 F600 diff --git a/fixtures/posts/rust/carvera-drill.nc b/fixtures/posts/rust/carvera-drill.nc index 7ab899b5..333ee236 100644 --- a/fixtures/posts/rust/carvera-drill.nc +++ b/fixtures/posts/rust/carvera-drill.nc @@ -11,7 +11,7 @@ T1 M6 M3 S6000 M400 M7 -G0 X8 Y8 Z12 +G0 X8 Y8 G0 X8 Y8 Z11 G1 X8 Y8 Z4 F150 G4 P0.5 diff --git a/fixtures/posts/rust/haas-program.nc b/fixtures/posts/rust/haas-program.nc index eddc7064..0c22e2e1 100644 --- a/fixtures/posts/rust/haas-program.nc +++ b/fixtures/posts/rust/haas-program.nc @@ -21,7 +21,7 @@ M6 G43 H7 M3 S12000 M8 -G1 X10. Y0. Z3. F1200. +G1 X10. F1200. M9 M5 M0 diff --git a/fixtures/posts/rust/homed-facing.json b/fixtures/posts/rust/homed-facing.json new file mode 100644 index 00000000..c6895525 --- /dev/null +++ b/fixtures/posts/rust/homed-facing.json @@ -0,0 +1,583 @@ +{ + "accept": [], + "frame": { + "origin_mm": [ + 0, + 0, + 0 + ], + "x": [ + 1, + 0, + 0 + ], + "y": [ + 0, + 1, + 0 + ], + "z": [ + 0, + 0, + 1 + ] + }, + "machine": { + "arcs": true, + "crash_model": { + "absent_components": { + "column": "synthetic stand", + "enclosure": "open stand", + "table": "remote support" + }, + "allowed_contacts": [ + { + "bodies": [ + "head", + "@tool" + ], + "reason": "tool mounted in spindle" + } + ], + "axes": [ + { + "drive": "head", + "max_mm": 500, + "min_mm": 0 + }, + { + "drive": "head", + "max_mm": 400, + "min_mm": 0 + }, + { + "drive": "head", + "max_mm": 0, + "min_mm": -300 + } + ], + "bodies": [ + { + "component": "spindle_head", + "id": "head", + "indexed_solids": {}, + "mount": "head", + "solids": [ + { + "kind": "box", + "max_mm": [ + 1, + 1, + 10 + ], + "min_mm": [ + -1, + -1, + 0 + ] + } + ] + } + ], + "controller_reference": "synthetic exact-stop controller", + "id": "homed-at-limits", + "initial_axes_mm": [ + 0, + 0, + 0 + ], + "initial_tool": null, + "options": { + "max_axis_tests": 1000000, + "max_findings": 128, + "spatial_resolution_mm": 0.05, + "stock_contact": { + "max_cell_reads": 2000000, + "max_findings": 128, + "max_nodes": 200000, + "spatial_resolution_mm": 0.001, + "tolerance_mm": 1e-05 + }, + "tolerance_mm": 1e-05 + }, + "process": "milling", + "program_end_route_mm": [], + "rapid_mode": "linear", + "revision": "1", + "tool_change_routes": { + "face8": { + "after_index_mm": [], + "before_index_mm": [], + "index_envelopes": [ + { + "kind": "box", + "max_mm": [ + 20, + 20, + 1 + ], + "min_mm": [ + -20, + -20, + -61 + ] + } + ], + "reference": "synthetic complete indexing enclosure", + "replaces": [ + "@tool" + ] + } + }, + "tools": [ + { + "body_solids": [], + "gauge_offset_max_mm": [ + 0, + 0, + 60 + ], + "gauge_offset_min_mm": [ + 0, + 0, + 60 + ], + "length_register": 1, + "tool": "face8" + } + ], + "units": "mm", + "version": 1, + "work_error_max_mm": [ + 0.02, + 0.02, + 0.02 + ], + "work_error_min_mm": [ + -0.02, + -0.02, + -0.02 + ], + "work_offset": 1, + "work_to_machine": { + "origin_mm": [ + 250.0, + 200.0, + -150.0 + ], + "x": [ + 1, + 0, + 0 + ], + "y": [ + 0, + 1, + 0 + ], + "z": [ + 0, + 0, + 1 + ] + } + }, + "decimals": 3, + "dialect": { + "axes": [ + "X", + "Y", + "Z" + ], + "beam_effect": "spindle_cw", + "beam_s_max": null, + "centers": [ + "I", + "J", + "K" + ], + "chip_break_lift_mm": 0.254, + "commands": [ + { + "code": "G0", + "effect": "rapid" + }, + { + "code": "G1", + "effect": "linear" + }, + { + "code": "G2", + "effect": "arc_cw" + }, + { + "code": "G3", + "effect": "arc_ccw" + }, + { + "code": "G21", + "effect": "units_mm" + }, + { + "code": "G20", + "effect": "units_inch" + }, + { + "code": "G90", + "effect": "absolute" + }, + { + "code": "G91.1", + "effect": "center_incremental" + }, + { + "code": "G17", + "effect": "plane_xy" + }, + { + "code": "G18", + "effect": "plane_xz" + }, + { + "code": "G19", + "effect": "plane_yz" + }, + { + "code": "G94", + "effect": "feed_per_minute" + }, + { + "code": "G97", + "effect": "rpm_mode" + }, + { + "code": "G40", + "effect": "radius_off" + }, + { + "code": "G41", + "effect": "radius_left" + }, + { + "code": "G42", + "effect": "radius_right" + }, + { + "code": "G49", + "effect": "length_off" + }, + { + "code": "G80", + "effect": "cycles_off" + }, + { + "code": "G92.1", + "effect": "frame_reset" + }, + { + "code": "G61.1", + "effect": "exact_stop" + }, + { + "code": "G43", + "effect": "length_on" + }, + { + "code": "M3", + "effect": "spindle_cw" + }, + { + "code": "M4", + "effect": "spindle_ccw" + }, + { + "code": "M5", + "effect": "spindle_off" + }, + { + "code": "M6", + "effect": "tool_change" + }, + { + "code": "M7", + "effect": "mist" + }, + { + "code": "M8", + "effect": "flood" + }, + { + "code": "M9", + "effect": "coolant_off" + }, + { + "code": "M0", + "effect": "stop" + }, + { + "code": "M1", + "effect": "optional_stop" + }, + { + "code": "M2", + "effect": "end" + }, + { + "code": "G4", + "effect": "dwell" + }, + { + "code": "G81", + "effect": "drill_cycle" + }, + { + "code": "G82", + "effect": "drill_dwell_cycle" + }, + { + "code": "G83", + "effect": "peck_cycle" + }, + { + "code": "G73", + "effect": "chip_break_cycle" + }, + { + "code": "G98", + "effect": "cycle_return_initial" + }, + { + "code": "G85", + "effect": "bore_cycle" + }, + { + "code": "G89", + "effect": "bore_dwell_cycle" + }, + { + "code": "G86", + "effect": "bore_stop_cycle" + }, + { + "code": "G33.1", + "effect": "tap_synchronized" + }, + { + "code": "G99", + "effect": "cycle_return_r" + } + ], + "compensation_register": true, + "compensation_with_move": false, + "compensation_word": "D", + "css_limit_word": null, + "cycle_dwell_unit": "s", + "dwell_max_s": 100000.0, + "dwell_resolution_s": 0.001, + "dwell_word": "P", + "feed_word": "F", + "fixed_modes": [], + "height_control_word": null, + "length_activation": "explicit", + "length_word": "H", + "oriented_edge_deg": null, + "parentheses_comments": true, + "peck_reentry_mm": 0.254, + "probe_fast_feed_mm_min": null, + "probe_switching": false, + "probing": null, + "radius_relative_tolerance": 0.001, + "radius_tolerance_mm": 0.00127, + "speed_word": "S", + "tap_pitch_word": null, + "thread_lead_word": "K", + "tool_change": "m6", + "tool_word": "T", + "work_offsets": [ + "G54", + "G55", + "G56", + "G57", + "G58", + "G59" + ], + "x_diameter": false + }, + "feed_tolerance_mm_min": 0.1, + "flood": true, + "frame": { + "origin_mm": [ + 0, + 0, + 0 + ], + "x": [ + 1, + 0, + 0 + ], + "y": [ + 0, + 1, + 0 + ], + "z": [ + 0, + 0, + 1 + ] + }, + "helices": true, + "max_feed_mm_min": 10000, + "max_length_register": 99, + "max_spindle_rpm": 30000, + "max_sweep_rad": 6.283185307179586, + "max_tool_number": 99, + "mist": false, + "name": "Three-axis mill", + "output_units": "mm", + "planes": [ + "xy", + "xz", + "yz" + ], + "rapid_mm_min": 6000, + "revision": "1", + "tip_travel_mm": null, + "tolerance_mm": 0.01, + "tool_change_home_z_mm": null, + "tool_change_position_mode": "preserve_spindle", + "tool_changes": true, + "tools": [ + { + "diameter_register": null, + "gauge_length_mm": 60, + "length_register": 1, + "number": 1, + "position_after_mm": null, + "tool": "face8" + } + ], + "traverse_feed_mm_min": null, + "work_offset": 1, + "work_to_machine": { + "origin_mm": [ + 250.0, + 200.0, + -150.0 + ], + "x": [ + 1, + 0, + 0 + ], + "y": [ + 0, + 1, + 0 + ], + "z": [ + 0, + 0, + 1 + ] + } + }, + "manifest": { + "initial_position_mm": [ + -250.0, + -200.0, + 90.0 + ], + "operations": [ + { + "axis": "x", + "clearance_z_mm": 12, + "coolant": "flood", + "edge_overlap_mm": null, + "entry_air_gap_mm": 1, + "feed_mm_min": 600, + "floor_z_mm": 8, + "id": "face", + "kind": "facing", + "length_register": 1, + "mode": "zigzag", + "plunge_mm_min": 150, + "reverse": false, + "spindle_rpm": 12000, + "stepdown_mm": 1, + "stepover_mm": 6, + "tolerance_mm": 1e-05, + "tool": "face8", + "tool_number": 1, + "work_offset": 1 + } + ], + "rapid_retracts": true, + "run": { + "id": "homed-facing-fixture", + "revision": "1@482b30d499a8e518383206c141b82a07f1c4542c2d22b5c4386ff488cf4c24bf" + }, + "stock": { + "cell_size_mm": 0.25, + "max_cells": 4294967295, + "max_mm": [ + 40, + 24, + 10 + ], + "min_mm": [ + 0, + 0, + 0 + ], + "units": "mm", + "version": 1 + }, + "sweep": { + "chord_error_mm": 0.002, + "max_cell_visits": 100000000, + "max_changed_cells": 4294967295, + "max_scratch_cells": 4294967295, + "max_segments": 100000, + "max_tip_step_mm": 0.1, + "tolerance_mm": 1e-05 + }, + "tool_change": { + "in_place": true + }, + "tools": [ + { + "cutter": { + "center_cutting": true, + "cutting_length_mm": 30, + "diameter_mm": 8, + "flutes": 3, + "id": "em8", + "material": "carbide", + "name": "em8", + "neck": null, + "overall_length_mm": 50, + "shank_diameter_mm": 8, + "shape": { + "kind": "flat" + } + }, + "gauge_length_mm": 60, + "holders": [ + { + "radius_max_mm": 5, + "radius_min_mm": 5, + "z_max_mm": 60, + "z_min_mm": 35 + } + ], + "id": "face8", + "stickout_mm": 35 + } + ], + "version": 1 + }, + "program_id": "top", + "run_id": "homed-facing-fixture" +} diff --git a/fixtures/posts/rust/homed-facing.nc b/fixtures/posts/rust/homed-facing.nc new file mode 100644 index 00000000..b2a4b34f --- /dev/null +++ b/fixtures/posts/rust/homed-facing.nc @@ -0,0 +1,44 @@ +G21 +G90 +G91.1 +G17 +G94 +G97 +G40 +G49 +G80 +G92.1 +G61.1 +M5 +M9 +G54 +T1 +M6 +G43 H1 +M3 S12000 +M8 +G0 Z12 +G0 X-5 Y3.2 Z12 +G1 X-5 Y3.2 Z9 F150 +G1 X45 Y3.2 Z9 F600 +G1 X45 Y9.067 Z9 F600 +G1 X-5 Y9.067 Z9 F600 +G1 X-5 Y14.933 Z9 F600 +G1 X45 Y14.933 Z9 F600 +G1 X45 Y20.8 Z9 F600 +G1 X-5 Y20.8 Z9 F600 +G0 X-5 Y20.8 Z12 +G0 X-5 Y3.2 Z12 +G1 X-5 Y3.2 Z8 F150 +G1 X45 Y3.2 Z8 F600 +G1 X45 Y9.067 Z8 F600 +G1 X-5 Y9.067 Z8 F600 +G1 X-5 Y14.933 Z8 F600 +G1 X45 Y14.933 Z8 F600 +G1 X45 Y20.8 Z8 F600 +G1 X-5 Y20.8 Z8 F600 +G0 X-5 Y20.8 Z12 +M9 +M5 +G49 +M2 diff --git a/fixtures/posts/rust/standalone-rest.nc b/fixtures/posts/rust/standalone-rest.nc index b4b73579..bd2e897c 100644 --- a/fixtures/posts/rust/standalone-rest.nc +++ b/fixtures/posts/rust/standalone-rest.nc @@ -17,7 +17,7 @@ M6 G43 H9 M3 S12000 M8 -G0 X-3 Y1.6 Z8 +G0 X-3 Y1.6 G1 X-3 Y1.6 Z5 F150 G1 X27 Y1.6 Z5 F600 G1 X27 Y3.428 Z5 F600 diff --git a/python/camlib/postprocessor.py b/python/camlib/postprocessor.py index e490648f..e0e06f90 100644 --- a/python/camlib/postprocessor.py +++ b/python/camlib/postprocessor.py @@ -236,6 +236,58 @@ class Command: _DWELL_CYCLES = frozenset(('drill_dwell_cycle', 'bore_dwell_cycle')) _BORE_CYCLES = frozenset(('bore_cycle', 'bore_dwell_cycle', 'bore_stop_cycle', 'fine_bore_cycle')) +# The axes a tool change leaves where the controller placed them, by +# tool_change_position_mode: z_home sends Z to its home (LinuxCNC +# TOOL_CHANGE_QUILL_UP, Centroid CNC12 M6), table moves every axis to the +# tool-change pose (TOOL_CHANGE_POSITION, G30). The other modes move no axis +# to a machine position. +_TOOL_CHANGE_PLACES = {'z_home': (2,), 'table': (0, 1, 2)} + + +def _uncommented(line, parentheses): + """The part of a block every decoder reads: before its first ';' and, + when the dialect makes them comments, outside parentheses. None for + unbalanced parentheses, which no decoder accepts.""" + body = line.split(';', 1)[0] + if not parentheses: + return body + out, depth = [], 0 + for ch in body: + if ch == '(': + depth += 1 + elif ch == ')': + if depth == 0: + return None + depth -= 1 + elif depth == 0: + out.append(ch) + return None if depth else ''.join(out) + + +def _axis_words(line, dialect): + """The work axes a block may write: those whose address letter appears in + it outside a comment, the rule of the machine check (``axis_words`` in + src/machine/session.rs). Any other appearance of the letter counts too, + which only writes more words. Unbalanced parentheses count every axis.""" + body = _uncommented(line, dialect.parentheses_comments) + if body is None: + return (True, True, True) + body = body.upper() + return tuple(axis in body for axis in dialect.axes) + + +def _changes_tool(line, dialect): + """Whether a block of a tool-change hook makes the change: the M6 word + (tool_change='m6'), or the T word that changes the tool itself.""" + body = _uncommented(line, dialect.parentheses_comments) + if body is None: + return False + words = body.split() + if dialect.tool_change == 'm6': + return any(c.effect == 'tool_change' and c.code in words for c in dialect.commands) + t = dialect.tool_word + return any(w.startswith(t) and w[len(t) : len(t) + 1].isdigit() for w in words) + # Word grid for exact arc radii: 1/(2 x 10^9) output units holds every word of # up to 9 decimals and half of one (lathe X words written as diameters). @@ -966,6 +1018,10 @@ def __init__(self, machine): self._modal = {} # The plane the program has selected so far (None: none written yet). self._plane = None + # Per work axis: still where the controller placed it (the start + # pose, or a tool change's machine position), with no block written + # since that names it. Set by _call from the blocks each hook writes. + self._placed = (False, False, False) def emit(self, *words): line = ' '.join(str(w) for w in words if w is not None and w != '') @@ -1148,6 +1204,7 @@ def _call(self, name, *args, limit=8): else: for line in islice(iter(returned), limit + 1): self.emit(line) + self._track_placed(name) if ( not self._lines and name != 'on_cycle' @@ -1156,6 +1213,36 @@ def _call(self, name, *args, limit=8): raise ValueError(f'{name} emitted no blocks') return self._lines[:] + def _track_placed(self, name): + """Which axes are still where the controller placed them after the + blocks the hook ``name`` wrote (``self._lines``). + + At the program start the controller holds every axis where it is + (the header moves none: PostEngine refuses one that does). A tool + change whose declared mode moves axes to machine positions places + those axes again, at its change block. Any block that names an axis + word commands that axis to a work position, through the + controller's actual work offset, so the axis leaves that state. A + probing cycle's macros move axes their blocks need not name: it + leaves every axis commanded.""" + if name == 'on_begin': + self._placed = (True, True, True) + return + if name == 'on_probe': + self._placed = (False, False, False) + return + d = self.machine.dialect + placed = list(getattr(self, '_placed', (False, False, False))) + places = _TOOL_CHANGE_PLACES.get(self.machine.tool_change_position_mode, ()) + for line in self._lines: + if name == 'on_tool_change' and _changes_tool(line, d): + for i in places: + placed[i] = True + for i, written in enumerate(_axis_words(line, d)): + if written: + placed[i] = False + self._placed = tuple(placed) + class GCodePost(PostProcessor): """Default formatter using the machine's declared dialect; normal Python.""" @@ -1733,6 +1820,26 @@ def on_motion(self, motion): # the source, its XY offset plus half a word of Z rounding; the # decoded block is still checked against the source. values = [position[i] if i < 2 else c.end[i] for i in axes] + placed = getattr(self, '_placed', (False, False, False)) + if ( + not isinstance(c, Arc) + and position is not None + and any(placed) + and not getattr(self, '_pending_compensation', None) + ): + # An axis the controller placed itself (the start pose, a tool + # change's machine position) that this move keeps gets no word: + # a word, even of the same value, commands the axis to that work + # position through the controller's actual work offset, so it + # would move by the offset's error (at a travel limit, beyond + # it). The decoders read an absent word as the current position + # (rule 5 of AGENTS.md: only what the controller needs). + # A block left with no axis word is no move: it is written whole, + # as a bare G0 is no motion block to the decoders. + kept = [k for k, i in enumerate(axes) if not (placed[i] and values[k] == position[i])] + if kept: + addresses = [addresses[k] for k in kept] + values = [values[k] for k in kept] if isinstance(c, Arc): # Actual decoded start accounts for earlier rounding. addresses.extend(d.centers[i] for i in (u, v)) @@ -3354,9 +3461,16 @@ def _format_default(self, fast, post, decoder, events, originals, ranges, cancel decoder.validate_initialized() if decoder.active is None or decoder.length is None or decoder.offset is None or decoder.tool_pending: raise ValueError('NC motion with unknown attribution/tool/length/offset') - lines, decoded, position, plane = fast.motions( - _json([e['motion'] for e in events[i:j]]), decoder.position, decoder.units, decoder.plane + lines, decoded, position, plane, placed = fast.motions( + _json([e['motion'] for e in events[i:j]]), + decoder.position, + decoder.units, + decoder.plane, + tuple(post._placed), ) + # The native batch wrote these motions' axis words (on_motion + # leaves out the words of axes the controller placed). + post._placed = tuple(placed) for event, block, words in zip(events[i:j], lines, decoded): blocks.append(block) if renumber and next_id is None: @@ -3450,10 +3564,11 @@ def consume(self, events, *, cancel=None): d.validate_initialized() if d.active is None or d.length is None or d.offset is None or d.tool_pending: raise ValueError('NC motion with unknown attribution/tool/length/offset') - raw, position, plane = self._session.consume_default( - _json(source), fast, d.position, d.units, d.plane, d.active.tool, cancel + raw, position, plane, placed = self._session.consume_default( + _json(source), fast, d.position, d.units, d.plane, d.active.tool, tuple(self.post._placed), cancel ) d.position, d.plane = tuple(position), plane + self.post._placed = tuple(placed) if plane is not None: d.ready.add('plane') # As in _format_default: the post's plane follows the batch. diff --git a/python/tests/fanuc_0imb_oracle.py b/python/tests/fanuc_0imb_oracle.py index 67b26957..254404ac 100644 --- a/python/tests/fanuc_0imb_oracle.py +++ b/python/tests/fanuc_0imb_oracle.py @@ -172,10 +172,12 @@ def read(self, line): required = {'units', 'frame', 'spindle', 'coolant', 90, 17, 94, 40, 49, 80, 61} if g != 1 or not required <= self.flags or self.active is None or self.length is None or self.offset is None: raise ValueError('oracle: motion state') - if set(words) != {'X', 'Y', 'Z', 'F'} or words['F'] <= 0: + # An axis word left out keeps that axis where it is (the post leaves + # out the words of axes the controller placed, #367). + if not ('F' in words and set(words) - {'F'} and set(words) <= {'X', 'Y', 'Z', 'F'}) or words['F'] <= 0: raise ValueError('oracle: G1 words') start = self.position - self.position = tuple(words[a] * self.units for a in 'XYZ') + self.position = tuple(words[a] * self.units if a in words else p for a, p in zip('XYZ', start)) if self.position == start: return [] self.count += 1 diff --git a/python/tests/test_feed_traverse.py b/python/tests/test_feed_traverse.py index 05f90a8b..4d7beaaa 100644 --- a/python/tests/test_feed_traverse.py +++ b/python/tests/test_feed_traverse.py @@ -287,9 +287,8 @@ def test_static_feed_limits_and_legacy_post_keep_explicit_clearance_semantics(se self.assertEqual(len(moves), 1) self.assertEqual(moves[0].kind, 'rapid') self.assertEqual(moves[0].feed_mm_min, 600) - self.assertRegex( - ''.join(c.text for c in chunks), r'G1 X10(?:\.0+)? Y0(?:\.0+)? Z3(?:\.0+)? F600(?:\.0+)?\n' - ) + # Y and Z stay where the tool change placed them: no words (#367). + self.assertRegex(''.join(c.text for c in chunks), r'G1 X10(?:\.0+)? F600(?:\.0+)?\n') scene = Scene('traverse-limits', '1', machine=MachineLimits((-100, -100, -100), (100, 100, 100), 500)) with Verifier(scene) as verifier: report = verifier.check(p.tools[0], motion) diff --git a/python/tests/test_placed_axes.py b/python/tests/test_placed_axes.py new file mode 100644 index 00000000..26c44e1c --- /dev/null +++ b/python/tests/test_placed_axes.py @@ -0,0 +1,214 @@ +"""Axis words a straight move leaves out (#367): an axis still where the +controller placed it (the start pose, a tool change's machine position) gets +no word until the program writes it, since a word, even of the same value, +commands the axis through the controller's actual work offset. The Python +default post, its native formatter and the Rust post write the same blocks.""" + +from dataclasses import replace +import json +import unittest + +import camlib +from camlib import ToolChangeInPlace, ToolChangePosition, ToolSetting +from camlib.export import ExportRefused +from camlib.machine import ( + AllowedContact, + Axis, + Box, + MachineBody, + MachineCheckOptions, + MachineModel, + ToolCalibration, + ToolChangeRoute, +) +from camlib.motion import WorkFrame +from camlib.post import GCodePost, post_job, post_job_input +from camlib.verification import StockContactOptions +from support.facing import facing_job +from test_rust_post import ROOT, plain +from test_tool_change_pose import job as drilling_job, machine as mill, tools as drilling_tools + +# Work zero in machine coordinates: the mill homes at X 0, Y 0 (its travel +# minimums) and Z 0 (its maximum), 250, 200 and 150 mm from work zero. +ORIGIN = (250.0, 200.0, -150.0) + + +def homed_model(tool, register, work_error_mm): + """A mill homed on its limits, the work frame known to +-work_error_mm.""" + g = tool.gauge_length_mm + return MachineModel( + 1, + 'mm', + 'homed-at-limits', + '1', + 'milling', + (Axis('head', 0, 500), Axis('head', 0, 400), Axis('head', -300, 0)), + 1, + WorkFrame(ORIGIN), + (-work_error_mm,) * 3, + (work_error_mm,) * 3, + (0, 0, 0), + None, + 'linear', + 'synthetic exact-stop controller', + (ToolCalibration(tool.id, register, (), (0, 0, g), (0, 0, g)),), + (MachineBody('head', 'spindle_head', 'head', (Box((-1, -1, 0), (1, 1, 10)),), {}),), + {'column': 'synthetic stand', 'table': 'remote support', 'enclosure': 'open stand'}, + (AllowedContact(('head', '@tool'), 'tool mounted in spindle'),), + { + tool.id: ToolChangeRoute( + 'synthetic complete indexing enclosure', (), (Box((-20, -20, -g - 1), (20, 20, 1)),), ('@tool',), () + ) + }, + (), + MachineCheckOptions(0.00001, 0.05, 1_000_000, 128, StockContactOptions()), + ) + + +def facing_from_home(work_error_mm=0.02): + """A Facing whose start is the home pose, and the homed LinuxCNC mill.""" + spec = facing_job() + tool = spec['tools'][0] + home = (-ORIGIN[0], -ORIGIN[1], -ORIGIN[2] - tool.gauge_length_mm) + setup = camlib.Setup( + 'top', + stock=spec['stock'], + tools=spec['tools'], + operations=tuple(camlib.OperationNode(op, sources=()) for op in spec['operations']), + initial_position_mm=home, + tool_change=ToolChangeInPlace(), + ) + job = camlib.Job('facing-from-home', '1', (setup,)) + setting = ToolSetting.for_tool(tool, number=1, length_register=1) + m = mill( + {}, + mode='preserve_spindle', + tool_table=(setting,), + work_to_machine=WorkFrame(ORIGIN), + crash_model=homed_model(tool, 1, work_error_mm), + ) + return job, m, home + + +def motion_blocks(text): + return [line for line in text.splitlines() if line.split()[:1] in (['G0'], ['G1'], ['G2'], ['G3'])] + + +class StartPoseTest(unittest.TestCase): + def test_first_move_from_a_pose_on_the_travel_limits_names_only_the_axis_it_moves(self): + job, m, home = facing_from_home() + released = job.post_nc('top', machine=m) + blocks = motion_blocks(released.text) + # Z down from home: X and Y are where the controller homed them, so + # the block names Z only. Then the first XY traverse names X and Y, + # and Z, which the first block wrote. + self.assertEqual(blocks[0], 'G0 Z12') + self.assertTrue(blocks[1].startswith('G0 X') and ' Y' in blocks[1] and blocks[1].endswith(' Z12'), blocks) + self.assertNotIn(f'X{home[0]:g}', released.text) + # The machine check holds the unwritten X and Y exactly at home, on + # their minimums, with a nonzero calibration interval: clear. + self.assertEqual(released.machine['status'], 'clear', released.machine) + self.assertTrue(released.machine['complete']) + self.assertEqual(tuple(released.findings), ()) + # The Rust post writes the same program and releases it too. + source = post_job_input(job, 'top', machine=m, run_id='homed-facing-fixture') + source['manifest']['run']['id'] = 'homed-facing-fixture' + rust = post_job(source) + self.assertTrue(rust['released'], rust.get('refused')) + self.assertEqual(rust['program'], released.text) + self.assertEqual(rust['machine']['status'], 'clear') + # tests/machine.rs posts this input without Python. + path = ROOT / 'fixtures/posts/rust/homed-facing' + self.assertEqual(plain(source), json.loads(path.with_suffix('.json').read_text())) + self.assertEqual(released.text, path.with_suffix('.nc').read_text()) + + def test_python_hooks_and_native_formatter_write_the_same_blocks(self): + job, m, _ = facing_from_home() + native = job.post_nc('top', machine=m).text + + class Hooks(GCodePost): + # The same post through the Python hooks (an override turns the + # native formatter off). + def on_motion(self, motion): + return super().on_motion(motion) + + self.assertEqual(job.post_nc('top', machine=m, post=Hooks).text, native) + + def test_without_the_rule_the_machine_check_refuses_the_first_block(self): + # The program as posted before #367 (every word on every block): the + # first block commands X and Y at home through the work offset, which + # straddles the minimums by the calibration interval. + job, m, home = facing_from_home() + + class EveryWord(GCodePost): + def on_motion(self, motion): + self._placed = (False, False, False) + return super().on_motion(motion) + + with self.assertRaises(ExportRefused) as refused: + job.post_nc('top', machine=m, post=EveryWord) + self.assertEqual(refused.exception.statuses, ('uncertain',)) + posted = job.post_nc('top', machine=m, post=EveryWord, accept={'uncertain'}) + self.assertEqual(motion_blocks(posted.text)[0], f'G0 X{home[0]:g} Y{home[1]:g} Z12') + details = ' '.join(f['detail'] for f in posted.machine['findings']) + self.assertIn('straddles the minimum 0.000000 mm', details) + + +class ToolChangeTest(unittest.TestCase): + def test_z_home_tool_change_places_z_until_the_program_moves_it(self): + m = mill( + {}, + mode='z_home', + tool_table=tuple( + ToolSetting.for_tool(t, number=k, length_register=k) + for k, t in enumerate(reversed(drilling_tools()), 1) + ), + tool_change_home_z_mm=92, + work_to_machine=WorkFrame(), + ) + # Z home puts the second tool's tip (gauge 80) at the drilling + # clearance, 12: its first move keeps Z. + job = drilling_job(ToolChangePosition(gauge_z_mm=92)) + released = job.post_nc('top', machine=m, accept={'unchecked_machine'}) + lines = released.text.splitlines() + changes = [i for i, line in enumerate(lines) if 'M6' in line.split()] + self.assertEqual(len(changes), 2) + first = [next(line for line in lines[c:] if line.split()[0] in ('G0', 'G1')) for c in changes] + # The first tool (gauge 75) comes down from Z home to the clearance: + # X and Y are still where the controller started, so Z only. The + # second keeps the Z M6 sent it to and writes no Z word; X and Y, + # written since, are written. + self.assertEqual(first, ['G0 Z12', 'G0 X8 Y8'], lines) + rust = post_job(post_job_input(job, 'top', machine=m, accept={'unchecked_machine'})) + self.assertTrue(rust['released']) + self.assertEqual(rust['program'], released.text) + + def test_placed_axes_follow_the_blocks_each_hook_writes(self): + from camlib.motion import Cycle, ToolChange + + def post(mode, **settings): + m = mill({'drill3': (0.0, 0.0, 40.0), 'drill5': (0.0, 0.0, 40.0)}, mode=mode, **settings) + p = GCodePost(m) + p._call( + 'on_begin', replace(drilling_job(None).compile().setup('top').program_header(), events=()), limit=32 + ) + return p + + p = post('table') + self.assertEqual(p._placed, (True, True, True)) + p._call('on_tool_change', ToolChange('drill3', 1, 1, (0, 0, 40))) + self.assertEqual(p._placed, (True, True, True)) + p._call('on_cycle', Cycle('drill', (8, 8), 4, 11, 40, 150, 3)) + self.assertEqual(p._placed, (False, False, False)) + p = post('z_home', tool_change_home_z_mm=100, work_to_machine=WorkFrame()) + p._placed = (False, False, False) + p._call('on_tool_change', ToolChange('drill3', 1, 1, (0, 0, 25))) + self.assertEqual(p._placed, (False, False, True)) + p = post('preserve_tip') + p._placed = (False, False, False) + p._call('on_tool_change', ToolChange('drill3', 1, 1, (0, 0, 40))) + self.assertEqual(p._placed, (False, False, False)) + + +if __name__ == '__main__': + unittest.main() diff --git a/python/tests/test_post_decode.py b/python/tests/test_post_decode.py index 003b167d..12084554 100644 --- a/python/tests/test_post_decode.py +++ b/python/tests/test_post_decode.py @@ -254,7 +254,9 @@ def user_helper(self, *args, **kwargs): e.begin(program) chunk = e.consume(program.events) self.assertEqual(chunk.motions, (program.events[4],)) - self.assertEqual(e.post.helper_calls, 5) # spindle S plus X/Y/Z/F + # Spindle S plus X/F: Y and Z stay where the tool change placed + # them, so the move writes no word for them (#367). + self.assertEqual(e.post.helper_calls, 3) for args in (('X', [float('nan')], 1, 3), ('X', [1000001.0], 1, 3), ('XY', [1.0], 1, 3), ('X', [1.0], 2, 3)): with self.assertRaises(ValueError): native.format_post_words(*args) diff --git a/python/tests/test_python_posts.py b/python/tests/test_python_posts.py index 219aa09e..b82995e8 100644 --- a/python/tests/test_python_posts.py +++ b/python/tests/test_python_posts.py @@ -126,7 +126,10 @@ def on_finish(self): engine.post.fail = False result = engine.finish() self.assertEqual(engine.post.observed, [expected]) - self.assertIn('terminal 10.0,0.0,3.0', result.text) + # The hook wrote the decoded position (10, 0, 3, checked + # above). Y and Z are never written (the tool change placed + # them, #367), so they are the declared values as given. + self.assertIn('terminal ' + ','.join(str(v) for v in expected), result.text) def test_precision_collapsed_lines_keep_checked_source_maps_without_fake_sweeps(self): from camlib.post import LoweringOptions @@ -991,7 +994,8 @@ def on_motion(self, motion): # Single-motion shortcut also follows arbitrary declared codes/addresses. d = replace(m.dialect, axes=('U', 'V', 'W'), feed_word='E').with_commands(linear='G101') chunks = list(post_program(p, replace(m, dialect=d))) - self.assertIn('G101 U10 V0 W3 E1200', chunks[1].text) + # V and W stay where the tool change placed them: no words (#367). + self.assertIn('G101 U10 E1200', chunks[1].text) self.assertEqual(chunks[1].motions, (p.events[4],)) def test_immutable_decoder_tables_and_custom_mutable_state_keep_batch_isolation(self): diff --git a/python/tests/test_siemens808d_iso_post.py b/python/tests/test_siemens808d_iso_post.py index 4a1ae898..c26ae882 100644 --- a/python/tests/test_siemens808d_iso_post.py +++ b/python/tests/test_siemens808d_iso_post.py @@ -345,7 +345,8 @@ def events(): rapid = replace(p.events[4], kind='rapid', feed_mm_min=None) job = replace(p, events=(*p.events[:3], rapid)) chunks = list(post_iso(job, m)) - self.assertIn('G1 X10. Y0. Z3. F3000.', ''.join(c.text for c in chunks)) + # Y and Z stay where the tool change placed them: no words (#367). + self.assertIn('G1 X10. F3000.', ''.join(c.text for c in chunks)) self.oracle(job, m, chunks) def test_complete_pocket_actual_stock_and_independent_literal_file(self): diff --git a/src/gcode/post.rs b/src/gcode/post.rs index 311f07ce..eef6fc94 100644 --- a/src/gcode/post.rs +++ b/src/gcode/post.rs @@ -61,6 +61,11 @@ pub struct DefaultPost { work_offset: Option, /// The next LinuxCNC O-word label for a protected probe move. probe_label: u32, + /// Per work axis: still where the controller placed it (the start pose, + /// or a tool change's machine position), with no block written since + /// that names it (`PostProcessor._placed`). Set by `call` from the + /// blocks each hook writes. + placed: [bool; 3], } /// `PostProcessor.version`/`GCodePost.version` of the Python post this one @@ -118,6 +123,54 @@ fn format_g(value: f64) -> String { fn step_digits(step: f64) -> usize { (-(step.log10() + 1e-9).floor()).max(0.) as usize } +/// The part of a block every decoder reads: before its first `;` and, when +/// the dialect makes them comments, outside parentheses. None for +/// unbalanced parentheses, which no decoder accepts (Python `_uncommented`). +fn uncommented(line: &str, parentheses: bool) -> Option { + let body = line.split(';').next().unwrap_or(""); + if !parentheses { + return Some(body.to_string()); + } + let (mut out, mut depth) = (String::new(), 0usize); + for ch in body.chars() { + match ch { + '(' => depth += 1, + ')' => depth = depth.checked_sub(1)?, + _ if depth == 0 => out.push(ch), + _ => {} + } + } + (depth == 0).then_some(out) +} +/// The work axes a block may write: those whose address letter appears in +/// it outside a comment, the rule of the machine check (`axis_words` in +/// `machine::session`). Any other appearance of the letter counts too, which +/// only writes more words. Unbalanced parentheses count every axis. +fn axis_words(line: &str, d: &super::machine::Dialect) -> [bool; 3] { + let Some(body) = uncommented(line, d.parentheses_comments) else { + return [true; 3]; + }; + let body = body.to_uppercase(); + std::array::from_fn(|k| d.axes.get(k).is_some_and(|a| body.contains(a.as_str()))) +} +/// Whether a block of a tool-change hook makes the change: the M6 word +/// (`tool_change = "m6"`), or the T word that changes the tool itself. +fn changes_tool(line: &str, d: &super::machine::Dialect) -> bool { + let Some(body) = uncommented(line, d.parentheses_comments) else { + return false; + }; + if d.tool_change == "m6" { + let Ok(code) = d.code("tool_change") else { + return false; + }; + return body.split_whitespace().any(|w| w == code); + } + let t = d.tool_word.as_str(); + body.split_whitespace().any(|w| { + w.strip_prefix(t) + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) + }) +} impl DefaultPost { pub fn new(machine: Machine) -> Self { @@ -146,6 +199,7 @@ impl DefaultPost { radii: BTreeMap::new(), work_offset: None, probe_label: 100, + placed: [false; 3], } } pub fn machine(&self) -> &Machine { @@ -354,6 +408,7 @@ impl DefaultPost { Hook::Finish => self.on_finish()?, Hook::Event(event) => self.on_event(event)?, } + self.track_placed(name); if self.lines.is_empty() && name != "on_cycle" && !(name == "on_cutter_compensation" && self.machine.dialect.compensation_with_move) @@ -363,6 +418,44 @@ impl DefaultPost { Ok(self.lines.clone()) } + /// `PostProcessor._track_placed`: which axes are still where the + /// controller placed them after the blocks the hook `name` wrote. + /// + /// At the program start the controller holds every axis where it is + /// (the header moves none: the engine refuses one that does). A tool + /// change whose declared mode moves axes to machine positions places + /// those axes again, at its change block. Any block that names an axis + /// word commands that axis to a work position, through the controller's + /// actual work offset, so the axis leaves that state. A probing cycle's + /// macros move axes their blocks need not name: it leaves every axis + /// commanded. + fn track_placed(&mut self, name: &str) { + match name { + "on_begin" => self.placed = [true; 3], + "on_probe" => self.placed = [false; 3], + _ => { + let d = &self.machine.dialect; + let places: &[usize] = match self.machine.tool_change_position_mode.as_str() { + "z_home" => &[2], + "table" => &[0, 1, 2], + _ => &[], + }; + for line in &self.lines { + if name == "on_tool_change" && changes_tool(line, d) { + for &i in places { + self.placed[i] = true; + } + } + for (placed, written) in self.placed.iter_mut().zip(axis_words(line, d)) { + if written { + *placed = false; + } + } + } + } + } + } + fn on_event(&mut self, event: &Event) -> Result<(), String> { let d = self.machine.dialect.clone(); match event { @@ -1399,6 +1492,27 @@ impl DefaultPost { .map(|i| if *i < 2 { position[*i] } else { end[*i] }) .collect(); } + if circular.is_none() + && let Some(position) = self.position_mm + && self.placed.iter().any(|p| *p) + && self.pending_compensation.as_ref().is_none_or(Vec::is_empty) + { + // An axis the controller placed itself (the start pose, a tool + // change's machine position) that this move keeps gets no word: + // a word, even of the same value, commands the axis to that work + // position through the controller's actual work offset, so it + // would move by the offset's error (at a travel limit, beyond + // it). The decoders read an absent word as the current position. + // A block left with no axis word is no move: it is written whole, + // as a bare G0 is no motion block to the decoders. + let kept: Vec = (0..axes.len()) + .filter(|&k| !(self.placed[axes[k]] && values[k] == position[axes[k]])) + .collect(); + if !kept.is_empty() { + addresses = kept.iter().map(|&k| addresses[k].clone()).collect(); + values = kept.iter().map(|&k| values[k]).collect(); + } + } if let Some((plane, _, _)) = circular { let [u, v, _] = plane.axes(); addresses.push(d.centers[u].clone()); diff --git a/tests/machine.rs b/tests/machine.rs index 57fac785..a1573417 100644 --- a/tests/machine.rs +++ b/tests/machine.rs @@ -829,3 +829,95 @@ fn a_commanded_axis_carries_the_interval_and_real_overtravel_is_caught() { (Status::Uncertain, "axis_x", 0.) ); } + +/// Posted by Python's `Job.post_nc` (python/tests/test_placed_axes.py): a +/// Facing whose start is the home pose of a LinuxCNC mill homed at X 0, Y 0 +/// (its travel minimums) and Z 0 (its maximum), its work frame known to +/// +-0.02 mm (#367). +const HOMED_FACING: &str = include_str!("../fixtures/posts/rust/homed-facing.json"); +const HOMED_FACING_NC: &str = include_str!("../fixtures/posts/rust/homed-facing.nc"); + +fn motion_blocks(program: &str) -> Vec<&str> { + program + .lines() + .filter(|l| ["G0", "G1"].contains(&l.split(' ').next().unwrap_or(""))) + .collect() +} + +#[test] +fn a_move_from_a_pose_on_the_travel_limits_writes_only_the_axes_it_moves() { + let report = camlib::post_job::run(HOMED_FACING, &AtomicBool::new(false)).unwrap(); + let report: serde_json::Value = serde_json::from_str(&report).unwrap(); + // Released without accepting anything: the machine check holds X and Y, + // which no block writes until the first traverse, exactly at home on + // their minimums. + assert_eq!(report["released"], true, "{report}"); + assert_eq!(report["accepted"], json!([])); + assert_eq!(report["machine"]["status"], "clear"); + assert_eq!(report["machine"]["complete"], true); + let program = report["program"].as_str().unwrap(); + assert_eq!(program, HOMED_FACING_NC); + // Z down from home names Z only (not X-250 Y-200, which would command + // X and Y through the work offset onto the limits); the traverse after + // it names every axis, Z included, since the first block wrote Z. + let blocks = motion_blocks(program); + assert_eq!(blocks[..2], ["G0 Z12", "G0 X-5 Y3.2 Z12"]); +} + +#[test] +fn a_z_home_tool_change_places_z_until_a_block_writes_it() { + let input: serde_json::Value = serde_json::from_str(HOMED_FACING).unwrap(); + let mut machine = input["machine"].clone(); + machine.as_object_mut().unwrap().remove("crash_model"); + // M6 sends the gauge line to machine Z 0: work Z 150, the 60 mm tool's + // tip at 90, as at the start. + machine["tool_change_position_mode"] = json!("z_home"); + machine["tool_change_home_z_mm"] = json!(0.); + let home = [-250., -200., 90.]; + let line = |id: u64, start: [f64; 3], end: [f64; 3]| { + json!({"kind": "motion", "motion": {"id": id, "operation": "op", "tool": "face8", + "curve": {"kind": "line", "start": start, "end": end}, "feed_mm_min": null, "kind": "rapid"}}) + }; + let change = |at: [f64; 3]| { + json!({"kind": "tool_change", "tool": "face8", "number": 1, "length_register": 1, "position_after_mm": at}) + }; + let over = [-5., 3.2, 12.]; + let program = json!({ + "version": 1, "id": "z-home", "revision": "1", "units": "mm", "tolerance_mm": 1e-6, + "frame": input["frame"], "initial_position_mm": home, + "tools": input["manifest"]["tools"], + "events": [ + {"kind": "work_offset", "number": 1}, + change(home), + {"kind": "spindle", "rpm": 12000, "direction": "cw"}, + line(1, home, [home[0], home[1], 12.]), + line(2, [home[0], home[1], 12.], over), + {"kind": "spindle", "rpm": 0, "direction": "cw"}, + change([over[0], over[1], 90.]), + {"kind": "spindle", "rpm": 12000, "direction": "cw"}, + line(3, [over[0], over[1], 90.], [0., 0., 90.]), + line(4, [0., 0., 90.], [0., 0., 12.]), + ], + }); + let out = camlib::gcode::post_program( + &json!({"program": program, "machine": machine}).to_string(), + &AtomicBool::new(false), + ) + .unwrap(); + let out: serde_json::Value = serde_json::from_str(&out).unwrap(); + let blocks = motion_blocks(out["program"].as_str().unwrap()); + // At the start every axis is placed; after the second M6, Z only: the + // move that keeps it writes X and Y, which earlier blocks wrote, and no + // Z, until the descent writes it. + assert_eq!( + blocks, + [ + "G0 Z12", + "G0 X-5 Y3.2 Z12", + "G0 X0 Y0", + "G0 X0 Y0 Z12" + ], + "{}", + out["program"] + ); +}