diff --git a/CHANGELOG.md b/CHANGELOG.md index e5ea0c7..4c35253 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,13 @@ Versions follow [semantic versioning](https://semver.org/), with `0.x` meaning t junction in place remains a known limitation documented in `docs/architecture.md`). A refused write leaves nothing outside the root; on multi-file saves such as `model.save`, the hull file inside the root may already be written before a linked sidecar is refused. +- Floodable length curves, for spacing watertight bulkheads: `seacraft floodable` and the MCP tool + `floodable_length` draw, for each position along the hull, the longest full-breadth compartment that can flood + without immersing the margin line (76 mm below the deck edge at side by default), upright and free to trim, one + curve per permeability. With a factor of subdivision and bulkhead positions, each compartment is judged against + the permissible length at its centre, as a table, JSON, CSV or an SVG plot with the terminals and the bulkhead + triangles, in English or Turkish. The curves are checked against a box barge's closed form and against + SeaCraft's damage solver, not against a published floodable length table. Not in the window yet. ## 0.7.0 (2026-11-26) diff --git a/DISCLAIMER.md b/DISCLAIMER.md index 687a8d2..1ae9dd0 100644 --- a/DISCLAIMER.md +++ b/DISCLAIMER.md @@ -51,6 +51,15 @@ calculations, in the figures read for this, show the same pattern, though not at program to the gaps measured. Nothing else about seakeeping has been compared with experiments: not other hulls, transom sterns, other headings, the irregular-sea statistics or the MSI. +Floodable length curves (`seacraft floodable`, the MCP tool `floodable_length`) follow the definitions in Rawson & +Tupper (*Basic Ship Theory*, Vol. 1) and Gillmer & Johnson (*Introduction to Naval Architecture*, 1982), the +trial-waterline method of Gillmer & Johnson and the triangle check of Rawson & Tupper; neither book prints worked +numbers. They are checked against a box barge's closed form and against SeaCraft's own +damage solver ([`docs/oracles.md`](docs/oracles.md) §53-§55), not against a published floodable length table or +approved software. The margin line is measured from the moulded deck edge, with no deck thickness, every +compartment is full breadth with one permeability, and the factor of subdivision is the user's: SeaCraft does not +compute it from the rules. A compartment that passes the check is not shown to meet SOLAS or any other rule. + The wave pattern (`seacraft waves`, the MCP tool `wave_pattern`, the Wave pattern view and Plan view contours in the window, the design report) is far-field thin-ship theory: free waves only, without the local disturbance, so near the hull it is not the hull wave profile. It is computed upright at the draft; heel and trim are ignored. It has been diff --git a/README.md b/README.md index 3d21548..2ecf5eb 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ FREE!ship does **not** use ordinate tables. `TFreeHydrostaticCalc.Calculate` | CPU z-buffer rasterizer + waterplane depth + PNG | `raster.rs` | | OBJ / STL / 3MF / PLY / IGES / HTML viewer | `export.rs` | | Deterministic damage stability (lost buoyancy) | `damage.rs` | +| Floodable length curves and the bulkhead check | `floodable.rs` | | IMO 2008 IS Code weather criterion | `weather.rs` | | Holtrop & Mennen still-water resistance | `resistance.rs` | | Michell thin-ship wave resistance | `michell.rs` | @@ -427,6 +428,15 @@ curve from equilibrium (heels 0–60°, free trim), and evaluates indicative SOLAS-style residual criteria (SOLAS II-1 Reg. 7-2 spirit: range $\ge 15^\circ$, max $GZ \ge 0.10$ m, area $\ge 0.015$ m·rad). +`floodable::evaluate` (`seacraft floodable hull.fef` / MCP `floodable_length`) +draws floodable length curves by trial waterlines tangent to the margin line +(76 mm below the deck edge at side by default): for each position, the longest +full-breadth compartment, centred there, that floods without immersing the +margin line, ship upright and free to trim, one curve per permeability. With a +factor of subdivision (`--factor`) and bulkhead positions (`--bulkheads`), each +compartment is judged against the permissible length at its centre; `--svg` +draws the curves with the terminals and the bulkhead triangles. + ### Project file (`hull.seacraft.json`) Design data that the `.fef` format has no place for lives in a sidecar next to diff --git a/crates/seacraft-cli/src/main.rs b/crates/seacraft-cli/src/main.rs index 9f2d2cc..88df729 100644 --- a/crates/seacraft-cli/src/main.rs +++ b/crates/seacraft-cli/src/main.rs @@ -93,6 +93,8 @@ enum Command { Heel(HeelArgs), /// Deterministic damage stability by the lost-buoyancy method Damage(DamageArgs), + /// Floodable length curves: the longest compartment that can flood without immersing the margin line + Floodable(FloodableArgs), /// Strip-theory heave and pitch motion RAOs in regular head seas (Salvesen, Tuck & Faltinsen 1970) Seakeeping(SeakeepingArgs), /// Linesplan: stations, buttocks and waterlines as SVG or DXF @@ -1425,6 +1427,47 @@ struct DamageArgs { json: bool, } +#[derive(Args, Debug)] +struct FloodableArgs { + /// Input .fef file + file: PathBuf, + /// Project file for `--condition` (defaults to the model's `.seacraft.json` sidecar) + #[arg(long, requires = "condition")] + project: Option, + /// Loading condition of the project to float at (default: the hull at its design draft) + #[arg(long)] + condition: Option, + /// Displacement (t), instead of a loading condition + #[arg(long)] + displacement: Option, + /// Longitudinal centre of gravity (m, model x); with `--displacement` + #[arg(long, requires = "displacement")] + lcg: Option, + /// Permeabilities, one curve each + #[arg(long, value_delimiter = ',', default_values_t = seacraft_core::floodable::DEFAULT_PERMEABILITIES)] + permeability: Vec, + /// Margin line depth below the deck edge (m) + #[arg(long, default_value_t = seacraft_core::floodable::DEFAULT_MARGIN_M)] + margin: f64, + /// Factor of subdivision: permissible length = factor x floodable length + #[arg(long)] + factor: Option, + /// Watertight bulkhead positions (m, model x), aft to forward, to check each compartment + #[arg(long, value_delimiter = ',')] + bulkheads: Vec, + /// Write the curves as an SVG plot + #[arg(long)] + svg: Option, + #[command(flatten)] + subdiv: SubdivArgsCli, + /// Emit JSON instead of a table + #[arg(long, conflicts_with = "csv")] + json: bool, + /// Emit CSV, one row per curve point + #[arg(long)] + csv: bool, +} + #[derive(Args, Debug)] struct SeakeepingArgs { /// Input .fef file @@ -1776,6 +1819,7 @@ fn run() -> Result<()> { Command::Materials(a) => cmd_materials(a, tr), Command::Heel(a) => cmd_heel(a, tr), Command::Damage(a) => cmd_damage(a, tr), + Command::Floodable(a) => cmd_floodable(a, tr), Command::Seakeeping(a) => cmd_seakeeping(a, tr), Command::Linesplan(a) => cmd_linesplan(a, tr), Command::Templates(a) => cmd_templates(a, tr), @@ -5025,6 +5069,156 @@ fn cmd_stability(a: StabilityArgs, tr: Tr) -> Result<()> { Ok(()) } +fn cmd_floodable(a: FloodableArgs, tr: Tr) -> Result<()> { + use seacraft_core::floodable::{self, FloodableOptions}; + let s = load(&a.file)?; + if a.displacement.is_some() && a.condition.is_some() { + bail!("give either --displacement or --condition, not both"); + } + let mut case = damage::DamageCase::default(); + if let Some(d) = a.displacement { + // `kg` does not enter the floodable length; set, it selects the explicit loading. + case.displacement_t = Some(d); + case.kg = Some(0.0); + case.lcg = a.lcg; + } else if let Some(name) = &a.condition { + let (source, path) = read_case_or_project(&a.file, a.project.as_deref())?; + let CaseSource::Project(p) = source else { + bail!("{} is not a project file", path.display()); + }; + case.loading_condition_name = Some(name.clone()); + case = p + .resolve_damage_case(&case) + .map_err(|e| anyhow::anyhow!("{}: {e}", path.display()))?; + } + let hopts = HydroOptions::from_surface( + &s, + SubdivisionOptions { + level: a.subdiv.level, + mode: a.subdiv.mode.into(), + }, + ); + let opts = FloodableOptions { + permeabilities: a.permeability.clone(), + margin_m: a.margin, + factor: a.factor, + bulkheads: a.bulkheads.clone(), + ..FloodableOptions::default() + }; + let res = floodable::evaluate(&s, &hopts, &case, &opts).map_err(|e| anyhow::anyhow!("{e}"))?; + + if let Some(path) = &a.svg { + let title = tr.fmt(Key::CliFloodableHeading, &[("name", &s.settings.name)]); + seacraft_core::io::write_atomic(path, floodable::svg_tr(&res, &title, tr)) + .with_context(|| format!("cannot write {}", path.display()))?; + if a.json || a.csv { + eprintln!( + "{}", + tr.fmt( + Key::CliCommonWrote, + &[("path", &path.display().to_string())] + ) + ); + } + } + if a.json { + println!("{}", serde_json::to_string_pretty(&res)?); + return Ok(()); + } + if a.csv { + println!("permeability,x_mid,length,x_aft,x_fwd,trim_m,draft"); + for c in &res.curves { + for p in &c.points { + println!( + "{},{:.4},{:.4},{:.4},{:.4},{:.4},{:.4}", + c.permeability, p.x_mid, p.length, p.x_aft, p.x_fwd, p.trim_m, p.draft + ); + } + } + for w in &res.warnings { + eprintln!("{}", tr.msg(w)); + } + return Ok(()); + } + + println!( + "{}", + tr.fmt(Key::CliFloodableHeading, &[("name", &s.settings.name)]) + ); + println!(); + let row = |label: &str, value: String| println!(" {label:<26} {value}"); + row( + tr.s(Key::CliFloodableLoading), + format!( + "{:.3} t, LCG {:.3} m, ρ {:.3} t/m³", + res.displacement_t, res.lcg, res.water_density + ), + ); + row( + tr.s(Key::FloodableSvgMarginLine), + tr.fmt( + Key::CliFloodableMarginVal, + &[("margin", &format!("{:.3}", res.margin_m))], + ), + ); + for c in &res.curves { + println!(); + println!( + "{}", + tr.fmt( + Key::CliFloodableCurve, + &[("mu", &format!("{:.2}", c.permeability))] + ) + ); + if c.points.is_empty() { + println!( + " {}", + tr.fmt( + Key::WarnFloodableNoCurve, + &[("mu", &format!("{:.2}", c.permeability))] + ) + ); + } else { + println!(" {}", tr.s(Key::CliFloodableColumns)); + for p in &c.points { + println!( + " {:>9.3} {:>9.3} {:>9.3} {:>9.3} {:>+9.3} {:>9.3}", + p.x_mid, p.length, p.x_aft, p.x_fwd, p.trim_m, p.draft + ); + } + } + // Without a curve the compartments are still listed, each not judged. + if !c.checks.is_empty() { + println!(); + println!( + " {}", + tr.fmt( + Key::CliFloodableChecks, + &[("factor", &format!("{:.2}", res.factor.unwrap_or(1.0)))] + ) + ); + for k in &c.checks { + let verdict = match k.passed { + Some(true) => tr.s(Key::CliFloodablePass), + Some(false) => tr.s(Key::CliFloodableFail), + None => tr.s(Key::CliFloodableNotJudged), + }; + let permissible = k + .permissible + .map_or_else(|| "-".to_owned(), |v| format!("{v:.3}")); + println!( + " {:>8.3} .. {:<8.3} {:>8.3} / {:>8} m {verdict}", + k.x_aft, k.x_fwd, k.length, permissible + ); + } + } + } + for w in &res.warnings { + eprintln!("{}", tr.msg(w)); + } + Ok(()) +} + enum CaseSource { /// A bare loading condition or damage case, still to be parsed. Bare(String), diff --git a/crates/seacraft-cli/src/mcp.rs b/crates/seacraft-cli/src/mcp.rs index e66d561..7cbaa4b 100644 --- a/crates/seacraft-cli/src/mcp.rs +++ b/crates/seacraft-cli/src/mcp.rs @@ -114,6 +114,7 @@ the skin deducted (ask the builder for skin_mm; it defaults to none), export_off Project data: project_get and project_set read and write the design sidecar (loading conditions, compartments, damage cases, windage). Evaluate loading conditions with loading_condition {name} (or inline case / case_path). Evaluate damage stability with damage_stability {name} (or inline case / case_path). +Draw floodable length curves (bulkhead spacing) with floodable_length {condition | displacement_t, lcg}. Tool failures come back as a normal result with isError true and a message; protocol errors are JSON-RPC errors. Resources: seacraft://hull (summary of the loaded hull) and seacraft://tools (catalogue with each tool's effect)."; @@ -855,6 +856,7 @@ impl McpServer { "heel_equilibrium" => self.heel_equilibrium(a), "weather_criterion" => self.weather_criterion(a), "damage_stability" => self.damage_stability(a), + "floodable_length" => self.floodable_length(a), "seakeeping_raos" => self.seakeeping_raos(a), "seakeeping_irregular" => self.seakeeping_irregular(a), "bonjean_curves" => self.bonjean_curves(a), @@ -1712,6 +1714,68 @@ impl McpServer { Ok(v) } + fn floodable_length(&mut self, a: &Map) -> Result { + use seacraft_core::floodable::{self, FloodableOptions}; + let err = |e: String| format!("floodable_length: {e}"); + let locale = opt_locale(a)?; + let displacement = opt_number(a, "displacement_t")?; + let condition = str_arg(a, "condition"); + if displacement.is_some() && condition.is_some() { + return Err(err( + "give either `condition` or `displacement_t`, not both".into() + )); + } + let lcg = opt_number(a, "lcg")?; + if lcg.is_some() && displacement.is_none() { + return Err(err("`lcg` needs `displacement_t`".into())); + } + let mut case = seacraft_core::damage::DamageCase::default(); + if let Some(d) = displacement { + // KG does not enter the floodable length; set, it selects the explicit loading. + case.displacement_t = Some(d); + case.kg = Some(0.0); + case.lcg = lcg; + } else if let Some(name) = condition { + case.loading_condition_name = Some(name.to_owned()); + case = self.project.resolve_damage_case(&case).map_err(err)?; + } + let mut opts = FloodableOptions::default(); + if let Some(v) = a.get("permeabilities").filter(|v| !v.is_null()) { + opts.permeabilities = numbers(v, "permeabilities")?; + } + if let Some(m) = opt_number(a, "margin_m")? { + opts.margin_m = m; + } + opts.factor = opt_number(a, "factor")?; + if let Some(v) = a.get("bulkheads").filter(|v| !v.is_null()) { + opts.bulkheads = numbers(v, "bulkheads")?; + } + let level = match a.get("level") { + None | Some(Value::Null) => self.opts.subdivision.level, + Some(_) => level_arg(a)?, + }; + let mut hopts = self.opts.clone(); + hopts.subdivision.level = level; + let res = floodable::evaluate(&self.surface, &hopts, &case, &opts).map_err(err)?; + let mut written = None; + if let Some(path) = str_arg(a, "svg_path").filter(|s| !s.trim().is_empty()) { + let tr = Tr::new(locale); + let title = tr.fmt( + Key::CliFloodableHeading, + &[("name", &self.surface.settings.name)], + ); + seacraft_core::io::write_atomic(path, floodable::svg_tr(&res, &title, tr)) + .map_err(|e| err(format!("cannot write {path}: {e}")))?; + written = Some(path.to_string()); + } + let mut v = serde_json::to_value(&res).map_err(|e| e.to_string())?; + if let Some(o) = v.as_object_mut() { + o.insert("backend".into(), json!("headless")); + o.insert("written".into(), json!(written)); + } + Ok(v) + } + fn seakeeping_raos(&mut self, a: &Map) -> Result { let draft = match a.get("draft").and_then(|v| v.as_f64()) { Some(d) => d, @@ -3525,6 +3589,36 @@ pub fn tool_definitions() -> Vec { ), Effect::ReadOnly, ), + tool( + "floodable_length", + "Floodable length curves (bulkhead spacing)", + "Floodable length curves by trial waterlines tangent to the margin line (margin_m below the deck edge at \ + side, 0.076 m by default): for each position along the hull, the longest full-breadth compartment, \ + centred there, that can flood (lost buoyancy, permeability mu) without immersing the margin line, \ + ship upright and free to trim. One curve per permeability (default 0.60, 0.85, 0.95). With `factor` \ + (factor of subdivision, 0-1) and `bulkheads` (x positions, aft to forward) each compartment is judged \ + against the permissible length at its centre (passed, failed, or null when the curve does not reach \ + it). Loading: a project `condition`, or `displacement_t` with optional `lcg`, or else the hull at the \ + session's draft, as `damage_stability` takes it: the design draft until a call such as hydro_compute \ + or optimize_hull measures at another. Give `svg_path` to also write the plot. Checked against a box barge's closed form and the damage \ + solver; not against a published floodable length table.", + obj( + json!({ + "condition": string("Name of a loading condition in the project"), + "displacement_t": number("Displacement in tonnes, instead of a condition"), + "lcg": number("Longitudinal centre of gravity (m, model x), with displacement_t"), + "permeabilities": {"type": "array", "items": {"type": "number"}, "description": "One curve per permeability, each in (0, 1]"}, + "margin_m": number("Margin line depth below the deck edge in metres (default 0.076)"), + "factor": number("Factor of subdivision in (0, 1]: permissible length = factor x floodable length"), + "bulkheads": {"type": "array", "items": {"type": "number"}, "description": "Watertight bulkhead x positions in metres, aft to forward"}, + "svg_path": string("Write the curves as an SVG plot here"), + "locale": string("Language of the SVG: en or tr (default en)"), + "level": integer("Subdivision level 0-6 (default: the server's)"), + }), + &[], + ), + Effect::ReadOnly, + ), tool( "seakeeping_raos", "Seakeeping RAOs (heave and pitch in regular head seas)", @@ -4490,6 +4584,11 @@ impl Remote { } self.request("damage.compute", p) } + "floodable_length" => Err( + "floodable_length does not run while connected to the SeaCraft window yet; use the headless \ + server (seacraft mcp without --connect) or `seacraft floodable`" + .into(), + ), "seakeeping_raos" => self.request("seakeeping.compute", Value::Object(a.clone())), "seakeeping_irregular" => { self.request("seakeeping.irregular", Value::Object(a.clone())) @@ -4985,6 +5084,7 @@ mod tests { "heel_equilibrium", "weather_criterion", "damage_stability", + "floodable_length", "seakeeping_raos", "seakeeping_irregular", "bonjean_curves", @@ -6362,6 +6462,64 @@ mod tests { fails(&mut s, 2, "damage_stability", json!({})); } + #[test] + fn floodable_length_tool_returns_curves() { + let mut s = McpServer::new(); + let res = ok( + &mut s, + 1, + "floodable_length", + json!({"level": 2, "permeabilities": [0.85], "factor": 0.5, "bulkheads": [3.0, 6.0, 9.0]}), + ); + assert_eq!(res["backend"], "headless"); + let curves = res["curves"].as_array().unwrap(); + assert_eq!(curves.len(), 1); + assert_eq!(curves[0]["permeability"].as_f64(), Some(0.85)); + assert!(curves[0]["points"].as_array().unwrap().len() > 10); + assert_eq!(curves[0]["checks"].as_array().unwrap().len(), 4); + assert_eq!(res["written"], Value::Null); + + let dir = + std::env::temp_dir().join(format!("seacraft-mcp-floodable-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let svg = dir.join("floodable.svg"); + let res = ok( + &mut s, + 2, + "floodable_length", + json!({"level": 2, "svg_path": svg.to_string_lossy(), "locale": "tr"}), + ); + assert_eq!(res["curves"].as_array().unwrap().len(), 3); + assert_eq!( + res["written"].as_str(), + Some(svg.to_string_lossy().as_ref()) + ); + assert!(std::fs::read_to_string(&svg) + .unwrap() + .contains("Su alabilir boy")); + std::fs::remove_dir_all(&dir).ok(); + + let err = fails( + &mut s, + 3, + "floodable_length", + json!({"bulkheads": [6.0, 3.0]}), + ); + assert!(err.contains("bulkhead"), "{err}"); + let err = fails(&mut s, 4, "floodable_length", json!({"condition": "Nope"})); + assert!(err.contains("Nope"), "{err}"); + let err = fails( + &mut s, + 5, + "floodable_length", + json!({"condition": "Design", "displacement_t": 10.0}), + ); + assert!(err.contains("not both"), "{err}"); + // An LCG without a displacement would otherwise be dropped without a word. + let err = fails(&mut s, 6, "floodable_length", json!({"lcg": 4.0})); + assert!(err.contains("displacement_t"), "{err}"); + } + #[test] fn damage_stability_by_name_equals_inline_case() { let mut s = McpServer::new(); diff --git a/crates/seacraft-cli/tests/floodable.rs b/crates/seacraft-cli/tests/floodable.rs new file mode 100644 index 0000000..1446845 --- /dev/null +++ b/crates/seacraft-cli/tests/floodable.rs @@ -0,0 +1,219 @@ +//! `seacraft floodable`, run as a user runs it. + +use std::process::{Command, Output}; + +fn example(name: &str) -> String { + format!("{}/../../examples/{name}", env!("CARGO_MANIFEST_DIR")) +} + +fn run_lang(lang: &str, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_seacraft")) + .env("SEACRAFT_LANG", lang) + .args(args) + .output() + .expect("run seacraft") +} + +fn stdout(lang: &str, args: &[&str]) -> String { + let out = run_lang(lang, args); + assert!( + out.status.success(), + "{args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).expect("utf-8") +} + +#[test] +fn floodable_json_has_three_curves_for_the_demo_hull() { + let hull = example("demo-hull.fef"); + let text = stdout( + "en", + &[ + "floodable", + &hull, + "--level", + "2", + "--bulkheads", + "3,6,9", + "--factor", + "0.5", + "--json", + ], + ); + let v: serde_json::Value = serde_json::from_str(&text).expect("json"); + let curves = v["curves"].as_array().expect("curves"); + assert_eq!(curves.len(), 3); + let mus: Vec = curves + .iter() + .map(|c| c["permeability"].as_f64().unwrap()) + .collect(); + assert_eq!(mus, vec![0.60, 0.85, 0.95]); + for c in curves { + assert!(c["points"].as_array().unwrap().len() > 10); + assert_eq!(c["checks"].as_array().unwrap().len(), 4); + } + assert_eq!(v["margin_m"].as_f64(), Some(0.076)); + assert_eq!(v["factor"].as_f64(), Some(0.5)); + assert!( + v.get("profile").is_none(), + "the profile is for the plot only" + ); +} + +#[test] +fn floodable_takes_a_loading_and_one_permeability() { + let hull = example("demo-hull.fef"); + let text = stdout( + "en", + &[ + "floodable", + &hull, + "--level", + "2", + "--displacement", + "11.0", + "--lcg", + "4.5", + "--permeability", + "0.85", + "--csv", + ], + ); + let mut lines = text.lines(); + assert_eq!( + lines.next(), + Some("permeability,x_mid,length,x_aft,x_fwd,trim_m,draft") + ); + let rows: Vec<&str> = lines.collect(); + assert!(rows.len() > 10); + assert!(rows.iter().all(|r| r.starts_with("0.85,"))); +} + +#[test] +fn floodable_table_in_turkish_names_the_curve() { + let hull = example("demo-hull.fef"); + let text = stdout( + "tr", + &["floodable", &hull, "--level", "2", "--bulkheads", "3,6,9"], + ); + assert!(text.contains("Su alabilir boy"), "{text}"); + assert!(text.contains("Sınır hattı"), "{text}"); +} + +#[test] +fn floodable_writes_an_svg() { + let dir = std::env::temp_dir().join(format!("seacraft-floodable-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let svg = dir.join("demo-floodable.svg"); + let hull = example("demo-hull.fef"); + stdout( + "en", + &[ + "floodable", + &hull, + "--level", + "2", + "--svg", + svg.to_str().unwrap(), + ], + ); + let text = std::fs::read_to_string(&svg).unwrap(); + assert!(text.starts_with(" Option { // SVG plots // --------------------------------------------------------------------------- -fn esc(s: &str) -> String { +pub(crate) fn esc(s: &str) -> String { s.replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('"', """) } -fn chart_frame(out: &mut String, title: &str, w: f64, h: f64) { +pub(crate) fn chart_frame(out: &mut String, title: &str, w: f64, h: f64) { let _ = writeln!(out, ""); let _ = writeln!( out, diff --git a/crates/seacraft-core/src/damage.rs b/crates/seacraft-core/src/damage.rs index 9c2b33c..22803d0 100644 --- a/crates/seacraft-core/src/damage.rs +++ b/crates/seacraft-core/src/damage.rs @@ -715,7 +715,7 @@ pub fn solve_damaged_floating( /// The sheer / deck edge of the hull, for the damaged freeboard: the open /// boundary of a hull that ends at the sheer ([`hull_deck_boundary_vertices`]), /// or the outline of the deck of a closed one ([`closed_hull_deck_edge`]). -fn hull_deck_edge_vertices(hull: &Hull) -> Vec { +pub(crate) fn hull_deck_edge_vertices(hull: &Hull) -> Vec { let open = hull_deck_boundary_vertices(hull); if open.is_empty() { closed_hull_deck_edge(hull) @@ -873,15 +873,34 @@ pub fn resolve_compartments( Ok(out) } -/// Full evaluation of deterministic damage stability by the lost-buoyancy method. -pub fn evaluate( +/// The loading a damage case floats at: displacement, centre of gravity, +/// water density and the volume the refined hull must float. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Particulars { + /// Displacement (t), appendages included. + pub displacement_t: f64, + /// Centre of gravity above the keel (m). + pub kg: f64, + /// Longitudinal centre of gravity (m, model x). + pub lcg: f64, + /// Transverse centre of gravity (m, + to starboard). + pub tcg: f64, + /// Water density (t/m³). + pub density: f64, + /// Volume the refined hull floats: Δ / (ρ · c_app) (m³). + pub target_volume: f64, +} + +/// Resolve a case's loading: `displacement_t` and `kg` given together win +/// (LCG defaulting to the hull's LCB at `opts.draft`); otherwise a loading +/// condition; otherwise the hull at its design draft. Used by [`evaluate`] +/// and by [`crate::floodable`]. +pub fn resolve_particulars( surface: &Surface, opts: &HydroOptions, + hull: &Hull, case: &DamageCase, -) -> Result { - validate(case)?; - let compartments = resolve_compartments(case, None)?; - let hull = Hull::new(surface, opts.subdivision); +) -> Particulars { let density = case .water_density .unwrap_or(opts.water_density / 1000.0) @@ -931,8 +950,33 @@ pub fn evaluate( } } }; + Particulars { + displacement_t, + kg, + lcg, + tcg, + density, + target_volume: displacement_t / (density * app_coeff), + } +} - let target_volume = displacement_t / (density * app_coeff); +/// Full evaluation of deterministic damage stability by the lost-buoyancy method. +pub fn evaluate( + surface: &Surface, + opts: &HydroOptions, + case: &DamageCase, +) -> Result { + validate(case)?; + let compartments = resolve_compartments(case, None)?; + let hull = Hull::new(surface, opts.subdivision); + let Particulars { + displacement_t, + kg, + lcg, + tcg, + density, + target_volume, + } = resolve_particulars(surface, opts, &hull, case); let mut warnings = Vec::new(); // 1. Intact equilibrium floating condition. @@ -1245,6 +1289,62 @@ fn evaluate_residual_criteria( }) } +/// A closed, creased L × B × D box barge from x = 0 to L, centred on y = 0, +/// keel at z = 0: the analytic test hull of the damage and floodable tests. +#[cfg(test)] +pub(crate) fn make_box_barge(length: f64, beam: f64, depth: f64) -> Surface { + let mut s = Surface::new(); + s.layers = vec![crate::mesh::Layer { + name: "Hull".into(), + symmetric: false, + use_in_hydrostatics: true, + visible: true, + ..crate::mesh::Layer::default() + }]; + s.settings = crate::mesh::ProjectSettings { + name: "barge".into(), + length, + beam, + draft: depth, + water_density: 1000.0, + appendage_coefficient: 1.0, + main_particulars_set: true, + ..crate::mesh::ProjectSettings::default() + }; + let (l, b) = (length, beam); + let corners = [ + (0.0, 0.0, 0.0), + (l, 0.0, 0.0), + (l, b, 0.0), + (0.0, b, 0.0), + (0.0, 0.0, depth), + (l, 0.0, depth), + (l, b, depth), + (0.0, b, depth), + ]; + for (x, y, z) in corners { + s.add_point(Vec3::new(x, y - b * 0.5, z)); + } + for face in [ + vec![0, 3, 2, 1], + vec![4, 5, 6, 7], + vec![0, 1, 5, 4], + vec![1, 2, 6, 5], + vec![2, 3, 7, 6], + vec![3, 0, 4, 7], + ] { + s.add_face(face, 0); + } + s.initialize_trace(); + for edge in &mut s.edges { + edge.crease = true; + } + for point in &mut s.points { + point.kind = crate::mesh::VertexKind::Corner; + } + s +} + #[cfg(test)] mod tests { use super::*; @@ -1297,59 +1397,6 @@ mod tests { assert!(err.contains("t/m³"), "{err}"); } - fn make_box_barge(length: f64, beam: f64, depth: f64) -> Surface { - let mut s = Surface::new(); - s.layers = vec![crate::mesh::Layer { - name: "Hull".into(), - symmetric: false, - use_in_hydrostatics: true, - visible: true, - ..crate::mesh::Layer::default() - }]; - s.settings = crate::mesh::ProjectSettings { - name: "barge".into(), - length, - beam, - draft: depth, - water_density: 1000.0, - appendage_coefficient: 1.0, - main_particulars_set: true, - ..crate::mesh::ProjectSettings::default() - }; - let (l, b) = (length, beam); - let corners = [ - (0.0, 0.0, 0.0), - (l, 0.0, 0.0), - (l, b, 0.0), - (0.0, b, 0.0), - (0.0, 0.0, depth), - (l, 0.0, depth), - (l, b, depth), - (0.0, b, depth), - ]; - for (x, y, z) in corners { - s.add_point(Vec3::new(x, y - b * 0.5, z)); - } - for face in [ - vec![0, 3, 2, 1], - vec![4, 5, 6, 7], - vec![0, 1, 5, 4], - vec![1, 2, 6, 5], - vec![2, 3, 7, 6], - vec![3, 0, 4, 7], - ] { - s.add_face(face, 0); - } - s.initialize_trace(); - for edge in &mut s.edges { - edge.crease = true; - } - for point in &mut s.points { - point.kind = crate::mesh::VertexKind::Corner; - } - s - } - /// Derived analytic test: /// Box barge L×B×D at draft T with a full-breadth midship compartment of length l /// and permeability μ extending above the waterline: diff --git a/crates/seacraft-core/src/floodable.rs b/crates/seacraft-core/src/floodable.rs new file mode 100644 index 0000000..194319a --- /dev/null +++ b/crates/seacraft-core/src/floodable.rs @@ -0,0 +1,2097 @@ +//! Floodable length curves by trial waterlines. +//! +//! The floodable length at a point is the length of a compartment, with that point as its centre, that can be +//! flooded without immersing any part of the margin line when the ship has no list; the margin line is at least +//! 76 mm below the bulkhead deck at side (Rawson & Tupper, *Basic Ship Theory*, Vol. 1, 5th ed., pp. 155-156; +//! Gillmer & Johnson, *Introduction to Naval Architecture*, 1982, pp. 180-182). Permissible length is the +//! floodable length times a factor of subdivision; a compartment passes when its length does not exceed the +//! permissible length at its centre (the triangle check of Rawson & Tupper, with base angle tan⁻¹ 2). +//! +//! The method is Gillmer & Johnson's. Each trial waterline is tangent to the margin line. The hull +//! floats it with the flooded compartment's water counted as lost buoyancy, so the lost volume is +//! `v = V_W − ∇` and its centroid follows from the moment balance `V_W · x_B − ∇ · LCG = v · x_c` +//! (Gillmer & Johnson Eq. 10-1 and 10-2, there by added weight, which gives the same waterline). The +//! compartment is the full-breadth slice of the hull under that waterline holding `v / μ` with its centroid at +//! `x_c`, found from the sectional areas under the waterline (Bonjean curves in Gillmer & Johnson). Compartments are +//! full breadth and the ship upright; the deck edge is the moulded sheer, with no deck thickness. + +use crate::damage::{hull_deck_edge_vertices, resolve_particulars, DamageCase, Particulars}; +use crate::hydro::{chain_paths, plane_segments, section_area, waterplane_for, Hull, HydroOptions}; +use crate::i18n::{Key, Msg}; +use crate::math::{Plane, Vec3}; +use crate::mesh::Surface; +use serde::{Deserialize, Serialize}; +use std::fmt::Write as _; + +/// The margin line's depth below the deck edge (m): 76 mm, the SOLAS 1960 figure. +pub const DEFAULT_MARGIN_M: f64 = 0.076; +/// Permeabilities drawn by default, one curve each. +pub const DEFAULT_PERMEABILITIES: [f64; 3] = [0.60, 0.85, 0.95]; +/// Sectional-area stations per trial waterline by default. +pub const DEFAULT_STATIONS: usize = 201; +/// Most trial waterlines one computation runs. +const MAX_WATERLINES: usize = 400; +/// Most sectional-area stations per trial waterline: fifty times the default, far finer than the panels. +pub const MAX_STATIONS: usize = 10_001; + +/// What to compute: permeabilities, margin line, and the optional bulkhead check. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct FloodableOptions { + /// One curve per permeability, each in (0, 1]. + pub permeabilities: Vec, + /// Margin line depth below the deck edge (m). + pub margin_m: f64, + /// Factor of subdivision in (0, 1]: permissible length = F × floodable length. + pub factor: Option, + /// Watertight bulkhead positions (model x, m), strictly increasing, inside the hull. + pub bulkheads: Vec, + /// Sectional-area stations per trial waterline (11 to [`MAX_STATIONS`]). + pub stations: usize, +} + +impl Default for FloodableOptions { + fn default() -> Self { + Self { + permeabilities: DEFAULT_PERMEABILITIES.to_vec(), + margin_m: DEFAULT_MARGIN_M, + factor: None, + bulkheads: Vec::new(), + stations: DEFAULT_STATIONS, + } + } +} + +/// One point of a floodable length curve: the compartment `[x_aft, x_fwd]` that floods the hull to the trial +/// waterline at `draft` and `trim_m`. +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +pub struct FloodablePoint { + /// Centre of the compartment (m, model x). + pub x_mid: f64, + /// Floodable length (m). + pub length: f64, + pub x_aft: f64, + pub x_fwd: f64, + /// Trim of the trial waterline (m, + bow-up). + pub trim_m: f64, + /// Draft of the trial waterline amidships above the keel, as [`waterplane_for`] takes it (m). + pub draft: f64, +} + +/// A compartment between neighbouring bulkheads (or a bulkhead and a hull end), judged at its centre. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct CompartmentCheck { + pub x_aft: f64, + pub x_fwd: f64, + pub length: f64, + /// Floodable length at the compartment's centre, if the curve reaches it. + pub floodable: Option, + /// Permissible length at the centre (factor × floodable). + pub permissible: Option, + /// `None` when the curve does not reach the centre: not judged, never passed. + pub passed: Option, + pub reason: Option, +} + +/// The floodable length curve for one permeability. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct FloodableCurve { + pub permeability: f64, + /// Sorted by `x_mid`. + pub points: Vec, + pub checks: Vec, +} + +/// Floodable length curves of a hull at one loading. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct FloodableResult { + pub displacement_t: f64, + pub lcg: f64, + /// t/m³. + pub water_density: f64, + pub margin_m: f64, + /// The hull's ends (m, model x): no compartment reaches past them. + pub hull_x_aft: f64, + pub hull_x_fwd: f64, + pub factor: Option, + /// Margin line points `(x, z)`, sorted by x. + pub margin_line: Vec<[f64; 2]>, + pub curves: Vec, + pub warnings: Vec, + /// The hull's centreline profile `(x, z)` polylines, for the plot; not part of the JSON. + #[serde(skip)] + pub profile: Vec>, +} + +/// Floodable length curves of `surface` at the loading `case` resolves to (its compartments are not used). +pub fn evaluate( + surface: &Surface, + hopts: &HydroOptions, + case: &DamageCase, + opts: &FloodableOptions, +) -> Result { + if let Some(name) = &case.loading_condition_name { + if case.loading_condition.is_none() { + return Err(format!( + "damage case `{}` refers to loading condition `{name}` by name; evaluate it through a project file", + case.name + )); + } + } + if let Some(lc) = &case.loading_condition { + crate::loading::validate(lc).map_err(|e| format!("loading condition: {e}"))?; + } + // `resolve_particulars` floors the density and the appendage coefficient; values that are not water or not + // a coefficient are errors here, in the range `damage::validate` holds a case's density to. + match case.water_density { + Some(rho) if !(0.5..=2.0).contains(&rho) => { + return Err(format!( + "`water_density` is in t/m³ and must be between 0.5 and 2.0 (got {rho})" + )); + } + None if !(500.0..=2000.0).contains(&hopts.water_density) => { + return Err(format!( + "the model's water density {} kg/m³ is not between 500 and 2000 kg/m³", + hopts.water_density + )); + } + _ => {} + } + let app = hopts.appendage_coefficient; + if !(app.is_finite() && app >= 1e-6) { + return Err(format!( + "appendage coefficient {app} is not a coefficient: it must be at least 1e-6" + )); + } + let hull = Hull::new(surface, hopts.subdivision); + let p = resolve_particulars(surface, hopts, &hull, case); + compute(&hull, &p, opts) +} + +/// Floodable length curves of a refined hull at the loading `p`. +pub fn compute( + hull: &Hull, + p: &Particulars, + opts: &FloodableOptions, +) -> Result { + compute_with_deck_edge(hull, p, opts, &hull_deck_edge_vertices(hull)) +} + +fn compute_with_deck_edge( + hull: &Hull, + p: &Particulars, + opts: &FloodableOptions, + deck_edge: &[Vec3], +) -> Result { + validate(opts)?; + validate_particulars(p)?; + if deck_edge.is_empty() { + return Err("the hull has no deck edge to draw a margin line under".into()); + } + let mut margin: Vec = deck_edge + .iter() + .map(|q| Vec3::new(q.x, q.y, q.z - opts.margin_m)) + .collect(); + margin.sort_by(|a, b| a.x.total_cmp(&b.x)); + // The ends of the hull's own panels: `verts` also holds points no panel uses. + let (x_aft, x_fwd) = + hull.tris + .iter() + .flatten() + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &i| { + let x = hull.verts[i].x; + (lo.min(x), hi.max(x)) + }); + if x_aft >= x_fwd { + return Err("the hull has no panels to float".into()); + } + validate_bulkheads(&opts.bulkheads, x_aft, x_fwd)?; + let grid = Grid::new(x_aft, x_fwd, opts.stations); + let closed = hull.closed_tris(); + let eval = |trim: f64| -> Trial { + let (draft, wp) = tangent_waterline(hull, &margin, trim); + let (v_w, b) = hull.buoyancy_in(&wp); + let lost = v_w - p.target_volume; + let mut trial = Trial { + trim, + lost, + floats: lost > 1e-9 * p.target_volume.max(1.0), + points: vec![None; opts.permeabilities.len()], + }; + if !trial.floats { + return trial; + } + let x_c = (v_w * b.x - p.target_volume * p.lcg) / lost; + if !x_c.is_finite() { + return trial; + } + let areas = crate::par::par_map(&grid.stations, |&x| { + section_area(&hull.verts, &closed, x, &wp) + }); + let cum = grid.cumulative(&areas); + for (slot, &mu) in trial.points.iter_mut().zip(&opts.permeabilities) { + *slot = cum + .compartment(lost / mu, x_c) + .map(|(a, b)| FloodablePoint { + x_mid: 0.5 * (a + b), + length: b - a, + x_aft: a, + x_fwd: b, + trim_m: trim, + draft, + }); + } + trial + }; + + let trials = sweep(hull, &margin, eval(0.0), &eval, x_fwd - x_aft); + // Free to trim: the loading is too heavy only when no trial waterline floats more than it. + if trials.iter().all(|t| !t.floats) { + return Err(format!( + "a displacement of {:.3} t already sinks the hull to its margin line at every trim tried", + p.displacement_t + )); + } + + let mut warnings = Vec::new(); + let curves = opts + .permeabilities + .iter() + .enumerate() + .map(|(i, &mu)| { + let mut points: Vec = + trials.iter().filter_map(|t| t.points[i]).collect(); + points.sort_by(|a, b| a.x_mid.total_cmp(&b.x_mid)); + // One point per centre, the longest, for both the plot and the checks. + points.dedup_by(|later, kept| { + let same = later.x_mid == kept.x_mid; + if same && later.length > kept.length { + *kept = *later; + } + same + }); + if points.is_empty() { + warnings.push(Msg::new(Key::WarnFloodableNoCurve).arg("mu", format!("{mu:.2}"))); + } + let mut curve = FloodableCurve { + permeability: mu, + points, + checks: Vec::new(), + }; + if !opts.bulkheads.is_empty() { + curve.checks = + check_compartments(&curve, &opts.bulkheads, x_aft, x_fwd, opts.factor); + } + curve + }) + .collect(); + Ok(FloodableResult { + displacement_t: p.displacement_t, + lcg: p.lcg, + water_density: p.density, + margin_m: opts.margin_m, + hull_x_aft: x_aft, + hull_x_fwd: x_fwd, + factor: opts.factor, + margin_line: margin.iter().map(|q| [q.x, q.z]).collect(), + curves, + warnings, + profile: centreline_profile(hull), + }) +} + +/// The hull cut at y = 0, as `(x, z)` polylines. +fn centreline_profile(hull: &Hull) -> Vec> { + let plane = Plane::new(Vec3::new(0.0, 1.0, 0.0), 0.0); + let segs = plane_segments(&hull.verts, &hull.closed_tris(), &plane); + let tol = 1e-7 * (hull.model_max.x - hull.model_min.x).max(1.0); + chain_paths(&segs, tol) + .into_iter() + .map(|(pts, closed)| { + let mut line: Vec<[f64; 2]> = pts.iter().map(|p| [p.x, p.z]).collect(); + if closed { + if let Some(&first) = line.first() { + line.push(first); + } + } + line + }) + .collect() +} + +fn validate(opts: &FloodableOptions) -> Result<(), String> { + if opts.permeabilities.is_empty() { + return Err("give at least one permeability".into()); + } + for &mu in &opts.permeabilities { + if !(mu > 0.0 && mu <= 1.0) { + return Err(format!("permeability {mu} is outside (0, 1]")); + } + } + if !(opts.margin_m.is_finite() && opts.margin_m >= 0.0) { + return Err(format!( + "margin line depth {} m is not a length", + opts.margin_m + )); + } + if let Some(f) = opts.factor { + if !(f > 0.0 && f <= 1.0) { + return Err(format!("factor of subdivision {f} is outside (0, 1]")); + } + } + if opts.stations < 11 { + return Err(format!( + "{} stations are too few; use at least 11", + opts.stations + )); + } + if opts.stations > MAX_STATIONS { + return Err(format!( + "{} stations are too many; use at most {MAX_STATIONS}", + opts.stations + )); + } + Ok(()) +} + +/// The loading must be a ship: a positive displacement and water density, the volume they float, and an LCG. +fn validate_particulars(p: &Particulars) -> Result<(), String> { + let positive = |v: f64| v.is_finite() && v > 0.0; + if !positive(p.displacement_t) || !positive(p.target_volume) { + return Err(format!( + "a displacement of {} t is not a ship to flood", + p.displacement_t + )); + } + if !positive(p.density) { + return Err(format!("water density {} t/m³ is not positive", p.density)); + } + if !p.lcg.is_finite() { + return Err(format!("LCG {} m is not a position", p.lcg)); + } + Ok(()) +} + +fn validate_bulkheads(bulkheads: &[f64], x_aft: f64, x_fwd: f64) -> Result<(), String> { + for &x in bulkheads { + if !(x > x_aft && x < x_fwd) { + return Err(format!( + "bulkhead at x = {x} m is not inside the hull ({x_aft:.3} to {x_fwd:.3} m)" + )); + } + } + if bulkheads.windows(2).any(|w| w[1] <= w[0]) { + return Err("bulkhead positions must increase from aft to forward, each once".into()); + } + Ok(()) +} + +/// The compartments the bulkheads make, from the aft end of the hull to its forward end, each judged against +/// the permissible length at its centre only: it passes when its length does not exceed the permissible length +/// there, so the apex of the triangle on it, as high as it is long, is not above the permissible curve. The +/// triangle's sides are not compared with the curve; where the curve dips steeply they can cross it. +fn check_compartments( + curve: &FloodableCurve, + bulkheads: &[f64], + x_aft: f64, + x_fwd: f64, + factor: Option, +) -> Vec { + let f = factor.unwrap_or(1.0); + let mut bounds = Vec::with_capacity(bulkheads.len() + 2); + bounds.push(x_aft); + bounds.extend_from_slice(bulkheads); + bounds.push(x_fwd); + bounds + .windows(2) + .map(|w| { + let (a, b) = (w[0], w[1]); + let floodable = floodable_at(curve, 0.5 * (a + b)); + let permissible = floodable.map(|l| f * l); + CompartmentCheck { + x_aft: a, + x_fwd: b, + length: b - a, + floodable, + permissible, + passed: permissible.map(|p| b - a <= p), + reason: floodable + .is_none() + .then(|| Msg::new(Key::FloodableCheckOutsideCurve)), + } + }) + .collect() +} + +/// One trial waterline and the compartment it gives for each permeability. +#[derive(Debug, Clone)] +struct Trial { + trim: f64, + /// Volume the waterline floats beyond the ship's (m³), negative when it floats less. + lost: f64, + /// The waterline floats more than the ship: there is water to lose. + floats: bool, + points: Vec>, +} + +/// Trims outward from even keel in both directions, past trims where no permeability gives a point yet, until +/// three in a row give none after one has; then trims between neighbours whose points lie far apart along the +/// hull or where a curve ends. Each direction has its own share of the waterlines, so a long run one way does +/// not starve the other. When no sampled trim gives a point, the trims around each sampled peak of the floated +/// volume are searched before the loading is called too heavy or its curves empty: the most can lie between +/// samples, where the margin point the waterline touches changes. +fn sweep( + hull: &Hull, + margin: &[Vec3], + even: Trial, + eval: &dyn Fn(f64) -> Trial, + span: f64, +) -> Vec { + let low = margin.iter().map(|q| q.z).fold(f64::INFINITY, f64::min); + let reach = 2.0 * (hull.model_max.z - hull.keel).max(1e-3); + let share = MAX_WATERLINES / 4; + // Fine enough near even keel, coarse enough that each direction's share reaches the whole trim range even + // where the margin line dips close to the keel. + let step = (0.05 * (low - hull.keel).max(1e-3)).max(reach / share as f64); + let even_hit = even.points.iter().any(Option::is_some); + let mut trials = vec![even]; + for sign in [1.0, -1.0] { + let mut seen = even_hit; + let mut misses = 0; + for k in 1..=share { + let trim = sign * step * k as f64; + if trim.abs() > reach { + break; + } + let t = eval(trim); + let any = t.points.iter().any(Option::is_some); + trials.push(t); + seen |= any; + misses = if any { 0 } else { misses + 1 }; + if seen && misses >= 3 { + break; + } + } + } + trials.sort_by(|a, b| a.trim.total_cmp(&b.trim)); + // No point yet: the ship floats nowhere it was sampled, or only barely, where the little water lost centres + // off the hull. The trims that float most may still give points, so they seed the refinement below. + if trials.iter().all(|t| t.points.iter().all(Option::is_none)) { + if let Some(t) = floating_between_samples(&trials, step, eval) { + trials.push(t); + trials.sort_by(|a, b| a.trim.total_cmp(&b.trim)); + } + } + + let gap = span / 50.0; + let min_dt = (step / 64.0).max(1e-4); + for _ in 0..16 { + let mut inserts = Vec::new(); + for w in trials.windows(2) { + if w[1].trim - w[0].trim <= min_dt { + continue; + } + let wide = w[0].points.iter().zip(&w[1].points).any(|pair| match pair { + (Some(a), Some(b)) => (a.x_mid - b.x_mid).abs() > gap, + (Some(_), None) | (None, Some(_)) => true, + (None, None) => false, + }); + if wide { + inserts.push(0.5 * (w[0].trim + w[1].trim)); + } + } + if inserts.is_empty() { + break; + } + for trim in inserts { + if trials.len() >= MAX_WATERLINES { + break; + } + trials.push(eval(trim)); + } + trials.sort_by(|a, b| a.trim.total_cmp(&b.trim)); + } + trials +} + +/// Most sampled peaks searched between their neighbours: the floated volume over trim has one peak for each +/// change of the margin point the waterline touches, a few on any real sheer. +const MAX_PEAKS: usize = 8; + +/// The trim that floats the ship most near a sampled peak, `trials` sorted by trim: around each sample that +/// floats at least as much as its neighbours, highest first, a golden-section search for the most floated +/// between those neighbours. The first maximum that gives a point is returned, else the one that floats most, +/// or `None` when none floats. +fn floating_between_samples( + trials: &[Trial], + step: f64, + eval: &dyn Fn(f64) -> Trial, +) -> Option { + const R: f64 = 0.618_033_988_749_895; // (√5 − 1) / 2 + let lost = |j: Option| { + j.and_then(|j| trials.get(j)) + .map_or(f64::NEG_INFINITY, |t| t.lost) + }; + let mut peaks: Vec = (0..trials.len()) + .filter(|&i| { + trials[i].lost >= lost(i.checked_sub(1)) && trials[i].lost >= lost(Some(i + 1)) + }) + .collect(); + peaks.sort_by(|&a, &b| trials[b].lost.total_cmp(&trials[a].lost)); + let mut best: Option = None; + for i in peaks.into_iter().take(MAX_PEAKS) { + let mut lo = i + .checked_sub(1) + .map_or(trials[i].trim - step, |j| trials[j].trim); + let mut hi = trials.get(i + 1).map_or(trials[i].trim + step, |t| t.trim); + let mut c = eval(hi - R * (hi - lo)); + let mut d = eval(lo + R * (hi - lo)); + for _ in 0..40 { + if c.lost > d.lost { + hi = d.trim; + d = c; + c = eval(hi - R * (hi - lo)); + } else { + lo = c.trim; + c = d; + d = eval(lo + R * (hi - lo)); + } + } + let top = if c.lost > d.lost { c } else { d }; + if !top.floats { + continue; + } + if top.points.iter().any(Option::is_some) { + return Some(top); + } + if best.as_ref().is_none_or(|b| top.lost > b.lost) { + best = Some(top); + } + } + best +} + +/// Stations along the hull: strictly inside its ends, where a section cut is well defined, plus the ends. +struct Grid { + /// The hull's aft end, the stations, the forward end. + xs: Vec, + stations: Vec, +} + +impl Grid { + fn new(x_aft: f64, x_fwd: f64, n: usize) -> Self { + let inset = 1e-6 * (x_fwd - x_aft); + let (a, b) = (x_aft + inset, x_fwd - inset); + let stations: Vec = (0..n) + .map(|i| a + (b - a) * i as f64 / (n - 1) as f64) + .collect(); + let mut xs = Vec::with_capacity(n + 2); + xs.push(x_aft); + xs.extend(&stations); + xs.push(x_fwd); + Self { xs, stations } + } + + /// Cumulative volume and moment from the aft end, by trapezoids over the sectional areas (the end + /// sections taken equal to their neighbours). + fn cumulative(&self, areas: &[f64]) -> Cumulative { + let mut a = Vec::with_capacity(areas.len() + 2); + a.push(areas[0]); + a.extend(areas); + a.push(areas[areas.len() - 1]); + Cumulative::new(self.xs.clone(), a) + } +} + +/// Volume Q(x) and moment M(x) of the hull under a waterline from its aft end to x, the sectional area linear +/// between stations. +struct Cumulative { + xs: Vec, + /// Sectional area at each of `xs`. + a: Vec, + q: Vec, + m: Vec, +} + +impl Cumulative { + fn new(xs: Vec, a: Vec) -> Self { + let mut q = vec![0.0; xs.len()]; + let mut m = vec![0.0; xs.len()]; + for k in 1..xs.len() { + let (x0, x1) = (xs[k - 1], xs[k]); + let dq = 0.5 * (a[k - 1] + a[k]) * (x1 - x0); + // ∫ x A dx over a linear A, exactly. + let dm = (x1 - x0) / 6.0 * (a[k - 1] * (2.0 * x0 + x1) + a[k] * (x0 + 2.0 * x1)); + q[k] = q[k - 1] + dq; + m[k] = m[k - 1] + dm; + } + Self { xs, a, q, m } + } + + /// The first x where Q reaches `u` (`last` false: a compartment's forward end) or the last x where Q is + /// still `u` (`last` true: its aft end), and M there; so a compartment never runs on into a dry end at + /// either end. Within an interval the area is linear, as in [`Cumulative::new`]: Q is inverted and M + /// integrated exactly there. + fn at_volume(&self, u: f64, last: bool) -> (f64, f64) { + let n = self.q.len(); + let k = if last { + self.q.partition_point(|&q| q <= u) + } else { + self.q.partition_point(|&q| q < u) + } + .clamp(1, n - 1); + let (q0, q1) = (self.q[k - 1], self.q[k]); + let (x0, x1) = (self.xs[k - 1], self.xs[k]); + if q1 - q0 <= 0.0 { + return (x0, self.m[k - 1]); + } + // A(x0 + t) = a0 + d·t, so Q = q0 + a0·t + d·t²/2: the root t ≥ 0 in its cancellation-free form. + let h = x1 - x0; + let a0 = self.a[k - 1]; + let d = (self.a[k] - a0) / h; + let r = (u - q0).clamp(0.0, q1 - q0); + let root = (a0 * a0 + 2.0 * d * r).max(0.0).sqrt(); + let t = if a0 + root > 0.0 { + (2.0 * r / (a0 + root)).clamp(0.0, h) + } else { + 0.0 + }; + // ∫ x A dx from x0 to x0 + t. + let dm = x0 * a0 * t + 0.5 * (x0 * d + a0) * t * t + d * t * t * t / 3.0; + (x0 + t, self.m[k - 1] + dm) + } + + /// The compartment `[a, b]` holding `need` with its centroid at `x_c`, or `None` past the hull's ends. + fn compartment(&self, need: f64, x_c: f64) -> Option<(f64, f64)> { + let total = *self.q.last()?; + if need.is_nan() || need <= 0.0 || need > total { + return None; + } + let centroid = |u: f64| -> (f64, f64, f64) { + let (a, ma) = self.at_volume(u, true); + let (b, mb) = self.at_volume(u + need, false); + (a, b, (mb - ma) / need) + }; + let (mut lo, mut hi) = (0.0, total - need); + let (_, _, g_lo) = centroid(lo); + let (_, _, g_hi) = centroid(hi); + let tol = 1e-9 * (self.xs[self.xs.len() - 1] - self.xs[0]).max(1.0); + if x_c < g_lo - tol || x_c > g_hi + tol { + return None; + } + for _ in 0..100 { + let mid = 0.5 * (lo + hi); + if centroid(mid).2 < x_c { + lo = mid; + } else { + hi = mid; + } + if hi - lo <= 1e-13 * total { + break; + } + } + let (a, b, _) = centroid(0.5 * (lo + hi)); + Some((a, b)) + } +} + +/// The trial waterline of trim `trim` tangent to the margin points: its draft and plane. +/// +/// [`waterplane_for`] puts the water at `keel + draft + trim/2` at x = 0 and `keel + draft − trim/2` at +/// x = L, so its height is `c − (trim / L)·x` with `c = keel + draft + trim/2`; touching the margin line from +/// below means `c = min_i (z_i + (trim / L)·x_i)`. +fn tangent_waterline(hull: &Hull, margin: &[Vec3], trim: f64) -> (f64, Plane) { + let l = hull.length.max(1e-6); + let c = margin + .iter() + .map(|q| q.z + trim / l * q.x) + .fold(f64::INFINITY, f64::min); + let draft = c - 0.5 * trim - hull.keel; + ( + draft, + waterplane_for(hull.keel, hull.length, draft, trim, 0.0), + ) +} + +/// Floodable length at `x`, interpolated along the curve; `None` outside it. Points sharing a centre count as +/// one, the longest. +pub fn floodable_at(curve: &FloodableCurve, x: f64) -> Option { + let pts = &curve.points; + let first = pts.first()?; + let last = pts.last()?; + if !(first.x_mid..=last.x_mid).contains(&x) { + return None; + } + // Points sharing a centre count as one, the longest, as `compute` keeps them. + let longest_at = |c: f64| { + pts[pts.partition_point(|p| p.x_mid < c)..pts.partition_point(|p| p.x_mid <= c)] + .iter() + .map(|p| p.length) + .fold(f64::NEG_INFINITY, f64::max) + }; + let k = pts.partition_point(|p| p.x_mid < x); + if pts[k].x_mid == x { + return Some(longest_at(x)); + } + // Strictly between the first and last points here, so 0 < k < len and the points differ in x. + let (x0, x1) = (pts[k - 1].x_mid, pts[k].x_mid); + let (l0, l1) = (longest_at(x0), longest_at(x1)); + let f = (x - x0) / (x1 - x0); + Some(l0 + f * (l1 - l0)) +} + +/// The curves as a standalone SVG chart in English: see [`svg_tr`]. +pub fn svg(res: &FloodableResult, title: &str) -> String { + svg_tr(res, title, crate::i18n::Tr::new(crate::i18n::Locale::En)) +} + +/// The curves as a standalone SVG chart: floodable length over x at one scale for both axes, so the terminals +/// and the bulkhead triangles have their true 2:1 slopes; one curve per permeability, the permissible length of +/// the first curve dashed when a factor is set, a triangle on each compartment of the first curve's check, and +/// below them the hull profile (centreline), the deck edge at side, the margin line and the bulkheads on their +/// own vertical scale. +pub fn svg_tr(res: &FloodableResult, title: &str, tr: crate::i18n::Tr) -> String { + use crate::curves::{chart_frame, esc}; + let (w, h) = (960.0, 600.0); + let (ml, mr, mt) = (64.0, 110.0, 46.0); + let band = 110.0; // profile band height (px) + let gap = 44.0; + let plot_w = w - ml - mr; + let plot_h = h - mt - gap - band - 40.0; + let span = (res.hull_x_fwd - res.hull_x_aft).max(1e-6); + // The curves and the compartments drawn on the first one, so no triangle loses its apex. + let checks = res.curves.first().map_or(&[][..], |c| &c.checks[..]); + let longest = res + .curves + .iter() + .flat_map(|c| c.points.iter().map(|p| p.length)) + .chain(checks.iter().map(|c| c.length)) + .fold(0.0, f64::max) + .max(1e-6); + // One scale for both axes (px per metre). + let k = (plot_w / span).min(plot_h / (1.08 * longest)); + let x0 = ml + 0.5 * (plot_w - k * span); + let base = mt + plot_h; + let sx = |x: f64| x0 + (x - res.hull_x_aft) * k; + let sy = |l: f64| base - l * k; + let top_len = plot_h / k; + + let mut out = String::with_capacity(16 * 1024); + chart_frame(&mut out, title, w, h); + out.push_str("\n"); + let _ = writeln!( + out, + "{}", + esc(title) + ); + + // Axes and grid. + let _ = writeln!( + out, + "", + sx(res.hull_x_aft), + k * span + ); + let step = nice_step(span.max(top_len) / 8.0); + let mut x = (res.hull_x_aft / step).ceil() * step; + while x <= res.hull_x_fwd + 1e-9 { + let _ = writeln!( + out, + "\n{2}", + sx(x), + base + 14.0, + fmt_tick(x) + ); + // Far from the origin `x + step` can round back to `x`. + let next = x + step; + if next <= x { + break; + } + x = next; + } + let mut l = step; + while l <= top_len + 1e-9 { + let _ = writeln!( + out, + "\n{5}", + sx(res.hull_x_aft), + sy(l), + sx(res.hull_x_fwd), + sx(res.hull_x_aft) - 4.0, + sy(l) + 4.0, + fmt_tick(l) + ); + l += step; + } + let _ = writeln!( + out, + "{}", + sx(res.hull_x_aft) - 40.0, + mt + 0.5 * plot_h, + esc(tr.s(Key::FloodableSvgLengthAxis)) + ); + + // Terminals: l = 2 (x − x_aft) and l = 2 (x_fwd − x), up to the top of the plot. + let rise = 0.5 * top_len; + let _ = writeln!( + out, + "", + sx(res.hull_x_aft), + sx(res.hull_x_aft + rise), + sy(top_len) + ); + let _ = writeln!( + out, + "", + sx(res.hull_x_fwd), + sx(res.hull_x_fwd - rise), + sy(top_len) + ); + + // Bulkhead triangles on the first curve's check. + if let Some(first) = res.curves.first() { + for c in &first.checks { + let class = match c.passed { + Some(true) => "pass", + Some(false) => "fail", + None => "unjudged", + }; + let mid = 0.5 * (c.x_aft + c.x_fwd); + let _ = writeln!( + out, + "", + sx(c.x_aft), + sx(mid), + sy(c.length.min(top_len)), + sx(c.x_fwd) + ); + } + } + + // Curves, and the first curve's permissible length. + let poly = |pts: &mut dyn Iterator| -> String { + pts.map(|(x, l)| format!("{:.1},{:.1}", sx(x), sy(l.min(top_len)))) + .collect::>() + .join(" ") + }; + // Labels at each curve's forward end, kept 13 px apart down to the plot's foot; when that many do not fit, + // closer, in a smaller font. + let mut labels: Vec<(f64, f64)> = Vec::new(); + for (i, c) in res.curves.iter().enumerate() { + if c.points.is_empty() { + continue; + } + let _ = writeln!( + out, + "", + i % 4, + poly(&mut c.points.iter().map(|p| (p.x_mid, p.length))) + ); + let last = c.points[c.points.len() - 1]; + labels.push((sy(last.length.min(top_len)) + 4.0, c.permeability)); + } + labels.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (top, foot) = (mt + 10.0, base + 4.0); + let pitch = match labels.len() { + 0 | 1 => 13.0, + n => f64::min(13.0, (foot - top) / (n - 1) as f64), + }; + for i in 1..labels.len() { + labels[i].0 = labels[i].0.max(labels[i - 1].0 + pitch); + } + if let Some(last) = labels.last_mut() { + last.0 = last.0.min(foot); + } + for i in (1..labels.len()).rev() { + labels[i - 1].0 = labels[i - 1].0.min(labels[i].0 - pitch); + } + let font = if pitch < 13.0 { + format!(" style=\"font-size:{:.1}px\"", 11.0 * pitch / 13.0) + } else { + String::new() + }; + for (y, mu) in labels { + let _ = writeln!( + out, + "μ = {mu:.2}", + sx(res.hull_x_fwd) + 6.0 + ); + } + if let (Some(f), Some(first)) = (res.factor, res.curves.first()) { + if !first.points.is_empty() { + let _ = writeln!( + out, + "", + poly(&mut first.points.iter().map(|p| (p.x_mid, f * p.length))) + ); + let _ = writeln!( + out, + "{}", + sx(res.hull_x_aft) + 4.0, + mt + 14.0, + esc(&tr.fmt( + Key::FloodableSvgPermissible, + &[ + ("factor", &format!("{f:.2}")), + ("mu", &format!("{:.2}", first.permeability)) + ] + )) + ); + } + } + if res.curves.iter().all(|c| c.points.is_empty()) { + let _ = writeln!( + out, + "{}", + ml, + mt + 30.0, + esc(tr.s(Key::FloodableSvgEmpty)) + ); + } + + // Profile band: hull, deck edge, margin line, bulkheads. + let band_top = base + gap; + let (z_lo, z_hi) = res + .profile + .iter() + .flatten() + .copied() + .chain(res.margin_line.iter().copied()) + .chain(res.margin_line.iter().map(|p| [p[0], p[1] + res.margin_m])) + .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| { + (lo.min(p[1]), hi.max(p[1])) + }); + if z_lo.is_finite() && z_hi > z_lo { + let kz = (band / (z_hi - z_lo)).min(k); + let sz = |z: f64| band_top + band - (z - z_lo) * kz; + for line in &res.profile { + let pts: Vec = line + .iter() + .map(|p| format!("{:.1},{:.1}", sx(p[0]), sz(p[1]))) + .collect(); + let _ = writeln!( + out, + "", + pts.join(" ") + ); + } + let margin = margin_profile(&res.margin_line); + let deck: Vec = margin + .iter() + .map(|p| format!("{:.1},{:.1}", sx(p[0]), sz(p[1] + res.margin_m))) + .collect(); + let _ = writeln!( + out, + "", + deck.join(" ") + ); + let pts: Vec = margin + .iter() + .map(|p| format!("{:.1},{:.1}", sx(p[0]), sz(p[1]))) + .collect(); + let _ = writeln!( + out, + "", + pts.join(" ") + ); + let _ = writeln!( + out, + "{}", + sx(res.hull_x_fwd) + 6.0, + sz(margin.last().map_or(z_hi, |p| p[1])) + 4.0, + esc(tr.s(Key::FloodableSvgMarginLine)) + ); + if let Some(first) = res.curves.first() { + for c in first.checks.iter().skip(1) { + let _ = writeln!( + out, + "", + sx(c.x_aft), + sz(z_lo), + sz(z_hi) + ); + } + } + } + out.push_str("\n"); + out +} + +/// The lowest margin point at each x, so a deck edge read on both sides draws one line. +fn margin_profile(margin: &[[f64; 2]]) -> Vec<[f64; 2]> { + let mut out: Vec<[f64; 2]> = Vec::new(); + for &p in margin { + match out.last_mut() { + Some(last) if (last[0] - p[0]).abs() < 1e-9 => last[1] = last[1].min(p[1]), + _ => out.push(p), + } + } + out +} + +fn nice_step(raw: f64) -> f64 { + let mag = 10f64.powf(raw.max(1e-9).log10().floor()); + let r = raw / mag; + mag * if r <= 1.0 { + 1.0 + } else if r <= 2.0 { + 2.0 + } else if r <= 5.0 { + 5.0 + } else { + 10.0 + } +} + +fn fmt_tick(v: f64) -> String { + let s = format!("{v:.2}"); + s.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::damage::make_box_barge; + use crate::subdiv::{SubdivisionMode, SubdivisionOptions}; + + const L: f64 = 10.0; + const B: f64 = 4.0; + const D: f64 = 2.0; + const M: f64 = DEFAULT_MARGIN_M; + + fn barge_hull() -> Hull { + Hull::new( + &make_box_barge(L, B, D), + SubdivisionOptions { + level: 0, + mode: SubdivisionMode::Loop, + }, + ) + } + + /// The barge floating `draft` at even keel in water of 1 t/m³, LCG amidships. + fn barge_particulars(draft: f64) -> Particulars { + let displacement_t = L * B * draft; + Particulars { + displacement_t, + kg: 1.0, + lcg: 0.5 * L, + tcg: 0.0, + density: 1.0, + target_volume: displacement_t, + } + } + + fn margin_points(hull: &Hull) -> Vec { + hull_deck_edge_vertices(hull) + .into_iter() + .map(|p| Vec3::new(p.x, p.y, p.z - M)) + .collect() + } + + /// ∫_a^b x^k h(x) dx for the barge's waterline height above the keel h(x) = c − s·x, clamped to [0, D]: + /// exact, split where h meets 0 or D. + fn int_h(a: f64, b: f64, c: f64, s: f64, k: i32) -> f64 { + let mut cuts = vec![a, b]; + if s.abs() > 1e-15 { + for level in [0.0, D] { + let x = (c - level) / s; + if x > a && x < b { + cuts.push(x); + } + } + } + cuts.sort_by(f64::total_cmp); + let mut total = 0.0; + for w in cuts.windows(2) { + let (x0, x1) = (w[0], w[1]); + let h_mid = c - s * 0.5 * (x0 + x1); + if h_mid <= 0.0 { + continue; + } + if h_mid >= D { + // ∫ x^k D dx + total += D * (x1.powi(k + 1) - x0.powi(k + 1)) / f64::from(k + 1); + } else { + // ∫ x^k (c − s x) dx + total += c * (x1.powi(k + 1) - x0.powi(k + 1)) / f64::from(k + 1) + - s * (x1.powi(k + 2) - x0.powi(k + 2)) / f64::from(k + 2); + } + } + total + } + + #[test] + fn tangent_waterline_touches_the_margin_line_and_stays_below_it() { + let hull = barge_hull(); + let margin = margin_points(&hull); + for trim in [-0.5, 0.0, 0.5] { + let (_, wp) = tangent_waterline(&hull, &margin, trim); + let lowest = margin + .iter() + .map(|p| wp.side(*p)) + .fold(f64::INFINITY, f64::min); + assert!(lowest.abs() < 1e-9, "trim {trim}: lowest side {lowest}"); + } + } + + /// Even keel, LCG amidships: the lost volume μ·l·B·z_m equals L·B·z_m − L·B·T, so + /// l = L (z_m − T) / (μ z_m), centred amidships (derived here from the lost-buoyancy balance). + #[test] + fn box_barge_even_keel_point_matches_closed_form() { + let hull = barge_hull(); + let t = 0.80; + let res = compute(&hull, &barge_particulars(t), &FloodableOptions::default()).unwrap(); + let z_m = D - M; + assert_eq!(res.curves.len(), 3); + for curve in &res.curves { + let mu = curve.permeability; + let p = curve + .points + .iter() + .find(|p| p.trim_m.abs() < 1e-9) + .unwrap_or_else(|| panic!("μ {mu}: no even-keel point")); + let expected = L * (z_m - t) / (mu * z_m); + assert!( + (p.x_mid - 0.5 * L).abs() < 1e-3, + "μ {mu}: x_mid {}", + p.x_mid + ); + assert!( + (p.length / expected - 1.0).abs() < 1e-3, + "μ {mu}: length {} vs {expected}", + p.length + ); + } + } + + /// Every point, trimmed or not, satisfies the lost-buoyancy balance computed with exact integrals of the + /// barge's linear waterline: μ B ∫_a^b h = B ∫_0^L h − ∇ and μ B ∫_a^b x h = B ∫_0^L x h − ∇ · LCG. + fn assert_balance(t: f64) { + let hull = barge_hull(); + let res = compute(&hull, &barge_particulars(t), &FloodableOptions::default()).unwrap(); + let vol = L * B * t; + let mut n = 0; + for curve in &res.curves { + let mu = curve.permeability; + for p in &curve.points { + // h(x) = draft + trim/2 − trim·x/L above the keel (z = 0). + let (c, s) = (p.draft + 0.5 * p.trim_m, p.trim_m / L); + let v_w = B * int_h(0.0, L, c, s, 0); + let m_w = B * int_h(0.0, L, c, s, 1); + let v_c = mu * B * int_h(p.x_aft, p.x_fwd, c, s, 0); + let m_c = mu * B * int_h(p.x_aft, p.x_fwd, c, s, 1); + assert!( + (v_c / (v_w - vol) - 1.0).abs() < 2e-3, + "μ {mu} trim {}: volume {v_c} vs {}", + p.trim_m, + v_w - vol + ); + assert!( + (m_c / (m_w - vol * 0.5 * L) - 1.0).abs() < 2e-3, + "μ {mu} trim {}: moment {m_c} vs {}", + p.trim_m, + m_w - vol * 0.5 * L + ); + n += 1; + } + } + assert!(n > 20, "only {n} points"); + } + + #[test] + fn box_barge_trimmed_points_satisfy_the_analytic_balance() { + assert_balance(0.80); + } + + #[test] + fn curve_covers_the_hull_and_stops_inside_its_ends() { + let hull = barge_hull(); + let res = compute( + &hull, + &barge_particulars(0.80), + &FloodableOptions::default(), + ) + .unwrap(); + assert_eq!((res.hull_x_aft, res.hull_x_fwd), (0.0, L)); + for curve in &res.curves { + assert!(curve.points.len() > 5, "μ {}", curve.permeability); + for p in &curve.points { + assert!(p.x_aft >= -1e-9 && p.x_fwd <= L + 1e-9 && p.x_aft < p.x_fwd); + assert!((p.x_mid - 0.5 * (p.x_aft + p.x_fwd)).abs() < 1e-12); + assert!((p.length - (p.x_fwd - p.x_aft)).abs() < 1e-12); + } + for w in curve.points.windows(2) { + assert!(w[0].x_mid <= w[1].x_mid); + assert!(w[1].x_mid - w[0].x_mid <= L / 50.0 + 1e-9, "gap {:?}", w); + } + } + } + + /// A light barge at large trims lifts one end of its bottom clear of the water: sections there are zero, + /// and the balance must still hold with finite, positive lengths. + #[test] + fn a_dried_end_keeps_the_solve_finite() { + let hull = barge_hull(); + let res = compute( + &hull, + &barge_particulars(0.20), + &FloodableOptions::default(), + ) + .unwrap(); + let dried = res.curves.iter().flat_map(|c| &c.points).any(|p| { + let (c, s) = (p.draft + 0.5 * p.trim_m, p.trim_m / L); + c < 0.0 || c - s * L < 0.0 + }); + assert!(dried, "no waterline dried an end"); + for p in res.curves.iter().flat_map(|c| &c.points) { + assert!(p.length.is_finite() && p.length > 0.0 && p.x_mid.is_finite()); + } + assert_balance(0.20); + } + + #[test] + fn heavier_than_the_margin_is_an_error() { + let hull = barge_hull(); + let err = compute( + &hull, + &barge_particulars(1.95), + &FloodableOptions::default(), + ) + .unwrap_err(); + assert!(err.contains("margin line"), "{err}"); + } + + /// Free to trim, a loading heavier than the even-keel margin waterline floats is not too heavy when a + /// trimmed one floats more: a deck rising 1 m from aft to forward puts the margin line at z = 1 + 0.1 x, so + /// at even keel the tangent waterline floats 40 m³ but the one parallel to it 60 m³ (hand integration over + /// the 10 × 4 m box), more than the 50 m³ ship. + #[test] + fn a_rising_margin_line_floods_trimmed_past_the_even_keel_limit() { + let hull = barge_hull(); + let deck: Vec = (0..=10) + .flat_map(|i| { + let x = i as f64; + [-0.5 * B, 0.5 * B].map(|y| Vec3::new(x, y, 1.0 + 0.1 * x + M)) + }) + .collect(); + let p = Particulars { + displacement_t: 50.0, + target_volume: 50.0, + lcg: 5.6, + ..barge_particulars(1.0) + }; + let res = compute_with_deck_edge(&hull, &p, &FloodableOptions::default(), &deck).unwrap(); + for curve in &res.curves { + assert!(!curve.points.is_empty(), "μ {}", curve.permeability); + assert!(curve.points.iter().all(|q| q.trim_m.abs() > 1e-9)); + } + } + + /// The trim that floats most can fall between the sweep's samples: with the margin line at z = 1 + 0.099 x + /// the tangent waterline lies along it at a trim of −0.99 m and floats 4 ∫ (1 + 0.099 x) dx = 59.8 m³, + /// but the 0.05 m samples either side, −0.95 and −1.00 m, float 59.0 and 59.6 m³ (hand integration over the + /// 10 × 4 m box). A 59.7 m³ ship is not too heavy, and with its LCG at 5.551 m, near that waterline's + /// centre of buoyancy (∫ x (1 + 0.099 x) dx / ∫ (1 + 0.099 x) dx = 83 / 14.95 = 5.552 m), the water lost + /// there centres on the hull, so every curve has points. A 59.599 m³ ship floats barely at the −1.00 m + /// sample (59.6 m³, the 0.001 m³ lost centred some 500 m off the hull), and still gets its curves from + /// the trims nearer −0.99 m. + #[test] + fn a_floating_trim_between_the_sweep_samples_is_found() { + let hull = barge_hull(); + let deck: Vec = (0..=10) + .flat_map(|i| { + let x = i as f64; + [-0.5 * B, 0.5 * B].map(|y| Vec3::new(x, y, 1.0 + 0.099 * x + M)) + }) + .collect(); + for volume in [59.7, 59.599] { + let p = Particulars { + displacement_t: volume, + target_volume: volume, + lcg: 5.551, + ..barge_particulars(1.0) + }; + let res = compute_with_deck_edge(&hull, &p, &FloodableOptions::default(), &deck) + .unwrap_or_else(|e| panic!("{volume} m³: {e}")); + for curve in &res.curves { + assert!( + !curve.points.is_empty(), + "{volume} m³, μ {}", + curve.permeability + ); + } + } + } + + /// A 10 m prism of V section, keel at z = 0 and sides y = ±z up to z = 2 m, so a section's area is z². + fn v_prism_hull() -> Hull { + let mut s = make_box_barge(L, B, D); + s.points.clear(); + s.faces.clear(); + s.edges.clear(); + for (x, y, z) in [ + (0.0, 0.0, 0.0), + (L, 0.0, 0.0), + (0.0, -2.0, 2.0), + (L, -2.0, 2.0), + (0.0, 2.0, 2.0), + (L, 2.0, 2.0), + ] { + s.add_point(Vec3::new(x, y, z)); + } + for face in [ + vec![0, 1, 3, 2], + vec![1, 0, 4, 5], + vec![2, 3, 5, 4], + vec![0, 2, 4], + vec![1, 5, 3], + ] { + s.add_face(face, 0); + } + s.initialize_trace(); + for edge in &mut s.edges { + edge.crease = true; + } + for point in &mut s.points { + point.kind = crate::mesh::VertexKind::Corner; + } + Hull::new( + &s, + SubdivisionOptions { + level: 0, + mode: SubdivisionMode::Loop, + }, + ) + } + + /// The trim that floats most can lie between samples around a peak other than the highest sample. On the + /// V prism with a sagging margin line at 1.40, 1.00 and 1.4125 m over x = 0, 5 and 10 m, a waterline through + /// the midship point at slope s floats ∫ (1 + s (x − 5))² dx = 10 + (5/6) τ² (τ = 10 s, hand integration) + /// until it lies along one of the two sheer lines: at |τ| = 0.80 m it floats 10.533 m³, on a 0.05 m sample, + /// and at |τ| = 0.825 m, between samples, 10.567 m³. A 10.55 m³ ship is not too heavy, whichever end the + /// steeper sheer is at. + #[test] + fn a_floating_trim_around_a_lower_sampled_peak_is_found() { + let hull = v_prism_hull(); + for (aft, fwd) in [(1.40, 1.4125), (1.4125, 1.40)] { + let deck: Vec = [(0.0, aft), (5.0, 1.0), (L, fwd)] + .into_iter() + .flat_map(|(x, z)| [-2.0, 2.0].map(|y| Vec3::new(x, y, z + M))) + .collect(); + let p = Particulars { + displacement_t: 10.55, + target_volume: 10.55, + ..barge_particulars(1.0) + }; + let res = compute_with_deck_edge(&hull, &p, &FloodableOptions::default(), &deck); + assert!(res.is_ok(), "sheer {aft}/{fwd}: {:?}", res.err()); + } + } + + /// A margin line dipping close to the keel at one end (z = 0.2 + 0.18 x) makes the fine trim step small; + /// the sweep must still reach the trims where the ship floats. The waterline parallel to that line floats + /// B ∫ (0.2 + 0.18 x) dx = 4 · 11 = 44 m³ (hand integration), more than the 30 m³ ship, at a trim of 1.8 m, + /// beyond the 1.0 m the old 0.01 m step reached in its 100 steps. + #[test] + fn a_margin_line_near_the_keel_still_sweeps_the_whole_trim_range() { + let hull = barge_hull(); + let deck: Vec = (0..=10) + .flat_map(|i| { + let x = i as f64; + [-0.5 * B, 0.5 * B].map(|y| Vec3::new(x, y, 0.2 + 0.18 * x + M)) + }) + .collect(); + let p = Particulars { + displacement_t: 30.0, + target_volume: 30.0, + lcg: 6.5, + ..barge_particulars(1.0) + }; + let res = compute_with_deck_edge(&hull, &p, &FloodableOptions::default(), &deck).unwrap(); + assert!( + res.curves + .iter() + .any(|c| c.points.iter().any(|q| q.trim_m.abs() > 1.0)), + "{:?}", + res.curves + .iter() + .map(|c| c.points.len()) + .collect::>() + ); + } + + /// With both ends of the hull dry under a waterline, a compartment holding all the water spans only the + /// wet part, the same at either end: dry [0, 2] and [4, 6] m around 1 m³ in each of [2, 3] and [3, 4] m + /// (sectional area linear 0 → 2 → 0 m², centroids 8/3 and 10/3 m) gives [2, 4] m. + #[test] + fn a_compartment_stops_at_the_water_at_both_dry_ends() { + let cum = Cumulative::new( + (0..=6).map(f64::from).collect(), + vec![0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0], + ); + let (a, b) = cum.compartment(2.0, 3.0).unwrap(); + assert!( + (a - 2.0).abs() < 1e-9 && (b - 4.0).abs() < 1e-9, + "[{a}, {b}]" + ); + } + + /// Inside one station interval the compartment's centroid is the slice's own: a unit sectional area over + /// [0, 2] m with stations at 0, 1 and 2 m puts 0.25 m³ centred at 0.25 m in [0.125, 0.375] m; and a + /// sectional area rising 0 → 2 m² over [0, 1] m (Q = x², M = 2x³/3) puts the 0.25 m³ after the first in + /// [0.5, √0.5] m, centred at (2/3)(√0.5³ − 0.5³)/0.25 m. + #[test] + fn a_compartment_inside_one_station_interval_has_its_own_centroid() { + let flat = Cumulative::new(vec![0.0, 1.0, 2.0], vec![1.0; 3]); + let (a, b) = flat.compartment(0.25, 0.25).unwrap(); + assert!( + (a - 0.125).abs() < 1e-9 && (b - 0.375).abs() < 1e-9, + "[{a}, {b}]" + ); + let rising = Cumulative::new(vec![0.0, 1.0], vec![0.0, 2.0]); + let fwd = 0.5f64.sqrt(); + let x_c = 2.0 / 3.0 * (fwd.powi(3) - 0.125) / 0.25; + let (a, b) = rising.compartment(0.25, x_c).unwrap(); + assert!( + (a - 0.5).abs() < 1e-9 && (b - fwd).abs() < 1e-9, + "[{a}, {b}]" + ); + } + + /// Two trials centred at one x give the longest of their lengths there, whichever sorts first. + #[test] + fn floodable_at_a_shared_centre_is_the_longest() { + let pt = |x_mid: f64, length: f64| FloodablePoint { + x_mid, + length, + x_aft: x_mid - 0.5 * length, + x_fwd: x_mid + 0.5 * length, + trim_m: 0.0, + draft: 1.0, + }; + // Both orders of the shared centre, at either end of an interval, interpolate from the longest. + for points in [ + vec![pt(4.0, 1.0), pt(5.0, 2.0), pt(5.0, 4.0), pt(6.0, 1.0)], + vec![pt(4.0, 1.0), pt(5.0, 4.0), pt(5.0, 2.0), pt(6.0, 1.0)], + ] { + let curve = FloodableCurve { + permeability: 0.85, + points, + checks: Vec::new(), + }; + assert_eq!(floodable_at(&curve, 5.0), Some(4.0)); + assert_eq!(floodable_at(&curve, 4.5), Some(2.5)); + assert_eq!(floodable_at(&curve, 5.5), Some(2.5)); + assert_eq!(floodable_at(&curve, 4.0), Some(1.0)); + assert_eq!(floodable_at(&curve, 6.0), Some(1.0)); + } + // Unique centres interpolate as before. + let curve = FloodableCurve { + permeability: 0.85, + points: vec![pt(4.0, 1.0), pt(5.0, 3.0), pt(6.0, 1.0)], + checks: Vec::new(), + }; + assert_eq!(floodable_at(&curve, 4.5), Some(2.0)); + } + + #[test] + fn floodable_at_a_nan_is_none() { + let hull = barge_hull(); + let res = compute(&hull, &barge_particulars(0.8), &FloodableOptions::default()).unwrap(); + assert_eq!(floodable_at(&res.curves[0], f64::NAN), None); + } + + #[test] + fn too_many_stations_is_an_error() { + let hull = barge_hull(); + let opts = FloodableOptions { + stations: MAX_STATIONS + 1, + ..FloodableOptions::default() + }; + let err = compute(&hull, &barge_particulars(0.8), &opts).unwrap_err(); + assert!(err.contains("too many"), "{err}"); + } + + fn barge_surface_options() -> (Surface, HydroOptions) { + let surface = make_box_barge(L, B, D); + let hopts = HydroOptions::from_surface( + &surface, + SubdivisionOptions { + level: 0, + mode: SubdivisionMode::Loop, + }, + ); + (surface, hopts) + } + + /// A loading condition named but not resolved through a project is an error, as in `damage::evaluate`, + /// not the design-draft loading. + #[test] + fn an_unresolved_loading_condition_name_is_an_error() { + let (surface, hopts) = barge_surface_options(); + let case = DamageCase { + loading_condition_name: Some("Departure".into()), + ..DamageCase::default() + }; + let err = evaluate(&surface, &hopts, &case, &FloodableOptions::default()).unwrap_err(); + assert!(err.contains("Departure"), "{err}"); + } + + /// A model's water density that is not water is an error, never floored to 100 kg/m³; a case's own + /// density still overrides the model's. + #[test] + fn a_water_density_that_is_not_water_is_an_error() { + let (surface, mut hopts) = barge_surface_options(); + let case = DamageCase { + displacement_t: Some(L * B * 0.8), + kg: Some(0.0), + ..DamageCase::default() + }; + for rho in [0.0, -1025.0, f64::NAN, f64::INFINITY, 50.0, 1.025] { + hopts.water_density = rho; + let err = evaluate(&surface, &hopts, &case, &FloodableOptions::default()).unwrap_err(); + assert!(err.contains("water density"), "{rho}: {err}"); + } + // A case's density is in t/m³: 1025 is kg/m³ given by mistake. + hopts.water_density = 1000.0; + for rho in [0.0, f64::NAN, 1025.0] { + let bad = DamageCase { + water_density: Some(rho), + ..case.clone() + }; + let err = evaluate(&surface, &hopts, &bad, &FloodableOptions::default()).unwrap_err(); + assert!(err.contains("water_density"), "{rho}: {err}"); + } + hopts.water_density = 0.0; + let own = DamageCase { + water_density: Some(1.0), + ..case + }; + let res = evaluate(&surface, &hopts, &own, &FloodableOptions::default()).unwrap(); + assert_eq!(res.water_density, 1.0); + } + + /// An appendage coefficient below 10⁻⁶ is an error, not floored to 10⁻⁶ (which would float another volume); + /// an invalid inline loading condition is an error, as in `damage::evaluate`. + #[test] + fn a_bad_appendage_coefficient_or_loading_condition_is_an_error() { + let (surface, mut hopts) = barge_surface_options(); + let case = DamageCase { + displacement_t: Some(L * B * 0.8), + kg: Some(0.0), + ..DamageCase::default() + }; + for c in [0.0, -1.0, f64::NAN, 5e-7] { + hopts.appendage_coefficient = c; + let err = evaluate(&surface, &hopts, &case, &FloodableOptions::default()).unwrap_err(); + assert!(err.contains("appendage"), "{c}: {err}"); + } + hopts.appendage_coefficient = 1.0; + let lc: crate::loading::LoadingCondition = serde_json::from_str( + r#"{"name": "Bad", "lightship": {"name": "Lightship", "mass_t": -5.0, "x": 5.0, "y": 0.0, "z": 1.0}}"#, + ) + .unwrap(); + let bad = DamageCase { + loading_condition: Some(lc), + ..DamageCase::default() + }; + let err = evaluate(&surface, &hopts, &bad, &FloodableOptions::default()).unwrap_err(); + assert!(err.contains("loading condition"), "{err}"); + } + + #[test] + fn bad_permeability_is_an_error() { + let hull = barge_hull(); + for mu in [0.0, 1.2, f64::NAN] { + let opts = FloodableOptions { + permeabilities: vec![0.85, mu], + ..FloodableOptions::default() + }; + let err = compute(&hull, &barge_particulars(0.8), &opts).unwrap_err(); + assert!( + err.contains("permeability") && err.contains(&format!("{mu}")), + "{err}" + ); + } + } + + #[test] + fn a_hull_without_a_deck_edge_is_an_error() { + let hull = barge_hull(); + let err = compute_with_deck_edge( + &hull, + &barge_particulars(0.8), + &FloodableOptions::default(), + &[], + ) + .unwrap_err(); + assert!(err.contains("deck edge"), "{err}"); + } + + /// A loading that is not a ship (no displacement, no water, an LCG that is not a number) is an error, never + /// a curve computed from NaN. + #[test] + fn unphysical_particulars_are_errors() { + let hull = barge_hull(); + let good = barge_particulars(0.8); + let cases = [ + Particulars { + displacement_t: 0.0, + target_volume: 0.0, + ..good + }, + Particulars { + displacement_t: -5.0, + target_volume: -5.0, + ..good + }, + Particulars { + displacement_t: f64::NAN, + target_volume: f64::NAN, + ..good + }, + Particulars { + density: 0.0, + ..good + }, + Particulars { + lcg: f64::NAN, + ..good + }, + Particulars { + lcg: f64::INFINITY, + ..good + }, + ]; + for p in cases { + let res = compute(&hull, &p, &FloodableOptions::default()); + assert!(res.is_err(), "{p:?} gave {:?}", res.map(|r| r.curves)); + } + } + + /// Hull ends come from the hull's own panels: a vertex the panels do not use (a layer that is not part of + /// the hydrostatic hull) does not move them. + #[test] + fn hull_ends_ignore_vertices_outside_the_panels() { + let mut hull = barge_hull(); + hull.verts.push(Vec3::new(-3.0, 0.0, 1.0)); + hull.verts.push(Vec3::new(L + 3.0, 0.0, 1.0)); + let res = compute(&hull, &barge_particulars(0.8), &FloodableOptions::default()).unwrap(); + assert_eq!((res.hull_x_aft, res.hull_x_fwd), (0.0, L)); + } + + /// A permeability's curve does not depend on which other permeabilities are asked with it. Light (8 t) + /// the demo hull at even keel needs more than its whole volume for μ 0.60, so that curve starts only + /// several trims out from even keel. + #[test] + fn a_curve_does_not_depend_on_the_other_permeabilities() { + let surface = crate::demo::demo_hull(false); + let hopts = HydroOptions::from_surface( + &surface, + SubdivisionOptions { + level: 2, + mode: SubdivisionMode::Loop, + }, + ); + let case = DamageCase { + displacement_t: Some(8.0), + kg: Some(0.0), + ..DamageCase::default() + }; + let run = |permeabilities: Vec| { + let opts = FloodableOptions { + permeabilities, + ..FloodableOptions::default() + }; + evaluate(&surface, &hopts, &case, &opts).unwrap() + }; + let alone = run(vec![0.60]); + let together = run(vec![0.60, 0.85, 0.95]); + let (a, t) = (&alone.curves[0], &together.curves[0]); + assert!(t.points.len() > 10, "together: {} points", t.points.len()); + assert!(a.points.len() > 10, "alone: {} points", a.points.len()); + let x = 0.5 * (t.points[0].x_mid + t.points[t.points.len() - 1].x_mid); + let (la, lt) = (floodable_at(a, x).unwrap(), floodable_at(t, x).unwrap()); + assert!( + (la / lt - 1.0).abs() < 1e-2, + "at x {x}: {la} alone, {lt} together" + ); + } + + fn check_opts(bulkheads: Vec, factor: Option) -> FloodableOptions { + FloodableOptions { + permeabilities: vec![0.85], + factor, + bulkheads, + ..FloodableOptions::default() + } + } + + #[test] + fn bulkheads_split_the_hull_and_are_judged_at_their_midpoints() { + let hull = barge_hull(); + let opts = check_opts(vec![2.0, 4.0, 6.0, 8.0], Some(0.5)); + let res = compute(&hull, &barge_particulars(0.8), &opts).unwrap(); + let curve = &res.curves[0]; + assert_eq!(res.factor, Some(0.5)); + assert_eq!(curve.checks.len(), 5); + let bounds = [0.0, 2.0, 4.0, 6.0, 8.0, L]; + let mut judged = 0; + for (c, w) in curve.checks.iter().zip(bounds.windows(2)) { + assert_eq!((c.x_aft, c.x_fwd), (w[0], w[1])); + assert!((c.length - (w[1] - w[0])).abs() < 1e-12); + if let Some(f) = c.floodable { + assert_eq!(Some(f), floodable_at(curve, 0.5 * (w[0] + w[1]))); + let permissible = c.permissible.unwrap(); + assert!((permissible - 0.5 * f).abs() < 1e-12); + assert_eq!(c.passed, Some(c.length <= permissible)); + judged += 1; + } + } + assert!(judged >= 3, "{judged} judged"); + // Amidships the floodable length is 6.87 m (μ 0.85): permissible 3.44 m, so a 2 m compartment passes. + assert_eq!(curve.checks[2].passed, Some(true)); + } + + #[test] + fn a_compartment_outside_the_curve_is_not_judged() { + let hull = barge_hull(); + // The μ 0.85 curve starts near x = 1.1 m: a 1 m end compartment (centre 0.5 m) lies outside it. + let opts = check_opts(vec![1.0, 9.0], None); + let res = compute(&hull, &barge_particulars(0.8), &opts).unwrap(); + let first = &res.curves[0].checks[0]; + assert!(res.curves[0].points[0].x_mid > 0.5); + assert_eq!(first.passed, None); + assert_eq!(first.floodable, None); + assert!(first.reason.is_some()); + // Without a factor, permissible length is the floodable length itself (F = 1). + let mid = &res.curves[0].checks[1]; + assert_eq!(mid.permissible, mid.floodable); + } + + #[test] + fn unsorted_or_outside_bulkheads_are_errors() { + let hull = barge_hull(); + for bulkheads in [ + vec![4.0, 2.0], + vec![3.0, 3.0], + vec![-1.0], + vec![11.0], + vec![f64::NAN], + ] { + let err = compute( + &hull, + &barge_particulars(0.8), + &check_opts(bulkheads.clone(), None), + ) + .unwrap_err(); + assert!(err.contains("bulkhead"), "{bulkheads:?}: {err}"); + } + } + + #[test] + fn factor_outside_zero_one_is_an_error() { + let hull = barge_hull(); + for f in [0.0, 1.5, f64::NAN] { + let err = compute( + &hull, + &barge_particulars(0.8), + &check_opts(vec![5.0], Some(f)), + ) + .unwrap_err(); + assert!(err.contains("factor of subdivision"), "{f}: {err}"); + } + } + + fn demo_hydro_options() -> (Surface, HydroOptions) { + let surface = crate::demo::demo_hull(false); + let hopts = HydroOptions::from_surface( + &surface, + SubdivisionOptions { + level: 3, + mode: SubdivisionMode::Loop, + }, + ); + (surface, hopts) + } + + /// Two SeaCraft methods agree (not an external source): flooding the compartment a curve point gives, as an + /// ordinary damage case (lost buoyancy, compartment clipped to the hull), floats the demo hull upright with + /// its deck edge 76 mm clear, i.e. the margin line awash, at the point's trim. Tolerances: the curve + /// integrates 201 sectional areas, the damage case a clipped solid of the refined hull; 5 mm of freeboard + /// and 20 mm of trim cover that difference on a 12 m hull. + #[test] + fn curve_points_flood_the_demo_hull_to_its_margin_line() { + use crate::damage::{Compartment, CompartmentSpec}; + let (surface, hopts) = demo_hydro_options(); + let opts = FloodableOptions { + permeabilities: vec![0.85], + ..FloodableOptions::default() + }; + let res = evaluate(&surface, &hopts, &DamageCase::default(), &opts).unwrap(); + let pts = &res.curves[0].points; + assert!(pts.len() > 10, "{} points", pts.len()); + let hull = Hull::new(&surface, hopts.subdivision); + for p in [pts[0], pts[pts.len() / 2], pts[pts.len() - 1]] { + let case = DamageCase { + name: "floodable point".into(), + compartments: vec![CompartmentSpec::Inline(Compartment { + name: "flooded".into(), + x_min: p.x_aft, + x_max: p.x_fwd, + y_min: -1e3, + y_max: 1e3, + z_min: hull.keel - 1.0, + z_max: hull.model_max.z + 1.0, + permeability: 0.85, + clip_to_hull: true, + })], + displacement_t: Some(res.displacement_t), + kg: Some(0.75 * (hull.model_max.z - hull.keel)), + lcg: Some(res.lcg), + water_density: Some(res.water_density), + ..DamageCase::default() + }; + let d = crate::damage::evaluate(&surface, &hopts, &case).unwrap(); + assert!( + d.heel_deg.abs() < 0.05, + "x {}: heel {}", + p.x_mid, + d.heel_deg + ); + let fb = d.freeboard_m.unwrap(); + assert!( + (fb - DEFAULT_MARGIN_M).abs() < 0.005, + "x {}: freeboard {fb} m", + p.x_mid + ); + assert!( + (d.trim_m - p.trim_m).abs() < 0.02, + "x {}: trim {} vs {}", + p.x_mid, + d.trim_m, + p.trim_m + ); + } + } + + /// Not published: recorded from SeaCraft on 2026-11-26 (demo hull, level 3, design draft, μ 0.85), to + /// catch a change, not to show the numbers are right (`docs/oracles.md`). The shape agrees with Gillmer & + /// Johnson's remark that the curve is "usually greatest amidships and least near the quarter length": here + /// least at the aft end, where the transom terminates it. + #[test] + fn demo_hull_curve_recorded() { + let (surface, hopts) = demo_hydro_options(); + let opts = FloodableOptions { + permeabilities: vec![0.85], + ..FloodableOptions::default() + }; + let res = evaluate(&surface, &hopts, &DamageCase::default(), &opts).unwrap(); + let close = |got: f64, want: f64| (got / want - 1.0).abs() < 5e-3; + assert!(close(res.displacement_t, 12.1), "Δ {}", res.displacement_t); + assert!(close(res.lcg, 4.30), "LCG {}", res.lcg); + let curve = &res.curves[0]; + assert!(curve.points.len() > 40, "{} points", curve.points.len()); + let min = curve + .points + .iter() + .min_by(|a, b| a.length.total_cmp(&b.length)) + .unwrap(); + assert!(close(min.length, 1.39), "least {} m", min.length); + assert!(close(min.x_mid, 0.701), "least at x {} m", min.x_mid); + let mid = floodable_at(curve, 6.0).unwrap(); + assert!(close(mid, 3.37), "at x = 6 m: {mid} m"); + } + + #[test] + fn svg_has_a_curve_per_permeability_and_a_triangle_per_compartment() { + let hull = barge_hull(); + let opts = FloodableOptions { + factor: Some(0.5), + bulkheads: vec![2.0, 4.0, 6.0, 8.0], + ..FloodableOptions::default() + }; + let res = compute(&hull, &barge_particulars(0.8), &opts).unwrap(); + assert!(!res.profile.is_empty()); + let en = svg(&res, "Barge "); + assert_eq!(en.matches("class=\"curve").count(), 3); + assert_eq!(en.matches("class=\"triangle").count(), 5); + assert_eq!(en.matches("class=\"permissible\"").count(), 1); + assert_eq!(en.matches("class=\"terminal\"").count(), 2); + assert!(en.contains("class=\"margin\"")); + assert!(en.contains("class=\"hull\"")); + assert!(en.contains("Barge <test>")); + assert!(en.contains("Floodable length")); + let tr = svg_tr(&res, "Duba", crate::i18n::Tr::new(crate::i18n::Locale::Tr)); + assert!(tr.contains("Su alabilir boy"), "{tr}"); + assert!(tr.contains("Sınır hattı")); + } + + /// The `(x, y)` points of each bulkhead triangle in an SVG. + fn triangles(svg: &str) -> Vec> { + svg.lines() + .filter(|l| l.contains("class=\"triangle")) + .map(|l| { + let pts = l + .split("points=\"") + .nth(1) + .unwrap() + .split('"') + .next() + .unwrap(); + pts.split(' ') + .map(|xy| { + let (x, y) = xy.split_once(',').unwrap(); + (x.parse().unwrap(), y.parse().unwrap()) + }) + .collect() + }) + .collect() + } + + /// A compartment longer than any floodable length still gets its whole triangle, as high as it is long, on + /// the one scale of both axes: deep in the water (1.90 m of the 1.924 m to the margin line) the curves are + /// short, the middle compartment is 8 m. + #[test] + fn the_plot_scale_holds_the_longest_compartment() { + let hull = barge_hull(); + let opts = FloodableOptions { + bulkheads: vec![1.0, 9.0], + ..FloodableOptions::default() + }; + let res = compute(&hull, &barge_particulars(1.90), &opts).unwrap(); + let longest = res + .curves + .iter() + .flat_map(|c| &c.points) + .map(|p| p.length) + .fold(0.0, f64::max); + assert!(longest < 8.0, "longest point {longest} m"); + let tris = triangles(&svg(&res, "Barge")); + assert_eq!(tris.len(), 3); + for t in tris { + let (base, apex) = ((t[2].0 - t[0].0), (t[0].1 - t[1].1)); + assert!( + (apex - base).abs() < 0.3, + "base {base} px, height {apex} px" + ); + } + } + + /// The y of every `<{tag} class="{class}" …>` attribute `attr`, or of every point of its `points`. + fn ys(svg: &str, tag: &str, class: &str, attr: &str) -> Vec { + let open = format!("<{tag} class=\"{class}\""); + svg.lines() + .filter(|l| l.starts_with(&open)) + .flat_map(|l| { + let key = format!(" {attr}=\""); + let v = &l[l.find(&key).unwrap() + key.len()..]; + let v = &v[..v.find('"').unwrap()]; + if attr == "points" { + v.split(' ') + .map(|p| p.split(',').nth(1).unwrap().parse().unwrap()) + .collect::>() + } else { + vec![v.parse().unwrap()] + } + }) + .collect() + } + + /// Every permeability's label stays beside the plot, between 10 px under its top (46 px) and 4 px under its + /// base (406 px), clear of the profile band and of each other, however many curves: 48 of them on the barge + /// at 0.8 m all have points. + #[test] + fn every_permeability_label_stays_inside_the_chart() { + let hull = barge_hull(); + let opts = FloodableOptions { + permeabilities: (0..48).map(|i| 0.60 + 0.4 * f64::from(i) / 47.0).collect(), + ..FloodableOptions::default() + }; + let res = compute(&hull, &barge_particulars(0.8), &opts).unwrap(); + assert!(res.curves.iter().all(|c| !c.points.is_empty())); + let out = svg(&res, "Barge"); + let labels: Vec = out + .lines() + .filter(|l| l.contains(">μ = ")) + .map(|l| { + let v = &l[l.find(" y=\"").unwrap() + 4..]; + v[..v.find('"').unwrap()].parse().unwrap() + }) + .collect(); + assert_eq!(labels.len(), 48); + assert!( + labels.iter().all(|&y| (55.95..=410.05).contains(&y)), + "{labels:?}" + ); + assert!(labels.windows(2).all(|w| w[1] > w[0]), "{labels:?}"); + } + + /// A side deck above the centreline profile is drawn inside the profile band (y 450 to 560 px): a profile + /// from z = 0 to 1 m, the deck at 2 m and the margin line 1.1 m under it. + #[test] + fn the_side_deck_stays_inside_the_profile_band() { + let res = FloodableResult { + displacement_t: 1.0, + lcg: 5.0, + water_density: 1.0, + margin_m: 1.1, + hull_x_aft: 0.0, + hull_x_fwd: 10.0, + factor: None, + margin_line: vec![[0.0, 0.9], [10.0, 0.9]], + curves: Vec::new(), + warnings: Vec::new(), + profile: vec![vec![ + [0.0, 0.0], + [10.0, 0.0], + [10.0, 1.0], + [0.0, 1.0], + [0.0, 0.0], + ]], + }; + let deck = ys(&svg(&res, "Deck"), "polyline", "deck", "points"); + assert!(!deck.is_empty()); + assert!( + deck.iter().all(|&y| (449.9..=560.1).contains(&y)), + "{deck:?}" + ); + } + + /// Hull ends far from the origin, where `x + step` rounds back to `x`, still end the x ticks. + #[test] + fn far_from_the_origin_the_ticks_end() { + let res = FloodableResult { + displacement_t: 1.0, + lcg: 0.0, + water_density: 1.0, + margin_m: M, + hull_x_aft: 1e16, + hull_x_fwd: 1e16 + 2.0, + factor: None, + margin_line: Vec::new(), + curves: Vec::new(), + warnings: Vec::new(), + profile: Vec::new(), + }; + let out = svg(&res, "Far"); + assert!(out.len() < 100_000, "{} bytes", out.len()); + } +} diff --git a/crates/seacraft-core/src/lib.rs b/crates/seacraft-core/src/lib.rs index 360f6af..f9c5603 100644 --- a/crates/seacraft-core/src/lib.rs +++ b/crates/seacraft-core/src/lib.rs @@ -47,6 +47,7 @@ pub mod examples; pub mod export; pub mod fef; pub mod flatten; +pub mod floodable; /// The embedded DejaVu fonts and their licence. pub mod fonts; pub mod heel; diff --git a/docs/architecture.md b/docs/architecture.md index da8421b..3c19197 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -41,6 +41,7 @@ crates/seacraft-core/ src/weather.rs IMO 2008 IS Code Part A §2.3 severe wind and rolling (weather) criterion src/loading.rs loading conditions: weights, tanks (box/hull-clipped), FSM/FSC, equilibrium + IMO src/damage.rs deterministic damage stability: lost buoyancy, equilibrium draft/trim/heel, residual GZ & SOLAS criteria + src/floodable.rs floodable length curves by trial waterlines, permissible length, bulkhead check, SVG plot src/linesplan.rs stations/buttocks/waterlines -> SVG/DXF/IGES + combs src/dxf.rs AutoCAD 2000 (AC1015) writer (ported, see ATTRIBUTION) src/templates.rs builder patterns: station moulds, profile, transom; skin deduction diff --git a/docs/i18n-glossary-tr.md b/docs/i18n-glossary-tr.md index 043b8f6..7fbf405 100644 --- a/docs/i18n-glossary-tr.md +++ b/docs/i18n-glossary-tr.md @@ -40,6 +40,10 @@ Terminology conventions for SeaCraft's Turkish (`tr`) translation. | Loading condition | Yükleme durumu | Yükleme durumu | | | Tank / Free surface | Tank / Serbest yüzey | Tank / Serbest yüzey | | | Damage stability / Compartment | Yaralı stabilite / Bölme | Yaralı stabilite / Bölme | | +| Floodable length | Su alabilir boy | Su alabilir boy | Maintainer's choice (2026-11-26) | +| Margin line | Sınır hattı | Sınır hattı | Maintainer's choice (2026-11-26) | +| Bulkhead | Perde | Perde | | +| Permissible length / Factor of subdivision | İzin verilen boy / Bölmelendirme faktörü | İzin verilen boy / Bölm. faktörü | | | Windage / Weather criterion | Rüzgâr alanı / Hava kriteri | Rüzgâr alanı / Hava kriteri | | | Resistance | Direnç | Direnç | | | Wave pattern | Dalga deseni | Dalga deseni | | diff --git a/docs/oracles.md b/docs/oracles.md index 142f429..d2fa82a 100644 --- a/docs/oracles.md +++ b/docs/oracles.md @@ -2119,3 +2119,112 @@ fillet figures are the tests' own inputs, not published values. Hand-derived: the fillet cross-section (plane geometry above), the box seams and the V bottom's angle. Nothing here is published; the figures are the builder's numbers applied to the modelled surface, not validated (`DISCLAIMER.md`), with no laminate thickness offset. + +--- + +## 53. Floodable Length: Box Barge Closed Form and Lost-Buoyancy Balance + +### Formula +The floodable length at a point is the length of a compartment, with that point as centre, that can be flooded +without immersing any part of the margin line when the ship has no list; the margin line is at least 76 mm (3 in) +below the bulkhead deck at side. Each trial waterline $W$ is tangent to the margin line; with $V_W$ and $x_B$ the +volume and centroid under it, $\nabla$ the floating volume and $\mu$ the permeability, the lost volume and its +centroid are +$$v = V_W - \nabla, \qquad x_c = \frac{V_W x_B - \nabla \cdot LCG}{v},$$ +and the compartment $[a, b]$ holds $v / \mu$ under $W$ with its centroid at $x_c$. + +For a box barge $L \times B \times D$ floating at $T$ with $LCG = L/2$ and margin line height $z_m = D - m$, the +even-keel point is amidships with +$$l = \frac{L (z_m - T)}{\mu \, z_m}.$$ +At a trimmed waterline the height above the keel is linear, $h(x) = c - s x$ (clamped to $[0, D]$), and the balance +$\mu B \int_a^b h\,dx = B \int_0^L h\,dx - \nabla$, $\mu B \int_a^b x h\,dx = B \int_0^L x h\,dx - \nabla \cdot L/2$ +is evaluated with exact piecewise integrals. + +### Tests +`crates/seacraft-core/src/floodable.rs`: +- `box_barge_even_keel_point_matches_closed_form`: $L = 10$, $B = 4$, $D = 2$ m, $T = 0.80$ m, $\rho = 1$ t/m³, + $m = 0.076$ m ($z_m = 1.924$ m), $\mu \in \{0.60, 0.85, 0.95\}$: $x_{mid} = 5.0$ m within $10^{-3}$ m and + $l = 5.842 / \mu$ m within $10^{-3}$ relative (9.737, 6.873, 6.149 m). +- `box_barge_trimmed_points_satisfy_the_analytic_balance`: every point of the three curves satisfies both balance + equations within $2 \times 10^{-3}$ relative. +- `a_dried_end_keeps_the_solve_finite`: the same at $T = 0.20$ m, where some trial waterlines lift one end of the + bottom out of the water. +- `tangent_waterline_touches_the_margin_line_and_stays_below_it`, `curve_covers_the_hull_and_stops_inside_its_ends`, + `bulkheads_split_the_hull_and_are_judged_at_their_midpoints` (factor 0.5: amidships 6.87 m floodable, 3.44 m + permissible, a 2 m compartment passes), `a_compartment_outside_the_curve_is_not_judged`, + `hull_ends_ignore_vertices_outside_the_panels`, and the error tests (`unphysical_particulars_are_errors` among them). +- `a_rising_margin_line_floods_trimmed_past_the_even_keel_limit`: the same box with a margin line + $z = 1 + 0.1x$ m (a deck rising 1 m aft to forward) and $\nabla = 50$ m³, $LCG = 5.6$ m. The even-keel tangent + waterline floats $B \cdot L \cdot 1 = 40$ m³, less than the ship; the waterline parallel to the margin line floats + $B \int_0^L (1 + 0.1x)\,dx = 60$ m³, more. Free to trim, every curve has points, all at nonzero trim, and no + error is raised. +- `a_margin_line_near_the_keel_still_sweeps_the_whole_trim_range`: the same box with a margin line + $z = 0.2 + 0.18x$ m, $\nabla = 30$ m³, $LCG = 6.5$ m. The waterline parallel to it, at a trim of 1.8 m, floats + $B \int_0^L (0.2 + 0.18x)\,dx = 44$ m³; the sweep reaches trims beyond 1.0 m and finds points there. +- `a_floating_trim_between_the_sweep_samples_is_found`: the same box with a margin line $z = 1 + 0.099x$ m. The + waterline along it, at a trim of −0.99 m, floats $B \int_0^L (1 + 0.099x)\,dx = 59.8$ m³ with + $x_B = 83 / 14.95 = 5.552$ m; the 0.05 m samples either side, −0.95 and −1.00 m, float 59.0 and 59.6 m³. With + $LCG = 5.551$ m, $\nabla = 59.7$ m³ (no sample floats it) and $\nabla = 59.599$ m³ (the −1.00 m sample floats it + by 0.001 m³, centred some 500 m off the hull) each give points on every curve and no error. +- `a_floating_trim_around_a_lower_sampled_peak_is_found`: a 10 m prism of V section (sides $y = \pm z$, sectional + area $z^2$) with a margin line through 1.40, 1.00 and 1.4125 m at $x = 0$, 5 and 10 m, and its mirror image. A + waterline through the midship point at trim $\tau$ floats $\int_0^L (1 + \tau (x - 5)/L)^2\,dx = 10 + \tfrac56 + \tau^2$ m³ until it lies along a sheer line: 10.533 m³ at $|\tau| = 0.80$ m (a sample) and 10.567 m³ at + $|\tau| = 0.825$ m (between samples). $\nabla = 10.55$ m³ is not too heavy in either orientation. +- `a_compartment_stops_at_the_water_at_both_dry_ends`: cumulative volumes by construction, dry over $[0, 2]$ and + $[4, 6]$ m with 1 m³ in each of $[2, 3]$ and $[3, 4]$ m (sectional area linear $0 \to 2 \to 0$ m², centroids + $8/3$ and $10/3$ m): the compartment holding all 2 m³ with its centroid at 3 m is $[2, 4]$ m within $10^{-9}$ m. +- `a_compartment_inside_one_station_interval_has_its_own_centroid`: a unit sectional area over $[0, 2]$ m with + stations at 0, 1 and 2 m puts 0.25 m³ centred at 0.25 m in $[0.125, 0.375]$ m; a sectional area rising + $0 \to 2$ m² over $[0, 1]$ m ($Q = x^2$, $M = 2x^3/3$) puts the 0.25 m³ after the first in $[0.5, \sqrt{0.5}]$ m. + Closed forms, derived here. +- `floodable_at_a_shared_centre_is_the_longest`: points by construction, two sharing the centre 5 m (2 and 4 m long, + in either order): 4 m at 5 m, and $1 + 0.5 (4 - 1) = 2.5$ m at 4.5 and 5.5 m by linear interpolation. +- `the_plot_scale_holds_the_longest_compartment`: at $T = 1.90$ m the longest point is under 8 m; with bulkheads at + 1 and 9 m each of the three SVG triangles is as high as its base is long within 0.3 px. +- `a_curve_does_not_depend_on_the_other_permeabilities` (demo hull, level 2, 8 t): the $\mu = 0.60$ curve asked + alone agrees with the same curve asked with 0.85 and 0.95 within 1 % at mid-range. SeaCraft against itself, not a + source. + +### Provenance +Both books give the definitions: the margin line 76 mm (3 in) below the bulkhead deck at side, the floodable length +centred at the point, and permissible length = floodable length × factor of subdivision (Rawson & Tupper, *Basic +Ship Theory*, Vol. 1, 5th ed., ch. 5, pp. 155-156; Gillmer & Johnson, *Introduction to Naval Architecture* (1982), +§10-1, pp. 180-182). Rawson & Tupper alone give the triangle check of base angle $\tan^{-1} 2$ and the forward and +after terminals at the ends. Gillmer & Johnson alone give the method: trial waterlines tangent to the margin line, +sectional areas to each waterline from Bonjean curves, the flooding water's position from a moment balance and the +compartment volume from it (Eq. 10-1 and 10-2). Neither book prints worked numbers. The box barge values are derived here from the lost-buoyancy balance, not published. +SeaCraft measures the margin line from the moulded deck edge (no deck thickness). + +--- + +## 54. Floodable Length: Cross-Check with the Damage Solver + +### Formula +A compartment from a floodable length curve, flooded as an ordinary damage case (lost buoyancy, compartment clipped +to the hull, `damage::evaluate`), must float the hull upright with the margin line awash: minimum freeboard to the +deck edge equal to the margin depth $m$, at the curve point's trim. + +### Tests +`crates/seacraft-core/src/floodable.rs::curve_points_flood_the_demo_hull_to_its_margin_line`: demo hull, level 3, +design-draft loading, $\mu = 0.85$, the first, middle and last points of the curve. Asserted: heel below 0.05°, +freeboard within 5 mm of 0.076 m, trim within 20 mm of the point's. Flooding the same compartments at $\mu = 0.95$ +instead fails the test (freeboard 0.016 m at the aft point). + +### Provenance +Agreement between two SeaCraft methods (sectional areas under trial waterlines against a clipped solid in the +damage equilibrium solver), not an external source. + +--- + +## 55. Floodable Length: Demo Hull, Recorded + +### Tests +`crates/seacraft-core/src/floodable.rs::demo_hull_curve_recorded`: demo hull, level 3, design draft, $\mu = 0.85$: +$\Delta = 12.1$ t, $LCG = 4.30$ m, least floodable length 1.39 m at $x = 0.701$ m, 3.37 m at $x = 6.0$ m, each +within 0.5 %. + +### Provenance +Not published: recorded from SeaCraft on 2026-11-26 to catch a change. The curve's shape (least near the aft end, +highest amidships, a second low near the forward quarter) agrees with Gillmer & Johnson's remark (glossary, p. 304) +that the floodable length "is usually greatest amidships and least near the quarter length". diff --git a/locales/en.json b/locales/en.json index 92068d0..209826d 100644 --- a/locales/en.json +++ b/locales/en.json @@ -139,6 +139,15 @@ "cli.edit.summary_line": " faces {fb} -> {fa}, points {pb} -> {pa}, creases {cb} -> {ca}", "cli.edit.validates": " validates: closed and manifold", "cli.example.wrote": "wrote {fef} and {sidecar} ({title}: {points} control points, {faces} faces, {layers} layers)", + "cli.floodable.checks": "Compartments against the permissible length (F = {factor}): x aft .. x fwd, length / permissible", + "cli.floodable.columns": " x mid length aft fwd trim draft (m)", + "cli.floodable.curve": "Floodable length curve, μ = {mu}", + "cli.floodable.fail": "fails", + "cli.floodable.heading": "Floodable length, {name}", + "cli.floodable.loading": "Loading", + "cli.floodable.margin_val": "{margin} m below the deck edge at side", + "cli.floodable.not_judged": "not judged: the curve does not reach its centre", + "cli.floodable.pass": "passes", "cli.generate.bwl": "BWL (m)", "cli.generate.cb": "Cb", "cli.generate.cols": " parameter target achieved", @@ -528,6 +537,11 @@ "export.ply": "PLY (ASCII)…", "export.stl": "STL (binary)…", "export.threemf": "3MF (welded mesh)…", + "floodable.check.outside_curve": "not judged: the floodable length curve does not reach the compartment’s centre", + "floodable.svg.empty": "No floodable length curve found", + "floodable.svg.length_axis": "Floodable length (m)", + "floodable.svg.margin_line": "Margin line", + "floodable.svg.permissible": "Permissible length, F = {factor} (μ = {mu})", "heel.badge.capsizes": "⚠ Capsizes", "heel.badge.past_vanishing": "⚠ Past vanishing angle", "heel.banner.cannot_float": "⚠ Cannot float", @@ -1770,6 +1784,7 @@ "warn.dsyhs.l_vol": "L/∇^(1/3) {value} is outside DSYHS valid range 4.34-8.50", "warn.dsyhs.lb": "L/B {lb} is outside DSYHS valid range 2.73-5.00", "warn.dsyhs.lcb": "LCB from FPP {value}·LWL is outside DSYHS valid range 0.50-0.56", + "warn.floodable.no_curve": "no floodable length curve found for permeability {mu}", "warn.hm.bt": "B/T {bt} is outside 2.1-4.0", "warn.hm.bulb": "bulb centre {z} m is above 0.6 T ({limit} m); the method uses 0.6 T", "warn.hm.cp": "Cp {cp} is outside 0.55-0.85", diff --git a/locales/tr.json b/locales/tr.json index 9d0a691..ca6734e 100644 --- a/locales/tr.json +++ b/locales/tr.json @@ -139,6 +139,15 @@ "cli.edit.summary_line": " yüzeyler {fb} -> {fa}, noktalar {pb} -> {pa}, keskin kenarlar {cb} -> {ca}", "cli.edit.validates": " kontrol edildi: kapalı ve manifold", "cli.example.wrote": "yazıldı: {fef} ve {sidecar} ({title}: {points} kontrol noktası, {faces} yüzey, {layers} katman)", + "cli.floodable.checks": "Bölmeler, izin verilen boya göre (F = {factor}): kıç x .. baş x, boy / izin verilen", + "cli.floodable.columns": " orta x boy kıç baş trim su çekimi (m)", + "cli.floodable.curve": "Su alabilir boy eğrisi, μ = {mu}", + "cli.floodable.fail": "geçmez", + "cli.floodable.heading": "Su alabilir boy, {name}", + "cli.floodable.loading": "Yükleme", + "cli.floodable.margin_val": "yandaki güverte kenarının {margin} m altında", + "cli.floodable.not_judged": "değerlendirilmedi: eğri bölmenin ortasına ulaşmıyor", + "cli.floodable.pass": "geçer", "cli.generate.bwl": "BWL (m)", "cli.generate.cb": "Cb", "cli.generate.cols": " parametre hedef gerçekleşen", @@ -528,6 +537,11 @@ "export.ply": "PLY (ASCII)…", "export.stl": "STL (ikili)…", "export.threemf": "3MF (birleşik ağ)…", + "floodable.check.outside_curve": "değerlendirilmedi: su alabilir boy eğrisi bölmenin ortasına ulaşmıyor", + "floodable.svg.empty": "Su alabilir boy eğrisi bulunamadı", + "floodable.svg.length_axis": "Su alabilir boy (m)", + "floodable.svg.margin_line": "Sınır hattı", + "floodable.svg.permissible": "İzin verilen boy, F = {factor} (μ = {mu})", "heel.badge.capsizes": "⚠ Alabora olur", "heel.badge.past_vanishing": "⚠ Sıfırlanma açısı aşıldı", "heel.banner.cannot_float": "⚠ Yüzemez", @@ -1770,6 +1784,7 @@ "warn.dsyhs.l_vol": "L/∇^(1/3) {value}, DSYHS geçerli aralığının (4.34-8.50) dışında", "warn.dsyhs.lb": "L/B {lb}, DSYHS geçerli aralığının (2.73-5.00) dışında", "warn.dsyhs.lcb": "FPP'den ölçülen LCB {value}·LWL, DSYHS geçerli aralığının (0.50-0.56) dışında", + "warn.floodable.no_curve": "{mu} geçirgenliği için su alabilir boy eğrisi bulunamadı", "warn.hm.bt": "B/T {bt}, 2.1-4.0 aralığının dışında", "warn.hm.bulb": "balb merkezi {z} m, 0.6 T değerinin ({limit} m) üzerinde; yöntem 0.6 T kullanır", "warn.hm.cp": "Cp {cp}, 0.55-0.85 aralığının dışında", diff --git a/skills/seacraft-stability-check/SKILL.md b/skills/seacraft-stability-check/SKILL.md index bc3bc97..5fff0f3 100644 --- a/skills/seacraft-stability-check/SKILL.md +++ b/skills/seacraft-stability-check/SKILL.md @@ -28,6 +28,7 @@ Ask for, or state as an assumption, KG, the draft or displacement, the LCG, and - For a full loaded ship (lightship, deadweight items, and slack tanks with free-surface correction `FSC = FSM / Δ`), run `loading_condition {"case_path": "examples/demo-loadcase.json"}` (or pass `"case"` inline) to evaluate `kg_fluid`, `gm_fluid`, the free-trim floating condition and IMO A.749 criteria directly. If `equilibrium_found` is false, report its `warnings`: the figures are measured at the input draft/trim, not at an equilibrium. - For the IMO 2008 IS Code Part A §2.3 severe wind and rolling (weather) criterion, run `weather_criterion {"draft": 0.62, "kg": 1.0, "free_trim": true, "bilge": "round"}` (optionally with `windage_extra` and `downflooding_deg`) to check steady-wind heel `phi0_deg <= 16` and gust energy balance `area_b_m_rad >= area_a_m_rad`. - For deterministic damage stability by the lost-buoyancy method, run `damage_stability {"case_path": "examples/demo-damage.json"}` (or pass `"case"` inline) to evaluate damaged equilibrium (draft, trim, heel/list), check deck-edge freeboard, and assess residual GZ curves and indicative SOLAS-style criteria. +- For bulkhead spacing, run `floodable_length` (a project `"condition"`, or `"displacement_t"` and `"lcg"`): one floodable length curve per permeability, the longest full-breadth compartment that floods without immersing the margin line (76 mm below the deck edge). Add `"factor"` (factor of subdivision, from the rules; ask the user, never invent one) and `"bulkheads"` to judge each compartment; `passed: null` means the curve does not reach that compartment, not that it passes. The curves are checked against a box barge and the damage solver, not a published table; say so. - To see where the hull settles when weights are added (deck cargo, a person at the rail, a mast-top mass), run `heel_equilibrium {"draft": 0.62, "kg": 2.2, "level": 3, "weights": [{"mass_t": 0.5, "x": 4, "y": 0.8, "z": 1.5}], "heel": 20}` (or `"condition": ""` to start from a loading condition). It is large-angle and always free to trim: read `summary` and `equilibrium.kind` (`stable` with its heel, trim and draft; `loll` with both heels; `capsizes`; `cannot_float`; `unresolved`), and at `heel` the split `lever_m = gz_m - heeling_arm_m`. Demo (T = 0.62 m, KG 2.2 m, level 3), 0.5 t at (4, 0.8, 1.5): heels 4.4° to starboard. Do not quote `tan φ = TCG / GM` instead: it is a small-angle estimate. - `condition.lcg_x` is the LCG used (defaults to the LCB at the given draft, 4.297 m on the demo). - `curves[].points[]` hold `kn`, `gz`, `draft` and `trim_m` per displacement. GZ at 0 degrees must be about 0 (1e-16 on the demo). If not, the condition is wrong.