diff --git a/CHANGELOG.md b/CHANGELOG.md index 838a6ba..f906b91 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ Versions follow [semantic versioning](https://semver.org/), with `0.x` meaning t ## Unreleased +- A large hull at a high subdivision level no longer freezes the window while it is refined: the window draws a + coarser level at once (level 3 for `container-230m`) and the full level replaces it when a background job has + built it, with "refining to level N…" in the status bar meanwhile. Smaller hulls (the demo hull up to level 4) + refine at once as before. +- One speed for resistance, waves and seakeeping. The Performance tab's speed slider now sits above all three + sections: it is marked on the resistance curve (click the curve to move it), the Wave pattern view computes at it, + and seakeeping runs at it. Changing the speed in the Wave pattern view moves the same speed; its kn / Fn switch + only changes how the speed reads. The Wave pattern view now opens at the Performance tab's speed (6 kn, or the + design speed) instead of Fn 0.30, and the design report's wave section uses it too. +- The Performance tab greys out the resistance curve and table rows where the method is outside the range it was + fitted to, instead of drawing them like the rest: the whole Holtrop & Mennen curve for a hull outside its Cp, L/B + or B/T range (the demo hull is, at L/B 3.02 and B/T 5.71), and the DSYHS speeds outside Fn 0.15 to 0.75. The + numbers stay; the plot's legend says which part is outside. +- The MCP `batch` tool now says what its rollback covers: on an error the session's model goes back to where it was + before the batch, but files written by earlier steps (a design report, an unfolded plate, a wave image) stay on disk. + It used to call the batch all-or-nothing (#8). Connected to the GUI, `load_hull`, `generate_hull` or `example` + inside a batch start a fresh history there, so the model is not rolled back past them. A rollback the GUI refuses, + or whose reply is lost, now shows as `restore_error` (unconfirmed) instead of passing in silence. + ## 0.7.0 (2026-11-26) SeaCraft in Turkish. The desktop app, the command line and every document SeaCraft writes can now be read in diff --git a/README.md b/README.md index 00e5ecb..2c62963 100644 --- a/README.md +++ b/README.md @@ -254,7 +254,8 @@ neighbouring extrema), and the summary names the speed regime in a sentence. The michell` adds the interference: the pair's wave resistance over twice one demihull's. In the window, Analysis → *Wave pattern* opens the pattern in the drawer under the viewports. One speed, typed or -scrubbed, drives the regime sentence, the wavelength against the waterline, hull speed, the highest crest, the wave +scrubbed, and the same one the Performance tab marks on the resistance curve and runs seakeeping at, drives the +regime sentence, the wavelength against the waterline, hull speed, the highest crest, the wave drag here, the wash height and, for a catamaran, the interference, each in plain words with units. A banner says first when thin-ship theory does not fit the hull. The map shows dark calm water, the hull footprint, the Kelvin wedge and the wash lines (drag one to move them); the plots give C_w against Fn with hull speed, humps and hollows diff --git a/ROADMAP.md b/ROADMAP.md index eb2216a..cabc4a0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -75,7 +75,11 @@ path; each cell is the range of the medians of separate runs, frame time then CP At level 5 the old path asks wgpu for a 403 MiB vertex buffer, over its 256 MiB limit, and panics, so `--no-gpu-hull` is no way out there. A new level 5 mesh of `container-230m` (1.29 million triangles, 103 MiB) -takes about 140 ms to build on the window thread and 12 ms to upload. +takes about 140 ms to build and 12 ms to upload. Since 2026-11-26 a mesh over about 24 000 refined faces is built in +a background job while the window draws the highest level under that at once (level 3 for `container-230m`), so an +edit no longer waits for it; orbiting is unchanged (alternating runs against 0.7.0 on a loaded machine). A pause of +about half a second after an edit to `container-230m` remains, at level 3 as well as 5, from something other than +the mesh; it is not yet profiled. - [x] Profile the cost per frame. - [x] Cut the waterline once per mesh and plane instead of once per view per frame. @@ -94,9 +98,10 @@ takes about 140 ms to build on the window thread and 12 ms to upload. - [ ] Floodable length curves. - [ ] VRML import, and edge extrusion in the GUI. -- [ ] One speed shared across the Performance tab and the Wave pattern view (resistance, waves, seakeeping). -- [ ] Grey out or cut the Holtrop curve where the method does not apply (on the demo hull R_T falls past - 7.25 kn). +- [x] One speed shared across the Performance tab and the Wave pattern view (resistance, waves, seakeeping). +- [x] Grey out the resistance curve where the method does not apply: all of the Holtrop curve for a hull outside + its Cp, L/B or B/T range, and DSYHS speeds outside Fn 0.15 to 0.75. Neither Holtrop paper prints a top Froude + number, so no Holtrop speed is greyed on that account. - [ ] A 3D wave surface in Perspective view. - [ ] A wave pattern method for planing hulls; the Wave pattern view's title, "Thin-ship theory (Michell)", then becomes a drop-down that picks the method. diff --git a/crates/seacraft-cli/src/mcp.rs b/crates/seacraft-cli/src/mcp.rs index 34bc43c..0679e14 100644 --- a/crates/seacraft-cli/src/mcp.rs +++ b/crates/seacraft-cli/src/mcp.rs @@ -750,41 +750,35 @@ impl McpServer { for (i, call) in calls.iter().enumerate() { let Some(call_obj) = call.as_object() else { - if let Some(mark) = mark_id { - let _ = remote.request("history.restore", json!({"mark": mark})); - } - return text_result( - &json!({ + return batch_remote_failed( + remote, + mark_id, + json!({ "failed": {"index": i, "name": "", "error": "each call must be an object"}, "completed": i, }), - true, ); }; let Some(name) = call_obj.get("name").and_then(Value::as_str) else { - if let Some(mark) = mark_id { - let _ = remote.request("history.restore", json!({"mark": mark})); - } - return text_result( - &json!({ + return batch_remote_failed( + remote, + mark_id, + json!({ "failed": {"index": i, "name": "", "error": "missing call `name`"}, "completed": i, }), - true, ); }; if name == "batch" { - if let Some(mark) = mark_id { - let _ = remote.request("history.restore", json!({"mark": mark})); - } - return text_result( - &json!({ + return batch_remote_failed( + remote, + mark_id, + json!({ "failed": {"index": i, "name": "batch", "error": "nested batch is rejected"}, "completed": i, }), - true, ); } @@ -794,15 +788,13 @@ impl McpServer { }; if let Err(e) = check_arguments(name, &args) { - if let Some(mark) = mark_id { - let _ = remote.request("history.restore", json!({"mark": mark})); - } - return text_result( - &json!({ + return batch_remote_failed( + remote, + mark_id, + json!({ "failed": {"index": i, "name": name, "error": e}, "completed": i, }), - true, ); } @@ -813,15 +805,13 @@ impl McpServer { results.push(val); } Err(e) => { - if let Some(mark) = mark_id { - let _ = remote.request("history.restore", json!({"mark": mark})); - } - return text_result( - &json!({ + return batch_remote_failed( + remote, + mark_id, + json!({ "failed": {"index": i, "name": name, "error": e}, "completed": i, }), - true, ); } } @@ -3901,12 +3891,20 @@ pub fn tool_definitions() -> Vec { ), tool( "batch", - "Run several tool calls atomically", - "Run tool calls in order, stopping at the first error. Each step is {name, arguments}. On an error earlier steps \ - are rolled back, so the batch is all-or-nothing (both headless and when connected to the GUI). Returns each \ - call's result on success, or {failed: {index, name, error}, completed: N} on failure. At most 100 calls; \ - nested batch is rejected, and so is export_panels with both `nest` and `path` (files on disk cannot be \ - rolled back; call it on its own).", + "Run several tool calls, restoring the model on error", + "Run tool calls in order, stopping at the first error, which restores the model (connected to the GUI, \ + not past a load_hull, generate_hull or example in the batch) but not files already written. Each step \ + is {name, arguments}. On an error the session's model is restored to what it was before the batch, \ + headless or connected to the GUI, but files written by earlier steps stay on disk, and so may a file \ + the failing step wrote before it failed (a hull saved before its sidecar): a design report, an \ + unfolded plate or a wave image is not removed. Connected to the GUI, a tool that replaces the whole \ + model (load_hull, generate_hull, example) starts a fresh history there, so the model from before it \ + is not restored. A failure with `restore_error` means the rollback could not be confirmed (the GUI \ + refused it, or its reply was lost). Connected, hull_info shows no geometry to check that by, so before \ + a batch that matters save the model with save_hull, and after such a failure load it again instead of \ + mending the model in place. Returns each call's result on success, or {failed: {index, name, error}, completed: N} on failure. \ + At most 100 calls; nested batch is rejected, and so is export_panels with both `nest` and `path` (call it \ + on its own).", obj( json!({ "calls": { @@ -3930,6 +3928,18 @@ pub fn tool_definitions() -> Vec { ] } +/// A connected batch failed: the GUI goes back to `mark`. A restore without a good reply is +/// reported as unconfirmed, not dropped: the GUI refused it (a model replaced in the batch started +/// a fresh history there), or it may have restored and lost the reply. +fn batch_remote_failed(remote: &mut Remote, mark: Option, mut failure: Value) -> Value { + if let Some(mark) = mark { + if let Err(e) = remote.request("history.restore", json!({"mark": mark})) { + failure["restore_error"] = Value::String(e); + } + } + text_result(&failure, true) +} + /// The tools as a markdown list: name, title, first sentence, effect. fn tool_catalogue() -> String { let mut out = String::from("# SeaCraft tools\n\n"); @@ -6472,6 +6482,53 @@ mod tests { handle.join().expect("server thread finished"); } + /// CodeRabbit (PR #22): when the GUI cannot restore the mark (a `load_hull` inside the batch + /// started a fresh history there), the failure says so instead of dropping the error. + #[test] + fn connected_batch_reports_a_failed_restore() { + use std::io::Write; + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let addr = listener.local_addr().expect("addr"); + + let handle = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().expect("accept"); + let mut reader = std::io::BufReader::new(stream.try_clone().expect("clone")); + let mut next = |expect: &str, reply: &[u8]| { + let mut line = String::new(); + reader.read_line(&mut line).expect("read"); + let v: Value = serde_json::from_str(line.trim()).expect("json"); + assert_eq!(v["method"], expect); + stream.write_all(reply).expect("write"); + }; + next("history.mark", b"{\"ok\":true,\"result\":{\"mark\":42}}\n"); + next( + "model.split_face", + b"{\"ok\":false,\"error\":\"split error\"}\n", + ); + next( + "history.restore", + b"{\"ok\":false,\"error\":\"unknown mark 42\"}\n", + ); + }); + + let mut s = McpServer::connect_no_auth(&addr.to_string()).expect("connect"); + let err_text = fails( + &mut s, + 1, + "batch", + json!({"calls": [{"name": "split_face", "arguments": {"face": 0}}]}), + ); + let fail_json: Value = serde_json::from_str(&err_text).expect("fail json"); + assert_eq!(fail_json["failed"]["name"], "split_face"); + assert!( + fail_json["restore_error"] + .as_str() + .is_some_and(|e| e.contains("unknown mark 42")), + "{fail_json}" + ); + handle.join().expect("server thread finished"); + } + #[test] fn mcp_connect_with_token_file_succeeds_end_to_end() { use std::io::Write; @@ -6798,6 +6855,58 @@ mod tests { assert_eq!(seen[1], json!({"path": "/tmp/lines.svg", "format": "svg"})); } + #[test] + fn batch_description_says_files_are_not_rolled_back() { + let mut s = McpServer::new(); + let list = request(&mut s, 1, "tools/list", json!({})); + let tool = list["result"]["tools"] + .as_array() + .unwrap() + .iter() + .find(|t| t["name"] == "batch") + .expect("batch") + .clone(); + let description = tool["description"].as_str().unwrap(); + assert!( + description.contains("files written by earlier steps stay on disk"), + "{description}" + ); + assert!(!description.contains("all-or-nothing"), "{description}"); + let title = tool["title"].as_str().unwrap_or_default(); + assert!(!title.to_lowercase().contains("atomic"), "{title}"); + // CodeRabbit (PR #22): the failing step itself can leave a file (a hull saved before + // its sidecar failed), and a hull loaded inside a GUI-connected batch is not undone. + assert!(description.contains("the failing step"), "{description}"); + assert!(description.contains("load_hull"), "{description}"); + assert!(description.contains("restore_error"), "{description}"); + // CodeRabbit (PR #22, second review): a lost reply also gives `restore_error`, so it says + // the rollback is unconfirmed, not that it failed, and to look before mending. + assert!( + description.contains("could not be confirmed"), + "{description}" + ); + // CodeRabbit (PR #22, third review): connected, hull_info shows no geometry, so the + // description names a baseline to take before the batch instead. + assert!( + description.contains("hull_info shows no geometry"), + "{description}" + ); + assert!(description.contains("save_hull"), "{description}"); + // CodeRabbit (fourth review): hydro_compute skips layers kept out of hydrostatics, so + // it is no baseline; the saved hull is, loaded again after a failure. + assert!(!description.contains("hydro_compute"), "{description}"); + assert!(description.contains("load it again"), "{description}"); + // The catalogue shows only the first sentence: it carries the caveat too. + let catalogue = tool_catalogue(); + let line = catalogue + .lines() + .find(|l| l.starts_with("- `batch`")) + .expect("batch in the catalogue"); + assert!(line.contains("files"), "{line}"); + // ...and the exception for a model replaced inside a connected batch. + assert!(line.contains("load_hull"), "{line}"); + } + #[test] fn export_templates_schema_lists_its_arguments() { let mut s = McpServer::new(); diff --git a/crates/seacraft-core/src/resistance.rs b/crates/seacraft-core/src/resistance.rs index a02b664..af943d8 100644 --- a/crates/seacraft-core/src/resistance.rs +++ b/crates/seacraft-core/src/resistance.rs @@ -17,10 +17,16 @@ //! percentage of the length) are derived from those measurements here. Nothing //! in this module looks at the control net. //! -//! Limits worth stating in the answer rather than hiding: Holtrop–Mennen was -//! fitted to `0.55 ≤ Cp ≤ 0.85`, `3.9 ≤ L/B ≤ 14.9`, `2.1 ≤ B/T ≤ 4.0` and -//! `Fn ≤ 0.55`. [`HoltropInput::warnings`] reports the ones a given hull -//! violates instead of silently extrapolating. +//! Limits worth stating in the answer rather than hiding: Holtrop–Mennen is +//! used here for `0.55 ≤ Cp ≤ 0.85`, `3.9 ≤ L/B ≤ 14.9` and `2.1 ≤ B/T ≤ 4.0`. +//! Neither paper prints these figures (1982, p. 166, limits the method to hull +//! forms resembling its average ship without a table), so their source is not +//! cited yet (`docs/oracles.md` §42). +//! [`HoltropInput::warnings`] reports the ones a given hull violates instead of +//! silently extrapolating, and [`HoltropInput::outside_fitted_range`] says +//! whether any does. Neither paper prints an upper Froude number: 1984 derives +//! its high-speed fit "for the speed range Fn > 0.55" (p. 273) and stops there, +//! so no speed is flagged on that account. //! //! Both papers print a worked example, and both are tests here. The 1984 //! example (50 m at 25-35 kn, all on the high-speed fit) reproduces `1+k1`, @@ -165,6 +171,26 @@ impl HoltropInput { /// The empirical validity ranges this hull falls outside, as short messages. pub fn warnings(&self) -> Vec { + let mut out = self.form_range_warnings(); + if self.bulb_area_m2 > 0.0 && self.bulb_centre_z > 0.6 * self.draft { + out.push( + Msg::new(Key::WarnHmBulb) + .arg("z", format!("{:.2}", self.bulb_centre_z)) + .arg("limit", format!("{:.2}", 0.6 * self.draft)), + ); + } + out + } + + /// Whether the hull's form lies outside the Cp, L/B or B/T range the method was fitted to, + /// so every speed's answer is an extrapolation. A bulb set above 0.6 T does not count: the + /// method caps its height there (Holtrop 1984, p. 273) and stays within the fit. + pub fn outside_fitted_range(&self) -> bool { + !self.form_range_warnings().is_empty() + } + + /// The Cp, L/B and B/T ranges this hull falls outside. + fn form_range_warnings(&self) -> Vec { let mut out = Vec::new(); let lb = self.length_wl / self.beam_wl; let bt = self.beam_wl / self.draft; @@ -177,13 +203,6 @@ impl HoltropInput { if !(2.1..=4.0).contains(&bt) { out.push(Msg::new(Key::WarnHmBt).arg("bt", format!("{bt:.2}"))); } - if self.bulb_area_m2 > 0.0 && self.bulb_centre_z > 0.6 * self.draft { - out.push( - Msg::new(Key::WarnHmBulb) - .arg("z", format!("{:.2}", self.bulb_centre_z)) - .arg("limit", format!("{:.2}", 0.6 * self.draft)), - ); - } out } } @@ -1910,6 +1929,30 @@ mod tests { assert!(w.iter().any(|s| s.to_string().contains("B/T")), "{w:?}"); } + /// A hull outside the Cp, L/B or B/T range is outside the fit; a bulb set too high is not, + /// because the method caps its height at 0.6 T and carries on. + #[test] + fn outside_fitted_range_follows_the_form_ranges_not_the_bulb_cap() { + let mut i = sample(); + assert!(!i.outside_fitted_range()); + i.bulb_area_m2 = 1.0; + i.bulb_centre_z = 0.9 * i.draft; + assert!(!i.warnings().is_empty()); + assert!( + !i.outside_fitted_range(), + "the bulb cap alone keeps the fit" + ); + for change in [ + |i: &mut HoltropInput| i.cp = 0.50, + |i: &mut HoltropInput| i.beam_wl = i.length_wl / 20.0, + |i: &mut HoltropInput| i.draft = i.beam_wl, + ] { + let mut j = sample(); + change(&mut j); + assert!(j.outside_fitted_range(), "{:?}", j.warnings()); + } + } + /// R8-2 A07. DSYHS regresses on the canoe body. The 10 m yacht floats /// at T = 1.85 m on its fin; its canoe body draws Tc = 0.45 m. The fin /// and rudder are closed shells of their own, so they are measured out: diff --git a/crates/seacraft-gui/src/analysis_views.rs b/crates/seacraft-gui/src/analysis_views.rs index 5672e48..4e04e20 100644 --- a/crates/seacraft-gui/src/analysis_views.rs +++ b/crates/seacraft-gui/src/analysis_views.rs @@ -684,8 +684,8 @@ pub fn to_csv_tr(table: &ViewTable, tr: Tr) -> String { let cells: Vec = (0..table.columns.len()) .map(|c| match row.get(c) { None => String::new(), - Some(EngCell::Text(t)) if t == NO_VALUE => String::new(), - Some(EngCell::Text(t)) => field(t), + Some(EngCell::Text(t) | EngCell::Muted(t)) if t == NO_VALUE => String::new(), + Some(EngCell::Text(t) | EngCell::Muted(t)) => field(t), Some(EngCell::Badge(passed, stale)) => { field(panels::criteria_badge_style_tr(*passed, *stale, tr).0) } diff --git a/crates/seacraft-gui/src/app.rs b/crates/seacraft-gui/src/app.rs index 9ab2c79..9d3b31c 100644 --- a/crates/seacraft-gui/src/app.rs +++ b/crates/seacraft-gui/src/app.rs @@ -45,6 +45,24 @@ pub const KG_UNSET_HINT: &str = "set KG first"; /// Undo steps kept. const UNDO_LIMIT: usize = 64; +/// The most refined faces (control-net faces × 4^level) built on the window thread. About 10 ms +/// of refinement: `container-230m` (313 faces) takes about 140 ms at level 5, about 320 000 faces +/// (ROADMAP M2). Above it the window draws a coarser level at once and a job builds the full one. +const SYNC_REFINED_FACE_BUDGET: usize = 24_000; + +/// The level to refine `net_faces` to on the window thread when `level` is asked for: the +/// highest within [`SYNC_REFINED_FACE_BUDGET`], never below level 1 (or `level`, if lower). +fn sync_level(net_faces: usize, level: u8) -> u8 { + let floor = level.min(1); + (floor..=level) + .rev() + .find(|&l| { + net_faces.saturating_mul(4usize.saturating_pow(u32::from(l))) + <= SYNC_REFINED_FACE_BUDGET + }) + .unwrap_or(floor) +} + /// Cached refined mesh, invalidated by the revision counter, level or mode. struct RenderCache { revision: u64, @@ -723,6 +741,10 @@ pub struct ResistanceRow { pub rt_kn: f64, pub pe_kw: Option, pub note: Option, + /// False where the method is outside the range it was fitted to: the whole Holtrop curve + /// for a hull outside its Cp, L/B or B/T range, a DSYHS speed outside Fn 0.15 to 0.75. The + /// Performance tab greys these out. + pub in_range: bool, } /// Consolidated resistance prediction result for GUI display. @@ -751,12 +773,21 @@ impl ResistanceResult { rt_kn: r.rt_n / 1000.0, pe_kw: Some(r.pe_w / 1000.0), note: None, + in_range: true, }) .collect(), warnings, rt_label: rt_label.to_string(), } } + + /// The same result with each row's `in_range` set by `in_range`. + pub fn with_in_range(mut self, in_range: impl Fn(&ResistanceRow) -> bool) -> Self { + for row in &mut self.rows { + row.in_range = in_range(row); + } + self + } } /// Which wave spectrum the sea-state section uses. @@ -903,7 +934,9 @@ pub fn compute_raos_with_sea( pub struct PerformanceState { pub method: ResistanceMethod, pub speeds_kn: (f64, f64, f64), - pub sk_speed_kn: f64, + /// The one speed (knots) that resistance marks, the wave pattern is computed at and + /// seakeeping runs at; the Wave pattern view shows it in knots or as a Froude number. + pub speed_kn: f64, pub kg: Option, pub kyy_frac: f64, pub points: usize, @@ -926,7 +959,7 @@ impl Default for PerformanceState { Self { method: ResistanceMethod::Holtrop, speeds_kn: (2.0, 12.0, 1.0), - sk_speed_kn: 6.0, + speed_kn: 6.0, kg: None, kyy_frac: 0.25, points: 30, @@ -991,6 +1024,8 @@ impl From for String { /// waterline length and beam at the report's draft when a current result knows them. struct ReportWaves { settings: crate::waves::WaveSettings, + /// The shared speed ([`PerformanceState::speed_kn`]). + speed_kn: f64, lengths: Option<(f64, f64)>, } @@ -1017,10 +1052,7 @@ impl ReportWaves { }) .or(Some((surface.settings.length, surface.settings.beam))) .filter(|(l, b)| *l > 0.0 && *b >= 0.0); - let (speed_m_s, froude) = match w.speed { - crate::waves::WaveSpeed::Knots(kn) => (kn * seacraft_core::resistance::KNOT, None), - crate::waves::WaveSpeed::Froude(f) => (1.0, Some(f)), - }; + let (speed_m_s, froude) = (self.speed_kn * seacraft_core::resistance::KNOT, None); let (wash, (ahead_l, behind_l, half_width_l)) = match lengths { Some((l, b)) => { let wash = crate::waves::wash_distance(w, l, b); @@ -1080,6 +1112,9 @@ pub struct App { cameras: [Camera; 4], active: usize, cache: Option, + /// The full-level refined mesh when it is too large to build on the window thread + /// ([`sync_level`]); keyed by [`App::mesh_key`]. + mesh_track: Track, selection: crate::selection::Selection, hovered_point: Option, selected_volume: Option, @@ -1496,6 +1531,7 @@ impl App { ], active: 0, cache: None, + mesh_track: Track::default(), selection: crate::selection::Selection::default(), hovered_point: None, selected_volume: None, @@ -1858,6 +1894,7 @@ impl App { self.picked_face = None; self.layer_panel = panels::LayerPanelState::default(); self.cache = None; + self.mesh_track.reset(); self.hydro.result = None; self.hydro.curves = None; self.hydro.hull = None; @@ -1929,22 +1966,45 @@ impl App { /// Refine the hull when anything it depends on changed. While a point is /// being dragged the preview drops to level 2; the full level returns when - /// the drag ends. + /// the drag ends. A mesh too large for the window thread ([`sync_level`]) + /// is drawn at a coarser level at once while a job builds the full one. fn sync_cache(&mut self) { + self.sync_cache_at(false); + } + + /// [`App::sync_cache`]; with `full`, the full level is built on this thread whatever its size. + fn sync_cache_at(&mut self, full: bool) { let Some(surface) = &self.surface else { self.cache = None; + self.mesh_track.reset(); return; }; - let level = if self.drag.is_some() { + let dragging = self.drag.is_some(); + let target = if dragging { self.level.min(2) } else { self.level }; + let quick = if dragging || full { + target + } else { + sync_level(surface.faces.len(), target) + }; let stale = match &self.cache { - Some(c) => c.revision != self.revision || c.level != level || c.mode != self.mode, + Some(c) => { + c.revision != self.revision + || c.mode != self.mode + || (c.level != target && c.level != quick) + } None => true, }; if stale { + let level = quick; + if level < self.level { + // A finished full-level mesh is being replaced by a coarser one (a drag's + // preview): it is due again once the drag ends. + self.mesh_track.unstamp(); + } let mesh = export::render_mesh(surface, level, self.mode); let net_lines = seacraft_core::netlines::NetLines::of(surface); let (min, max) = crate::render::display_extents(surface); @@ -1976,6 +2036,17 @@ impl App { max, }); } + let key = self.mesh_key(); + let short = self.cache.as_ref().is_some_and(|c| c.level < target); + // Nothing to build in the background during a drag (it previews at level 2) or for a + // mesh already at the full level. A job in flight is kept, not forgotten: its worker + // cannot be stopped, so a new one waits for it, and its result is dropped by key. + if !(dragging || full || !short) && self.mesh_track.ready(key) { + let surface = surface.clone(); + let (level, mode) = (target, self.mode); + self.mesh_track + .start(key, move || Ok(export::render_mesh(&surface, level, mode))); + } if self.display.waterplane { let options = &self.hydro.options; let plane = seacraft_core::hydro::waterplane( @@ -2008,7 +2079,9 @@ impl App { { cache.curves_stale = false; cache.curves_for = Some(want); - let opts = self.display.section_options(level, self.mode); + // Cut at the level drawn: a preview's curves are cut again when the full + // mesh replaces it. + let opts = self.display.section_options(cache.level, self.mode); cache.curves = Some(seacraft_core::linesplan::curves_3d(surface, opts)); } } @@ -2233,16 +2306,7 @@ impl App { self.project_changed(); } DockAction::Windage(panels::WindageAction::None) => {} - DockAction::Performance(panels::PerformanceAction::Changed) => { - self.performance_changed(); - } - DockAction::Performance(panels::PerformanceAction::Compute) => { - self.start_performance_compute() - } - DockAction::Performance(panels::PerformanceAction::OpenWaveView) => { - self.set_wave_view_open(true); - } - DockAction::Performance(panels::PerformanceAction::None) => {} + DockAction::Performance(a) => self.apply_performance_action(a), } self.record_project_edit(ui.ctx(), before, pre_drag, pre_focus); } @@ -2328,6 +2392,13 @@ impl App { SubdivisionMode::CatmullClark => "Catmull-Clark", }, )); + if self.mesh_refining() { + ui.spinner(); + ui.label(tr.fmt( + seacraft_core::i18n::Key::StatusRefiningMesh, + &[("level", &self.level.to_string())], + )); + } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.label(format!("v{}", seacraft_core::VERSION)); if let Some(p) = self.cursor_world { @@ -3212,7 +3283,7 @@ impl App { .filter(|v| v.is_finite() && *v > 0.0); if let Some(v) = speed { self.perf_state.speeds_kn = crate::new_design::speed_range(v); - self.perf_state.sk_speed_kn = v; + self.perf_state.speed_kn = v; self.performance_changed(); } } @@ -5387,6 +5458,34 @@ impl App { ]) } + /// The full-level mesh's inputs: the geometry, the level and the mode. + fn mesh_key(&self) -> u64 { + revision_key(&[self.revision, u64::from(self.level), self.mode as u64]) + } + + /// Take a finished full-level mesh: it replaces the preview when it is for the current + /// geometry, level and mode (the track drops any other). + fn install_mesh(&mut self, mesh: RenderMesh) { + let Some(cache) = self.cache.as_mut() else { + return; + }; + // Also skipped when the full level is already there (built at once by `refresh_cache` + // while the job ran): the same mesh again would only throw away the BVH and waterline. + if cache.revision != self.revision + || cache.mode != self.mode + || cache.level == self.level + || self.drag.is_some() + { + return; + } + cache.mesh = mesh; + cache.level = self.level; + cache.bvh = None; + cache.waterline = None; + // The section curves were cut from the preview: cut them again from this mesh. + cache.curves_stale = cache.curves.is_some(); + } + fn resistance_key(&self) -> u64 { revision_key(&[self.revision, self.hydro_rev, self.perf_rev]) } @@ -5398,6 +5497,7 @@ impl App { self.revision, self.hydro_rev, crate::waves::settings_key(&self.perf_state.waves), + self.perf_state.speed_kn.to_bits(), ]) } @@ -5932,6 +6032,76 @@ impl App { self.last_change = Some(std::time::Instant::now()); } + /// The waterline length and beam the Wave pattern view converts by: the kept pattern's, + /// else the hydrostatics'. + fn wave_lengths(&self) -> (Option, Option) { + let measured = self.perf_state.wave_result.as_ref(); + let length_wl = measured + .map(|w| w.length_wl) + .or_else(|| self.hydro.result.as_ref().map(|h| h.lwl)) + .filter(|l| *l > 0.0); + let beam_wl = measured + .map(|w| w.beam_wl) + .or_else(|| self.hydro.result.as_ref().map(|h| h.bwl)); + (length_wl, beam_wl) + } + + /// The shared speed as the Wave pattern view reads it: a Froude number when it shows one and + /// a waterline length is known, else knots. + pub fn wave_speed(&self) -> crate::waves::WaveSpeed { + let knots = crate::waves::WaveSpeed::Knots(self.perf_state.speed_kn); + match self.wave_lengths().0 { + Some(l) if self.perf_state.waves.froude_unit => knots.in_unit(false, l), + _ => knots, + } + } + + /// Set the shared speed, in knots or as a Froude number (converted by the view's waterline + /// length; without one a Froude number is ignored), and show it in that unit. + pub fn set_wave_speed(&mut self, speed: crate::waves::WaveSpeed) { + let kn = match (speed, self.wave_lengths().0) { + (crate::waves::WaveSpeed::Knots(kn), _) => Some(kn), + (crate::waves::WaveSpeed::Froude(_), Some(l)) => { + Some(speed.m_s(l) / seacraft_core::resistance::KNOT) + } + (crate::waves::WaveSpeed::Froude(_), None) => None, + }; + self.perf_state.waves.froude_unit = !speed.is_knots(); + if let Some(kn) = kn.filter(|v| v.is_finite() && *v >= 0.0) { + self.set_shared_speed(kn); + } + } + + /// Set the speed resistance, waves and seakeeping share (knots). The resistance curve does not + /// depend on it and stays current; the wave pattern and the RAOs key on it. + fn set_shared_speed(&mut self, speed_kn: f64) { + if self.perf_state.speed_kn != speed_kn { + self.perf_state.speed_kn = speed_kn; + self.speed_changed(); + } + } + + /// The shared speed moved: the results that depend on it recompute after the quiet period. + fn speed_changed(&mut self) { + self.last_change = Some(std::time::Instant::now()); + } + + /// Apply what the Performance tab asked for on one frame, all of it. + fn apply_performance_action(&mut self, a: panels::PerformanceAction) { + // A change bumps the revision, which already covers a speed moved with it. + if a.changed { + self.performance_changed(); + } else if a.speed_changed { + self.speed_changed(); + } + if a.compute { + self.start_performance_compute(); + } + if a.open_wave_view { + self.set_wave_view_open(true); + } + } + /// Open the Wave pattern view in the drawer (it computes while open), or close it if it is the /// view shown. pub fn set_wave_view_open(&mut self, open: bool) { @@ -5987,6 +6157,7 @@ impl App { self.hydro.options.draft, self.hydro.options.water_density, &self.perf_state.waves, + crate::waves::WaveSpeed::Knots(self.perf_state.speed_kn), ) { Ok(w) => { self.perf_state.wave_result = Some(w); @@ -6012,9 +6183,10 @@ impl App { let draft = self.hydro.options.draft; let rho = self.hydro.options.water_density; let settings = self.perf_state.waves.clone(); + let speed = crate::waves::WaveSpeed::Knots(self.perf_state.speed_kn); let key = self.waves_key(); self.waves_track.start(key, move || { - crate::waves::compute_waves(&surface, subdivision, draft, rho, &settings) + crate::waves::compute_waves(&surface, subdivision, draft, rho, &settings, speed) }); } @@ -6026,6 +6198,7 @@ impl App { self.perf_rev, self.project_rev, self.loading_selected as u64, + self.perf_state.speed_kn.to_bits(), ]) } @@ -6167,7 +6340,8 @@ impl App { } } } - let busy = self.hydro.track.busy() + let busy = self.mesh_track.busy() + || self.hydro.track.busy() || self.hydro.curves_track.busy() || self.loading_track.busy() || self.damage_track.busy() @@ -6187,6 +6361,15 @@ impl App { /// Take the results of finished jobs. A failure goes to the status line /// (and stays on its tab until the inputs change). fn poll_jobs(&mut self) { + // A mesh is never installed during a drag, so it waits for the release: taken now, the + // track would call it current and never build it again. + if self.drag.is_none() { + match self.mesh_track.poll(self.mesh_key()) { + Some(Ok(mesh)) => self.install_mesh(mesh), + Some(Err(e)) => self.log_job_failure(seacraft_core::i18n::Key::JobRefinedHull, &e), + None => {} + } + } let key = self.hydro_key(); match self.hydro.track.poll(key) { Some(Ok(out)) => self.install_hydro(out), @@ -6670,6 +6853,7 @@ impl App { }); let waves = self.waves_needed().then(|| ReportWaves { settings: self.perf_state.waves.clone(), + speed_kn: self.perf_state.speed_kn, lengths, }); Some((opts, waves)) @@ -8020,7 +8204,7 @@ impl App { }; Ok(SeakeepingSpec { draft, - speed_kn: self.perf_state.sk_speed_kn, + speed_kn: self.perf_state.speed_kn, kg, kyy, points: Some(self.perf_state.points), @@ -8306,6 +8490,36 @@ impl App { self.cache.as_ref().map(|c| &c.mesh) } + /// The level the cached mesh was refined to (test hook). + pub fn render_cache_level(&self) -> Option { + self.cache.as_ref().map(|c| c.level) + } + + /// The cached mesh is for the model as it is now (test hook). + pub fn render_cache_is_current(&self) -> bool { + self.cache + .as_ref() + .is_some_and(|c| c.revision == self.revision && c.mode == self.mode) + } + + /// The hull is drawn at a coarser level while the full one is built in the background. + pub fn mesh_refining(&self) -> bool { + self.drag.is_none() + && self + .surface + .as_ref() + .is_some_and(|s| sync_level(s.faces.len(), self.level) < self.level) + && self.cache.as_ref().is_some_and(|c| { + c.revision == self.revision && c.mode == self.mode && c.level < self.level + }) + && self.mesh_track.failure(self.mesh_key()).is_none() + } + + /// The background mesh job in flight is for the current geometry, level and mode (test hook). + pub fn mesh_job_is_current(&self) -> bool { + self.mesh_track.running_for() == Some(self.mesh_key()) + } + /// Cached net lines for the current surface, once [`Self::refresh_cache`] has run. pub fn net_lines(&self) -> Option<&seacraft_core::netlines::NetLines> { self.cache.as_ref().map(|c| &c.net_lines) @@ -9081,7 +9295,14 @@ impl App { /// Refine the hull now if anything it depends on changed (the control /// socket's `ui.render` needs a mesh without waiting for a frame). pub fn refresh_cache(&mut self) { - self.sync_cache(); + self.sync_cache_at(true); + } + + /// Refine as a frame does, without drawing or collecting finished jobs: a large hull gets + /// its preview and a background job for the full level (test hook; a frame may collect a + /// fast job in the same pass, which makes "still refining" a race). + pub fn sync_render_cache(&mut self) { + self.sync_cache_at(false); } /// A status line for an action that changed nothing about the model. @@ -9609,14 +9830,17 @@ fn compute_resistance_impl( rt_kn: r.rt_n / 1000.0, pe_kw: Some(r.pe_w / 1000.0), note: None, + in_range: true, }) .collect(); + let outside = input.outside_fitted_range(); Ok(ResistanceResult { method: "Holtrop & Mennen".to_string(), rows, warnings, rt_label: "R_T (kN)".to_string(), - }) + } + .with_in_range(|_| !outside)) } ResistanceMethod::Dsyhs => { let dsyhs_in = resistance::DsyhsInput::measure(&hull, opts) @@ -9636,6 +9860,7 @@ fn compute_resistance_impl( rt_kn: r.rt_n / 1000.0, pe_kw: Some(r.pe_w / 1000.0), note: None, + in_range: true, }) .collect(); Ok(ResistanceResult { @@ -9643,7 +9868,8 @@ fn compute_resistance_impl( rows, warnings, rt_label: "R_T (kN)".to_string(), - }) + } + .with_in_range(|r| (0.15..=0.75).contains(&r.fn_))) } ResistanceMethod::Savitsky => { let setup = @@ -9664,6 +9890,7 @@ fn compute_resistance_impl( rt_kn: p.resistance_n / 1000.0, pe_kw: Some(p.pe_w / 1000.0), note: Some(format!("trim {:.1}°", p.trim_deg)), + in_range: true, }) .collect(); Ok(ResistanceResult { @@ -9722,6 +9949,7 @@ fn compute_resistance_impl( rt_kn: r.rt_n / 1000.0, pe_kw: Some(r.pe_w / 1000.0), note: Some(format!("Rw {:.2} kN", r.rw_n / 1000.0)), + in_range: true, }) .collect(); Ok(ResistanceResult { @@ -10500,16 +10728,12 @@ impl App { .map(str::to_owned); let heeled_or_trimmed = self.hydro.options.heel_deg != 0.0 || self.hydro.options.trim != 0.0; + let (length_wl, beam_wl) = self.wave_lengths(); let measured = self.perf_state.wave_result.as_ref(); - let length_wl = measured - .map(|w| w.length_wl) - .or_else(|| self.hydro.result.as_ref().map(|h| h.lwl)); - let beam_wl = measured - .map(|w| w.beam_wl) - .or_else(|| self.hydro.result.as_ref().map(|h| h.bwl)); let drag = self.wave_drag(); let before = self.perf_state.waves.clone(); let mut settings = before.clone(); + let mut speed_kn = self.perf_state.speed_kn; let mut map = self.wave_map; let tr = self.tr(); let mut action = WaveViewAction::None; @@ -10524,6 +10748,7 @@ impl App { ui, WaveViewPanel { settings: &mut settings, + speed_kn: &mut speed_kn, result: measured, drag, stale, @@ -10545,13 +10770,14 @@ impl App { WaveViewAction::SaveImage => self.open_dialog(DialogKind::WaveImage), WaveViewAction::Close => self.close_analysis_view(), WaveViewAction::Open(other) => self.open_analysis_view(other), - WaveViewAction::SetSpeed(speed) => settings.speed = speed, + WaveViewAction::SetSpeed(kn) => speed_kn = kn, WaveViewAction::SetSpacing(spacing) => settings.cat_spacing_m = Some(spacing), WaveViewAction::SetWashDistance(d) => settings.wash_distance_m = Some(d), } if settings != before { self.set_wave_settings(settings); } + self.set_shared_speed(speed_kn); } /// The Heel view in the drawer under the viewports. @@ -10915,3 +11141,51 @@ impl App { } } } + +#[cfg(test)] +mod mesh_budget_tests { + use super::sync_level; + + /// Net faces from `seacraft info`: demo-hull 81, wigley 180, container-230m 313. + #[test] + fn sync_level_keeps_small_hulls_whole() { + assert_eq!(sync_level(81, 4), 4); + assert_eq!(sync_level(313, 3), 3); + assert_eq!(sync_level(313, 5), 3); + assert_eq!(sync_level(180, 4), 3); + assert_eq!(sync_level(10_000, 2), 1, "never below level 1"); + assert_eq!(sync_level(10_000, 0), 0); + } +} + +#[cfg(test)] +mod performance_action_tests { + use super::App; + use crate::analysis_views::AnalysisView; + use crate::panels::PerformanceAction; + + /// Agy review 2: a field committed on the same frame as a click on the curve or the + /// Compute button gives two actions; the App applies both instead of keeping the last. + #[test] + fn every_action_of_one_frame_is_applied() { + let demo = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/demo-hull.fef"); + let mut app = App::headless_for_test(Some(demo)); + let rev = app.perf_rev; + app.apply_performance_action(PerformanceAction { + changed: true, + speed_changed: true, + compute: true, + open_wave_view: true, + }); + assert_eq!( + app.perf_rev, + rev + 1, + "the change marks the curve out of date" + ); + assert!( + app.resistance_track.busy(), + "the Compute click starts the curve" + ); + assert_eq!(app.analysis.open, Some(AnalysisView::Waves)); + } +} diff --git a/crates/seacraft-gui/src/control.rs b/crates/seacraft-gui/src/control.rs index d9e769f..b579c5c 100644 --- a/crates/seacraft-gui/src/control.rs +++ b/crates/seacraft-gui/src/control.rs @@ -2566,7 +2566,7 @@ fn handle_inner( let speed_kn = number(p, "speed_kn")? .or(number(p, "speed")?) - .unwrap_or(app.performance_state().sk_speed_kn); + .unwrap_or(app.performance_state().speed_kn); let kg = number(p, "kg")? .or(app.effective_performance_kg()) .ok_or("performance.compute: set KG first (or pass `kg`)")?; diff --git a/crates/seacraft-gui/src/heel_view/mod.rs b/crates/seacraft-gui/src/heel_view/mod.rs index 26f4bd7..4e1b502 100644 --- a/crates/seacraft-gui/src/heel_view/mod.rs +++ b/crates/seacraft-gui/src/heel_view/mod.rs @@ -2187,11 +2187,13 @@ fn gz_plot( label: tr.s(Key::HeelPlotGzMomentSeries).into(), points: pts(|s| draw::righting_moment_knm(s.displacement_t, s.gz_m)), dashed: false, + muted: false, }, PlotSeries { label: tr.s(Key::HeelPlotHeelingMomentSeries).into(), points: pts(|s| draw::righting_moment_knm(s.displacement_t, s.heeling_arm_m)), dashed: true, + muted: false, }, ] } else { @@ -2200,11 +2202,13 @@ fn gz_plot( label: tr.s(Key::HeelPlotGzLeverSeries).into(), points: pts(|s| s.gz_m), dashed: false, + muted: false, }, PlotSeries { label: tr.s(Key::HeelPlotHeelingArmSeries).into(), points: pts(|s| s.heeling_arm_m), dashed: true, + muted: false, }, ] }; diff --git a/crates/seacraft-gui/src/jobs.rs b/crates/seacraft-gui/src/jobs.rs index 86ceaff..180f941 100644 --- a/crates/seacraft-gui/src/jobs.rs +++ b/crates/seacraft-gui/src/jobs.rs @@ -136,6 +136,12 @@ impl Track { self.job = None; } + /// The stored result was thrown away (the caller replaced it): it is due again. A running + /// job is kept, and so is a failure. + pub fn unstamp(&mut self) { + self.stamp = None; + } + /// Forget everything: no result, no job, no failure. pub fn reset(&mut self) { *self = Self::default(); diff --git a/crates/seacraft-gui/src/panels.rs b/crates/seacraft-gui/src/panels.rs index 6950894..dea934a 100644 --- a/crates/seacraft-gui/src/panels.rs +++ b/crates/seacraft-gui/src/panels.rs @@ -2275,13 +2275,17 @@ pub fn report_options_tr( changed } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PerformanceAction { - None, - Changed, - Compute, +/// What the user asked for on one frame. Several can come together (a field committed by the +/// same click that moved the speed or pressed Compute), so each is a flag and the App applies all. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PerformanceAction { + /// An input the resistance and the RAOs depend on changed. + pub changed: bool, + /// The shared speed moved (it is in the state already): only what depends on it recomputes. + pub speed_changed: bool, + pub compute: bool, /// "Open wave pattern": show the Wave pattern view in the Analysis drawer. - OpenWaveView, + pub open_wave_view: bool, } pub struct PerformancePanel<'a> { @@ -2306,7 +2310,7 @@ pub fn performance(ui: &mut egui::Ui, panel: PerformancePanel<'_>) -> Performanc /// Localized form of [`performance`]. pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> PerformanceAction { - let mut action = PerformanceAction::None; + let mut action = PerformanceAction::default(); theme::heading(ui, tr.s(Key::PerfTitle)); ui.add_space(4.0); @@ -2315,7 +2319,7 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> ui.horizontal(|ui| { let btn = ui.add_enabled(!is_busy, egui::Button::new(tr.s(Key::CommonCompute))); if btn.clicked() { - action = PerformanceAction::Compute; + action.compute = true; } if is_busy { ui.spinner(); @@ -2329,6 +2333,21 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> } }); + // One speed for the three sections below: marked on the resistance curve, the wave + // pattern's speed, and the speed seakeeping runs at. + let speed_max = panel.state.speeds_kn.1.max(20.0); + let speed_resp = theme::slider( + ui, + egui::Slider::new(&mut panel.state.speed_kn, 0.0..=speed_max) + .text(tr.s(Key::PerfSpeedKn)) + .step_by(0.5) + .clamping(egui::SliderClamping::Edits), + ) + .on_hover_text(tr.s(Key::PerfSpeedSharedTip)); + if speed_resp.changed() { + action.speed_changed = true; + } + ui.add_space(4.0); ui.separator(); ui.strong(tr.s(Key::PerfResistanceHeading)); @@ -2349,7 +2368,7 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> .selectable_value(&mut panel.state.method, m, m.label_tr(tr)) .clicked() { - action = PerformanceAction::Changed; + action.changed = true; } } }); @@ -2376,14 +2395,22 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> .prefix(tr.s(Key::PerfStepColon)), ); if r1.changed() || r2.changed() || r3.changed() { - action = PerformanceAction::Changed; + action.changed = true; } }); if let Some(res) = &panel.state.resistance { + let mut picked = None; stale_section_tr(ui, panel.stale_resistance, tr, |ui| { - resistance_results(ui, res, tr); + picked = resistance_results(ui, res, panel.state.speed_kn, tr); }); + if let Some(kn) = picked { + let kn = (kn * 10.0).round() / 10.0; + if kn != panel.state.speed_kn { + panel.state.speed_kn = kn; + action.speed_changed = true; + } + } } ui.add_space(4.0); @@ -2395,7 +2422,7 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> .on_hover_text(tr.s(Key::PerfOpenWavePatternTip)) .clicked() { - action = PerformanceAction::OpenWaveView; + action.open_wave_view = true; } if let Some(sentence) = panel.wave_regime { ui.label(egui::RichText::new(sentence).color(theme::TEXT_SECONDARY)); @@ -2406,22 +2433,12 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> ui.strong(tr.s(Key::PerfSeakeepingHeading)); ui.add_space(2.0); - let speed_resp = theme::slider( - ui, - egui::Slider::new(&mut panel.state.sk_speed_kn, 0.0..=20.0) - .text(tr.s(Key::PerfSpeedKn)) - .step_by(0.5), - ); - if speed_resp.changed() { - action = PerformanceAction::Changed; - } - ui.horizontal(|ui| { ui.label("KG"); let mut cur_kg = panel.state.kg.or(panel.default_kg); if kg_field(ui, &mut cur_kg, false, 50.0, 84.0, tr) { panel.state.kg = cur_kg; - action = PerformanceAction::Changed; + action.changed = true; } let default = match panel.default_kg { Some(kg) => format!("{kg:.2} m"), @@ -2430,7 +2447,7 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> if panel.state.kg.is_some() { if ui.small_button(tr.s(Key::CommonResetCap)).clicked() { panel.state.kg = None; - action = PerformanceAction::Changed; + action.changed = true; } ui.label(tr.fmt( Key::PerfKgDefaultSource, @@ -2458,7 +2475,7 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> ) .on_hover_text(tr.s(Key::PerfFrequenciesTip)); if kyy_resp.changed() || pts_resp.changed() { - action = PerformanceAction::Changed; + action.changed = true; } }); @@ -2471,29 +2488,41 @@ pub fn performance_tr(ui: &mut egui::Ui, panel: PerformancePanel<'_>, tr: Tr) -> ui.add_space(4.0); ui.separator(); if sea_state_section(ui, panel.state, panel.stale_raos, tr) { - action = PerformanceAction::Changed; + action.changed = true; } action } -/// The resistance curve and its table. -fn resistance_results(ui: &mut egui::Ui, res: &crate::app::ResistanceResult, tr: Tr) { +/// The resistance curve and its table, with the shared speed marked on the curve. Returns the +/// speed (knots) the user clicked or dragged to on the plot. +fn resistance_results( + ui: &mut egui::Ui, + res: &crate::app::ResistanceResult, + speed_kn: f64, + tr: Tr, +) -> Option { for w in &res.warnings { ui.colored_label(theme::WARN, format!("⚠ {}", w.render(tr))); } - let series = vec![( - res.method.clone(), - res.rows.iter().map(|r| (r.speed_kn, r.rt_kn)).collect(), - )]; - plot_xy_tr( + let series = resistance_series(res, tr); + let caption = tr.fmt( + Key::PlotXyCaption, + &[ + ("title", tr.s(Key::PerfPlotResistance)), + ("y", &res.rt_label), + ("x", tr.s(Key::PerfPlotSpeedKn)), + ], + ); + let (_, picked) = plot_interactive_sized( ui, - tr.s(Key::PerfPlotResistance), - tr.s(Key::PerfPlotSpeedKn), - &res.rt_label, + &caption, &series, - tr, + Some(speed_kn), + &[], + None, + PLOT_HEIGHT, ); ui.add_space(2.0); @@ -2509,6 +2538,49 @@ fn resistance_results(ui: &mut egui::Ui, res: &crate::app::ResistanceResult, tr: &resistance_table(res), tr, ); + picked +} + +/// The resistance curve as plot series: the whole curve in the method's colour, then, when any +/// speed is outside the method's range, the segments touching one drawn again on top greyed out, +/// with a NaN between separate stretches so the plotter breaks the grey line there. +pub fn resistance_series(res: &crate::app::ResistanceResult, tr: Tr) -> Vec { + let points: Vec<(f64, f64)> = res.rows.iter().map(|r| (r.speed_kn, r.rt_kn)).collect(); + // A segment is grey when either end is out of range; a lone speed has no segment. + let out = |i: usize| !res.rows[i].in_range; + let mut grey: Vec<(f64, f64)> = Vec::new(); + let mut last: Option = None; + for i in 1..points.len() { + if !(out(i - 1) || out(i)) { + continue; + } + if last != Some(i - 1) { + if !grey.is_empty() { + grey.push((f64::NAN, f64::NAN)); + } + grey.push(points[i - 1]); + } + grey.push(points[i]); + last = Some(i); + } + if points.len() == 1 && out(0) { + grey.push(points[0]); + } + let mut series = vec![PlotSeries { + label: res.method.clone(), + points, + dashed: false, + muted: false, + }]; + if !grey.is_empty() { + series.push(PlotSeries { + label: tr.fmt(Key::PerfPlotOutsideRange, &[("method", &res.method)]), + points: grey, + dashed: false, + muted: true, + }); + } + series } /// The natural periods and the motion RAO plot. @@ -3472,6 +3544,8 @@ pub enum EngCell { Text(String), /// A criteria verdict: passed, stale. Badge(bool, bool), + /// Text drawn greyed out: a value outside its method's range, kept but played down. + Muted(String), } impl From for EngCell { @@ -3538,6 +3612,10 @@ pub fn eng_table_tr( (t.clone(), body_font.clone(), theme::TEXT_MUTED) } (_, Some(EngCell::Text(t))) => (t.clone(), body_font.clone(), theme::TEXT_PRIMARY), + (ColumnKind::Number, Some(EngCell::Muted(t))) => { + (t.clone(), mono_font.clone(), theme::TEXT_MUTED) + } + (_, Some(EngCell::Muted(t))) => (t.clone(), body_font.clone(), theme::TEXT_MUTED), }; painter.layout_no_wrap(text, font, colour) }; @@ -3666,13 +3744,21 @@ pub fn resistance_table(res: &crate::app::ResistanceResult) -> Vec> res.rows .iter() .map(|r| { + let cell = |text: String| { + if r.in_range { + EngCell::Text(text) + } else { + EngCell::Muted(text) + } + }; vec![ - format!("{:.2}", r.speed_kn).into(), - format!("{:.3}", r.fn_).into(), - format!("{:.2}", r.rt_kn).into(), - r.pe_kw - .map_or_else(|| "—".to_owned(), |pe| format!("{pe:.2}")) - .into(), + cell(format!("{:.2}", r.speed_kn)), + cell(format!("{:.3}", r.fn_)), + cell(format!("{:.2}", r.rt_kn)), + cell( + r.pe_kw + .map_or_else(|| "—".to_owned(), |pe| format!("{pe:.2}")), + ), ] }) .collect() @@ -4115,6 +4201,7 @@ fn draw_plot( ) -> egui::Rect { let style = PlotStyle { dashed: &[], + muted: &[], x_range: None, sense: egui::Sense::hover(), }; @@ -4127,11 +4214,29 @@ fn draw_plot( struct PlotStyle<'a> { /// Series `i` is dashed when `dashed[i]` (missing: solid). dashed: &'a [bool], + /// Series `i` is greyed out when `muted[i]` (missing: its palette colour): drawn in + /// [`theme::TEXT_MUTED`], a little wider so it covers a curve beneath, legend entry too. + muted: &'a [bool], /// Fix the x axis to this range instead of fitting it (with zero) to the data. x_range: Option<(f64, f64)>, sense: egui::Sense, } +impl PlotStyle<'_> { + fn is_muted(&self, i: usize) -> bool { + self.muted.get(i).copied().unwrap_or(false) + } + + /// Series `i`'s colour: grey when muted, else its place in the palette. + fn colour(&self, i: usize) -> egui::Color32 { + if self.is_muted(i) { + theme::TEXT_MUTED + } else { + theme::PLOT_SERIES[i % theme::PLOT_SERIES.len()] + } + } +} + /// The plot [`draw_plot`] draws, returning its response (legend included) and its axes. fn plot_core( ui: &mut egui::Ui, @@ -4154,10 +4259,7 @@ fn plot_core( } for (i, (label, _)) in series.iter().enumerate() { if !label.is_empty() { - entries.push(( - format!("━ {label}"), - theme::PLOT_SERIES[i % theme::PLOT_SERIES.len()], - )); + entries.push((format!("━ {label}"), style.colour(i))); } } } @@ -4189,8 +4291,9 @@ fn plot_core( } axes.paint_frame(&painter); for (i, (_, pts)) in series.iter().enumerate() { - let colour = theme::PLOT_SERIES[i % theme::PLOT_SERIES.len()]; - let stroke = egui::Stroke::new(1.4, colour); + let colour = style.colour(i); + let width = if style.is_muted(i) { 2.2 } else { 1.4 }; + let stroke = egui::Stroke::new(width, colour); let dashed = style.dashed.get(i).copied().unwrap_or(false); for run in axes.polylines(pts) { if run.len() == 1 { @@ -4223,6 +4326,8 @@ pub struct PlotSeries { pub label: String, pub points: Vec<(f64, f64)>, pub dashed: bool, + /// Greyed out (see [`PlotStyle`]'s `muted`). + pub muted: bool, } /// The plot as [`plot_xy`] draws it (same theme, axes and legend), plus dashed vertical `marks`, @@ -4266,8 +4371,10 @@ pub fn plot_interactive_sized( .map(|s| (s.label.clone(), s.points.clone())) .collect(); let dashed: Vec = series.iter().map(|s| s.dashed).collect(); + let muted: Vec = series.iter().map(|s| s.muted).collect(); let style = PlotStyle { dashed: &dashed, + muted: &muted, x_range, sense: egui::Sense::click_and_drag(), }; @@ -6926,6 +7033,7 @@ mod tests { label: String::new(), points: vec![(0.1, 1.0), (1.0, 3.0)], dashed: false, + muted: false, }]; let ctx = egui::Context::default(); theme::apply(&ctx); @@ -7128,6 +7236,7 @@ mod tests { rt_kn: 1.23456, pe_kw: Some(3.8), note: None, + in_range: true, }, crate::app::ResistanceRow { speed_kn: 7.5, @@ -7135,6 +7244,7 @@ mod tests { rt_kn: 2.5, pe_kw: None, note: None, + in_range: true, }, ], warnings: Vec::new(), @@ -7143,7 +7253,7 @@ mod tests { let rows = resistance_table(&res); let text = |r: usize, c: usize| match &rows[r][c] { EngCell::Text(t) => t.clone(), - EngCell::Badge(..) => unreachable!(), + EngCell::Badge(..) | EngCell::Muted(_) => unreachable!(), }; assert_eq!( [text(0, 0), text(0, 1), text(0, 2), text(0, 3)], diff --git a/crates/seacraft-gui/src/theme.rs b/crates/seacraft-gui/src/theme.rs index b82b7d4..d8a40e7 100644 --- a/crates/seacraft-gui/src/theme.rs +++ b/crates/seacraft-gui/src/theme.rs @@ -492,6 +492,10 @@ impl<'a> Num<'a> { pub fn update_while_editing(self, update: bool) -> Self { Self(self.0.update_while_editing(update)) } + /// `false`: the range bounds what the user types or drags, not the value shown. + pub fn clamp_existing_to_range(self, clamp: bool) -> Self { + Self(self.0.clamp_existing_to_range(clamp)) + } } impl egui::Widget for Num<'_> { diff --git a/crates/seacraft-gui/src/wave_view.rs b/crates/seacraft-gui/src/wave_view.rs index a54ff4a..1aecade 100644 --- a/crates/seacraft-gui/src/wave_view.rs +++ b/crates/seacraft-gui/src/wave_view.rs @@ -1,5 +1,6 @@ //! The Wave pattern view in the Analysis drawer: one speed you can scrub drives the speed regime, -//! humps and hollows of wave drag, catamaran interference, wash at a distance and the picture. +//! humps and hollows of wave drag, catamaran interference, wash at a distance and the picture. It is +//! the Performance tab's speed, the one resistance and seakeeping use too. //! //! The panel never changes the model or the app: it edits the wave settings it is given (view //! inputs, like the other Analysis views' inputs) and returns what the user asked for as a @@ -25,7 +26,8 @@ pub enum WaveViewAction { Changed, /// "Save image…": PNG, SVG or VTI. SaveImage, - SetSpeed(WaveSpeed), + /// A speed (knots), from a click on the drag plot. + SetSpeed(f64), /// A catamaran spacing (m), from the spacing plot. SetSpacing(f64), /// A wash distance (m), from dragging the wash line. @@ -56,6 +58,9 @@ pub struct MapState { /// The wave view's inputs. pub struct WaveViewPanel<'a> { pub settings: &'a mut WaveSettings, + /// The speed resistance, waves and seakeeping share (knots); the view edits it in knots or + /// as a Froude number. + pub speed_kn: &'a mut f64, /// The last pattern computed, current or not (`current`, `stale`). pub result: Option<&'a WaveResult>, /// The wave-drag curve, when current. @@ -96,6 +101,7 @@ pub fn panel(ui: &mut egui::Ui, p: WaveViewPanel<'_>) -> WaveViewAction { pub fn panel_tr(ui: &mut egui::Ui, p: WaveViewPanel<'_>, tr: Tr) -> WaveViewAction { let WaveViewPanel { settings, + speed_kn, result, drag, stale, @@ -138,7 +144,7 @@ pub fn panel_tr(ui: &mut egui::Ui, p: WaveViewPanel<'_>, tr: Tr) -> WaveViewActi ui.label(egui::RichText::new(tr.s(Key::WaveMethodTitle)).strong()) .on_hover_text(tr.s(Key::WaveMethodHover)); ui.separator(); - if speed_control(ui, settings, length_wl, tr) { + if speed_control(ui, settings, speed_kn, length_wl, tr) { action = WaveViewAction::Changed; } if let Some(r) = result { @@ -217,13 +223,35 @@ pub fn panel_tr(ui: &mut egui::Ui, p: WaveViewPanel<'_>, tr: Tr) -> WaveViewActi } /// The number field, the kn/Fn switch and the slider (Fn 0.10 to 1.00, shown in the field's unit). -/// True when the speed changed. -fn speed_control(ui: &mut egui::Ui, s: &mut WaveSettings, length_wl: Option, tr: Tr) -> bool { +/// The speed is the shared one, in knots; the field shows it as a Froude number when the settings +/// say so and a waterline length is known, else in knots. True when the speed or its unit changed. +fn speed_control( + ui: &mut egui::Ui, + s: &mut WaveSettings, + speed_kn: &mut f64, + length_wl: Option, + tr: Tr, +) -> bool { let mut changed = false; ui.label(tr.s(Key::WaveCtlSpeed)) .on_hover_text(tr.s(Key::WaveCtlSpeedTip)); - let knots = s.speed.is_knots(); - let (mut value, range) = match s.speed { + let shown = |kn: f64| shown_speed(kn, s.froude_unit, length_wl); + let current = *speed_kn; + let to_kn = |v: WaveSpeed| match (v, length_wl) { + (WaveSpeed::Knots(kn), _) => kn, + (WaveSpeed::Froude(_), Some(l)) => v.m_s(l) / KNOT, + (WaveSpeed::Froude(_), None) => current, + }; + let speed = shown(*speed_kn); + let knots = speed.is_knots(); + let in_unit = |v: f64| { + if knots { + WaveSpeed::Knots(v) + } else { + WaveSpeed::Froude(v) + } + }; + let (mut value, range) = match speed { WaveSpeed::Knots(v) => (v, 0.1..=100.0), WaveSpeed::Froude(v) => (v, 0.01..=2.0), }; @@ -232,41 +260,44 @@ fn speed_control(ui: &mut egui::Ui, s: &mut WaveSettings, length_wl: Option theme::num(&mut value) .speed(if knots { 0.05 } else { 0.002 }) .range(range) + // The shared speed can be outside this field's range (0 kn from the Performance + // slider, or a unit switch): showing it must not write a clamped speed back. + .clamp_existing_to_range(false) .max_decimals(3), ) .on_hover_text(tr.s(Key::WaveCtlSpeedDragTip)) .changed() { - s.speed = if knots { - WaveSpeed::Knots(value) - } else { - WaveSpeed::Froude(value) - }; + *speed_kn = to_kn(in_unit(value)); changed = true; } - let mut to_knots = knots; + // The unit is only how the speed reads: switching it does not move the speed. Without a + // waterline length the speed reads in knots, and "Fn" cannot be picked. + let (selected, fn_enabled) = unit_switch(s.froude_unit, length_wl); + let mut froude = selected; theme::segmented(ui, |ui| { - ui.selectable_value(&mut to_knots, true, "kn") + ui.selectable_value(&mut froude, false, "kn") .on_hover_text(tr.s(Key::WaveCtlKnTip)); - ui.selectable_value(&mut to_knots, false, "Fn") - .on_hover_text(tr.s(Key::WaveCtlFnTip)); + ui.add_enabled_ui(fn_enabled, |ui| { + ui.selectable_value(&mut froude, true, "Fn") + .on_hover_text(tr.s(Key::WaveCtlFnTip)) + .on_disabled_hover_text(tr.s(Key::WaveCtlFnNoLengthTip)); + }); }); - if to_knots != knots { - // The speed itself does not jump: the value converts by the waterline length. - s.speed = match length_wl { - Some(l) => s.speed.in_unit(to_knots, l), - None if to_knots => WaveSpeed::Knots(value), - None => WaveSpeed::Froude(value), - }; + if froude != selected { + s.froude_unit = froude; changed = true; } // The slider spans Fn 0.10 to 1.00 in the field's unit. It edits a copy, so a typed value // outside its range is kept until the slider itself is moved. - let unit = |f: f64| match (knots, length_wl) { - (true, Some(l)) => f * (GRAVITY * l).sqrt() / KNOT, - _ => f, - }; - if !knots || length_wl.is_some() { + if let Some(l) = length_wl { + let unit = |f: f64| { + if knots { + f * (GRAVITY * l).sqrt() / KNOT + } else { + f + } + }; let (lo, hi) = (unit(SLIDER_FN.0), unit(SLIDER_FN.1)); let mut v = value; let r = theme::slider( @@ -277,17 +308,29 @@ fn speed_control(ui: &mut egui::Ui, s: &mut WaveSettings, length_wl: Option ) .on_hover_text(tr.s(Key::WaveCtlSpeedSliderTip)); if r.changed() && v != value { - s.speed = if knots { - WaveSpeed::Knots(v) - } else { - WaveSpeed::Froude(v) - }; + *speed_kn = to_kn(in_unit(v)); changed = true; } } changed } +/// The shared speed (knots) as the view shows it: a Froude number when `froude_unit` is set and a +/// waterline length (m) is known, else knots. +fn shown_speed(speed_kn: f64, froude_unit: bool, length_wl: Option) -> WaveSpeed { + match length_wl.filter(|l| *l > 0.0) { + Some(l) if froude_unit => WaveSpeed::Knots(speed_kn).in_unit(false, l), + _ => WaveSpeed::Knots(speed_kn), + } +} + +/// The kn / Fn switch: whether "Fn" is the unit shown, and whether it can be picked (it needs a +/// waterline length). +fn unit_switch(froude_unit: bool, length_wl: Option) -> (bool, bool) { + let known = length_wl.is_some_and(|l| l > 0.0); + (froude_unit && known, known) +} + /// The short reasons thin-ship theory does not fit, for the banner: "L/B 3.1", "wide transom", /// "Fn 0.05 outside 0.20–1.00". Empty when it fits. pub fn fit_reasons(r: &WaveResult) -> Vec { @@ -379,7 +422,7 @@ fn body_columns( action = WaveViewAction::SetWashDistance(d); } if !wide { - let asked = plots(ui, r, drag, settings, map, tr); + let asked = plots(ui, r, drag, map, tr); if asked != WaveViewAction::None { action = asked; } @@ -387,7 +430,7 @@ fn body_columns( }); if wide { ui.allocate_ui_with_layout(egui::vec2(plots_w, size.y), top_down, |ui| { - let asked = plots(ui, r, drag, settings, map, tr); + let asked = plots(ui, r, drag, map, tr); if asked != WaveViewAction::None { action = asked; } @@ -850,7 +893,6 @@ fn plots( ui: &mut egui::Ui, r: &WaveResult, drag: Option<&WaveDrag>, - settings: &WaveSettings, map: &mut MapState, tr: Tr, ) -> WaveViewAction { @@ -876,11 +918,13 @@ fn plots( label: tr.s(Key::WavePlotPairRatio).into(), points: r.spacing_scan.clone(), dashed: false, + muted: false, }, PlotSeries { label: tr.s(Key::WavePlotNoInterference).into(), points: vec![(s0, 1.0), (s1, 1.0)], dashed: true, + muted: false, }, ]; let fn_s = format!("{:.2}", r.field.froude); @@ -904,11 +948,13 @@ fn plots( label: tr.s(Key::WavePlotCatSeries).into(), points: pair.clone(), dashed: false, + muted: false, }, PlotSeries { label: tr.s(Key::WavePlotTwoMonoSeries).into(), points: mono, dashed: true, + muted: false, }, ], pair, @@ -919,6 +965,7 @@ fn plots( label: String::new(), points: mono.clone(), dashed: false, + muted: false, }], mono, ), @@ -950,11 +997,9 @@ fn plots( &marks, Some(SLIDER_FN), ) { - let knots = settings.speed.is_knots(); - action = WaveViewAction::SetSpeed( - WaveSpeed::Froude((f * 1000.0).round() / 1000.0) - .in_unit(knots, d.length_wl), - ); + let fn_ = (f * 1000.0).round() / 1000.0; + action = + WaveViewAction::SetSpeed(WaveSpeed::Froude(fn_).m_s(d.length_wl) / KNOT); } let fn_s = format!("{fn_now:.2}"); let kn_s = format!("{:.1}", r.field.speed_m_s / KNOT); @@ -989,6 +1034,7 @@ fn plots( .zip(r.wash_cut.zeta.iter().copied()) .collect(), dashed: false, + muted: false, }]; let d_s = format!("{:.1}", r.wash_distance_m); let caption = tr.fmt(Key::WavePlotWashCaption, &[("d", &d_s)]); @@ -1182,6 +1228,17 @@ fn bottom_row( mod tests { use super::*; + /// Review I2: without a waterline length the speed reads in knots, so "kn" is the unit + /// selected and "Fn" cannot be picked; with one, the switch follows the setting. + #[test] + fn the_unit_switch_shows_the_unit_drawn() { + assert_eq!(unit_switch(true, None), (false, false)); + assert_eq!(unit_switch(false, None), (false, false)); + assert_eq!(unit_switch(true, Some(10.7)), (true, true)); + assert_eq!(unit_switch(false, Some(10.7)), (false, true)); + assert_eq!(shown_speed(6.0, true, None), WaveSpeed::Knots(6.0)); + } + #[test] fn interference_is_worded() { assert_eq!(interference_words(0.88), "favourable (−12 %)"); diff --git a/crates/seacraft-gui/src/waves.rs b/crates/seacraft-gui/src/waves.rs index 0dd28fd..482a627 100644 --- a/crates/seacraft-gui/src/waves.rs +++ b/crates/seacraft-gui/src/waves.rs @@ -73,7 +73,10 @@ pub enum WaveDomain { /// What the Wave pattern view asks of the wave pattern. #[derive(Debug, Clone, PartialEq)] pub struct WaveSettings { - pub speed: WaveSpeed, + /// Show the speed as a Froude number rather than in knots. The speed itself is the + /// Performance tab's ([`crate::app::PerformanceState::speed_kn`]), one for resistance, + /// waves and seakeeping; this is only how the view reads it. + pub froude_unit: bool, pub domain: WaveDomain, /// Demihull centreline separation (m); `None` for a monohull. pub cat_spacing_m: Option, @@ -92,7 +95,7 @@ pub struct WaveSettings { impl Default for WaveSettings { fn default() -> Self { Self { - speed: WaveSpeed::Froude(0.30), + froude_unit: true, domain: WaveDomain::Auto, cat_spacing_m: None, clip_m: None, @@ -225,12 +228,13 @@ pub fn compute_waves( draft: f64, rho: f64, settings: &WaveSettings, + speed: WaveSpeed, ) -> Result { let grid = michell_grid(surface, subdivision, draft)?; let (length_wl, beam_wl) = (grid.length_wl, grid.beam_wl); let wash_distance_m = wash_distance(settings, length_wl, beam_wl); let (ahead_l, behind_l, half_width_l) = domain_l(settings, length_wl, wash_distance_m); - let speed_m_s = settings.speed.m_s(length_wl); + let speed_m_s = speed.m_s(length_wl); let opts = WavePatternOptions { ahead_l, behind_l, @@ -363,13 +367,10 @@ pub fn drag_key(cat_spacing_m: Option) -> u64 { h.finish() } -/// A key over every setting that changes the result: all but `kelvin_wedge` and `plan_contours`. +/// A key over every setting that changes the result: all but `froude_unit`, `kelvin_wedge` and +/// `plan_contours`. The speed is not a setting here: the caller keys it. pub fn settings_key(settings: &WaveSettings) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); - match settings.speed { - WaveSpeed::Knots(v) => (0u8, v.to_bits()).hash(&mut h), - WaveSpeed::Froude(v) => (1u8, v.to_bits()).hash(&mut h), - } match settings.domain { WaveDomain::Auto => 0u8.hash(&mut h), WaveDomain::Manual { @@ -484,6 +485,9 @@ mod tests { assert!(image.pixels[0].r() > image.pixels[0].b()); } + /// The view's old default speed, which these tests were written at. + const FN_030: WaveSpeed = WaveSpeed::Froude(0.30); + fn demo() -> (seacraft_core::mesh::Surface, SubdivisionOptions, f64) { let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../examples/demo-hull.fef"); let text = std::fs::read_to_string(path).expect("read demo-hull.fef"); @@ -499,7 +503,15 @@ mod tests { #[test] fn demo_pattern_is_calm_ahead_and_has_contours() { let (surface, subdiv, draft) = demo(); - let w = compute_waves(&surface, subdiv, draft, RHO, &WaveSettings::default()).unwrap(); + let w = compute_waves( + &surface, + subdiv, + draft, + RHO, + &WaveSettings::default(), + FN_030, + ) + .unwrap(); let f = &w.field; let (nx, ny) = (f.xs.len(), f.ys.len()); assert!((f.froude - 0.3).abs() < 1e-12, "Fn {}", f.froude); @@ -542,7 +554,7 @@ mod tests { cat_spacing_m: Some(8.0), ..WaveSettings::default() }; - let w = compute_waves(&surface, subdiv, draft, RHO, &settings).unwrap(); + let w = compute_waves(&surface, subdiv, draft, RHO, &settings, FN_030).unwrap(); let f = &w.field; let nx = f.xs.len(); let nearest = |y: f64| { @@ -578,7 +590,7 @@ mod tests { ..WaveSettings::default() }, ] { - match compute_waves(&surface, subdiv, draft, RHO, &settings) { + match compute_waves(&surface, subdiv, draft, RHO, &settings, FN_030) { Ok(w) => assert_eq!(w.image.size, [w.field.xs.len(), w.field.ys.len()]), Err(e) => assert!(!e.is_empty()), } @@ -588,7 +600,7 @@ mod tests { #[test] fn no_waterline_is_an_error() { let (surface, subdiv, _) = demo(); - let err = compute_waves(&surface, subdiv, 0.0, RHO, &WaveSettings::default()) + let err = compute_waves(&surface, subdiv, 0.0, RHO, &WaveSettings::default(), FN_030) .expect_err("no waterline at draft 0"); assert!(err.contains("Michell"), "{err}"); } @@ -631,18 +643,14 @@ mod tests { plan_contours: !base.plan_contours, ..base.clone() }, + WaveSettings { + froude_unit: !base.froude_unit, + ..base.clone() + }, ] { assert_eq!(settings_key(&same), k0); } let changed = [ - WaveSettings { - speed: WaveSpeed::Froude(0.31), - ..base.clone() - }, - WaveSettings { - speed: WaveSpeed::Knots(0.30), - ..base.clone() - }, WaveSettings { domain: WaveDomain::Manual { ahead_m: 5.0, @@ -679,7 +687,7 @@ mod tests { for (i, s) in changed.iter().enumerate() { assert_ne!(settings_key(s), k0, "setting {i}"); } - assert_ne!(settings_key(&changed[2]), settings_key(&changed[3])); + assert_ne!(settings_key(&changed[0]), settings_key(&changed[1])); } #[test] @@ -718,11 +726,16 @@ mod tests { #[test] fn demo_result_has_every_readout() { let (surface, subdiv, draft) = demo(); - let settings = WaveSettings { - speed: WaveSpeed::Froude(0.45), - ..WaveSettings::default() - }; - let w = compute_waves(&surface, subdiv, draft, RHO, &settings).unwrap(); + let settings = WaveSettings::default(); + let w = compute_waves( + &surface, + subdiv, + draft, + RHO, + &settings, + WaveSpeed::Froude(0.45), + ) + .unwrap(); assert_eq!(w.regime, Regime::HullSpeed); assert!(w.wash.is_some()); assert!(w.drag_here.rw_n > 0.0); @@ -747,7 +760,7 @@ mod tests { cat_spacing_m: Some(8.0), ..WaveSettings::default() }; - let w = compute_waves(&surface, subdiv, draft, RHO, &settings).unwrap(); + let w = compute_waves(&surface, subdiv, draft, RHO, &settings, FN_030).unwrap(); assert_eq!(w.spacing_scan.len(), 40); assert!( w.spacing_scan[0].0 >= 2.0 * w.beam_wl - 1e-12, @@ -773,7 +786,7 @@ mod tests { wash_distance_m: Some(9.0), ..WaveSettings::default() }; - let w = compute_waves(&surface, subdiv, draft, RHO, &settings).unwrap(); + let w = compute_waves(&surface, subdiv, draft, RHO, &settings, FN_030).unwrap(); assert!(w.wash.is_some()); assert_eq!(w.wash_distance_m, 9.0); } @@ -813,11 +826,16 @@ mod tests { #[test] fn very_low_speed_still_computes_with_its_wash() { let (surface, subdiv, draft) = demo(); - let settings = WaveSettings { - speed: WaveSpeed::Froude(0.05), - ..WaveSettings::default() - }; - let w = compute_waves(&surface, subdiv, draft, RHO, &settings).unwrap(); + let settings = WaveSettings::default(); + let w = compute_waves( + &surface, + subdiv, + draft, + RHO, + &settings, + WaveSpeed::Froude(0.05), + ) + .unwrap(); let ds = w.wash_cut.s[1] - w.wash_cut.s[0]; assert!(ds < 0.5 * w.field.transverse_wavelength_m, "ds {ds}"); assert!(w.field.xs.len() * w.field.ys.len() <= 250_000); diff --git a/crates/seacraft-gui/tests/analysis.rs b/crates/seacraft-gui/tests/analysis.rs index 5efedc1..c52644f 100644 --- a/crates/seacraft-gui/tests/analysis.rs +++ b/crates/seacraft-gui/tests/analysis.rs @@ -107,7 +107,7 @@ fn open_from_menu( fn cell(row: &[EngCell], c: usize) -> &str { match &row[c] { - EngCell::Text(t) => t, + EngCell::Text(t) | EngCell::Muted(t) => t, EngCell::Badge(..) => panic!("a badge in column {c}"), } } diff --git a/crates/seacraft-gui/tests/frame_cache.rs b/crates/seacraft-gui/tests/frame_cache.rs index 397a47b..a7b8bc3 100644 --- a/crates/seacraft-gui/tests/frame_cache.rs +++ b/crates/seacraft-gui/tests/frame_cache.rs @@ -434,3 +434,183 @@ fn each_view_draws_a_kept_waterline_mesh_and_only_a_moved_view_rebuilds_it() { assert_waterline_mesh_fresh(&ctx, &app, i); } } + +fn container() -> (App, egui::Context) { + let path = format!( + "{}/../../examples/container-230m.fef", + env!("CARGO_MANIFEST_DIR") + ); + let mut app = App::headless_for_test(Some(&path)); + // 313 faces at level 4 is about 80 000 refined faces: over the budget for the window thread. + app.set_subdivision_level(4); + (app, egui::Context::default()) +} + +/// Frames (sleeping between them) until the level 4 mesh is in, checking each frame that the +/// cached mesh is for the current model. Panics after 60 s. +fn frames_until_refined(ctx: &egui::Context, app: &mut App) { + let start = std::time::Instant::now(); + loop { + frame(ctx, app, Vec::new()); + assert!(app.render_cache_is_current(), "a stale mesh is never drawn"); + if !app.mesh_refining() { + return; + } + assert!( + start.elapsed().as_secs() < 60, + "the level 4 mesh never came" + ); + std::thread::sleep(std::time::Duration::from_millis(20)); + } +} + +/// A large hull draws a level 3 preview at once and the full level 4 from a background job. +#[test] +fn large_hull_refines_in_the_background() { + let (mut app, ctx) = container(); + app.sync_render_cache(); + assert_eq!( + app.render_cache_level(), + Some(3), + "the preview, built at once" + ); + assert!(app.render_cache_is_current()); + assert!(app.mesh_refining()); + frames_until_refined(&ctx, &mut app); + assert_eq!(app.render_cache_level(), Some(4)); +} + +/// An edit while the level 4 job runs: the old job's mesh is dropped, and a job for the edited +/// hull brings level 4 back. +#[test] +fn a_superseded_mesh_job_is_dropped() { + let (mut app, ctx) = container(); + app.sync_render_cache(); + assert!(app.mesh_refining()); + let p = app.surface().unwrap().points[10].p; + app.move_point(10, p + seacraft_core::math::Vec3::new(0.0, 0.0, 0.5)) + .expect("move"); + frames_until_refined(&ctx, &mut app); + assert_eq!(app.render_cache_level(), Some(4)); + let moved = app.surface().unwrap().points[10].p; + assert!((moved.z - p.z - 0.5).abs() < 1e-9); + // The mesh drawn is the moved hull's, not the one the superseded job built. + let expected = + seacraft_core::export::render_mesh(app.surface().unwrap(), 4, app.subdivision_mode()); + assert_eq!( + app.render_cache().unwrap().verts, + expected.verts, + "the edited hull's level 4 mesh" + ); +} + +/// Agy review 3: no "refining" on the status bar for a hull whose full level builds at once, +/// on the frame where the level was raised but the mesh is not rebuilt yet. +#[test] +fn a_small_hull_never_reads_as_refining() { + let mut app = App::headless_for_test(Some(&demo_path())); + app.set_subdivision_level(3); + app.sync_render_cache(); + app.set_subdivision_level(4); + assert!( + !app.mesh_refining(), + "level 4 is built at once for 81 faces" + ); +} + +/// `refresh_cache` (the control channel's `ui.render`) builds the full level at once. +#[test] +fn refresh_cache_is_full_level_at_once() { + let (mut app, _ctx) = container(); + app.refresh_cache(); + assert_eq!(app.render_cache_level(), Some(4)); + assert!(!app.mesh_refining()); +} + +/// A small hull at level 4 stays on the window thread, as before. +#[test] +fn small_hull_refines_at_once() { + let mut app = App::headless_for_test(Some(&demo_path())); + app.set_subdivision_level(4); + let ctx = egui::Context::default(); + frame(&ctx, &mut app, Vec::new()); + assert_eq!(app.render_cache_level(), Some(4)); + assert!(!app.mesh_refining()); +} + +/// Agy review 5: opening another model drops the closed one's mesh job, so the new model's job +/// starts at once instead of after it. +#[test] +fn opening_a_model_drops_the_old_mesh_job() { + let (mut app, _ctx) = container(); + app.sync_render_cache(); + assert!(app.mesh_job_is_current()); + let path = format!( + "{}/../../examples/container-230m.fef", + env!("CARGO_MANIFEST_DIR") + ); + app.open_model(std::path::Path::new(&path)).expect("open"); + app.set_subdivision_level(4); + app.sync_render_cache(); + assert!(app.mesh_job_is_current(), "the new model's job runs"); +} + +/// The control point drawn nearest the middle of view 1, on screen. +fn point_in_view(app: &App) -> egui::Pos2 { + let rect = app.viewport_rect(1); + let transform = app.cameras()[1].transform(); + app.surface() + .unwrap() + .points + .iter() + .filter_map(|p| transform.project(p.p, rect)) + .filter(|s| rect.shrink(20.0).contains(*s)) + .min_by(|a, b| { + a.distance(rect.center()) + .total_cmp(&b.distance(rect.center())) + }) + .expect("a point in view") +} + +/// CodeRabbit (PR #22): a press that starts a point drag while the full-level mesh is building +/// keeps that job accounted for, so a release does not start a second build beside it. A release +/// without a move then installs the mesh the job built. +#[test] +fn a_drag_keeps_the_running_mesh_job() { + let (mut app, ctx) = container(); + // Lay the views out at level 3 (built at once, no job), then raise the level on the press. + app.set_subdivision_level(3); + frame(&ctx, &mut app, Vec::new()); + let screen = point_in_view(&app); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(screen)]); + app.set_subdivision_level(5); + frame(&ctx, &mut app, vec![button(screen, true)]); + frame(&ctx, &mut app, Vec::new()); + assert!(app.mesh_job_is_current(), "the press kept the level 5 job"); + frame(&ctx, &mut app, vec![button(screen, false)]); + frames_until_refined(&ctx, &mut app); + assert_eq!(app.render_cache_level(), Some(5)); +} + +/// CodeRabbit (PR #22, second review): a click on a point after the full level is in drops the +/// mesh to the drag preview; the release must build the full level again, not stop at the +/// preview because the finished job still reads as current. +#[test] +fn a_click_after_refinement_builds_the_full_level_again() { + let (mut app, ctx) = container(); + frames_until_refined(&ctx, &mut app); + assert_eq!(app.render_cache_level(), Some(4)); + let screen = point_in_view(&app); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(screen)]); + frame(&ctx, &mut app, vec![button(screen, true)]); + frame(&ctx, &mut app, Vec::new()); + frame(&ctx, &mut app, vec![button(screen, false)]); + frame(&ctx, &mut app, Vec::new()); + assert!( + app.mesh_job_is_current() || app.render_cache_level() == Some(4), + "the release builds level 4 again (level {:?})", + app.render_cache_level() + ); + frames_until_refined(&ctx, &mut app); + assert_eq!(app.render_cache_level(), Some(4)); +} diff --git a/crates/seacraft-gui/tests/performance.rs b/crates/seacraft-gui/tests/performance.rs index e6dbcea..217cb33 100644 --- a/crates/seacraft-gui/tests/performance.rs +++ b/crates/seacraft-gui/tests/performance.rs @@ -3,10 +3,12 @@ use std::time::{Duration, Instant}; use eframe::egui; +use seacraft_core::i18n::{Locale, Tr}; use seacraft_core::resistance; use seacraft_core::seakeeping; use seacraft_core::subdiv::SubdivisionOptions; -use seacraft_gui::app::{DesignDock, ResistanceResult}; +use seacraft_gui::app::{DesignDock, ResistanceMethod, ResistanceResult, ResistanceRow}; +use seacraft_gui::panels::resistance_series; use seacraft_gui::App; fn demo_path() -> String { @@ -85,7 +87,8 @@ fn performance_tab_and_computations() { &expected_core, holtrop_in.warnings(), "R_T (kN)", - ); + ) + .with_in_range(|_| !holtrop_in.outside_fitted_range()); assert_eq!(res, expected_res); assert_eq!(app.resistance_result(), Some(&expected_res)); @@ -122,3 +125,137 @@ fn performance_tab_and_computations() { Some(&expected_rep.frequencies) ); } + +fn example(name: &str) -> String { + format!("{}/../../examples/{name}.fef", env!("CARGO_MANIFEST_DIR")) +} + +fn resistance_of( + name: &str, + method: ResistanceMethod, + speeds: (f64, f64, f64), +) -> ResistanceResult { + let mut app = App::headless_for_test(Some(&example(name))); + app.set_subdivision_level(2); + app.performance_state_mut().method = method; + app.performance_state_mut().speeds_kn = speeds; + app.compute_resistance_blocking() + .expect("compute resistance") + .clone() +} + +/// The demo hull's L/B (3.02) and B/T (5.71) lie outside Holtrop's ranges, so every speed is +/// outside the fit; the container ship lies inside them, so none is. +#[test] +fn holtrop_rows_outside_the_fitted_form_are_out_of_range() { + let demo = resistance_of("demo-hull", ResistanceMethod::Holtrop, (4.0, 14.0, 2.0)); + assert!(!demo.rows.is_empty()); + assert!(demo.rows.iter().all(|r| !r.in_range), "{:?}", demo.rows); + let ship = resistance_of( + "container-230m", + ResistanceMethod::Holtrop, + (10.0, 24.0, 2.0), + ); + assert!(!ship.rows.is_empty()); + assert!(ship.rows.iter().all(|r| r.in_range), "{:?}", ship.rows); +} + +/// DSYHS is fitted for Fn 0.15 to 0.75: the speeds outside are out of range, the rest in. +#[test] +fn dsyhs_rows_outside_its_froude_range_are_out_of_range() { + let res = resistance_of("yacht-10m", ResistanceMethod::Dsyhs, (1.0, 15.0, 1.0)); + assert!(res.rows.iter().any(|r| r.in_range)); + assert!(res.rows.iter().any(|r| !r.in_range)); + for r in &res.rows { + assert_eq!(r.in_range, (0.15..=0.75).contains(&r.fn_), "{r:?}"); + } +} + +fn row(speed_kn: f64, in_range: bool) -> ResistanceRow { + ResistanceRow { + speed_kn, + fn_: 0.0, + rt_kn: speed_kn * 2.0, + pe_kw: None, + note: None, + in_range, + } +} + +fn result(rows: Vec) -> ResistanceResult { + ResistanceResult { + method: "Holtrop & Mennen".into(), + rows, + warnings: Vec::new(), + rt_label: "R_T (kN)".into(), + } +} + +/// The whole curve in the method's colour, and the segments touching an out-of-range speed drawn +/// again on top in grey, broken (NaN) between separate stretches. +#[test] +fn resistance_series_grey_the_segments_out_of_range() { + let tr = Tr::new(Locale::En); + let flags = [true, true, false, true, true, false]; + let res = result( + flags + .iter() + .enumerate() + .map(|(i, f)| row(i as f64, *f)) + .collect(), + ); + let series = resistance_series(&res, tr); + assert_eq!(series.len(), 2); + assert!(!series[0].muted); + assert_eq!(series[0].label, "Holtrop & Mennen"); + assert_eq!(series[0].points.len(), 6); + assert!(series[1].muted); + assert!(series[1].label.contains("outside"), "{}", series[1].label); + let xs: Vec = series[1].points.iter().map(|p| p.0).collect(); + assert_eq!(xs.len(), 6, "{xs:?}"); + assert_eq!(&xs[..3], &[1.0, 2.0, 3.0]); + assert!(xs[3].is_nan()); + assert_eq!(&xs[4..], &[4.0, 5.0]); +} + +#[test] +fn a_curve_all_in_range_has_no_grey_series() { + let res = result((0..4).map(|i| row(i as f64, true)).collect()); + let series = resistance_series(&res, Tr::new(Locale::En)); + assert_eq!(series.len(), 1); + assert!(!series[0].muted); +} + +#[test] +fn a_curve_all_out_of_range_is_grey_end_to_end() { + let res = result((0..4).map(|i| row(i as f64, false)).collect()); + let series = resistance_series(&res, Tr::new(Locale::En)); + assert_eq!(series.len(), 2); + assert_eq!(series[1].points, series[0].points); + // One speed alone is a grey point, not an empty series. + let one = result(vec![row(3.0, false)]); + let series = resistance_series(&one, Tr::new(Locale::En)); + assert_eq!(series[1].points, vec![(3.0, 6.0)]); +} + +/// The Performance tab draws the grey curve without panicking. +#[test] +fn the_performance_tab_draws_a_grey_curve() { + let mut app = App::headless_for_test(Some(&demo_path())); + app.set_subdivision_level(2); + let ctx = egui::Context::default(); + app.set_show_performance(true); + app.compute_resistance_blocking().expect("resistance"); + frame(&ctx, &mut app); + frame(&ctx, &mut app); +} + +/// The table keeps every number, and greys the rows outside the method's range. +#[test] +fn resistance_table_greys_rows_out_of_range() { + use seacraft_gui::panels::{resistance_table, EngCell}; + let rows = resistance_table(&result(vec![row(1.0, true), row(2.0, false)])); + assert!(rows[0].iter().all(|c| matches!(c, EngCell::Text(_)))); + assert!(rows[1].iter().all(|c| matches!(c, EngCell::Muted(_)))); + assert_eq!(rows[1][0], EngCell::Muted("2.00".into())); +} diff --git a/crates/seacraft-gui/tests/waves.rs b/crates/seacraft-gui/tests/waves.rs index 053280a..76aaefe 100644 --- a/crates/seacraft-gui/tests/waves.rs +++ b/crates/seacraft-gui/tests/waves.rs @@ -119,7 +119,8 @@ fn open_view_computes_by_itself() { a.wave_current().is_some() && a.wave_drag().is_some() }); let w = app.wave_current().expect("the pattern"); - assert!((w.field.froude - 0.3).abs() < 1e-12); + // At the shared speed, 6 kn by default. + assert!((w.field.speed_m_s - 6.0 * seacraft_core::resistance::KNOT).abs() < 1e-12); assert!(!app.wave_settings().plan_contours, "Plan contours stay off"); } @@ -137,11 +138,8 @@ fn scrubbing_settles_on_the_last_speed() { let (mut app, ctx) = demo_with_waves(); for k in 0..10 { let fn_ = 0.30 + 0.02 * k as f64; - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(fn_), - ..app.wave_settings().clone() - }); - // The demo starts at Fn 0.30, so the first step does not move the key. + app.set_wave_speed(WaveSpeed::Froude(fn_)); + // The first step may land on the speed already shown (6 kn is Fn 0.301 on the demo). if k > 0 { assert!(app.wave_current().is_none(), "Fn {fn_}: the key moved"); } @@ -164,10 +162,7 @@ fn scrubbing_settles_on_the_last_speed() { #[test] fn a_settings_change_hides_the_old_pattern_at_once() { let (mut app, ctx) = demo_with_waves(); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.4), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Froude(0.4)); assert!( app.wave_current().is_none(), "the Fn 0.3 pattern is out of date" @@ -346,7 +341,15 @@ fn demo_parts( }; let mesh = seacraft_core::export::render_mesh(&surface, 2, Default::default()); let draft = surface.settings.draft; - let w = compute_waves(&surface, subdiv, draft, 1025.0, settings).unwrap(); + let w = compute_waves( + &surface, + subdiv, + draft, + 1025.0, + settings, + WaveSpeed::Froude(0.30), + ) + .unwrap(); (surface, mesh, w) } @@ -513,11 +516,8 @@ fn stale_pattern_is_not_drawn() { assert!(contoured(&out), "the current pattern is drawn"); assert!(texts(&out) .iter() - .any(|t| t.starts_with("Waves · Fn 0.300"))); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.45), - ..app.wave_settings().clone() - }); + .any(|t| t.starts_with("Waves · Fn 0.301"))); + app.set_wave_speed(WaveSpeed::Froude(0.45)); let out = frame(&ctx, &mut app, Vec::new()); assert!( !contoured(&out), @@ -590,10 +590,7 @@ fn view_marks_a_stale_result() { #[test] fn speed_is_an_input() { let (mut app, ctx) = demo_with_waves(); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Knots(8.0), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Knots(8.0)); frames_until(&ctx, &mut app, "the 8 kn pattern", |a| { a.wave_current().is_some() }); @@ -723,10 +720,7 @@ fn shown_pattern_goes_into_the_report() { .unwrap() .contains("id=\"waves\"")); app.set_wave_view_open(true); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Knots(6.0), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Knots(6.0)); let html = scratch("report-shown.html"); app.write_report_blocking(&html).unwrap(); let text = std::fs::read_to_string(&html).unwrap(); @@ -741,10 +735,7 @@ fn drag_curve_ignores_speed() { app.set_wave_view_open(true); app.compute_wave_drag_blocking().unwrap(); assert!(app.wave_drag().is_some()); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.42), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Froude(0.42)); assert!(app.wave_drag().is_some(), "the curve is still current"); app.set_wave_settings(WaveSettings { cat_spacing_m: Some(8.0), @@ -778,10 +769,7 @@ fn view_texts(ctx: &egui::Context, app: &mut App) -> Vec { #[test] fn view_shows_plain_readouts() { let (mut app, ctx) = demo_with_waves(); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.45), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Froude(0.45)); let texts = view_texts(&ctx, &mut app); for want in [ "Around hull speed", @@ -854,12 +842,12 @@ fn catamaran_shows_interference() { #[test] fn typed_low_speed_is_kept_and_flagged() { let (mut app, ctx) = demo_with_waves(); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.05), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Froude(0.05)); let texts = view_texts(&ctx, &mut app); - assert_eq!(app.wave_settings().speed, WaveSpeed::Froude(0.05)); + let WaveSpeed::Froude(f) = app.wave_speed() else { + panic!("{:?}", app.wave_speed()) + }; + assert!((f - 0.05).abs() < 1e-9, "Fn {f}"); let banner = texts .iter() .find(|t| t.starts_with("Thin-ship theory does not fit this hull")) @@ -1062,8 +1050,8 @@ fn dragging_the_drag_marker_sets_the_speed() { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at)]); frame(&ctx, &mut app, vec![button(at, true)]); frame(&ctx, &mut app, vec![button(at, false)]); - let WaveSpeed::Froude(f) = app.wave_settings().speed else { - panic!("{:?}", app.wave_settings().speed) + let WaveSpeed::Froude(f) = app.wave_speed() else { + panic!("{:?}", app.wave_speed()) }; assert!(f > 0.30 && f <= 1.0, "Fn {f}"); } @@ -1312,10 +1300,7 @@ fn f5_with_an_older_wave_job_running_starts_no_second_job() { app.open_analysis_view(AnalysisView::Waves); app.recompute_stale(); assert!(app.waves_running_current(), "F5 starts the pattern"); - app.set_wave_settings(WaveSettings { - speed: WaveSpeed::Froude(0.45), - ..app.wave_settings().clone() - }); + app.set_wave_speed(WaveSpeed::Knots(9.0)); // No frame in between: the first job is still in flight, whether or not its thread ended. app.recompute_stale(); assert!( @@ -1381,3 +1366,83 @@ fn report_takes_no_waterline_from_heeled_hydrostatics() { }; assert_eq!(wash_at(10.0), wash_at(0.0)); } + +/// One speed: a speed set in the Wave pattern view is the Performance tab's speed, which +/// seakeeping runs at. +#[test] +fn wave_view_speed_moves_the_seakeeping_speed() { + let (mut app, _ctx) = demo_with_waves(); + let lwl = app.wave_current().map(|w| w.length_wl).expect("a pattern"); + app.set_wave_speed(WaveSpeed::Knots(8.0)); + assert_eq!(app.performance_state().speed_kn, 8.0); + assert_eq!(app.seakeeping_spec().expect("demo KG").speed_kn, 8.0); + // A Froude number converts by the waterline length the view shows. + app.set_wave_speed(WaveSpeed::Froude(0.40)); + let kn = + 0.40 * (seacraft_core::resistance::GRAVITY * lwl).sqrt() / seacraft_core::resistance::KNOT; + assert!((app.performance_state().speed_kn - kn).abs() < 1e-9); + let WaveSpeed::Froude(f) = app.wave_speed() else { + panic!("{:?}", app.wave_speed()) + }; + assert!((f - 0.40).abs() < 1e-9, "Fn {f}"); +} + +/// The Performance tab's speed drives the wave pattern. +#[test] +fn performance_speed_moves_the_wave_speed() { + let (mut app, ctx) = demo_with_waves(); + app.performance_state_mut().speed_kn = 9.0; + frames_until(&ctx, &mut app, "the 9 kn pattern", |a| { + a.wave_current().is_some_and(|w| { + (w.field.speed_m_s - 9.0 * seacraft_core::resistance::KNOT).abs() < 1e-12 + }) + }); +} + +/// With no hull there is no waterline length to give a Froude number by: the speed reads in knots. +#[test] +fn froude_unit_without_a_hull_reads_in_knots() { + let app = App::headless_empty(); + assert!(app.wave_settings().froude_unit); + assert_eq!( + app.wave_speed(), + WaveSpeed::Knots(app.performance_state().speed_kn) + ); +} + +/// Review I1: the resistance curve does not depend on the shared speed, so moving the speed +/// leaves it current; the RAOs, which do, go out of date. +#[test] +fn moving_the_speed_keeps_the_resistance_current() { + let (mut app, _ctx) = demo_with_waves(); + app.compute_resistance_blocking().expect("resistance"); + app.compute_raos_blocking().expect("raos"); + assert!(!app.stale_results().contains(&"resistance")); + app.set_wave_speed(WaveSpeed::Knots(8.0)); + let stale = app.stale_results(); + assert!(!stale.contains(&"resistance"), "{stale:?}"); + assert!(stale.contains(&"RAOs"), "{stale:?}"); +} + +/// Agy review 1: drawing the Wave pattern view does not move the shared speed. Its speed field +/// has a narrower range (Fn 0.01–2, 0.1–100 kn) than the Performance slider, and a field that +/// clamps the value it is shown would write the clamped speed back on the next frame. +#[test] +fn drawing_the_wave_view_keeps_a_speed_outside_its_field_range() { + let (mut app, ctx) = demo_with_waves(); + for (froude_unit, kn) in [(true, 0.0), (false, 0.0), (false, 150.0)] { + app.set_wave_settings(WaveSettings { + froude_unit, + ..app.wave_settings().clone() + }); + app.performance_state_mut().speed_kn = kn; + for _ in 0..3 { + frame(&ctx, &mut app, vec![]); + } + assert_eq!( + app.performance_state().speed_kn, + kn, + "Fn unit {froude_unit}" + ); + } +} diff --git a/docs/oracles.md b/docs/oracles.md index 634333d..e8a1015 100644 --- a/docs/oracles.md +++ b/docs/oracles.md @@ -1395,6 +1395,14 @@ switched at $L/\nabla^{1/3} = 12$, i.e. 1728, and gave up to +0.001065); and the at $0.6\,T$ in $c_3$ and $R_B$, as 1984 p. 273 says it "should not exceed the upper limit of 0.6 $T_F$", with a warning when the input is higher. +Neither paper prints an upper Froude number (re-read 2026-11-26): 1982 gives none, and 1984 derives the high-speed +fit "for the speed range Fn > 0.55" (p. 273) without a top. The Performance tab therefore greys the Holtrop curve +only for a hull outside the Cp, L/B or B/T range (`HoltropInput::outside_fitted_range`, +`outside_fitted_range_follows_the_form_ranges_not_the_bulb_cap`), never by speed. Those three ranges are not +printed in either paper either: 1982 says only that "the application is limited to hull forms resembling the average +ship described by the main dimensions and form coefficients used in the method" (p. 166, re-read 2026-11-26, no +table of limits on that page). Where SeaCraft's figures come from is not yet cited. + The correlation allowance is taken on $S$, by the 1982 formula. The 1984 example's totals take it on $S + S_{APP}$; the test adds the appendages' share back and says so. diff --git a/locales/en.json b/locales/en.json index c6bf297..62b1a10 100644 --- a/locales/en.json +++ b/locales/en.json @@ -692,6 +692,7 @@ "job.heel_hull": "Heel view hull", "job.hydrostatics": "Hydrostatics", "job.loading": "Loading compute", + "job.refined_hull": "Refined hull", "job.resistance": "Resistance compute", "job.seakeeping": "Seakeeping compute", "job.wave_drag": "Wave drag curve", @@ -1173,6 +1174,7 @@ "perf.natural_periods": "Natural periods: Heave T_n = {heave}, Pitch T_n = {pitch}", "perf.open_wave_pattern": "Open wave pattern", "perf.open_wave_pattern_tip": "The far-field (thin-ship) wave pattern, wave drag over speed and wash, in the Analysis drawer", + "perf.plot.outside_range": "{method}, outside the method's fitted range", "perf.plot.resistance": "Resistance", "perf.plot.speed_kn": "Speed (kn)", "perf.rao.heave_label": "Heave z/ζ", @@ -1202,6 +1204,7 @@ "perf.sea.summary": "{sea} at {speed} kn: Hs check {hs} m, T1 {t1} s, Tz {tz} s", "perf.seakeeping_heading": "Seakeeping (head-sea RAOs)", "perf.speed_kn": "Speed (kn)", + "perf.speed_shared_tip": "One speed for the three sections: marked on the resistance curve (click the curve to move it), the wave pattern's speed and the speed seakeeping runs at.", "perf.speeds_kn_colon": "Speeds (kn):", "perf.step_colon": "step: ", "perf.title": "Performance", @@ -1522,6 +1525,7 @@ "status.presets_loaded_from": "loaded {count} connected presets from {path}", "status.presets_written": "wrote example presets to {path}", "status.project_settings_applied": "project settings applied", + "status.refining_mesh": "refining to level {level}…", "status.report_writing": "writing report {path}…", "status.restored_mark": "restored to mark {id}", "status.results_stale.one": "{count} result out of date · F5", @@ -1708,6 +1712,7 @@ "wave.computing_pattern": "Computing the wave pattern…", "wave.ctl.catamaran": "Catamaran", "wave.ctl.catamaran_tip": "Two copies of this hull side by side; their wave systems add up, and can cancel or reinforce each other", + "wave.ctl.fn_no_length_tip": "A Froude number needs the waterline length, which is not known yet: the speed reads in knots.", "wave.ctl.fn_tip": "Froude number: the speed divided by √(g × waterline length). The same Froude number gives the same shape of wave pattern on a small or a large hull.", "wave.ctl.kn_tip": "Knots: nautical miles per hour (1 kn = 0.514 m/s)", "wave.ctl.plan_contours": "Contours on Plan view", diff --git a/locales/tr.json b/locales/tr.json index c4c6583..3d5ec17 100644 --- a/locales/tr.json +++ b/locales/tr.json @@ -692,6 +692,7 @@ "job.heel_hull": "Meyil görünümü teknesi", "job.hydrostatics": "Hidrostatik", "job.loading": "Yükleme hesabı", + "job.refined_hull": "Alt bölünmüş tekne", "job.resistance": "Direnç hesabı", "job.seakeeping": "Denizcilik hesabı", "job.wave_drag": "Dalga direnci eğrisi", @@ -1173,6 +1174,7 @@ "perf.natural_periods": "Doğal periyotlar: Dalıp-çıkma T_n = {heave}, Baş-kıç T_n = {pitch}", "perf.open_wave_pattern": "Dalga desenini aç", "perf.open_wave_pattern_tip": "Analiz çekmecesinde uzak alan (ince gemi) dalga deseni, hıza göre dalga direnci ve dalga izi", + "perf.plot.outside_range": "{method}, yöntemin geçerlilik aralığı dışında", "perf.plot.resistance": "Direnç", "perf.plot.speed_kn": "Hız (kn)", "perf.rao.heave_label": "Dalıp-çıkma z/ζ", @@ -1202,6 +1204,7 @@ "perf.sea.summary": "{sea}, {speed} kn hızında: Hs kontrol {hs} m, T1 {t1} s, Tz {tz} s", "perf.seakeeping_heading": "Denizcilik (baş dalgası RAO)", "perf.speed_kn": "Hız (kn)", + "perf.speed_shared_tip": "Üç bölüm için tek hız: direnç eğrisinde işaretlenir (taşımak için eğriye tıklayın), dalga deseninin hızıdır ve denizcilik hesabı bu hızda yapılır.", "perf.speeds_kn_colon": "Hızlar (kn):", "perf.step_colon": "adım: ", "perf.title": "Performans", @@ -1522,6 +1525,7 @@ "status.presets_loaded_from": "{path} konumundan {count} bağlı düzenleme ön ayarı yüklendi", "status.presets_written": "örnek ön ayarlar yazıldı: {path}", "status.project_settings_applied": "proje ayarları uygulandı", + "status.refining_mesh": "seviye {level} hazırlanıyor…", "status.report_writing": "rapor yazılıyor {path}…", "status.restored_mark": "{id} işaretine geri dönüldü", "status.results_stale.one": "{count} sonuç güncel değil · F5", @@ -1708,6 +1712,7 @@ "wave.computing_pattern": "Dalga deseni hesaplanıyor…", "wave.ctl.catamaran": "Katamaran", "wave.ctl.catamaran_tip": "Bu gövdenin yan yana iki kopyası; dalga sistemleri üst üste biner, birbirini sönümleyebilir veya güçlendirebilir", + "wave.ctl.fn_no_length_tip": "Froude sayısı için su hattı boyu gerekir ve henüz bilinmiyor: hız knot olarak gösterilir.", "wave.ctl.fn_tip": "Froude sayısı: hızın √(g × su hattı boyu) değerine bölümü. Aynı Froude sayısı küçük veya büyük teknede aynı dalga deseni biçimini verir.", "wave.ctl.kn_tip": "Knot: saatte deniz mili (1 kn = 0.514 m/s)", "wave.ctl.plan_contours": "Plan görünümünde eş yükseltiler", diff --git a/skills/seacraft-hull-design/SKILL.md b/skills/seacraft-hull-design/SKILL.md index 577bb23..1bc7c4b 100644 --- a/skills/seacraft-hull-design/SKILL.md +++ b/skills/seacraft-hull-design/SKILL.md @@ -28,10 +28,10 @@ Write the targets down with units and tolerances (for example 1 % on volume) bef 1. Main dimensions: `transform_hull {"lwl": 12.0, "draft": 0.7}` scales x and z so the waterline length and draft hit the targets, anchored at the aft end, centreline and keel. It scales the whole model (the demo went from 11.85 to 15.00 m3 and its overall length from 12.0 to 13.45 m), so re-run `hydro_compute` and expect every coefficient to shift. `"bwl"`, `"scale": [sx, sy, sz]`, `"translate"` and `"mirror": "y"` also exist. 2. Displacement: change draft first. `hydro_table {"steps": 5}` lists TPC and volume per draft so you can interpolate instead of guessing (demo: 1.77 t at 0.207 m, 6.14 t at 0.413 m, 12.15 t at 0.62 m). -3. LCB and Cp: move control points of the affected stations fore or aft with `move_point {"index": 50, "xyz": [7.9, 1.5, 0.54]}` or shift several points together with `move_points {"points": [50, 51], "delta": [0.1, 0.0, 0.0]}`. The reply gives `moved` (and `before`/`after` on `move_point`): read `before` first with a harmless move to the same place, or take coordinates from the `.fef`. Optional `"connected"` draws neighbouring points along using a built-in preset name (`"Blend both ways"`, `"Blend lengthwise"`, `"Blend around station"`, `"Nudge"`, `"Move station"`, `"Beam only"`, `"Height only"`) or an inline preset object (`{name?, reach, falloff, spread, follow_axes?, stop_at_creases?}`, `name` defaulting to `"custom"`), and optional `"reach_m"` (positive finite metres) overrides the preset's reach: e.g. `move_points {"points": [50], "delta": [0.1, 0.0, 0.0], "connected": "Blend lengthwise", "reach_m": 2.0}`. A preset only says how points move and nothing about the result is checked or made fair by it. Move by at most 2 to 3 % of length per step, then re-measure. On a symmetric layer y below 0 is clamped (`clamped` in `move_point`), and in a multi-point or connected move any centreline follower or multi-seed centreline point stays on `y = 0`. Multiple actions can be chained atomically with `batch {"calls": [{"name": "move_point", "arguments": {"index": 50, "xyz": [7.9, 1.5, 0.54]}}, {"name": "hydro_compute", "arguments": {"draft": 0.62, "kg": 2.2}}]}`: any failure rolls back earlier steps. +3. LCB and Cp: move control points of the affected stations fore or aft with `move_point {"index": 50, "xyz": [7.9, 1.5, 0.54]}` or shift several points together with `move_points {"points": [50, 51], "delta": [0.1, 0.0, 0.0]}`. The reply gives `moved` (and `before`/`after` on `move_point`): read `before` first with a harmless move to the same place, or take coordinates from the `.fef`. Optional `"connected"` draws neighbouring points along using a built-in preset name (`"Blend both ways"`, `"Blend lengthwise"`, `"Blend around station"`, `"Nudge"`, `"Move station"`, `"Beam only"`, `"Height only"`) or an inline preset object (`{name?, reach, falloff, spread, follow_axes?, stop_at_creases?}`, `name` defaulting to `"custom"`), and optional `"reach_m"` (positive finite metres) overrides the preset's reach: e.g. `move_points {"points": [50], "delta": [0.1, 0.0, 0.0], "connected": "Blend lengthwise", "reach_m": 2.0}`. A preset only says how points move and nothing about the result is checked or made fair by it. Move by at most 2 to 3 % of length per step, then re-measure. On a symmetric layer y below 0 is clamped (`clamped` in `move_point`), and in a multi-point or connected move any centreline follower or multi-seed centreline point stays on `y = 0`. Multiple actions can be chained with `batch {"calls": [{"name": "move_point", "arguments": {"index": 50, "xyz": [7.9, 1.5, 0.54]}}, {"name": "hydro_compute", "arguments": {"draft": 0.62, "kg": 2.2}}]}`: any failure rolls back the model to where it was before the batch, though files already written stay on disk (a failure with `restore_error` means the rollback could not be confirmed, for instance after `load_hull`, `generate_hull` or `example` inside a batch connected to the GUI, which start a fresh history there; connected, `hull_info` shows no geometry, so before a batch that matters `save_hull` the model, and after such a failure `load_hull` it again instead of mending the model in place). 4. Hard edges: `set_crease {"a": 4, "b": 5, "crease": true}` for chines and transoms. `split_face` and `insert_edge` add control detail where a face is too coarse. 5. Trim at a speed: `trim_scan {"speed_kn": 8, "from": -0.4, "to": 0.4, "steps": 9}` holds displacement by solving the draft at each trim and reports the cheapest. `at_boundary: true` means widen the range. -6. Cut resistance at a design speed: `optimize_hull {"speed_kn": 8}` runs a bounded search over Cp, LCB and L/B (station shift and an x/y stretch), re-solves the draft so displacement holds, and scores each candidate with Holtrop-Mennen (Savitsky for a planing hull). Add `"kg": 1.0, "min_gm": 0.5` to hold stability, `"vars": ["cp", "lcb"]` to leave the beam alone, `"lcb_band": [0.4, 0.55]` to keep LCB (fraction of LWL from aft) in range. **It edits the model**: the session hull becomes the optimised one and the draft moves to the one that holds the displacement. Save the original first, or wrap the call in `batch` so a later failure rolls it back. Read `report.baseline` against `report.optimised`, `constraints_met`, `variables[].at_bound` (a bound hit means widen it with `bounds`) and `warnings`; it is a local search of a few smooth parameters, not a form optimiser. +6. Cut resistance at a design speed: `optimize_hull {"speed_kn": 8}` runs a bounded search over Cp, LCB and L/B (station shift and an x/y stretch), re-solves the draft so displacement holds, and scores each candidate with Holtrop-Mennen (Savitsky for a planing hull). Add `"kg": 1.0, "min_gm": 0.5` to hold stability, `"vars": ["cp", "lcb"]` to leave the beam alone, `"lcb_band": [0.4, 0.55]` to keep LCB (fraction of LWL from aft) in range. **It edits the model**: the session hull becomes the optimised one and the draft moves to the one that holds the displacement. Save the original first, or wrap the call in `batch` so a later failure rolls the model back (files already written stay). Read `report.baseline` against `report.optimised`, `constraints_met`, `variables[].at_bound` (a bound hit means widen it with `bounds`) and `warnings`; it is a local search of a few smooth parameters, not a form optimiser. 7. Look: `render_png {"path": "/tmp/shaded.png", "view": "perspective"}`, then `"view": "body"` for sections. 8. Save: `save_hull {"path": "design-v2.fef"}`. Without `path` it overwrites the file it came from, so save under a new name first.