From 0d680021f95fbaa54098c67eb3bb94957eb31442 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 21:38:41 -0600
Subject: [PATCH 01/12] feat(dev): experimental 3MF output for Print shell
model exports
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- assets::threemf: GLB triangles (stl::glb_mesh, transforms baked, Z-up)
as a core-spec 3MF in metres; vertices shared by exact f32 equality,
degenerate triangles left out; XML streamed into a deflated zip.
- assets::print: write_meshes writes the STL and/or 3MF next to the GLB
from one triangle read; ModelDone reports them as `meshes`.
- three_mf in ModelOptions (not part of the cache key) and
AssetExportModelRequest (serde default) in the real/mock backends and
TS mirror/mock; samples regenerated.
- CLI `dev export-model --3mf` (experimental), refused with --preset full.
- Export dialog: "Also write a 3MF (experimental)" switch with badge,
"Save as…" button, a line saying where the STL/3MF go.
- zip 9 (deflate via flate2/zlib-rs only) in starorg-data.
- Docs: user guide and addendum.
---
Cargo.lock | 2 +
app/src-tauri/src/contract/assets.rs | 3 +
app/src-tauri/src/contract/mock_assets.rs | 11 +-
app/src-tauri/src/contract/real/assets.rs | 15 +-
app/src-tauri/src/contract/tests_assets.rs | 5 +
app/src-tauri/tests/real_assets.rs | 1 +
app/src/components/assets/AssetPanel.svelte | 18 ++-
app/src/components/assets/ModelViewer.svelte | 2 +-
app/src/lib/contract/assets.ts | 2 +
app/src/lib/contract/mock-assets.ts | 5 +-
app/src/lib/contract/samples.gen.json | 4 +-
app/tests/assetmock.test.ts | 2 +-
crates/starorg-cli/src/asset_cmds.rs | 61 ++++----
crates/starorg-cli/src/lib.rs | 4 +
crates/starorg-cli/tests/dev_assets.rs | 24 ++++
crates/starorg-data/Cargo.toml | 3 +
crates/starorg-data/src/assets.rs | 5 +-
crates/starorg-data/src/assets/model.rs | 28 ++--
crates/starorg-data/src/assets/print.rs | 69 +++++++++
crates/starorg-data/src/assets/stl.rs | 11 +-
crates/starorg-data/src/assets/tests.rs | 123 +++++++++++++++-
crates/starorg-data/src/assets/threemf.rs | 136 ++++++++++++++++++
docs/plans/specs/starorg-codex-v1-addendum.md | 15 +-
docs/user-guide.md | 7 +-
24 files changed, 485 insertions(+), 71 deletions(-)
create mode 100644 crates/starorg-data/src/assets/print.rs
create mode 100644 crates/starorg-data/src/assets/threemf.rs
diff --git a/Cargo.lock b/Cargo.lock
index 6997b35..ec97e97 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4823,6 +4823,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.21",
"ww2ogg",
+ "zip",
]
[[package]]
@@ -6986,6 +6987,7 @@ checksum = "e3476fd497ac8af5b1ec7b51acab7bef380f7e8dd8e0487595bafd839417a302"
dependencies = [
"constant_time_eq",
"crc32fast",
+ "flate2",
"getrandom 0.4.3",
"indexmap 2.14.2",
"libc",
diff --git a/app/src-tauri/src/contract/assets.rs b/app/src-tauri/src/contract/assets.rs
index 35b379e..7fd0ccf 100644
--- a/app/src-tauri/src/contract/assets.rs
+++ b/app/src-tauri/src/contract/assets.rs
@@ -185,6 +185,9 @@ pub struct AssetExportModelRequest {
pub lod: u32,
/// Also an STL next to the GLB.
pub stl: bool,
+ /// Also a 3MF next to the GLB (Print shell only, like the STL).
+ #[serde(default)]
+ pub three_mf: bool,
/// Export even with less free memory than the preset may need (after `needs-decision`).
pub force: bool,
/// Full only: the paint to wear, a [`ModelPaint::tag`] from `asset_model_paints`
diff --git a/app/src-tauri/src/contract/mock_assets.rs b/app/src-tauri/src/contract/mock_assets.rs
index 191108c..f95ff7e 100644
--- a/app/src-tauri/src/contract/mock_assets.rs
+++ b/app/src-tauri/src/contract/mock_assets.rs
@@ -21,6 +21,10 @@ pub const EXPORTS: &str = "/synthetic/exports";
pub const CACHE_DEFAULT: &str = "/synthetic/cache/assets";
pub const CACHE_OTHER: &str = "/synthetic/other-drive/asset-cache";
pub const CACHE_MAX: u64 = 2 * 1024 * 1024 * 1024;
+/// The mock's STL and 3MF of a print-shell export: an AEGS_Javelin LOD 0's STL, and a 3MF a
+/// quarter of it (an RSI_Skylark's 3MF was 0.25 of its STL).
+pub const STL_BYTES: u64 = 183_149_634;
+pub const THREE_MF_BYTES: u64 = 45_000_000;
/// Mock asset state (per backend).
#[derive(Debug, Default)]
@@ -1002,6 +1006,7 @@ impl AssetBackend for MockBackend {
preset: req.preset,
lod: starorg_data::assets::model::effective_lod(lod, &self.known_lods(&req.what)),
stl: req.stl,
+ three_mf: req.three_mf,
paint: req.paint.clone(),
layers: req.layers,
};
@@ -1032,8 +1037,10 @@ impl AssetBackend for MockBackend {
"{EXPORTS}/{}",
starorg_data::assets::model::file_name(name, &o)
)),
- files: 1 + req.stl as u32,
- bytes: bytes + if req.stl { 183_149_634 } else { 0 },
+ files: 1 + req.stl as u32 + req.three_mf as u32,
+ bytes: bytes
+ + if req.stl { STL_BYTES } else { 0 }
+ + if req.three_mf { THREE_MF_BYTES } else { 0 },
cached: held.is_some(),
failed: Vec::new(),
note: None,
diff --git a/app/src-tauri/src/contract/real/assets.rs b/app/src-tauri/src/contract/real/assets.rs
index 3092c1a..ee3b7fb 100644
--- a/app/src-tauri/src/contract/real/assets.rs
+++ b/app/src-tauri/src/contract/real/assets.rs
@@ -919,6 +919,7 @@ impl AssetBackend for RealBackend {
preset: req.preset,
lod: model::effective_lod(asked, &self.known_lods(&key, &req.what)),
stl: req.stl,
+ three_mf: req.three_mf,
paint: req.paint.clone(),
layers: req.layers,
};
@@ -972,12 +973,12 @@ impl AssetBackend for RealBackend {
let n = std::fs::copy(&hit, &out).map_err(io)?;
let mut files = 1;
let mut bytes = n;
- if o.stl {
+ if o.stl || o.three_mf {
let glb = std::fs::read(&hit).map_err(io)?;
- let (_, len) =
- starorg_data::assets::stl::glb_file_to_stl(&glb, &out.with_extension("stl"))
- .map_err(|e| err(ErrorCode::Internal, e.message))?;
- files += 1;
+ let (n, len) = starorg_data::assets::print::write_meshes(&glb, &out, &o)
+ .map_err(|e| err(ErrorCode::Internal, e.message))?
+ .files_bytes();
+ files += n;
bytes += len;
}
return Ok(export_result(
@@ -1024,8 +1025,8 @@ impl AssetBackend for RealBackend {
d.peak_rss.map(|b| b / 1_048_576).unwrap_or(0)
),
);
- let files = 1 + d.stl_path.is_some() as u32;
- let bytes = d.bytes + d.stl_bytes.unwrap_or(0);
+ let (n, len) = starorg_data::assets::print::files_bytes(&d.meshes);
+ let (files, bytes) = (1 + n, d.bytes + len);
Ok(export_result(Some(d.path), files, bytes, false))
}
diff --git a/app/src-tauri/src/contract/tests_assets.rs b/app/src-tauri/src/contract/tests_assets.rs
index 06e7d5c..dfad734 100644
--- a/app/src-tauri/src/contract/tests_assets.rs
+++ b/app/src-tauri/src/contract/tests_assets.rs
@@ -215,6 +215,7 @@ pub(super) fn asset_samples() -> Vec<(&'static str, Value)> {
preset,
lod,
stl,
+ three_mf: stl,
force: false,
paint: None,
layers: false,
@@ -451,6 +452,7 @@ fn every_asset_command_but_the_cache_refuses_while_developer_mode_is_off() {
preset: ModelPreset::Full,
lod: 1,
stl: false,
+ three_mf: false,
force: false,
paint: None,
layers: false,
@@ -539,6 +541,7 @@ fn the_mock_caches_previews_sounds_and_models_and_switches_folders() {
preset: ModelPreset::Full,
lod: 1,
stl: false,
+ three_mf: false,
force: false,
paint: None,
layers: false,
@@ -663,6 +666,7 @@ fn the_model_view_steps_through_lods_with_estimates_the_guard_and_the_cache() {
preset: ModelPreset::PrintShell,
lod: 3,
stl: false,
+ three_mf: false,
force: false,
paint: None,
layers: false,
@@ -796,6 +800,7 @@ fn a_full_export_wears_a_paint_and_refuses_one_the_ship_lacks() {
preset,
lod: 1,
stl: false,
+ three_mf: false,
force: false,
paint: Some(paint.into()),
layers: true,
diff --git a/app/src-tauri/tests/real_assets.rs b/app/src-tauri/tests/real_assets.rs
index 0de825c..ee8a1b9 100644
--- a/app/src-tauri/tests/real_assets.rs
+++ b/app/src-tauri/tests/real_assets.rs
@@ -391,6 +391,7 @@ fn extract_and_exports_respect_dialogs_and_the_game_folder() {
preset: ModelPreset::PrintShell,
lod: 0,
stl: false,
+ three_mf: false,
force: false,
paint: None,
layers: false,
diff --git a/app/src/components/assets/AssetPanel.svelte b/app/src/components/assets/AssetPanel.svelte
index a1c6bf2..19241b7 100644
--- a/app/src/components/assets/AssetPanel.svelte
+++ b/app/src/components/assets/AssetPanel.svelte
@@ -12,7 +12,9 @@
import Download from '@lucide/svelte/icons/download';
import LoaderCircle from '@lucide/svelte/icons/loader-circle';
import ChevronDown from '@lucide/svelte/icons/chevron-down';
+ import FlaskConical from '@lucide/svelte/icons/flask-conical';
import * as Dialog from '@/components/ui/dialog';
+ import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import Segmented from '@/components/common/Segmented.svelte';
import SwitchRow from '@/components/common/SwitchRow.svelte';
@@ -87,6 +89,7 @@
let preset = $state('print-shell');
let lod = $state(0);
let stl = $state(false);
+ let threeMf = $state(false);
/** Full only: the paint ('' = the fitted one) and StarBreaker's layer materials. */
let paint = $state('');
let layers = $state(false);
@@ -97,7 +100,10 @@
function setPreset(p: ModelPreset) {
preset = p;
lod = DEFAULT_LOD[p];
- if (p === 'full') stl = false;
+ if (p === 'full') {
+ stl = false;
+ threeMf = false;
+ }
}
// A new record forgets the last one's paints and choice.
$effect(() => {
@@ -132,6 +138,8 @@
const p = paints?.paints.find((x) => x.tag.toLowerCase() === e.toLowerCase());
return p ? paintLabel(p) : 'default';
});
+ /** The extra files written next to the GLB: `STL/3MF`, `STL`, `3MF` or ''. */
+ const meshNames = $derived(preset === 'full' ? '' : [stl && 'STL', threeMf && '3MF'].filter(Boolean).join('/'));
/** Set when the backend says free memory is short: the dialog asks before going on. */
let memWarn = $state(null);
async function exportModel(force = false) {
@@ -140,7 +148,7 @@
exporting = true;
try {
const full = preset === 'full';
- const r = await assetApi.exportModel({ target: $state.snapshot(target), what: guid, name, preset, lod, stl, force, paint: full && paint ? paint : null, layers: full && layers });
+ const r = await assetApi.exportModel({ target: $state.snapshot(target), what: guid, name, preset, lod, stl: !full && stl, three_mf: !full && threeMf, force, paint: full && paint ? paint : null, layers: full && layers });
if (r.cancelled) toast('info', 'Export cancelled', 'Nothing was written.');
else toast('success', `Exported ${name}${r.cached ? ' from the cache' : ''}`, [bytesText(r.bytes), r.note, r.path, r.failed.length ? `${r.failed.length} failed` : ''].filter(Boolean).join(' · '));
} catch (e) {
@@ -239,6 +247,9 @@
(stl = v)} disabled={preset === 'full'} />
+ (threeMf = v)} disabled={preset === 'full'}>
+ Experimental
+
{#if preset === 'full'}
{/if}
+
You pick where the GLB goes{meshNames ? `; the ${meshNames} ${meshNames.includes('/') ? 'are' : 'is'} written next to it` : ''}.
{PERSONAL_USE}
-
+
diff --git a/app/src/components/assets/ModelViewer.svelte b/app/src/components/assets/ModelViewer.svelte
index d4a8954..0e94361 100644
--- a/app/src/components/assets/ModelViewer.svelte
+++ b/app/src/components/assets/ModelViewer.svelte
@@ -242,7 +242,7 @@
if (!shown) return;
exporting = true;
try {
- const r = await assetApi.exportModel({ target: $state.snapshot(target), what: guid, name, preset: 'print-shell', lod: shown.lod, stl: false, force: false });
+ const r = await assetApi.exportModel({ target: $state.snapshot(target), what: guid, name, preset: 'print-shell', lod: shown.lod, stl: false, three_mf: false, force: false });
if (r.cancelled) toast('info', 'Export cancelled', 'Nothing was written.');
else toast('success', `Exported ${name}${r.cached ? ' from the cache' : ''}`, [mbText(r.bytes), r.path].filter(Boolean).join(' · '));
} catch (e) {
diff --git a/app/src/lib/contract/assets.ts b/app/src/lib/contract/assets.ts
index 3b1aab8..5f04357 100644
--- a/app/src/lib/contract/assets.ts
+++ b/app/src/lib/contract/assets.ts
@@ -203,6 +203,8 @@ export interface AssetExportModelRequest {
preset: ModelPreset;
lod: number;
stl: boolean;
+ /** Also a 3MF next to the GLB (Print shell only, like the STL); absent = false. */
+ three_mf?: boolean;
/** Export even with less free memory than the preset may need (after `needs-decision`). */
force: boolean;
/** Full only: the paint to wear (a `ModelPaint.tag`); null/absent = the fitted one. */
diff --git a/app/src/lib/contract/mock-assets.ts b/app/src/lib/contract/mock-assets.ts
index 40baac0..ca2a2db 100644
--- a/app/src/lib/contract/mock-assets.ts
+++ b/app/src/lib/contract/mock-assets.ts
@@ -110,6 +110,9 @@ export const modelFileName = (name: string, o: KeyOpts) => {
const GIB = 1024 ** 3;
const MAX_LOD = 4;
const MODEL_CHUNK = 8 * 1024 * 1024;
+/** As `mock_assets.rs`: the STL and 3MF of a print-shell export (a Javelin LOD 0's STL, a 3MF a quarter of it). */
+const STL_BYTES = 183149634;
+const THREE_MF_BYTES = 45000000;
/** `model::effective_lod`: the most detailed LOD the mesh has at or below the asked one. */
export const effectiveLod = (asked: number, lods: number[]): number => {
const r = Math.min(asked, MAX_LOD);
@@ -443,7 +446,7 @@ export function createAssetMock(data: AssetMockData, ctx: AssetMockCtx): { handl
if (bytes <= data.cacheMax / 4) add(k, bytes);
}
const name = req.name || recName;
- return { cancelled: false, path: `${data.exports}/${modelFileName(name, o)}`, files: 1 + (req.stl ? 1 : 0), bytes: bytes + (req.stl ? 183149634 : 0), cached: held !== null, failed: [], note: null };
+ return { cancelled: false, path: `${data.exports}/${modelFileName(name, o)}`, files: 1 + (req.stl ? 1 : 0) + (req.three_mf ? 1 : 0), bytes: bytes + (req.stl ? STL_BYTES : 0) + (req.three_mf ? THREE_MF_BYTES : 0), cached: held !== null, failed: [], note: null };
},
asset_model_paints: ({ req }) => {
on(req.target);
diff --git a/app/src/lib/contract/samples.gen.json b/app/src/lib/contract/samples.gen.json
index cc1d5fa..ce80f9b 100644
--- a/app/src/lib/contract/samples.gen.json
+++ b/app/src/lib/contract/samples.gen.json
@@ -186,11 +186,11 @@
"state": "stopped"
},
"asset_export_model": {
- "bytes": 239548230,
+ "bytes": 284548230,
"cached": false,
"cancelled": false,
"failed": [],
- "files": 2,
+ "files": 3,
"note": null,
"path": "/synthetic/exports/SYN_Ship_002-print-lod0.glb"
},
diff --git a/app/tests/assetmock.test.ts b/app/tests/assetmock.test.ts
index 3633797..38b1bc7 100644
--- a/app/tests/assetmock.test.ts
+++ b/app/tests/assetmock.test.ts
@@ -82,7 +82,7 @@ test('every asset sample of the Rust mock comes back equal from the TS mock', as
got.asset_sound = await h.asset_sound({ req: { target: live, sound: first } });
got.asset_sound_cached = await h.asset_sound({ req: { target: live, sound: first } });
got.asset_export_sounds = await h.asset_export_sounds({ req: { target: live, what: ship(1), sounds: [], wem: false } });
- const model = (preset: 'full' | 'print-shell', lod: number, stl: boolean) => ({ req: { target: live, what: ship(2), name: 'SYN_Ship_002', preset, lod, stl, force: false } });
+ const model = (preset: 'full' | 'print-shell', lod: number, stl: boolean) => ({ req: { target: live, what: ship(2), name: 'SYN_Ship_002', preset, lod, stl, three_mf: stl, force: false } });
got.asset_export_model = await h.asset_export_model(model('print-shell', 0, true));
got.asset_export_model_cached = await h.asset_export_model(model('print-shell', 0, false));
got.asset_export_model_full = await h.asset_export_model(model('full', 1, false));
diff --git a/crates/starorg-cli/src/asset_cmds.rs b/crates/starorg-cli/src/asset_cmds.rs
index 281f7b5..60cdb21 100644
--- a/crates/starorg-cli/src/asset_cmds.rs
+++ b/crates/starorg-cli/src/asset_cmds.rs
@@ -13,6 +13,7 @@ use starorg_core::memlimit;
use starorg_data::assets::audio::{self, SoundRef};
use starorg_data::assets::files;
use starorg_data::assets::model::{self, ModelOptions, ModelPreset};
+use starorg_data::assets::print;
use starorg_data::assets::wemcodec;
use starorg_data::assets::{AssetArchive, AssetError};
use starorg_data::assetworker;
@@ -208,6 +209,7 @@ pub fn run(g: &GlobalOpts, cmd: DevCmd) -> ExitCode {
preset,
lod,
stl,
+ three_mf,
paint,
layers,
cache_dir,
@@ -223,6 +225,7 @@ pub fn run(g: &GlobalOpts, cmd: DevCmd) -> ExitCode {
preset,
lod: lod.unwrap_or(preset.default_lod()).min(model::MAX_LOD),
stl,
+ three_mf,
paint,
layers,
};
@@ -234,6 +237,14 @@ pub fn run(g: &GlobalOpts, cmd: DevCmd) -> ExitCode {
"--paint and --layers need --preset full (a print shell has no materials)",
);
}
+ if preset == ModelPreset::Full && three_mf {
+ return fail(
+ g,
+ exit::USAGE,
+ "usage",
+ "--3mf needs --preset print (a 3MF is for 3D printing the shell)",
+ );
+ }
export_model(
g,
&what,
@@ -417,33 +428,25 @@ fn export_model(
o.lod = model::effective_lod(o.lod, &model::cached_lods(c, &t.channel, &t.build, what));
}
let key = o.cache_key(what);
- // A cached GLB: no archive read at all (an STL is made from it here).
+ // A cached GLB: no archive read at all (an STL or 3MF is made from it here).
if let Some(hit) = c
.as_ref()
.and_then(|c| c.get(&t.channel, &t.build, Kind::Models, &key, "glb"))
{
let r = copy_out(&hit, &out_abs).and_then(|n| {
- let stl = if o.stl {
+ let m = if o.stl || o.three_mf {
let glb = std::fs::read(&hit)?;
- let s = out_abs.with_extension("stl");
- starorg_data::assets::stl::glb_file_to_stl(&glb, &s)
- .map(|x| Some((s, x)))
+ print::write_meshes(&glb, &out_abs, &o)
.map_err(|e| std::io::Error::other(e.message))?
+ .files
} else {
- None
+ Vec::new()
};
- Ok((n, stl))
+ Ok((n, m))
});
return match r {
- Ok((n, stl)) => {
- report_model(
- g,
- &out_abs,
- n,
- stl.as_ref().map(|s| (&s.0, s.1.0)),
- true,
- None,
- );
+ Ok((n, m)) => {
+ report_model(g, &out_abs, n, &m, true, None);
ExitCode::from(exit::OK)
}
Err(e) => fail(g, exit::ERROR, "error", &e.to_string()),
@@ -498,15 +501,7 @@ fn export_model(
let _ = c.put_copy(&t.channel, &t.build, Kind::Models, &key, "glb", &out_abs);
let _ = model::cache_lods(c, &t.channel, &t.build, what, &d.lods);
}
- let stl = d.stl_path.as_ref().map(PathBuf::from);
- report_model(
- g,
- &out_abs,
- d.bytes,
- stl.as_ref().zip(d.stl_path.as_ref().and(d.triangles)),
- false,
- Some(&d),
- );
+ report_model(g, &out_abs, d.bytes, &d.meshes, false, Some(&d));
ExitCode::from(exit::OK)
}
Err(e) => asset_fail(g, &e),
@@ -517,16 +512,17 @@ fn report_model(
g: &GlobalOpts,
out: &Path,
bytes: u64,
- stl: Option<(&PathBuf, u64)>,
+ meshes: &[print::MeshFile],
cached: bool,
done: Option<&model::ModelDone>,
) {
+ let mesh_path = |kind: &str| meshes.iter().find(|m| m.kind == kind).map(|m| &m.path);
if g.json {
println!(
"{}",
json!({ "schema": JSON_SCHEMA, "out": out, "bytes": bytes, "cached": cached,
- "stl": stl.map(|s| s.0),
- "triangles": done.and_then(|d| d.triangles).or(stl.map(|s| s.1)),
+ "stl": mesh_path("stl"), "3mf": mesh_path("3mf"),
+ "triangles": done.and_then(|d| d.triangles).or(meshes.first().map(|m| m.triangles)),
"lod": done.map(|d| d.lod), "lods": done.map(|d| &d.lods),
"peak_rss": done.and_then(|d| d.peak_rss), "ms": done.map_or(0, |d| d.ms) })
);
@@ -553,10 +549,13 @@ fn report_model(
if cached { ", from the cache" } else { "" },
out.display()
);
- if let Some((p, n)) = stl {
+ for m in meshes {
eprintln!(
- "starorg-codex: STL ({n} triangles) written to {}",
- p.display()
+ "starorg-codex: {} ({} triangles, {} bytes) written to {}",
+ m.kind.to_ascii_uppercase(),
+ m.triangles,
+ m.bytes,
+ m.path
);
}
}
diff --git a/crates/starorg-cli/src/lib.rs b/crates/starorg-cli/src/lib.rs
index 2f32b02..bdb3507 100644
--- a/crates/starorg-cli/src/lib.rs
+++ b/crates/starorg-cli/src/lib.rs
@@ -582,6 +582,10 @@ pub enum DevCmd {
/// Also write an STL next to the GLB (geometry, transforms baked, Z-up).
#[arg(long)]
stl: bool,
+ /// Print only (experimental): also write a 3MF next to the GLB (for slicers: real
+ /// size in metres, Z-up, shared vertices).
+ #[arg(long = "3mf")]
+ three_mf: bool,
/// Full only: wear this paint, by its tag (`dev model-paints` lists them); default:
/// the paint the default loadout fits.
#[arg(long, value_name = "TAG")]
diff --git a/crates/starorg-cli/tests/dev_assets.rs b/crates/starorg-cli/tests/dev_assets.rs
index 584449a..5397956 100644
--- a/crates/starorg-cli/tests/dev_assets.rs
+++ b/crates/starorg-cli/tests/dev_assets.rs
@@ -307,3 +307,27 @@ fn a_cache_folder_in_the_game_folder_or_prefix_is_refused_at_use() {
);
assert!(!bad.exists());
}
+
+#[test]
+fn a_3mf_needs_the_print_preset() {
+ let t = tempfile::tempdir().unwrap();
+ let a = p4k(t.path()).display().to_string();
+ let item = dcb::guid_text(1, 2);
+ let out = t.path().join("m.glb");
+ let o = run(
+ t.path(),
+ &[
+ "dev",
+ "export-model",
+ &item,
+ "--3mf",
+ "--out",
+ out.to_str().unwrap(),
+ "--test-p4k",
+ &a,
+ ],
+ );
+ assert_eq!(o.status.code(), Some(2));
+ assert!(String::from_utf8_lossy(&o.stderr).contains("--3mf needs --preset print"));
+ assert!(!out.exists() && !out.with_extension("3mf").exists());
+}
diff --git a/crates/starorg-data/Cargo.toml b/crates/starorg-data/Cargo.toml
index 5532f7b..918f1f6 100644
--- a/crates/starorg-data/Cargo.toml
+++ b/crates/starorg-data/Cargo.toml
@@ -28,6 +28,9 @@ starbreaker-cryxml.workspace = true
starbreaker-common.workspace = true
# GLB -> STL for the print-shell preset (already in the tree through starbreaker-3d).
gltf = { version = "1", default-features = false, features = ["utils"] }
+# The 3MF package (a deflated zip). zip is already in the tree through tauri-plugin-updater and
+# flate2's pure Rust zlib-rs backend through other crates; no zopfli, no other codecs.
+zip = { version = "9", default-features = false, features = ["deflate-flate2-zlib-rs"] }
# PNG encoding of decoded textures in memory (already in the tree through starbreaker-dds).
image = { version = "0.25", default-features = false, features = ["png"] }
thiserror.workspace = true
diff --git a/crates/starorg-data/src/assets.rs b/crates/starorg-data/src/assets.rs
index f9b2e7a..9740c72 100644
--- a/crates/starorg-data/src/assets.rs
+++ b/crates/starorg-data/src/assets.rs
@@ -10,7 +10,8 @@
//! extraction of files and folders.
//! - [`audio`]: a record's audio triggers (DataCore) -> ATL triggers -> Wwise banks -> media;
//! WEM -> Ogg Vorbis. Ported from StarBreaker's app (`audio_commands.rs`).
-//! - [`model`]: entity -> GLB with the "Full" or "Print shell" preset, optional STL.
+//! - [`model`]: entity -> GLB with the "Full" or "Print shell" preset, optional STL
+//! ([`stl`]) and 3MF ([`threemf`]) next to it.
//!
//! Lazy: [`AssetArchive::open`] reads only the archive index. The DataCore is read on the first
//! request that needs a record (sounds, models); the Wwise/ATL index on the first sounds
@@ -19,9 +20,11 @@
pub mod audio;
pub mod files;
pub mod model;
+pub mod print;
pub mod stl;
#[cfg(any(test, feature = "synthetic-dcb"))]
pub mod synthetic;
+pub mod threemf;
pub mod wemcodec;
use crate::extract::{DCB_ENTRY, DCB_FALLBACK_ENTRY, INI_ENTRY, MAX_DCB_BYTES};
diff --git a/crates/starorg-data/src/assets/model.rs b/crates/starorg-data/src/assets/model.rs
index a54988a..99e835c 100644
--- a/crates/starorg-data/src/assets/model.rs
+++ b/crates/starorg-data/src/assets/model.rs
@@ -71,6 +71,9 @@ pub struct ModelOptions {
/// Also write an STL next to the GLB (geometry, node transforms baked).
#[serde(default)]
pub stl: bool,
+ /// Also write a 3MF next to the GLB (the STL's triangles, shared vertices, in metres).
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub three_mf: bool,
/// Full only: the paint to wear, by the ship's SubGeometry tag ([`ModelPaint::tag`]);
/// `None` = the paint the default loadout fits.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -112,7 +115,7 @@ impl ModelOptions {
}
/// The asset cache key of this export of `what` (a record GUID or name):
- /// `-print-lod3`, one file per record, preset and LOD (the STL is never cached).
+ /// `-print-lod3`, one file per record, preset and LOD (the STL and 3MF are never cached).
pub fn cache_key(&self, what: &str) -> String {
format!(
"{}-{}",
@@ -276,8 +279,9 @@ pub struct ModelDone {
pub bytes: u64,
pub record: String,
pub name: String,
- pub stl_path: Option,
- pub stl_bytes: Option,
+ /// The STL/3MF files written next to the GLB.
+ #[serde(default)]
+ pub meshes: Vec,
/// Triangles in the GLB (every node's triangle primitives).
pub triangles: Option,
pub ms: u64,
@@ -301,9 +305,8 @@ pub fn export_model(
progress: &(dyn Fn(f32, &str) -> bool + Sync),
) -> AssetResult {
a.check_out(out)?;
- let stl_out = o.stl.then(|| out.with_extension("stl"));
- if let Some(s) = &stl_out {
- a.check_out(s)?;
+ for x in super::print::mesh_outputs(out, o).into_iter().flatten() {
+ a.check_out(&x)?;
}
let started = Instant::now();
if !progress(0.0, "Reading the DataCore") {
@@ -359,20 +362,17 @@ pub fn export_model(
bytes: bytes.len() as u64,
record: r.id.to_string(),
name: record_short_name(db, r),
- stl_path: None,
- stl_bytes: None,
+ meshes: Vec::new(),
triangles: super::stl::glb_triangle_count(&bytes),
ms: 0,
peak_rss: None,
lod,
lods,
};
- if let Some(s) = stl_out {
- progress(0.97, "Writing STL");
- let (n, len) = super::stl::glb_file_to_stl(&bytes, &s)?;
- done.stl_path = Some(s.display().to_string());
- done.stl_bytes = Some(len);
- done.triangles = Some(n);
+ if o.stl || o.three_mf {
+ progress(0.97, "Writing STL/3MF");
+ let m = super::print::write_meshes(&bytes, out, o)?;
+ done.meshes = m.files;
}
drop(bytes);
done.ms = started.elapsed().as_millis() as u64;
diff --git a/crates/starorg-data/src/assets/print.rs b/crates/starorg-data/src/assets/print.rs
new file mode 100644
index 0000000..8f05246
--- /dev/null
+++ b/crates/starorg-data/src/assets/print.rs
@@ -0,0 +1,69 @@
+//! The STL and 3MF written next to a Print shell GLB (addendum 7.16): the GLB's triangles
+//! ([`super::stl::glb_mesh`]) written as [`super::stl`] and [`super::threemf`] files.
+
+use super::AssetResult;
+use super::model::ModelOptions;
+use serde::{Deserialize, Serialize};
+use std::path::{Path, PathBuf};
+
+/// One STL or 3MF file written.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MeshFile {
+ /// `stl` or `3mf`.
+ pub kind: String,
+ pub path: String,
+ pub bytes: u64,
+ pub triangles: u64,
+}
+
+/// The files written next to a GLB.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct Meshes {
+ pub files: Vec,
+}
+
+impl Meshes {
+ /// Files written and their bytes.
+ pub fn files_bytes(&self) -> (u32, u64) {
+ files_bytes(&self.files)
+ }
+}
+
+/// Count and bytes of `files`.
+pub fn files_bytes(files: &[MeshFile]) -> (u32, u64) {
+ (files.len() as u32, files.iter().map(|f| f.bytes).sum())
+}
+
+/// Where the STL and 3MF of the GLB `out` go (next to it), when asked.
+pub fn mesh_outputs(out: &Path, o: &ModelOptions) -> [Option; 2] {
+ [
+ o.stl.then(|| out.with_extension("stl")),
+ o.three_mf.then(|| out.with_extension("3mf")),
+ ]
+}
+
+/// Write the STL and/or 3MF `o` asks for next to the GLB `out`, from its bytes (the triangles
+/// are read once for both).
+pub fn write_meshes(glb: &[u8], out: &Path, o: &ModelOptions) -> AssetResult {
+ let [stl, three_mf] = mesh_outputs(out, o);
+ let mut m = Meshes::default();
+ if stl.is_none() && three_mf.is_none() {
+ return Ok(m);
+ }
+ let tris = super::stl::glb_mesh(glb)?;
+ let file = |kind: &str, p: &Path, (triangles, bytes): (u64, u64)| MeshFile {
+ kind: kind.into(),
+ path: p.display().to_string(),
+ bytes,
+ triangles,
+ };
+ if let Some(p) = stl {
+ let r = super::stl::write_stl(&tris, &p)?;
+ m.files.push(file("stl", &p, r));
+ }
+ if let Some(p) = three_mf {
+ let r = super::threemf::write_3mf(&tris, &p)?;
+ m.files.push(file("3mf", &p, r));
+ }
+ Ok(m)
+}
diff --git a/crates/starorg-data/src/assets/stl.rs b/crates/starorg-data/src/assets/stl.rs
index d4fb8bc..7f59e8a 100644
--- a/crates/starorg-data/src/assets/stl.rs
+++ b/crates/starorg-data/src/assets/stl.rs
@@ -181,11 +181,16 @@ pub fn write_stl(tris: &[[[f32; 3]; 3]], out: &Path) -> AssetResult<(u64, u64)>
Ok((tris.len() as u64, 84 + 50 * tris.len() as u64))
}
-/// GLB bytes -> STL file.
-pub fn glb_file_to_stl(glb: &[u8], out: &Path) -> AssetResult<(u64, u64)> {
+/// [`glb_triangles`], refusing a model without any (what the STL and 3MF writers start from).
+pub fn glb_mesh(glb: &[u8]) -> AssetResult> {
let tris = glb_triangles(glb)?;
if tris.is_empty() {
return Err(AssetError::invalid("the model has no triangles"));
}
- write_stl(&tris, out)
+ Ok(tris)
+}
+
+/// GLB bytes -> STL file.
+pub fn glb_file_to_stl(glb: &[u8], out: &Path) -> AssetResult<(u64, u64)> {
+ write_stl(&glb_mesh(glb)?, out)
}
diff --git a/crates/starorg-data/src/assets/tests.rs b/crates/starorg-data/src/assets/tests.rs
index b019f2d..6cd6340 100644
--- a/crates/starorg-data/src/assets/tests.rs
+++ b/crates/starorg-data/src/assets/tests.rs
@@ -304,7 +304,10 @@ fn a_paint_names_its_subgeometry_tag_after_an_at() {
fn model_options_from_older_requests_have_no_paint() {
let o: ModelOptions =
serde_json::from_value(serde_json::json!({ "preset": "full", "lod": 1 })).unwrap();
- assert_eq!((o.paint.as_deref(), o.layers, o.stl), (None, false, false));
+ assert_eq!(
+ (o.paint.as_deref(), o.layers, o.stl, o.three_mf),
+ (None, false, false, false)
+ );
let back = serde_json::to_value(&o).unwrap();
assert!(back.get("paint").is_none() && back.get("layers").is_none());
}
@@ -387,6 +390,120 @@ fn glb_to_stl_bakes_transforms() {
);
}
+fn unzip(path: &std::path::Path) -> std::collections::BTreeMap {
+ use std::io::Read;
+ let mut z = zip::ZipArchive::new(std::fs::File::open(path).unwrap()).unwrap();
+ (0..z.len())
+ .map(|i| {
+ let mut f = z.by_index(i).unwrap();
+ assert_eq!(f.compression(), zip::CompressionMethod::Deflated);
+ let mut s = String::new();
+ f.read_to_string(&mut s).unwrap();
+ (f.name().unwrap().to_string(), s)
+ })
+ .collect()
+}
+
+#[test]
+fn glb_to_3mf_shares_vertices_and_bakes_the_stl_transform() {
+ let t = tempfile::tempdir().unwrap();
+ let out = t.path().join("x.3mf");
+ let (n, len) = threemf::glb_file_to_3mf(&one_triangle_glb(), &out).unwrap();
+ assert_eq!(n, 1);
+ assert_eq!(len, std::fs::metadata(&out).unwrap().len());
+ assert!(!t.path().join("x.3mf.part").exists());
+ let files = unzip(&out);
+ assert_eq!(
+ files.keys().map(String::as_str).collect::>(),
+ ["3D/3dmodel.model", "[Content_Types].xml", "_rels/.rels"]
+ );
+ assert!(
+ files["[Content_Types].xml"]
+ .contains("application/vnd.ms-package.3dmanufacturing-3dmodel+xml")
+ );
+ assert!(files["_rels/.rels"].contains(r#"Target="/3D/3dmodel.model""#));
+ let m = &files["3D/3dmodel.model"];
+ assert!(m.contains(r#""#));
+ assert!(m.contains(r#"\n\n",
- "\n",
- r#""#,
- "\n\n\n"
-);
-
-/// A shared-vertex mesh: unique vertices and triangles indexing them.
-pub struct IndexedMesh {
- pub vertices: Vec<[f32; 3]>,
- pub triangles: Vec<[u32; 3]>,
+/// The length unit of a 3MF model.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
+pub enum Unit {
+ /// StarBreaker's game units, real size (the default, untouched export).
+ #[default]
+ Meter,
+ /// A scaled print ([`super::print`]).
+ Millimeter,
}
-/// Share vertices by exact `f32` bits (`-0.0` counts as `0.0`). Triangles with a non-finite
-/// coordinate or two equal corners are dropped (3MF requires three distinct vertices).
-pub fn index_mesh(tris: &[[[f32; 3]; 3]]) -> IndexedMesh {
- let mut ids: HashMap<[u32; 3], u32> = HashMap::with_capacity(tris.len());
- let mut vertices = Vec::with_capacity(tris.len());
- let mut triangles = Vec::with_capacity(tris.len());
- for t in tris {
- if t.iter().flatten().any(|c| !c.is_finite()) {
- continue;
+impl Unit {
+ /// The `unit` attribute value.
+ pub fn xml(self) -> &'static str {
+ match self {
+ Unit::Meter => "meter",
+ Unit::Millimeter => "millimeter",
}
- let mut idx = [0u32; 3];
- for (i, p) in idx.iter_mut().zip(t) {
- // +0.0 for -0.0: same point, one vertex.
- let p = p.map(|c| if c == 0.0 { 0.0 } else { c });
- *i = *ids.entry(p.map(f32::to_bits)).or_insert_with(|| {
- vertices.push(p);
- (vertices.len() - 1) as u32
- });
- }
- if idx[0] != idx[1] && idx[1] != idx[2] && idx[0] != idx[2] {
- triangles.push(idx);
+ }
+
+ /// Millimetres in one unit (1000 for metres).
+ pub fn mm(self) -> f32 {
+ match self {
+ Unit::Meter => 1000.0,
+ Unit::Millimeter => 1.0,
}
}
- IndexedMesh {
- vertices,
- triangles,
+}
+
+/// How several objects are placed in the build.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
+pub enum Layout {
+ /// One build item per object (split pieces: each printed on its own).
+ #[default]
+ Separate,
+ /// One build item made of every object as a component (multicolor parts of one model,
+ /// which slicers show as one object with parts, one filament each).
+ Assembly,
+}
+
+/// One object of a 3MF: a mesh with an optional name and display colour (`RGBA`).
+#[derive(Debug, Clone, Copy)]
+pub struct Object<'a> {
+ pub name: &'a str,
+ pub mesh: &'a Mesh,
+ pub color: Option<[u8; 4]>,
+}
+
+fn esc(s: &str) -> String {
+ let mut o = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => o.push_str("&"),
+ '<' => o.push_str("<"),
+ '>' => o.push_str(">"),
+ '"' => o.push_str("""),
+ '\'' => o.push_str("'"),
+ c if (c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r') => o.push(' '),
+ c => o.push(c),
+ }
}
+ o
}
-/// Write a 3MF package of `tris`; returns (triangles written, bytes).
+/// A shared-vertex mesh: unique vertices and triangles indexing them.
+pub type IndexedMesh = Mesh;
+
+/// Share vertices by exact `f32` bits (`-0.0` counts as `0.0`). Triangles with a non-finite
+/// coordinate or two equal corners are dropped (3MF requires three distinct vertices).
+pub fn index_mesh(tris: &[[[f32; 3]; 3]]) -> Mesh {
+ Mesh::from_triangles(tris)
+}
+
+/// Write a 3MF package of `tris` (one object, metres); returns (triangles written, bytes).
pub fn write_3mf(tris: &[[[f32; 3]; 3]], out: &Path) -> AssetResult<(u64, u64)> {
let mesh = index_mesh(tris);
- if mesh.triangles.is_empty() {
+ write_3mf_objects(
+ &[Object {
+ name: "",
+ mesh: &mesh,
+ color: None,
+ }],
+ Unit::Meter,
+ Layout::Separate,
+ out,
+ )
+}
+
+/// Write a 3MF package of `objects` in `unit`, placed by `layout`; empty objects are left out.
+/// Colours become one `basematerials` group (`displaycolor`). Returns (triangles, bytes).
+pub fn write_3mf_objects(
+ objects: &[Object<'_>],
+ unit: Unit,
+ layout: Layout,
+ out: &Path,
+) -> AssetResult<(u64, u64)> {
+ let objects: Vec<&Object> = objects
+ .iter()
+ .filter(|o| !o.mesh.triangles.is_empty())
+ .collect();
+ if objects.is_empty() {
return Err(AssetError::invalid("the model has no triangles"));
}
+ let n = objects.len() as u32;
+ let tris: u64 = objects.iter().map(|o| o.mesh.triangles.len() as u64).sum();
+ let verts: u64 = objects.iter().map(|o| o.mesh.vertices.len() as u64).sum();
+ let assembly = layout == Layout::Assembly && n > 1;
+ let colored = objects.iter().any(|o| o.color.is_some());
+ // Object ids 1..=n, the assembly n + 1, the materials n + 2 (written first).
+ let mat_id = n + 2;
let io = |e: std::io::Error| AssetError::internal(format!("{}: {e}", out.display()));
let zerr = |e: zip::result::ZipError| AssetError::internal(format!("{}: {e}", out.display()));
let (part, file) = super::new_part(out)?;
@@ -98,20 +151,78 @@ pub fn write_3mf(tris: &[[[f32; 3]; 3]], out: &Path) -> AssetResult<(u64, u64)>
z.start_file("_rels/.rels", opts).map_err(zerr)?;
z.write_all(RELS.as_bytes()).map_err(io)?;
// About 45 bytes per vertex and 40 per triangle: Zip64 only when that may pass 4 GB.
- let guess = 64 * (mesh.vertices.len() as u64 + mesh.triangles.len() as u64);
+ let guess = 64 * (verts + tris);
z.start_file("3D/3dmodel.model", opts.large_file(guess > u32::MAX as u64))
.map_err(zerr)?;
{
let mut w = std::io::BufWriter::with_capacity(1 << 16, &mut z);
- w.write_all(MODEL_HEAD.as_bytes()).map_err(io)?;
- for [x, y, z] in &mesh.vertices {
- writeln!(w, r#""#).map_err(io)?;
+ write!(
+ w,
+ concat!(
+ r#""#,
+ "\n",
+ r#""#,
+ "\n",
+ r#"StarOrg Codex (StarBreaker GLB, Z-up)"#,
+ "\n\n",
+ ),
+ unit.xml()
+ )
+ .map_err(io)?;
+ if colored {
+ writeln!(w, r#""#).map_err(io)?;
+ for (i, o) in objects.iter().enumerate() {
+ let [r, g, b, a] = o.color.unwrap_or([0x9a, 0x9a, 0x9a, 0xff]);
+ let name = if o.name.is_empty() {
+ format!("part{}", i + 1)
+ } else {
+ esc(o.name)
+ };
+ writeln!(
+ w,
+ r##""##
+ )
+ .map_err(io)?;
+ }
+ w.write_all(b"\n").map_err(io)?;
+ }
+ for (i, o) in objects.iter().enumerate() {
+ let id = i as u32 + 1;
+ write!(w, r#"\n\n\n").map_err(io)?;
+ for [x, y, z] in &o.mesh.vertices {
+ writeln!(w, r#""#).map_err(io)?;
+ }
+ w.write_all(b"\n\n").map_err(io)?;
+ for [a, b, c] in &o.mesh.triangles {
+ writeln!(w, r#""#).map_err(io)?;
+ }
+ w.write_all(b"\n\n\n")
+ .map_err(io)?;
+ }
+ if assembly {
+ writeln!(w, r#""#, n + 1).map_err(io)?;
+ w.write_all(b"\n").map_err(io)?;
+ for id in 1..=n {
+ writeln!(w, r#""#).map_err(io)?;
+ }
+ w.write_all(b"\n\n").map_err(io)?;
}
- w.write_all(b"\n\n").map_err(io)?;
- for [a, b, c] in &mesh.triangles {
- writeln!(w, r#""#).map_err(io)?;
+ w.write_all(b"\n\n").map_err(io)?;
+ if assembly {
+ writeln!(w, r#""#, n + 1).map_err(io)?;
+ } else {
+ for id in 1..=n {
+ writeln!(w, r#""#).map_err(io)?;
+ }
}
- w.write_all(MODEL_TAIL.as_bytes()).map_err(io)?;
+ w.write_all(b"\n\n").map_err(io)?;
w.flush().map_err(io)?;
}
let f = z
@@ -127,7 +238,7 @@ pub fn write_3mf(tris: &[[[f32; 3]; 3]], out: &Path) -> AssetResult<(u64, u64)>
if r.is_err() {
let _ = std::fs::remove_file(&part);
}
- Ok((mesh.triangles.len() as u64, r?))
+ Ok((tris, r?))
}
/// GLB bytes -> 3MF file; returns (triangles written, bytes).
diff --git a/docs/Home.md b/docs/Home.md
index f32ab09..132c180 100644
--- a/docs/Home.md
+++ b/docs/Home.md
@@ -1,7 +1,7 @@
---
title: StarOrg Codex
tags: [docs]
-updated: 2026-11-15
+updated: 2026-11-17
---
# StarOrg Codex
@@ -24,6 +24,7 @@ updated: 2026-11-15
## Plans
- [[plans/specs/starorg-codex-v1|v1 spec]] ([plain](plans/specs/starorg-codex-v1.md))
- [[plans/specs/starorg-codex-v1-addendum|v1 addendum: dumps, LUG hooks, Smart Citizen import, StarOrg Tools sync, fleet and ships, dev mode (explorer item finder, assets, memory limit), strings grouping and owners, gamedata port, local MCP server, stale reasons, blueprint markers, quest item hints]] ([plain](plans/specs/starorg-codex-v1-addendum.md))
+- [[plans/specs/model-print|Model export: 3D print processing (experimental)]] ([plain](plans/specs/model-print.md))
## Repo (outside the vault, plain links only)
- [README](../README.md) · [Contributing](../CONTRIBUTING.md) · [Agent and repo guide](../AGENTS.md) · [Patches and pull requests](../PATCH.md) · [Code of Conduct](../CODE_OF_CONDUCT.md) · [Security policy](../SECURITY.md)
diff --git a/docs/README.md b/docs/README.md
index 1c518bd..442cadc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,7 +1,7 @@
---
title: StarOrg Codex docs
tags: [docs]
-updated: 2026-11-15
+updated: 2026-11-17
---
# StarOrg Codex docs
@@ -27,6 +27,7 @@ updated: 2026-11-15
- [v1 spec](plans/specs/starorg-codex-v1.md)
- [v1 addendum: dumps, LUG hooks, Smart Citizen import, StarOrg Tools sync, fleet and ships, dev mode (explorer item finder, assets, memory limit), strings grouping and owners, gamedata port, local MCP server, stale reasons, blueprint markers, quest item hints](plans/specs/starorg-codex-v1-addendum.md)
+- [Model export: 3D print processing (experimental)](plans/specs/model-print.md)
- Decisions: [Tauri + Svelte UI](decisions/tauri-svelte-ui.md) · [StarBreaker as a library](decisions/starbreaker-as-library.md) · [Own patch format](decisions/own-patch-format.md) · [Rename to starorg-codex (0.3.0)](decisions/rename-to-starorg-codex.md)
- [Now](plans/now/todo.md) · [Next](plans/next/backlog.md) · [Later](plans/later/ideas.md)
diff --git a/docs/plans/now/todo.md b/docs/plans/now/todo.md
index c83be9a..4195fb3 100644
--- a/docs/plans/now/todo.md
+++ b/docs/plans/now/todo.md
@@ -1,7 +1,7 @@
---
title: Now
tags: [docs, plans, now]
-updated: 2026-11-15
+updated: 2026-11-17
---
# Now
@@ -33,6 +33,11 @@ Developer mode (addendum §7)
- [ ] Backlinks ("Referenced by", Q-D2) and the `starorg-gamedata` domain outputs as a source ([#15](https://github.com/voidput/starorg-codex/issues/15))
- [ ] Owner: open Explorer on LIVE in the real app and try a type export ([#15](https://github.com/voidput/starorg-codex/issues/15))
+Model export 3D print processing, experimental — [[specs/model-print]] ([plain](../specs/model-print.md))
+
+- [ ] Fill the stubs (scale: drop tiny + bed check; voxel: solid, thicken, hollow, pegs, extract; split; color; simplify; weapons) per the spec's module table
+- [ ] Owner: print a Skylark from `dev print-glb` output and report what the slicer says
+
Local MCP server, experimental (addendum §10)
- [ ] Owner: connect Claude Code / Claude Desktop to the app's server on a real install and try the tools ([#15](https://github.com/voidput/starorg-codex/issues/15))
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
new file mode 100644
index 0000000..bdb7ae9
--- /dev/null
+++ b/docs/plans/specs/model-print.md
@@ -0,0 +1,102 @@
+---
+title: "Model export: 3D print processing (experimental)"
+tags: [docs, plans, specs]
+status: active
+updated: 2026-11-17
+---
+
+# Model export: 3D print processing (experimental)
+
+Experimental processing of the **STL/3MF** written next to a **Print shell** GLB
+([addendum 7.16](starorg-codex-v1-addendum.md)). The GLB stays as exported (glTF Y-up,
+metres); the STL/3MF are Z-up. Every option is **off by default** and labelled experimental
+(UI badge "Experimental", CLI help "(experimental)"); the model always sits on the bed.
+Only `no_weapons` changes the GLB (it is part of the cache key: `print-lod0-noweapons`).
+
+## Options
+
+`assets::print::PrintOptions` (serde, every field defaulted, one nested `print` object in
+`AssetExportModelRequest` and `ModelOptions`; mirrored in `app/src/lib/contract/assets.ts`,
+defaults and checks in `app/src/lib/printoptions.ts`).
+
+| Option | Type, default | CLI | Needs |
+|---|---|---|---|
+| `scale` | `none` \| `fit-mm` (f32, UI default 150) \| `ratio` (u32, 1:N) | `--fit-mm N` \| `--scale-ratio N` (exclusive) | |
+| `bed_mm` | `[f32; 3]`, `[256, 256, 256]` (remembered by the UI) | `--bed XxYxZ` | |
+| `shrink_to_bed` | bool | `--shrink-to-bed` | |
+| `drop_small_mm` | `Option` (1.0 when on) | `--drop-small MM` | |
+| `solid` + `solid_res_mm` | bool + 0.1 \| 0.2 \| 0.4 (0.2) | `--solid [RES]` | a scale or `shrink_to_bed` |
+| `thicken_mm` | `Option` (0.8) | `--thicken MM` | `solid` |
+| `hollow` | `Option<{wall_mm 2.0, drain_mm 3.0}>` | `--hollow WALL[,DRAIN]` | `solid` |
+| `peg_mm` | `Option`: 3 \| 5 \| 6, 8 mm deep | `--peg MM` | `split` |
+| `split` | bool | `--split` | `solid` |
+| `multicolor` | bool | `--multicolor` | |
+| `simplify_tris` | `Option` (200000, at least 1000) | `--simplify N` | |
+| `no_weapons` | bool (changes the GLB) | `--no-weapons` | |
+
+`PrintOptions::validate` refuses values out of range and options without what they need; the
+same messages come from the CLI (exit 2), the backends (`invalid`) and the TS check (the
+dialog disables "Save as…"). Print options with `--preset full` are refused by the CLI and
+ignored by the backends (as a Print shell ignores paints).
+
+## Pipeline
+
+`print::apply(mesh, &PrintOptions, progress) -> AssetResult`, fixed order:
+
+1. classify groups (multicolor only; otherwise groups are dropped)
+2. drop tiny parts (measured at print size)
+3. scale (`scale::factor`: real size stays metres, `unit="meter"`; any scale or shrink -> mm)
+4. sit on the bed (min z = 0)
+5. bed check / shrink to the bed, sit on the bed
+6. voxel solid, 7. thicken, 8. hollow + drain, 9. pegs (at `split::plan`'s cuts)
+10. split into pieces
+11. extract per group (`voxel::extract`, then `color::by_group`)
+12. simplify (the triangle budget shared by part size)
+13. sit on the bed again (each split piece alone, else all together)
+14. write: one 3MF with every part (`color::layout`: one assembly for multicolor without
+ split, else one build item per part; display colours as `basematerials`); one STL, or one
+ STL per part for separate parts (`ship-piece-1.stl`)
+
+Input: `Mesh::from_glb` (shared vertices, degenerate triangles dropped, each triangle's group is
+its GLB node path such as `geo_body` or `hardpoint_weapon_left/mesh_gun`).
+
+## Module ownership
+
+Each feature agent edits **only its file** (and may add `#[cfg(test)] mod tests` inside it);
+signatures below are final. Shared files (`print/mod.rs`, `threemf.rs`, `stl.rs`, the contract,
+CLI, UI) belong to the foundation; ask before changing them.
+
+| File | Owner | Implement |
+|---|---|---|
+| `crates/starorg-data/src/assets/print/scale.rs` | scale | `drop_tiny(&mut Mesh, min_size: f32) -> usize`, `bed_check(&mut Mesh, &PrintOptions, Unit, &mut Vec) -> AssetResult<()>` (done: `factor`, `scale`, `sit_on_bed`) |
+| `crates/starorg-data/src/assets/print/voxel.rs` | voxel | `voxelize(&Mesh, res, Progress) -> AssetResult`, `thicken(&mut VoxelGrid, min, Progress) -> AssetResult<()>`, `hollow(&mut VoxelGrid, wall, drain, &mut Vec, Progress) -> AssetResult<()>`, `peg(&mut VoxelGrid, &[Cut], diameter, depth, &mut Vec) -> AssetResult<()>`, `extract(&VoxelGrid, Progress) -> AssetResult`; keeps the `VoxelGrid` API |
+| `crates/starorg-data/src/assets/print/split.rs` | split | `plan(&VoxelGrid, bed: [f32; 3]) -> Vec`, `split(VoxelGrid, &[Cut]) -> Vec` |
+| `crates/starorg-data/src/assets/print/color.rs` | color | `classify(&mut Mesh)`, `by_group(&Mesh) -> Vec<(String, Mesh)>`, `color_of(&str) -> Option<[u8; 4]>` (done: `layout`) |
+| `crates/starorg-data/src/assets/print/simplify.rs` | simplify | `simplify(&mut Mesh, target: u32, Progress) -> AssetResult<()>` |
+| `crates/starorg-data/src/assets/model.rs` (`strip_weapons` only) | weapons | `strip_weapons(&Database<'static>, &mut LoadoutTree) -> usize` |
+
+Lengths passed to the steps are in mesh units (after step 3: millimetres, or metres at real
+size); the pipeline converts the options' millimetres. `Progress` is
+`&(dyn Fn(f32, &str) -> bool + Sync)`; false cancels (`AssetError::cancelled`).
+
+Shared types (`print/mod.rs`): `Mesh { vertices, triangles, groups: Option>, labels }`
+with `from_triangles`, `from_labeled`, `from_glb`, `bounds`, `soup`, `subset`,
+`retain_triangles`, `compact`, `append`, `map_vertices`; `Aabb`; `Cut { axis, at }`;
+`Part { name, mesh, color }`; `PrintOutput { parts, unit, layout, notes }`. `VoxelGrid`
+(`voxel.rs`): `new`, `get`/`set`/`is_solid`, `center`, `cell_at`, `crop`, `cells(_mut)`,
+`count_solid`; a cell is 0 (empty) or 1 + its group. `threemf::write_3mf_objects(&[Object],
+Unit, Layout, path)`.
+
+## Testing on real GLBs
+
+`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
+pipeline on an existing GLB (both files without `--stl`/`--3mf`), reading no game files; e.g.
+on a Skylark LOD 4 Print shell (98 376 triangles) `--fit-mm 150` takes about 1 s in a debug build.
+Notes from the steps are printed (and in `--json`, the app's export note).
+
+## Status
+
+Foundation done: options, contract in all four layers, CLI flags and `dev print-glb`, the
+dialog's "3D print (experimental)" section, the writer (units, several objects, assemblies,
+colours), `factor`/`scale`/`sit_on_bed`, `layout`. Stubs: the rest of the table above
+(`voxelize`/`extract` refuse "not available in this build yet"; the others pass through).
diff --git a/docs/user-guide.md b/docs/user-guide.md
index 2e762ef..54707b8 100644
--- a/docs/user-guide.md
+++ b/docs/user-guide.md
@@ -1,7 +1,7 @@
---
title: User guide
tags: [docs]
-updated: 2026-11-15
+updated: 2026-11-17
---
# User guide
@@ -175,6 +175,12 @@ For players who want to look things up in the game data. Read only on the game.
the GLB goes; the STL and 3MF are written next to it with the same name. The 3MF is
experimental: the mesh is the game's, not made for printing, so it may need repair in the
slicer.
+ With an STL or 3MF on, **3D print (experimental)** offers print processing of those files
+ (the GLB stays as exported): a size (longest side in mm or 1:N), the bed size (remembered),
+ shrink to the bed, leaving out tiny parts, a voxel solid (thicken, hollow with a drain hole,
+ split to fit the bed with peg holes), multicolor objects, simplify, and no weapons. All are
+ off by default and experimental; some are not built yet and say so. CLI: the same flags on
+ `dev export-model --preset print`, and `dev print-glb` for a GLB you already have.
A **Full** export can wear any paint the ship has (**Paint**, listed with their in-game names;
default: the one fitted) and can include **Layer materials (experimental)**, the textures of
each material's layers (bigger files; some surfaces may look wrong).
From e175f1547b9768e6ce3390017178eef4813a0f19 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:06:42 -0600
Subject: [PATCH 03/12] feat(dev): experimental Print shell export without
weapons
strip_weapons drops gun mounts, guns, mining lasers, tractor beams,
missile racks, missiles and bombs from the loadout before StarBreaker
assembles the GLB; turret bodies, countermeasures, thrusters and paint
stay. The export notes how many loadout parts were left out. The types
come from the LIVE loadouts of 15 ships; real_weapons checks four.
---
crates/starorg-data/src/assets/model.rs | 159 +++++++++++++++++++++-
crates/starorg-data/tests/real_weapons.rs | 85 ++++++++++++
docs/plans/specs/model-print.md | 18 +++
3 files changed, 255 insertions(+), 7 deletions(-)
create mode 100644 crates/starorg-data/tests/real_weapons.rs
diff --git a/crates/starorg-data/src/assets/model.rs b/crates/starorg-data/src/assets/model.rs
index 97397cc..4985f81 100644
--- a/crates/starorg-data/src/assets/model.rs
+++ b/crates/starorg-data/src/assets/model.rs
@@ -346,6 +346,7 @@ pub fn export_model(
let lod = effective_lod(o.lod, &lods);
let opts = export_options(&ModelOptions { lod, ..o.clone() });
let paint = o.paint().map(|tag| choose_paint(db, r, tag)).transpose()?;
+ let mut stripped = 0;
let bytes = crate::extract::guarded("model export", || {
let idx = EntityIndex::new(db);
let mut tree = resolve_loadout_indexed(&idx, r);
@@ -353,7 +354,7 @@ pub fn export_model(
wear_paint(&mut tree, p);
}
if o.no_weapons() {
- strip_weapons(db, &mut tree);
+ stripped = strip_weapons(db, &mut tree);
}
let p = starbreaker_common::Progress::with_callback(progress);
let res = starbreaker_3d::assemble_glb_with_loadout_with_progress(
@@ -404,6 +405,12 @@ pub fn export_model(
done.meshes = m.files;
done.notes = m.notes;
}
+ if o.no_weapons() {
+ done.notes.insert(
+ 0,
+ format!("Without weapons (experimental): {stripped} loadout parts left out"),
+ );
+ }
drop(bytes);
done.ms = started.elapsed().as_millis() as u64;
done.peak_rss = peak_rss_bytes();
@@ -619,13 +626,70 @@ fn choose_paint(db: &Database<'static>, r: &Record, tag: &str) -> AssetResult bool {
+ WEAPON_TYPES.iter().any(|w| w.eq_ignore_ascii_case(ty))
+ || (ty.eq_ignore_ascii_case("UtilityTurret") && sub.eq_ignore_ascii_case("GunTurret"))
+}
+
+/// Leave the weapons out of a Print shell's loadout (experimental `no_weapons`): remove the
+/// nodes whose item [`is_weapon`] (guns, their mounts, missile racks and missiles) with what
+/// they hold, keeping turrets' bodies and everything else. The root always stays. Returns how
+/// many nodes were removed, counting each removed node's descendants.
pub fn strip_weapons(db: &Database<'static>, tree: &mut LoadoutTree) -> usize {
- let _ = (db, tree);
- 0
+ let ty = format!("{ATTACH}.Type");
+ let sub = format!("{ATTACH}.SubType");
+ strip_where(&mut tree.root, &|n| {
+ let t = query_text(db, &n.record, &ty).unwrap_or_default();
+ let s = query_text(db, &n.record, &sub).unwrap_or_default();
+ is_weapon(&t, &s)
+ })
+}
+
+/// Remove `node`'s descendants for which `drop` is true (not looking below them); the count
+/// includes their own descendants.
+fn strip_where(node: &mut LoadoutNode, drop: &dyn Fn(&LoadoutNode) -> bool) -> usize {
+ let mut removed = 0;
+ node.children.retain(|c| {
+ let gone = drop(c);
+ if gone {
+ removed += count_nodes(c);
+ }
+ !gone
+ });
+ for c in &mut node.children {
+ removed += strip_where(c, drop);
+ }
+ removed
+}
+
+fn count_nodes(n: &LoadoutNode) -> usize {
+ 1 + n.children.iter().map(count_nodes).sum::()
}
/// Fit `p` on the root's paint port (adding the port when the default loadout leaves it out).
@@ -654,3 +718,84 @@ fn wear_paint(tree: &mut LoadoutTree, p: &PaintItem) {
children: Vec::new(),
});
}
+
+#[cfg(test)]
+mod weapon_tests {
+ use super::*;
+
+ fn node(record: Record, name: &str, children: Vec) -> LoadoutNode {
+ LoadoutNode {
+ record,
+ entity_name: name.into(),
+ item_port_name: format!("hardpoint_{name}"),
+ helper_bone_name: None,
+ no_rotation: false,
+ offset_position: [0.0; 3],
+ offset_rotation: [0.0; 3],
+ detach_direction: [0.0; 3],
+ port_flags: String::new(),
+ port_tags: String::new(),
+ geometry_path: None,
+ material_path: None,
+ children,
+ }
+ }
+
+ #[test]
+ fn weapons_are_the_guns_their_mounts_and_the_missiles() {
+ for (t, s) in [
+ ("WeaponGun", "Gun"),
+ ("Turret", "GunTurret"),
+ ("Turret", "BallTurret"),
+ ("Turret", "NoseMounted"),
+ ("MissileLauncher", "MissileRack"),
+ ("Missile", "Missile"),
+ ("WeaponMining", "Gun"),
+ ("TractorBeam", "UNDEFINED"),
+ ("UtilityTurret", "GunTurret"),
+ ("weapongun", "gun"),
+ ] {
+ assert!(is_weapon(t, s), "{t}/{s}");
+ }
+ for (t, s) in [
+ ("TurretBase", "MannedTurret"),
+ ("UtilityTurret", "MannedTurret"),
+ ("WeaponDefensive", "CountermeasureLauncher"),
+ ("MainThruster", "FixedThruster"),
+ ("Paints", "UNDEFINED"),
+ ("Module", "UNDEFINED"),
+ ("ToolArm", "UNDEFINED"),
+ ("LandingSystem", "UNDEFINED"),
+ ("", ""),
+ ] {
+ assert!(!is_weapon(t, s), "{t}/{s}");
+ }
+ }
+
+ #[test]
+ fn stripping_removes_weapon_subtrees_and_keeps_turret_bodies() {
+ let (_t, a) = super::super::tests::open();
+ let r = *a.db().unwrap().records().first().unwrap();
+ let gun = |n: &str| node(r, n, vec![node(r, "barrel", vec![])]);
+ let mut root = node(
+ r,
+ "ship",
+ vec![
+ node(r, "thruster", vec![]),
+ node(r, "mount", vec![gun("gun")]),
+ node(r, "turret_body", vec![node(r, "mount", vec![gun("gun")])]),
+ node(r, "paint", vec![]),
+ ],
+ );
+ let removed = strip_where(&mut root, &|n| n.entity_name == "mount");
+ assert_eq!(removed, 6);
+ let names: Vec<&str> = root
+ .children
+ .iter()
+ .map(|c| c.entity_name.as_str())
+ .collect();
+ assert_eq!(names, ["thruster", "turret_body", "paint"]);
+ assert!(root.children[1].children.is_empty());
+ assert_eq!(strip_where(&mut root, &|n| n.entity_name == "ship"), 0);
+ }
+}
diff --git a/crates/starorg-data/tests/real_weapons.rs b/crates/starorg-data/tests/real_weapons.rs
new file mode 100644
index 0000000..20d2d7f
--- /dev/null
+++ b/crates/starorg-data/tests/real_weapons.rs
@@ -0,0 +1,85 @@
+//! Print shell without weapons (experimental) on a real LIVE install: the guns, their mounts
+//! and the missiles leave a few ships' loadouts, their turret bodies, thrusters and paint stay.
+//! Read only. Ignored by default:
+//!
+//! ```sh
+//! cargo test --release -p starorg-data --test real_weapons -- --ignored --nocapture
+//! ```
+//!
+//! `STARORG_GAME_DIR` as in `real_archives`; `STARORG_SHIPS` (comma separated) for other ships.
+
+use starbreaker_datacore::database::Database;
+use starbreaker_datacore::loadout::{EntityIndex, LoadoutNode, resolve_loadout_indexed};
+use starorg_data::assets::model::strip_weapons;
+use starorg_data::assets::{AssetArchive, find_record};
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+fn live_p4k() -> PathBuf {
+ std::env::var_os("STARORG_GAME_DIR")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| {
+ PathBuf::from(
+ "/mnt/games/star-citizen/drive_c/Program Files/Roberts Space Industries/StarCitizen",
+ )
+ })
+ .join("LIVE")
+ .join("Data.p4k")
+}
+
+fn names(n: &LoadoutNode, out: &mut BTreeMap) {
+ *out.entry(n.entity_name.clone()).or_default() += 1;
+ for c in &n.children {
+ names(c, out);
+ }
+}
+
+fn count(n: &LoadoutNode) -> usize {
+ 1 + n.children.iter().map(count).sum::()
+}
+
+fn has(m: &BTreeMap, part: &str) -> bool {
+ m.keys().any(|k| k.contains(part))
+}
+
+#[test]
+#[ignore]
+fn weapons_leave_real_loadouts() {
+ let a = AssetArchive::open(&live_p4k()).unwrap();
+ let db: &Database<'static> = a.db().unwrap();
+ let idx = EntityIndex::new(db);
+ let ships = std::env::var("STARORG_SHIPS")
+ .unwrap_or_else(|_| "RSI_Skylark,AEGS_Gladius,DRAK_Cutlass_Black,ANVL_Arrow".into());
+ for ship in ships.split(',') {
+ let r = find_record(db, ship).unwrap();
+ let mut tree = resolve_loadout_indexed(&idx, r);
+ let before_n = count(&tree.root);
+ let mut before = BTreeMap::new();
+ names(&tree.root, &mut before);
+ let removed = strip_weapons(db, &mut tree);
+ let mut after = BTreeMap::new();
+ names(&tree.root, &mut after);
+ assert_eq!(count(&tree.root) + removed, before_n, "{ship}");
+ let gone: Vec = before
+ .iter()
+ .filter_map(|(k, &n)| {
+ let left = after.get(k).copied().unwrap_or(0);
+ (n > left).then(|| format!("{k} x{}", n - left))
+ })
+ .collect();
+ println!(
+ "{ship}: {removed} of {before_n} nodes removed: {}",
+ gone.join(", ")
+ );
+ assert!(removed > 0, "{ship}");
+ for w in ["Mount_Gimbal", "LaserRepeater", "MISL_", "MRCK_"] {
+ assert!(!has(&after, w), "{ship} keeps {w}");
+ }
+ assert!(has(&after, "Thruster"), "{ship} lost its thrusters");
+ // A manned turret's body (`TurretBase`, `DRAK_Cutlass_SCItem_Turret_Black`) stays.
+ assert!(
+ !has(&before, "_SCItem_Turret") || has(&after, "_SCItem_Turret"),
+ "{ship} lost a turret body"
+ );
+ }
+}
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
index bdb7ae9..08fc83f 100644
--- a/docs/plans/specs/model-print.md
+++ b/docs/plans/specs/model-print.md
@@ -87,6 +87,24 @@ with `from_triangles`, `from_labeled`, `from_glb`, `bounds`, `soup`, `subset`,
`count_solid`; a cell is 0 (empty) or 1 + its group. `threemf::write_3mf_objects(&[Object],
Unit, Layout, path)`.
+## Without weapons
+
+`model::strip_weapons` removes, before StarBreaker assembles the GLB, every loadout node whose
+item's `AttachDef.Type` is `Turret` (a gun's own mount: `Mount_Gimbal_*` `GunTurret`, the
+Arrow's chin `BallTurret`, `NoseMounted` cannons), `WeaponGun`, `WeaponMining`, `TractorBeam`,
+`WeaponAttachment`, `MissileLauncher`, `Missile`, `BombLauncher` or `Bomb`, or `UtilityTurret`
+`GunTurret` (a mining laser gimbal), with everything below it (`model::is_weapon`). Kept:
+turret bodies (`TurretBase` and `UtilityTurret` `MannedTurret`: Cutlass/Retaliator domes, MOLE
+cabs, whose guns still go), countermeasure launchers (`WeaponDefensive`), thrusters, seats,
+doors, modules, the paint. The list comes from the LIVE loadouts of 15 ships. The export adds
+the note "Without weapons (experimental): N loadout parts left out".
+
+LIVE, Print shell LOD 4, STL triangles with and without: Skylark 98 376 -> 71 121 (18 nodes:
+3 `Mount_Gimbal_S2`, 3 `KLWE_LaserRepeater_S2`, 2 missile racks, 10 missiles); Gladius
+104 142 -> 59 000 (20 nodes: 3 gimbals, 3 guns and the Gatling's 4 attachments, 4 racks, 6
+missiles). `cargo test --release -p starorg-data --test real_weapons -- --ignored` checks
+Skylark, Gladius, Cutlass Black and Arrow.
+
## Testing on real GLBs
`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
From 59cc45af1007233d18a212dafcad226563397af4 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:07:34 -0600
Subject: [PATCH 04/12] feat(print): scale placement, bed check and dropping
tiny parts (experimental)
sit_on_bed centres x/y as well as putting the bottom at z = 0. bed_check
turns a scaled model 90 degrees about Z when only that fits, shrinks it
with shrink-to-bed (turned when that keeps it larger) or notes that it
does not fit; real size in metres is not checked. drop_tiny welds
corners, finds loose parts and leaves out those whose bounding-box
diagonal at print size is under the limit. The pipeline now measures a
fit size after small parts are dropped.
---
crates/starorg-cli/tests/dev_assets.rs | 8 +-
crates/starorg-data/src/assets/print/mod.rs | 2 +
crates/starorg-data/src/assets/print/scale.rs | 530 +++++++++++++++++-
crates/starorg-data/src/assets/print/tests.rs | 2 +-
docs/plans/specs/model-print.md | 23 +-
5 files changed, 545 insertions(+), 20 deletions(-)
diff --git a/crates/starorg-cli/tests/dev_assets.rs b/crates/starorg-cli/tests/dev_assets.rs
index 5ac7b08..662aaa7 100644
--- a/crates/starorg-cli/tests/dev_assets.rs
+++ b/crates/starorg-cli/tests/dev_assets.rs
@@ -495,9 +495,15 @@ fn print_glb_writes_the_stl_and_3mf_of_a_glb_through_the_pipeline() {
let f = |o: usize| f32::from_le_bytes(stl[o..o + 4].try_into().unwrap());
let zs = [f(84 + 12 + 8), f(84 + 24 + 8), f(84 + 36 + 8)];
assert_eq!(zs.iter().copied().fold(f32::INFINITY, f32::min), 0.0);
+ // 100 mm wide, centred on the bed.
let xs = [f(84 + 12), f(84 + 24), f(84 + 36)];
+ let (lo, hi) = xs
+ .iter()
+ .fold((f32::INFINITY, f32::NEG_INFINITY), |(a, b), &x| {
+ (a.min(x), b.max(x))
+ });
assert!(
- (xs.iter().copied().fold(0.0, f32::max) - 100.0).abs() < 1e-3,
+ (hi - lo - 100.0).abs() < 1e-3 && (lo + hi).abs() < 1e-3,
"{xs:?}"
);
// Only the 3MF when asked; --no-weapons is for export-model.
diff --git a/crates/starorg-data/src/assets/print/mod.rs b/crates/starorg-data/src/assets/print/mod.rs
index 773a2b5..6627cd7 100644
--- a/crates/starorg-data/src/assets/print/mod.rs
+++ b/crates/starorg-data/src/assets/print/mod.rs
@@ -578,6 +578,8 @@ pub fn apply(mut mesh: Mesh, o: &PrintOptions, progress: Progress<'_>) -> AssetR
)));
}
}
+ // A fit size is the longest side of what is left.
+ let s = scale::factor(&mesh.bounds().unwrap_or(bounds), o);
scale::scale(&mut mesh, s.k);
let unit = s.unit;
let per_mm = 1.0 / unit.mm();
diff --git a/crates/starorg-data/src/assets/print/scale.rs b/crates/starorg-data/src/assets/print/scale.rs
index 76077be..57235fa 100644
--- a/crates/starorg-data/src/assets/print/scale.rs
+++ b/crates/starorg-data/src/assets/print/scale.rs
@@ -1,12 +1,12 @@
//! Print size (experimental): the scale mode, sitting on the bed, the bed check (or shrinking
//! to the bed) and leaving out tiny parts. Pipeline steps 2-5 and 13 of [`super::apply`].
//!
-//! Owner: the scale agent. [`factor`], [`scale`] and [`sit_on_bed`] are done; [`drop_tiny`] and
-//! [`bed_check`] are pass-through stubs.
+//! Owner: the scale agent.
use super::{Aabb, Mesh, PrintOptions, ScaleMode};
use crate::assets::AssetResult;
use crate::assets::threemf::Unit;
+use std::collections::{HashMap, HashSet};
/// How the mesh (metres) is scaled: multiply every coordinate by `k`; the result is in `unit`.
#[derive(Debug, Clone, Copy, PartialEq)]
@@ -44,37 +44,533 @@ pub fn scale(mesh: &mut Mesh, k: f32) {
}
}
-/// Move `meshes` together so the lowest point of all of them is at z = 0 (always applied).
+/// Move `meshes` together so the lowest point of all of them is at z = 0 and the middle of
+/// their combined footprint at x = y = 0, the middle of the bed (always applied).
pub fn sit_on_bed(meshes: &mut [&mut Mesh]) {
- let low = meshes
+ let Some(b) = meshes
.iter()
.filter_map(|m| m.bounds())
- .map(|b| b.min[2])
- .fold(f32::INFINITY, f32::min);
- if low.is_finite() && low != 0.0 {
+ .reduce(|a, b| Aabb {
+ min: [0, 1, 2].map(|i| a.min[i].min(b.min[i])),
+ max: [0, 1, 2].map(|i| a.max[i].max(b.max[i])),
+ })
+ else {
+ return;
+ };
+ let d = [
+ (b.min[0] + b.max[0]) / 2.0,
+ (b.min[1] + b.max[1]) / 2.0,
+ b.min[2],
+ ];
+ if d.iter().all(|c| c.is_finite()) && d != [0.0; 3] {
for m in meshes.iter_mut() {
- m.map_vertices(|[x, y, z]| [x, y, z - low]);
+ m.map_vertices(|[x, y, z]| [x - d[0], y - d[1], z - d[2]]);
}
}
}
-/// TODO(scale agent): leave out connected parts whose largest side is under `min_size` (mesh
-/// units, metres here: the pipeline converts `drop_small_mm` at print size). Returns how many
-/// parts were left out. Stub: keeps everything.
+/// Corners closer than this fraction of `min_size` count as one when finding loose parts.
+const WELD_FRACTION: f32 = 1e-3;
+
+/// Leave out loose parts whose bounding-box diagonal is under `min_size` (mesh units; the
+/// pipeline converts `drop_small_mm` at print size). A loose part is a set of triangles joined
+/// by shared corners, after welding corners closer than [`WELD_FRACTION`] of `min_size` (GLB
+/// nodes often repeat the corners along a seam). A small part inside or touching a larger one
+/// without sharing a corner is still loose. Returns how many parts were left out.
pub fn drop_tiny(mesh: &mut Mesh, min_size: f32) -> usize {
- let _ = (mesh, min_size);
- 0
+ if !(min_size.is_finite() && min_size > 0.0) || mesh.is_empty() {
+ return 0;
+ }
+ let mut sets = Sets::new(mesh.vertices.len());
+ weld(&mesh.vertices, min_size * WELD_FRACTION, &mut sets);
+ for t in &mesh.triangles {
+ sets.join(t[0], t[1]);
+ sets.join(t[0], t[2]);
+ }
+ let roots: Vec = mesh.triangles.iter().map(|t| sets.root(t[0])).collect();
+ // The bounds of each part, by its root vertex.
+ let mut parts: HashMap = HashMap::new();
+ for (t, root) in mesh.triangles.iter().zip(&roots) {
+ for &i in t {
+ let p = mesh.vertices[i as usize];
+ let b = parts.entry(*root).or_insert(Aabb { min: p, max: p });
+ for (k, c) in p.iter().enumerate() {
+ b.min[k] = b.min[k].min(*c);
+ b.max[k] = b.max[k].max(*c);
+ }
+ }
+ }
+ let small: HashSet = parts
+ .iter()
+ .filter(|(_, b)| diagonal(b) < min_size)
+ .map(|(r, _)| *r)
+ .collect();
+ if !small.is_empty() {
+ mesh.retain_triangles(|t| !small.contains(&roots[t]));
+ }
+ small.len()
+}
+
+fn diagonal(b: &Aabb) -> f32 {
+ b.size().iter().map(|s| s * s).sum::().sqrt()
}
-/// TODO(scale agent): compare the mesh (in `unit`, sitting on the bed) with `o.bed_mm`; when
-/// larger, shrink it to fit with `o.shrink_to_bed` (and say so in `notes`), else add a note
-/// that it does not fit (with `o.split`, the split makes pieces that do). Stub: nothing.
+/// Join every pair of vertices closer than `eps` (a hash grid of `eps` cells, each vertex
+/// compared with those in the 27 cells around its own).
+fn weld(vertices: &[[f32; 3]], eps: f32, sets: &mut Sets) {
+ if !(eps.is_finite() && eps > 0.0) {
+ return;
+ }
+ let cell = |p: [f32; 3]| p.map(|c| (c / eps).floor() as i64);
+ let mut grid: HashMap<[i64; 3], Vec> = HashMap::with_capacity(vertices.len());
+ let eps2 = eps * eps;
+ for (i, &p) in vertices.iter().enumerate() {
+ let c = cell(p);
+ for dx in -1..=1 {
+ for dy in -1..=1 {
+ for dz in -1..=1 {
+ let Some(near) = grid.get(&[c[0] + dx, c[1] + dy, c[2] + dz]) else {
+ continue;
+ };
+ for &j in near {
+ let q = vertices[j as usize];
+ let d2: f32 = (0..3).map(|k| (p[k] - q[k]).powi(2)).sum();
+ if d2 <= eps2 {
+ sets.join(i as u32, j);
+ }
+ }
+ }
+ }
+ }
+ grid.entry(c).or_default().push(i as u32);
+ }
+}
+
+/// Union-find over vertex indices.
+struct Sets(Vec);
+
+impl Sets {
+ fn new(n: usize) -> Self {
+ Self((0..n as u32).collect())
+ }
+
+ fn root(&mut self, mut i: u32) -> u32 {
+ while self.0[i as usize] != i {
+ let up = self.0[self.0[i as usize] as usize];
+ self.0[i as usize] = up;
+ i = up;
+ }
+ i
+ }
+
+ fn join(&mut self, a: u32, b: u32) {
+ let (a, b) = (self.root(a), self.root(b));
+ if a != b {
+ self.0[a.max(b) as usize] = a.min(b);
+ }
+ }
+}
+
+/// Room left for `f32` rounding when comparing with the bed, millimetres.
+const BED_SLACK_MM: f32 = 1e-3;
+
+/// Compare the mesh (in `unit`, sitting on the bed) with `o.bed_mm`; nothing at real size
+/// (metres: no print size was chosen, a ship never fits). When it fits only turned
+/// 90 degrees about Z, turn it. When it fits neither way: with `o.shrink_to_bed`, shrink it
+/// (turned when that leaves it larger) so it does; otherwise add a note that it does not fit
+/// (with `o.split`, the split cuts it into pieces that do). Each change is noted.
pub fn bed_check(
mesh: &mut Mesh,
o: &PrintOptions,
unit: Unit,
notes: &mut Vec,
) -> AssetResult<()> {
- let _ = (mesh, o, unit, notes);
+ let Some(b) = mesh.bounds().filter(|_| unit == Unit::Millimeter) else {
+ return Ok(());
+ };
+ let s = b.size();
+ let bed = o.bed_mm;
+ let fits = |x: f32, y: f32| {
+ x <= bed[0] + BED_SLACK_MM && y <= bed[1] + BED_SLACK_MM && s[2] <= bed[2] + BED_SLACK_MM
+ };
+ if fits(s[0], s[1]) {
+ return Ok(());
+ }
+ let bed_txt = size(bed);
+ if fits(s[1], s[0]) {
+ turn(mesh);
+ notes.push(format!(
+ "Turned 90 degrees about Z to fit the {bed_txt} bed (experimental)."
+ ));
+ return Ok(());
+ }
+ if !o.shrink_to_bed {
+ let then = if o.split {
+ "the split cuts it into pieces that fit"
+ } else {
+ "pick a smaller scale, shrink to the bed or split it"
+ };
+ notes.push(format!(
+ "At {} the model is larger than the {bed_txt} bed: {then} (experimental).",
+ size(s)
+ ));
+ return Ok(());
+ }
+ let room = |x: f32, y: f32| {
+ ratio(bed[0], x)
+ .min(ratio(bed[1], y))
+ .min(ratio(bed[2], s[2]))
+ };
+ let (k0, k90) = (room(s[0], s[1]), room(s[1], s[0]));
+ let turned = k90 > k0;
+ let k = k0.max(k90);
+ if turned {
+ turn(mesh);
+ }
+ scale(mesh, k);
+ let now = if turned { [s[1], s[0], s[2]] } else { s }.map(|v| v * k);
+ notes.push(format!(
+ "Shrunk to {}% to fit the {bed_txt} bed{}, now {} (experimental).",
+ pct(k),
+ if turned {
+ ", turned 90 degrees about Z"
+ } else {
+ ""
+ },
+ size(now),
+ ));
Ok(())
}
+
+/// How much `have` must be scaled to fit in `room` (at most 1; 1 when `have` is 0).
+fn ratio(room: f32, have: f32) -> f32 {
+ if have > 0.0 {
+ (room / have).min(1.0)
+ } else {
+ 1.0
+ }
+}
+
+/// Turn 90 degrees about Z (counter-clockwise from above: x, y -> -y, x).
+fn turn(mesh: &mut Mesh) {
+ mesh.map_vertices(|[x, y, z]| [-y, x, z]);
+}
+
+/// Millimetres to one decimal, without a trailing `.0`.
+fn mm(v: f32) -> String {
+ let r = (v * 10.0).round() / 10.0;
+ if r.fract() == 0.0 {
+ format!("{r:.0}")
+ } else {
+ format!("{r:.1}")
+ }
+}
+
+/// A size in millimetres as text.
+fn size(s: [f32; 3]) -> String {
+ format!("{} x {} x {} mm", mm(s[0]), mm(s[1]), mm(s[2]))
+}
+
+fn pct(k: f32) -> String {
+ let p = k * 100.0;
+ if p >= 10.0 {
+ format!("{p:.0}")
+ } else {
+ format!("{p:.2}")
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::assets::print::apply;
+
+ /// A closed box from `min` to `max`, 12 triangles.
+ fn cube(min: [f32; 3], max: [f32; 3]) -> Mesh {
+ let c = |i: usize| {
+ [
+ if i & 1 == 0 { min[0] } else { max[0] },
+ if i & 2 == 0 { min[1] } else { max[1] },
+ if i & 4 == 0 { min[2] } else { max[2] },
+ ]
+ };
+ let faces = [
+ [0, 2, 3, 1],
+ [4, 5, 7, 6],
+ [0, 1, 5, 4],
+ [2, 6, 7, 3],
+ [0, 4, 6, 2],
+ [1, 3, 7, 5],
+ ];
+ let mut tris = Vec::new();
+ for [a, b, cc, d] in faces {
+ tris.push([c(a), c(b), c(cc)]);
+ tris.push([c(a), c(cc), c(d)]);
+ }
+ Mesh::from_triangles(&tris)
+ }
+
+ fn joined(parts: &[Mesh]) -> Mesh {
+ let mut m = Mesh::default();
+ for p in parts {
+ m.append(p);
+ }
+ m
+ }
+
+ fn opts(bed: [f32; 3], shrink: bool, split: bool) -> PrintOptions {
+ PrintOptions {
+ bed_mm: bed,
+ shrink_to_bed: shrink,
+ split,
+ ..Default::default()
+ }
+ }
+
+ fn all() -> impl Fn(f32, &str) -> bool + Sync {
+ |_, _| true
+ }
+
+ #[test]
+ fn sitting_on_the_bed_centres_x_y_and_puts_the_bottom_at_zero() {
+ let mut a = cube([2.0, 3.0, -1.5], [4.0, 5.0, 0.5]);
+ let mut b = cube([10.0, 3.0, 1.0], [12.0, 9.0, 2.0]);
+ sit_on_bed(&mut [&mut a, &mut b]);
+ let (a, b) = (a.bounds().unwrap(), b.bounds().unwrap());
+ assert_eq!((a.min, a.max), ([-5.0, -3.0, 0.0], [-3.0, -1.0, 2.0]));
+ assert_eq!((b.min, b.max), ([3.0, -3.0, 2.5], [5.0, 3.0, 3.5]));
+ // No triangles: nothing to move.
+ sit_on_bed(&mut [&mut Mesh::default()]);
+ }
+
+ #[test]
+ fn tiny_loose_parts_are_left_out_by_their_diagonal() {
+ let mut m = joined(&[
+ cube([0.0, 0.0, 0.0], [10.0, 10.0, 10.0]),
+ // Diagonal 0.866: left out at 1.0.
+ cube([20.0, 0.0, 0.0], [20.5, 0.5, 0.5]),
+ // Diagonal 1.039 (0.6 a side): kept.
+ cube([30.0, 0.0, 0.0], [30.6, 0.6, 0.6]),
+ // Inside the big box but loose: a part of its own, left out.
+ cube([5.0, 5.0, 5.0], [5.1, 5.1, 5.1]),
+ ]);
+ assert_eq!(m.triangles.len(), 48);
+ assert_eq!(drop_tiny(&mut m, 1.0), 2);
+ assert_eq!(m.triangles.len(), 24);
+ assert_eq!(m.vertices.len(), 16);
+ let b = m.bounds().unwrap();
+ assert_eq!((b.min, b.max), ([0.0, 0.0, 0.0], [30.6, 10.0, 10.0]));
+ // Nothing smaller left; a bad size does nothing.
+ assert_eq!(drop_tiny(&mut m, 1.0), 0);
+ assert_eq!(drop_tiny(&mut m, 0.0), 0);
+ assert_eq!(drop_tiny(&mut m, f32::NAN), 0);
+ assert_eq!(m.triangles.len(), 24);
+ }
+
+ #[test]
+ fn corners_repeated_along_a_seam_are_welded_into_one_part() {
+ // Two halves of a 0.8 bar meeting at a seam, their corners off by a hair: one part
+ // (diagonal 1.15, kept), not two (0.82 each, both left out).
+ let mut m = joined(&[
+ cube([0.0, 0.0, 0.0], [0.4, 0.6, 0.6]),
+ cube([0.400_000_6, 0.0, 0.0], [0.8, 0.6, 0.6]),
+ ]);
+ assert_eq!(drop_tiny(&mut m, 1.0), 0);
+ assert_eq!(m.triangles.len(), 24);
+ // A gap: two parts.
+ let mut m = joined(&[
+ cube([0.0, 0.0, 0.0], [0.4, 0.6, 0.6]),
+ cube([0.41, 0.0, 0.0], [0.8, 0.6, 0.6]),
+ ]);
+ assert_eq!(drop_tiny(&mut m, 1.0), 2);
+ assert!(m.is_empty());
+ }
+
+ #[test]
+ fn groups_stay_with_the_triangles_kept() {
+ let mut big = cube([0.0; 3], [10.0; 3]);
+ big.groups = Some(vec![0; 12]);
+ big.labels = vec!["hull".into()];
+ let mut small = cube([20.0; 3], [20.1; 3]);
+ small.groups = Some(vec![0; 12]);
+ small.labels = vec!["glass".into()];
+ let mut m = joined(&[big, small]);
+ assert_eq!(drop_tiny(&mut m, 1.0), 1);
+ assert_eq!(m.groups.as_ref().map(Vec::len), Some(12));
+ assert!((0..12).all(|t| m.label(m.group(t)) == "hull"));
+ }
+
+ #[test]
+ fn a_model_that_fits_is_left_alone() {
+ let mut m = cube([-100.0, -50.0, 0.0], [100.0, 50.0, 80.0]);
+ let before = m.clone();
+ let mut notes = Vec::new();
+ bed_check(
+ &mut m,
+ &opts([256.0; 3], true, false),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ assert_eq!(m, before);
+ // Exactly the bed fits too.
+ let mut m = cube([-128.0, -128.0, 0.0], [128.0, 128.0, 256.0]);
+ bed_check(
+ &mut m,
+ &opts([256.0; 3], false, false),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ assert!(notes.is_empty(), "{notes:?}");
+ // Real size (metres) is not checked.
+ let mut m = cube([0.0; 3], [0.1, 0.2, 0.25]);
+ bed_check(
+ &mut m,
+ &opts([256.0; 3], false, false),
+ Unit::Meter,
+ &mut notes,
+ )
+ .unwrap();
+ assert!(notes.is_empty(), "{notes:?}");
+ }
+
+ #[test]
+ fn a_model_that_fits_turned_is_turned() {
+ // 150 long in y on a 200 x 100 bed.
+ let mut m = cube([-40.0, -75.0, 0.0], [40.0, 75.0, 50.0]);
+ let mut notes = Vec::new();
+ let o = opts([200.0, 100.0, 100.0], false, false);
+ bed_check(&mut m, &o, Unit::Millimeter, &mut notes).unwrap();
+ let b = m.bounds().unwrap();
+ assert_eq!((b.min, b.max), ([-75.0, -40.0, 0.0], [75.0, 40.0, 50.0]));
+ assert_eq!(notes.len(), 1);
+ assert!(notes[0].contains("Turned 90 degrees"), "{notes:?}");
+ assert!(notes[0].contains("200 x 100 x 100 mm"), "{notes:?}");
+ }
+
+ #[test]
+ fn a_model_too_large_gets_a_note_or_is_shrunk_to_fit() {
+ let big = || cube([-200.0, -50.0, 0.0], [200.0, 50.0, 60.0]);
+ let bed = [256.0; 3];
+ let mut m = big();
+ let mut notes = Vec::new();
+ bed_check(
+ &mut m,
+ &opts(bed, false, false),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ assert_eq!(m, big());
+ assert!(notes[0].contains("At 400 x 100 x 60 mm"), "{notes:?}");
+ assert!(notes[0].contains("shrink to the bed"), "{notes:?}");
+ notes.clear();
+ bed_check(
+ &mut m,
+ &opts(bed, false, true),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ assert!(notes[0].contains("the split cuts it"), "{notes:?}");
+ // Real size (metres, no print size chosen): not checked, not shrunk.
+ let ship = || cube([-10.0, -4.0, 0.0], [10.0, 4.0, 5.0]);
+ let mut m20 = ship();
+ notes.clear();
+ bed_check(&mut m20, &opts(bed, true, false), Unit::Meter, &mut notes).unwrap();
+ assert_eq!(m20, ship());
+ assert!(notes.is_empty(), "{notes:?}");
+ // Shrunk: 400 -> 256 (64%).
+ notes.clear();
+ bed_check(
+ &mut m,
+ &opts(bed, true, false),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ let s = m.bounds().unwrap().size();
+ assert!(
+ (s[0] - 256.0).abs() < 1e-3 && (s[1] - 64.0).abs() < 1e-3,
+ "{s:?}"
+ );
+ assert!(notes[0].contains("Shrunk to 64%"), "{notes:?}");
+ assert!(notes[0].contains("now 256 x 64 x 38.4 mm"), "{notes:?}");
+ assert!(!notes[0].contains("turned"), "{notes:?}");
+ }
+
+ #[test]
+ fn shrinking_turns_the_model_when_that_keeps_it_larger() {
+ // 300 x 150 on a 100 x 200 bed: 1/3 as it is, 2/3 turned.
+ let mut m = cube([-150.0, -75.0, 0.0], [150.0, 75.0, 10.0]);
+ let mut notes = Vec::new();
+ let o = opts([100.0, 200.0, 100.0], true, false);
+ bed_check(&mut m, &o, Unit::Millimeter, &mut notes).unwrap();
+ let s = m.bounds().unwrap().size();
+ assert!(
+ (s[0] - 100.0).abs() < 1e-3 && (s[1] - 200.0).abs() < 1e-3,
+ "{s:?}"
+ );
+ assert!(notes[0].contains("Shrunk to 67%"), "{notes:?}");
+ assert!(notes[0].contains("turned 90 degrees"), "{notes:?}");
+ // Too tall: z sets the shrink.
+ let mut m = cube([-10.0, -10.0, 0.0], [10.0, 10.0, 500.0]);
+ notes.clear();
+ bed_check(
+ &mut m,
+ &opts([256.0; 3], true, false),
+ Unit::Millimeter,
+ &mut notes,
+ )
+ .unwrap();
+ assert!((m.bounds().unwrap().size()[2] - 256.0).abs() < 1e-3);
+ }
+
+ #[test]
+ fn the_pipeline_drops_tiny_parts_at_print_size_and_shrinks_to_the_bed() {
+ // A 20 m hull and a loose 0.1 m box 30 m out: at fit 150 mm over 30.1 m (k 4.98) the
+ // box is 0.86 mm across.
+ let m = joined(&[
+ cube([0.0, 0.0, 0.0], [20.0, 8.0, 5.0]),
+ cube([30.0, 0.0, 0.0], [30.1, 0.1, 0.1]),
+ ]);
+ let o = PrintOptions {
+ scale: ScaleMode::FitMm(150.0),
+ drop_small_mm: Some(0.8),
+ ..Default::default()
+ };
+ let out = apply(m.clone(), &o, &all()).unwrap();
+ assert_eq!(out.triangles(), 24, "{:?}", out.notes);
+ let o = PrintOptions {
+ drop_small_mm: Some(1.0),
+ ..o
+ };
+ let out = apply(m.clone(), &o, &all()).unwrap();
+ assert_eq!(out.triangles(), 12);
+ assert!(
+ out.notes.iter().any(|n| n.contains("Left out 1 parts")),
+ "{:?}",
+ out.notes
+ );
+ // The fit is the longest side of what is left (not 30.1 m with the box), centred.
+ let b = out.parts[0].mesh.bounds().unwrap();
+ assert!((b.size()[0] - 150.0).abs() < 1e-3, "{b:?}");
+ assert!((b.min[0] + b.max[0]).abs() < 1e-3 && (b.min[1] + b.max[1]).abs() < 1e-3);
+ assert_eq!(b.min[2], 0.0);
+ // Real size in mm, shrunk to the bed.
+ let o = PrintOptions {
+ shrink_to_bed: true,
+ ..Default::default()
+ };
+ let out = apply(cube([0.0; 3], [20.0, 8.0, 5.0]), &o, &all()).unwrap();
+ assert_eq!(out.unit, Unit::Millimeter);
+ let b = out.parts[0].mesh.bounds().unwrap();
+ assert!((b.size()[0] - 256.0).abs() < 1e-2, "{b:?}");
+ assert!(
+ out.notes.iter().any(|n| n.contains("Shrunk to 1.28%")),
+ "{:?}",
+ out.notes
+ );
+ }
+}
diff --git a/crates/starorg-data/src/assets/print/tests.rs b/crates/starorg-data/src/assets/print/tests.rs
index e9ac544..0397530 100644
--- a/crates/starorg-data/src/assets/print/tests.rs
+++ b/crates/starorg-data/src/assets/print/tests.rs
@@ -276,7 +276,7 @@ fn the_default_pipeline_only_sits_the_model_on_the_bed_in_metres() {
assert_eq!(out.parts.len(), 1);
assert!(out.notes.is_empty());
let b = out.parts[0].mesh.bounds().unwrap();
- assert_eq!((b.min, b.max), ([2.0, 3.0, 0.0], [4.0, 5.0, 2.0]));
+ assert_eq!((b.min, b.max), ([-1.0, -1.0, 0.0], [1.0, 1.0, 2.0]));
assert_eq!(out.triangles(), 12);
}
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
index bdb7ae9..4842085 100644
--- a/docs/plans/specs/model-print.md
+++ b/docs/plans/specs/model-print.md
@@ -39,6 +39,27 @@ same messages come from the CLI (exit 2), the backends (`invalid`) and the TS ch
dialog disables "Save as…"). Print options with `--preset full` are refused by the CLI and
ignored by the backends (as a Print shell ignores paints).
+### Scale, bed and small parts (`scale.rs`)
+
+- **Scale**: none keeps real size in metres (3MF `unit="meter"`); fit-mm makes the longest
+ side N mm; ratio 1:N gives mm = m × 1000 / N; shrink-to-bed alone starts from real size in
+ mm. Any of these writes millimetres (3MF `unit="millimeter"`, STL numbers in mm). Fit-mm
+ measures what is left after small parts are dropped.
+- **Sit on the bed** (always, steps 4 and 13): lowest z = 0 and the middle of the footprint at
+ x = y = 0, all parts moved together (each split piece on its own).
+- **Bed check** (scaled models only; real size in metres is never checked): fits as is → no
+ change; fits only turned 90° about Z → turned, with a note; fits neither way → with
+ shrink-to-bed, scaled down (turned when that keeps it larger) with a note giving the
+ percentage and the new size, else a note with the size and what to do (`split` → "the split
+ cuts it into pieces that fit"). 1 µm slack for f32 rounding.
+- **Drop small parts**: corners closer than 1/1000 of the size are welded (union-find over a
+ hash grid), triangles joined by corners form a loose part, and parts whose bounding-box
+ **diagonal** at print size is under N mm are left out ("Left out K parts smaller than N mm.").
+ A small part inside or touching a bigger one without sharing a corner counts as loose. Real
+ data: Skylark LOD 4 (98 376 tris) at fit 150 mm drops 655 parts (→ 94 844 tris) at 1 mm,
+ 906 at 3 mm; Carrack LOD 4 (401 933 tris) at fit 250 mm drops 16 020 parts (→ 278 622) at
+ 0.3 mm; 0.15 s and about 1 s in a release build.
+
## Pipeline
`print::apply(mesh, &PrintOptions, progress) -> AssetResult`, fixed order:
@@ -46,7 +67,7 @@ ignored by the backends (as a Print shell ignores paints).
1. classify groups (multicolor only; otherwise groups are dropped)
2. drop tiny parts (measured at print size)
3. scale (`scale::factor`: real size stays metres, `unit="meter"`; any scale or shrink -> mm)
-4. sit on the bed (min z = 0)
+4. sit on the bed (min z = 0, x/y centred)
5. bed check / shrink to the bed, sit on the bed
6. voxel solid, 7. thicken, 8. hollow + drain, 9. pegs (at `split::plan`'s cuts)
10. split into pieces
From 99aba9d3a2a3ea4ad98c8bba9db123533848c303 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:08:49 -0600
Subject: [PATCH 05/12] feat(print): simplify parts with quadric edge collapse
(experimental)
Garland-Heckbert QEM in pure Rust: link condition, no flips or slivers, open edges and group borders held by border planes, non-manifold vertices fixed, small open pieces never erased. Closed parts stay closed; parts within budget are unchanged.
---
.../starorg-data/src/assets/print/simplify.rs | 753 +++++++++++++++++-
docs/plans/specs/model-print.md | 16 +
2 files changed, 764 insertions(+), 5 deletions(-)
diff --git a/crates/starorg-data/src/assets/print/simplify.rs b/crates/starorg-data/src/assets/print/simplify.rs
index 7f0d623..d038a15 100644
--- a/crates/starorg-data/src/assets/print/simplify.rs
+++ b/crates/starorg-data/src/assets/print/simplify.rs
@@ -2,14 +2,757 @@
//! groups). Pipeline step 12 of [`super::apply`], which shares `simplify_tris` among the parts
//! by their triangle counts.
//!
-//! Owner: the simplify agent. [`simplify`] is a pass-through stub.
+//! Quadric error metric edge collapse (Garland and Heckbert), in pure Rust:
+//!
+//! - each vertex carries the area-weighted quadric of its faces' planes, plus a plane through
+//! every open edge and every edge between two groups (perpendicular to its face), so holes
+//! and colour borders keep their place;
+//! - the cheapest edge collapses first, to the point that minimises the summed quadric (an
+//! endpoint or the midpoint when that point is ill-conditioned or far off the edge);
+//! - a collapse is refused when it would break the surface: the edge's link condition (the
+//! vertices both ends share are exactly the edge's opposite corners), an inner edge joining
+//! two boundary vertices, a face that would flip or fold (its normal turning by more than
+//! [`MAX_TURN_COS`]) or become a sliver, two faces that would coincide, or a small open
+//! piece (a lone triangle, a strip) that would be erased;
+//! - vertices on non-manifold edges (more than two faces) never move, so a soup of overlapping
+//! GLB meshes is simplified only where it is a proper surface.
+//!
+//! A closed (watertight, consistently wound) mesh stays closed. The result has about `target`
+//! triangles, never more than it had; fewer collapses happen when the checks refuse the rest.
use super::{Mesh, Progress};
-use crate::assets::AssetResult;
+use crate::assets::{AssetError, AssetResult};
+use std::cmp::Ordering;
+use std::collections::{BinaryHeap, HashMap, HashSet};
-/// TODO(simplify agent): reduce `mesh` to about `target` triangles (never more than it has),
-/// keeping it closed where it was. Stub: no-op.
+/// A collapse is refused when a remaining face's normal would turn by more than about 78°.
+const MAX_TURN_COS: f64 = 0.2;
+/// Open edges and group borders weigh this much more than a face of the same area.
+const BORDER_WEIGHT: f64 = 10.0;
+/// How many collapses between progress reports (and cancel checks).
+const REPORT_EVERY: usize = 2048;
+/// Passes over the remaining edges, for collapses refused earlier that later become possible.
+const MAX_PASSES: usize = 4;
+
+/// Reduce `mesh` to about `target` triangles (never more than it has), keeping it closed where
+/// it was, its winding and its triangles' groups. A mesh at or under `target` is left as is.
pub fn simplify(mesh: &mut Mesh, target: u32, progress: Progress<'_>) -> AssetResult<()> {
- let _ = (mesh, target, progress);
+ let target = target.max(4) as usize;
+ if mesh.triangles.len() <= target {
+ return Ok(());
+ }
+ let mut s = State::new(mesh);
+ let start = s.alive_count;
+ for _ in 0..MAX_PASSES {
+ let before = s.alive_count;
+ s.fill_heap();
+ s.run(target, start, progress)?;
+ if s.alive_count <= target || s.alive_count == before {
+ break;
+ }
+ }
+ s.write_back(mesh);
Ok(())
}
+
+/// A symmetric 4x4 quadric: `a2 ab ac ad b2 bc bd c2 cd d2`.
+#[derive(Clone, Copy, Default)]
+struct Quadric([f64; 10]);
+
+impl Quadric {
+ /// `w` times the squared distance to the plane `n·p + d = 0` (`n` unit length).
+ fn plane(n: [f64; 3], d: f64, w: f64) -> Quadric {
+ let [a, b, c] = n;
+ Quadric(
+ [
+ a * a,
+ a * b,
+ a * c,
+ a * d,
+ b * b,
+ b * c,
+ b * d,
+ c * c,
+ c * d,
+ d * d,
+ ]
+ .map(|x| x * w),
+ )
+ }
+
+ fn add(&mut self, o: &Quadric) {
+ for (a, b) in self.0.iter_mut().zip(o.0) {
+ *a += b;
+ }
+ }
+
+ fn sum(a: &Quadric, b: &Quadric) -> Quadric {
+ let mut q = *a;
+ q.add(b);
+ q
+ }
+
+ fn eval(&self, p: [f64; 3]) -> f64 {
+ let q = &self.0;
+ let [x, y, z] = p;
+ q[0] * x * x
+ + 2.0 * q[1] * x * y
+ + 2.0 * q[2] * x * z
+ + 2.0 * q[3] * x
+ + q[4] * y * y
+ + 2.0 * q[5] * y * z
+ + 2.0 * q[6] * y
+ + q[7] * z * z
+ + 2.0 * q[8] * z
+ + q[9]
+ }
+
+ /// The point minimising the quadric, when the 3x3 system is well conditioned.
+ fn optimum(&self) -> Option<[f64; 3]> {
+ let q = &self.0;
+ let (a, b, c, e, f, i) = (q[0], q[1], q[2], q[4], q[5], q[7]);
+ let r = [-q[3], -q[6], -q[8]];
+ let det = a * (e * i - f * f) - b * (b * i - f * c) + c * (b * f - e * c);
+ let scale = (a.abs() + e.abs() + i.abs()).powi(3);
+ if !det.is_finite() || det.abs() <= 1e-10 * scale || scale == 0.0 {
+ return None;
+ }
+ let x =
+ (r[0] * (e * i - f * f) - b * (r[1] * i - f * r[2]) + c * (r[1] * f - e * r[2])) / det;
+ let y =
+ (a * (r[1] * i - f * r[2]) - r[0] * (b * i - f * c) + c * (b * r[2] - r[1] * c)) / det;
+ let z =
+ (a * (e * r[2] - r[1] * f) - b * (b * r[2] - r[1] * c) + r[0] * (b * f - e * c)) / det;
+ let p = [x, y, z];
+ p.iter().all(|v| v.is_finite()).then_some(p)
+ }
+}
+
+fn sub(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
+ [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+}
+
+fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
+ [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+ ]
+}
+
+fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+
+fn len(a: [f64; 3]) -> f64 {
+ dot(a, a).sqrt()
+}
+
+fn normal(p: [[f64; 3]; 3]) -> [f64; 3] {
+ cross(sub(p[1], p[0]), sub(p[2], p[0]))
+}
+
+/// A candidate collapse in the heap: cheapest first.
+struct Cand {
+ cost: f64,
+ /// The vertex kept, the vertex removed, and where the kept one moves.
+ keep: u32,
+ gone: u32,
+ to: [f64; 3],
+ /// Both vertices' versions when this was computed (stale when either changed).
+ ver: [u32; 2],
+}
+
+impl PartialEq for Cand {
+ fn eq(&self, o: &Self) -> bool {
+ self.cmp(o) == Ordering::Equal
+ }
+}
+impl Eq for Cand {}
+impl PartialOrd for Cand {
+ fn partial_cmp(&self, o: &Self) -> Option {
+ Some(self.cmp(o))
+ }
+}
+impl Ord for Cand {
+ fn cmp(&self, o: &Self) -> Ordering {
+ // Reversed: BinaryHeap is a max-heap.
+ o.cost.total_cmp(&self.cost)
+ }
+}
+
+struct State {
+ pos: Vec<[f64; 3]>,
+ quad: Vec,
+ tris: Vec<[u32; 3]>,
+ alive: Vec,
+ alive_count: usize,
+ /// Per vertex, the triangles that use it (dead ones are pruned on the way).
+ vt: Vec>,
+ /// On a non-manifold edge: never moves.
+ locked: Vec,
+ /// On an open edge.
+ boundary: Vec,
+ removed: Vec,
+ version: Vec,
+ heap: BinaryHeap,
+}
+
+impl State {
+ fn new(mesh: &Mesh) -> State {
+ let nv = mesh.vertices.len();
+ let pos: Vec<[f64; 3]> = mesh.vertices.iter().map(|v| v.map(f64::from)).collect();
+ let mut quad = vec![Quadric::default(); nv];
+ let mut vt: Vec> = vec![Vec::new(); nv];
+ // Face planes.
+ for (t, tri) in mesh.triangles.iter().enumerate() {
+ let p = tri.map(|i| pos[i as usize]);
+ let n = normal(p);
+ let l = len(n);
+ if l > 0.0 {
+ let n = n.map(|c| c / l);
+ let q = Quadric::plane(n, -dot(n, p[0]), l * 0.5);
+ for &i in tri {
+ quad[i as usize].add(&q);
+ }
+ }
+ for &i in tri {
+ vt[i as usize].push(t as u32);
+ }
+ }
+ // Edges: open, non-manifold, group borders.
+ let mut edges: HashMap<(u32, u32), Vec> =
+ HashMap::with_capacity(mesh.triangles.len() * 2);
+ for (t, tri) in mesh.triangles.iter().enumerate() {
+ for k in 0..3 {
+ let (a, b) = (tri[k], tri[(k + 1) % 3]);
+ edges
+ .entry((a.min(b), a.max(b)))
+ .or_default()
+ .push(t as u32);
+ }
+ }
+ let mut locked = vec![false; nv];
+ let mut boundary = vec![false; nv];
+ let border = |quad: &mut [Quadric], a: u32, b: u32, t: u32| {
+ let p = mesh.triangles[t as usize].map(|i| pos[i as usize]);
+ let (pa, pb) = (pos[a as usize], pos[b as usize]);
+ let e = sub(pb, pa);
+ let n = cross(e, normal(p));
+ let l = len(n);
+ if l > 0.0 {
+ let n = n.map(|c| c / l);
+ let q = Quadric::plane(n, -dot(n, pa), BORDER_WEIGHT * dot(e, e));
+ quad[a as usize].add(&q);
+ quad[b as usize].add(&q);
+ }
+ };
+ for (&(a, b), ts) in &edges {
+ match ts.len() {
+ 1 => {
+ boundary[a as usize] = true;
+ boundary[b as usize] = true;
+ border(&mut quad, a, b, ts[0]);
+ }
+ 2 => {
+ if mesh.group(ts[0] as usize) != mesh.group(ts[1] as usize) {
+ border(&mut quad, a, b, ts[0]);
+ border(&mut quad, a, b, ts[1]);
+ }
+ }
+ _ => {
+ locked[a as usize] = true;
+ locked[b as usize] = true;
+ }
+ }
+ }
+ State {
+ pos,
+ quad,
+ alive: vec![true; mesh.triangles.len()],
+ alive_count: mesh.triangles.len(),
+ tris: mesh.triangles.clone(),
+ vt,
+ locked,
+ boundary,
+ removed: vec![false; nv],
+ version: vec![0; nv],
+ heap: BinaryHeap::new(),
+ }
+ }
+
+ /// Every remaining edge, once.
+ fn fill_heap(&mut self) {
+ self.heap.clear();
+ let mut seen: HashSet<(u32, u32)> = HashSet::with_capacity(self.alive_count * 2);
+ for t in 0..self.tris.len() {
+ if !self.alive[t] {
+ continue;
+ }
+ let tri = self.tris[t];
+ for k in 0..3 {
+ let (a, b) = (tri[k], tri[(k + 1) % 3]);
+ if seen.insert((a.min(b), a.max(b))) {
+ self.push(a, b);
+ }
+ }
+ }
+ }
+
+ fn push(&mut self, a: u32, b: u32) {
+ let (ai, bi) = (a as usize, b as usize);
+ if self.locked[ai] && self.locked[bi] {
+ return;
+ }
+ let q = Quadric::sum(&self.quad[ai], &self.quad[bi]);
+ let (pa, pb) = (self.pos[ai], self.pos[bi]);
+ let (keep, gone, to) = if self.locked[ai] || (self.boundary[ai] && !self.boundary[bi]) {
+ (a, b, pa)
+ } else if self.locked[bi] || (self.boundary[bi] && !self.boundary[ai]) {
+ (b, a, pb)
+ } else {
+ let mid = [
+ (pa[0] + pb[0]) * 0.5,
+ (pa[1] + pb[1]) * 0.5,
+ (pa[2] + pb[2]) * 0.5,
+ ];
+ let el = len(sub(pb, pa));
+ let mut best = (q.eval(mid), mid);
+ for p in [pa, pb] {
+ let c = q.eval(p);
+ if c < best.0 {
+ best = (c, p);
+ }
+ }
+ if let Some(p) = q.optimum()
+ && len(sub(p, mid)) <= el
+ {
+ let c = q.eval(p);
+ if c < best.0 {
+ best = (c, p);
+ }
+ }
+ (a, b, best.1)
+ };
+ let cost = q.eval(to).max(0.0);
+ self.heap.push(Cand {
+ cost,
+ keep,
+ gone,
+ to,
+ ver: [self.version[keep as usize], self.version[gone as usize]],
+ });
+ }
+
+ fn prune(&mut self, v: u32) {
+ let alive = &self.alive;
+ self.vt[v as usize].retain(|&t| alive[t as usize]);
+ }
+
+ fn run(&mut self, target: usize, start: usize, progress: Progress<'_>) -> AssetResult<()> {
+ let mut done = 0usize;
+ let need = (start - target).max(1) as f32;
+ while self.alive_count > target {
+ let Some(c) = self.heap.pop() else { break };
+ let (k, g) = (c.keep as usize, c.gone as usize);
+ if self.removed[k] || self.removed[g] || c.ver != [self.version[k], self.version[g]] {
+ continue;
+ }
+ if !self.collapse(c.keep, c.gone, c.to) {
+ continue;
+ }
+ done += 1;
+ if done.is_multiple_of(REPORT_EVERY) {
+ let f = (start - self.alive_count) as f32 / need;
+ if !progress(f, "Simplifying") {
+ return Err(AssetError::cancelled());
+ }
+ }
+ }
+ Ok(())
+ }
+
+ /// The other vertices of `v`'s live triangles.
+ fn ring(&self, v: u32) -> Vec {
+ let mut r: Vec = self.vt[v as usize]
+ .iter()
+ .flat_map(|&t| self.tris[t as usize])
+ .filter(|&x| x != v)
+ .collect();
+ r.sort_unstable();
+ r.dedup();
+ r
+ }
+
+ /// Collapse `gone` into `keep`, moved to `to`, when that keeps the surface sound.
+ fn collapse(&mut self, keep: u32, gone: u32, to: [f64; 3]) -> bool {
+ self.prune(keep);
+ self.prune(gone);
+ let (ki, gi) = (keep as usize, gone as usize);
+ // The triangles on the edge, and their opposite corners.
+ let shared: Vec = self.vt[gi]
+ .iter()
+ .copied()
+ .filter(|&t| self.tris[t as usize].contains(&keep))
+ .collect();
+ if shared.is_empty() || shared.len() > 2 {
+ return false;
+ }
+ // An inner edge between two boundary vertices would pinch the surface.
+ if shared.len() == 2 && self.boundary[ki] && self.boundary[gi] {
+ return false;
+ }
+ let mut opposite: Vec = shared
+ .iter()
+ .flat_map(|&t| self.tris[t as usize])
+ .filter(|&x| x != keep && x != gone)
+ .collect();
+ opposite.sort_unstable();
+ opposite.dedup();
+ if opposite.len() != shared.len() {
+ return false;
+ }
+ // Link condition.
+ let (rk, rg) = (self.ring(keep), self.ring(gone));
+ let common = rk.iter().filter(|x| rg.binary_search(x).is_ok()).count();
+ if common != opposite.len() {
+ return false;
+ }
+ // Never erase a small open piece: the kept vertex and each opposite corner keep a face.
+ let left = |v: u32| {
+ self.vt[v as usize]
+ .iter()
+ .any(|&t| self.alive[t as usize] && !shared.contains(&t))
+ };
+ if !(left(keep) || left(gone)) || !opposite.iter().all(|&o| left(o)) {
+ return false;
+ }
+ // No fold, flip or sliver among the faces that move; no two faces becoming one.
+ let mut seen: Vec<[u32; 3]> = Vec::new();
+ for &v in &[keep, gone] {
+ for &t in &self.vt[v as usize] {
+ let tri = self.tris[t as usize];
+ if tri.contains(&keep) && tri.contains(&gone) {
+ continue;
+ }
+ let old = tri.map(|i| self.pos[i as usize]);
+ let new_tri = tri.map(|i| if i == gone { keep } else { i });
+ let new = new_tri.map(|i| if i == keep { to } else { self.pos[i as usize] });
+ let (no, nn) = (normal(old), normal(new));
+ let (lo, ln) = (len(no), len(nn));
+ if lo > 0.0 {
+ if ln <= 1e-12 * lo || dot(no, nn) < MAX_TURN_COS * lo * ln {
+ return false;
+ }
+ // A sliver: the new face's area tiny against its longest edge squared.
+ let e = (0..3)
+ .map(|k| dot(sub(new[k], new[(k + 1) % 3]), sub(new[k], new[(k + 1) % 3])))
+ .fold(0.0, f64::max);
+ if ln < 1e-3 * e {
+ return false;
+ }
+ }
+ let mut key = new_tri;
+ key.sort_unstable();
+ if seen.contains(&key) {
+ return false;
+ }
+ seen.push(key);
+ }
+ }
+ // Apply.
+ for &t in &shared {
+ self.alive[t as usize] = false;
+ self.alive_count -= 1;
+ }
+ let moved: Vec = self.vt[gi].clone();
+ for t in moved {
+ if !self.alive[t as usize] {
+ continue;
+ }
+ for i in &mut self.tris[t as usize] {
+ if *i == gone {
+ *i = keep;
+ }
+ }
+ self.vt[ki].push(t);
+ }
+ self.vt[gi].clear();
+ self.prune(keep);
+ self.pos[ki] = to;
+ let q = self.quad[gi];
+ self.quad[ki].add(&q);
+ self.boundary[ki] |= self.boundary[gi];
+ self.locked[ki] |= self.locked[gi];
+ self.removed[gi] = true;
+ self.version[ki] += 1;
+ self.version[gi] += 1;
+ for n in self.ring(keep) {
+ self.push(keep, n);
+ }
+ true
+ }
+
+ fn write_back(self, mesh: &mut Mesh) {
+ mesh.vertices = self.pos.iter().map(|p| p.map(|c| c as f32)).collect();
+ mesh.triangles = self.tris;
+ let alive = self.alive;
+ mesh.retain_triangles(|t| alive[t]);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ fn all() -> impl Fn(f32, &str) -> bool + Sync {
+ |_, _| true
+ }
+
+ /// An icosphere of radius `r`, `n` subdivisions (20 * 4^n triangles), outward winding.
+ fn sphere(r: f32, n: u32) -> Mesh {
+ let t = (1.0 + 5f32.sqrt()) / 2.0;
+ let mut v: Vec<[f32; 3]> = vec![
+ [-1.0, t, 0.0],
+ [1.0, t, 0.0],
+ [-1.0, -t, 0.0],
+ [1.0, -t, 0.0],
+ [0.0, -1.0, t],
+ [0.0, 1.0, t],
+ [0.0, -1.0, -t],
+ [0.0, 1.0, -t],
+ [t, 0.0, -1.0],
+ [t, 0.0, 1.0],
+ [-t, 0.0, -1.0],
+ [-t, 0.0, 1.0],
+ ];
+ let mut f: Vec<[u32; 3]> = vec![
+ [0, 11, 5],
+ [0, 5, 1],
+ [0, 1, 7],
+ [0, 7, 10],
+ [0, 10, 11],
+ [1, 5, 9],
+ [5, 11, 4],
+ [11, 10, 2],
+ [10, 7, 6],
+ [7, 1, 8],
+ [3, 9, 4],
+ [3, 4, 2],
+ [3, 2, 6],
+ [3, 6, 8],
+ [3, 8, 9],
+ [4, 9, 5],
+ [2, 4, 11],
+ [6, 2, 10],
+ [8, 6, 7],
+ [9, 8, 1],
+ ];
+ let norm = |p: [f32; 3]| {
+ let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt();
+ p.map(|c| c / l * r)
+ };
+ v = v.into_iter().map(norm).collect();
+ for _ in 0..n {
+ let mut mid: HashMap<(u32, u32), u32> = HashMap::new();
+ let mut nf = Vec::new();
+ for tri in &f {
+ let mut m = [0u32; 3];
+ for k in 0..3 {
+ let (a, b) = (tri[k], tri[(k + 1) % 3]);
+ m[k] = *mid.entry((a.min(b), a.max(b))).or_insert_with(|| {
+ let (pa, pb) = (v[a as usize], v[b as usize]);
+ v.push(norm([
+ (pa[0] + pb[0]) / 2.0,
+ (pa[1] + pb[1]) / 2.0,
+ (pa[2] + pb[2]) / 2.0,
+ ]));
+ (v.len() - 1) as u32
+ });
+ }
+ nf.push([tri[0], m[0], m[2]]);
+ nf.push([tri[1], m[1], m[0]]);
+ nf.push([tri[2], m[2], m[1]]);
+ nf.push([m[0], m[1], m[2]]);
+ }
+ f = nf;
+ }
+ Mesh {
+ vertices: v,
+ triangles: f,
+ groups: None,
+ labels: Vec::new(),
+ }
+ }
+
+ /// A cube from -1 to 1, each face an `n` x `n` grid (12 n² triangles), outward winding.
+ fn grid_cube(n: usize) -> Mesh {
+ let mut tris = Vec::new();
+ let s = |i: usize| -1.0 + 2.0 * i as f32 / n as f32;
+ for axis in 0..3 {
+ for side in [-1.0f32, 1.0] {
+ let (u, w) = ((axis + 1) % 3, (axis + 2) % 3);
+ let p = |i: usize, j: usize| {
+ let mut p = [0.0; 3];
+ p[axis] = side;
+ p[u] = s(i);
+ p[w] = s(j);
+ p
+ };
+ for i in 0..n {
+ for j in 0..n {
+ let (a, b, c, d) = (p(i, j), p(i + 1, j), p(i + 1, j + 1), p(i, j + 1));
+ if side > 0.0 {
+ tris.push([a, b, c]);
+ tris.push([a, c, d]);
+ } else {
+ tris.push([a, c, b]);
+ tris.push([a, d, c]);
+ }
+ }
+ }
+ }
+ }
+ Mesh::from_triangles(&tris)
+ }
+
+ /// Every directed edge appears once and its reverse once: closed and consistently wound.
+ fn closed(m: &Mesh) -> bool {
+ let mut e: HashMap<(u32, u32), u32> = HashMap::new();
+ for t in &m.triangles {
+ for k in 0..3 {
+ *e.entry((t[k], t[(k + 1) % 3])).or_default() += 1;
+ }
+ }
+ e.iter()
+ .all(|(&(a, b), &n)| n == 1 && e.get(&(b, a)) == Some(&1))
+ }
+
+ /// Signed volume (positive for outward winding).
+ fn volume(m: &Mesh) -> f64 {
+ m.triangles
+ .iter()
+ .map(|t| {
+ let p = t.map(|i| m.vertices[i as usize].map(f64::from));
+ dot(p[0], cross(p[1], p[2])) / 6.0
+ })
+ .sum()
+ }
+
+ #[test]
+ fn a_sphere_stays_closed_round_and_outward() {
+ let mut m = sphere(10.0, 4);
+ assert_eq!(m.triangles.len(), 5120);
+ assert!(closed(&m));
+ let v0 = volume(&m);
+ simplify(&mut m, 1000, &all()).unwrap();
+ let n = m.triangles.len();
+ assert!((900..=1000).contains(&n), "{n} triangles");
+ assert!(closed(&m), "not closed after simplify");
+ for p in &m.vertices {
+ let r = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt();
+ assert!((r - 10.0).abs() < 0.3, "vertex off the sphere: r = {r}");
+ }
+ let v1 = volume(&m);
+ assert!(v1 > 0.0 && (v1 - v0).abs() / v0 < 0.03, "{v0} -> {v1}");
+ // Euler characteristic of a sphere.
+ let e = n * 3 / 2;
+ assert_eq!(m.vertices.len() as i64 - e as i64 + n as i64, 2);
+ }
+
+ #[test]
+ fn a_flat_faced_cube_keeps_its_shape_exactly() {
+ let mut m = grid_cube(10);
+ assert_eq!(m.triangles.len(), 1200);
+ simplify(&mut m, 100, &all()).unwrap();
+ assert!(m.triangles.len() <= 100, "{}", m.triangles.len());
+ assert!(closed(&m));
+ let b = m.bounds().unwrap();
+ for k in 0..3 {
+ assert!((b.min[k] + 1.0).abs() < 1e-4 && (b.max[k] - 1.0).abs() < 1e-4);
+ }
+ for p in &m.vertices {
+ let on = p.iter().map(|c| c.abs()).fold(0.0f32, f32::max);
+ assert!((on - 1.0).abs() < 1e-4, "vertex off the cube: {p:?}");
+ }
+ assert!((volume(&m) - 8.0).abs() < 1e-3);
+ }
+
+ #[test]
+ fn a_mesh_at_or_under_the_budget_is_unchanged() {
+ let m0 = sphere(1.0, 2);
+ let mut m = m0.clone();
+ simplify(&mut m, 320, &all()).unwrap();
+ assert_eq!(m, m0);
+ simplify(&mut m, 100_000, &all()).unwrap();
+ assert_eq!(m, m0);
+ }
+
+ #[test]
+ fn groups_follow_their_triangles_and_an_open_edge_stays_put() {
+ // A sphere's lower half: an open rim at z = 0, two groups split by x.
+ let s = sphere(5.0, 4);
+ let keep: Vec = (0..s.triangles.len())
+ .filter(|&t| s.triangle(t).iter().all(|p| p[2] <= 1e-4))
+ .collect();
+ let mut m = s.subset(keep);
+ m.compact();
+ let groups: Vec = (0..m.triangles.len())
+ .map(|t| u32::from(m.triangle(t)[0][0] > 0.0))
+ .collect();
+ m.groups = Some(groups);
+ m.labels = vec!["a".into(), "b".into()];
+ let rim = |m: &Mesh| m.vertices.iter().filter(|p| p[2].abs() < 1e-4).count();
+ let n0 = m.triangles.len();
+ simplify(&mut m, (n0 / 4) as u32, &all()).unwrap();
+ assert!(
+ m.triangles.len() <= n0 / 4 + n0 / 20,
+ "{}",
+ m.triangles.len()
+ );
+ assert_eq!(m.groups.as_ref().unwrap().len(), m.triangles.len());
+ assert!(m.groups.as_ref().unwrap().contains(&0));
+ assert!(m.groups.as_ref().unwrap().contains(&1));
+ assert!(rim(&m) >= 3);
+ // The rim stays on z = 0 (no vertex pulled above it).
+ assert!(m.vertices.iter().all(|p| p[2] <= 1e-3));
+ }
+
+ #[test]
+ fn small_open_pieces_are_never_erased() {
+ // A lone triangle and a quad beside a sphere that has to shrink a lot.
+ let mut m = sphere(1.0, 4);
+ let lone = Mesh::from_triangles(&[[[5.0, 0.0, 0.0], [6.0, 0.0, 0.0], [5.0, 1.0, 0.0]]]);
+ let quad = Mesh::from_triangles(&[
+ [[8.0, 0.0, 0.0], [9.0, 0.0, 0.0], [9.0, 1.0, 0.0]],
+ [[8.0, 0.0, 0.0], [9.0, 1.0, 0.0], [8.0, 1.0, 0.0]],
+ ]);
+ m.append(&lone);
+ m.append(&quad);
+ simplify(&mut m, 100, &all()).unwrap();
+ let near = |x: f32| (0..m.triangles.len()).any(|t| m.triangle(t)[0][0] >= x - 0.01);
+ assert!(near(8.0), "quad erased");
+ let lone_left = (0..m.triangles.len())
+ .any(|t| m.triangle(t).iter().all(|p| (5.0..=6.0).contains(&p[0])));
+ assert!(lone_left, "lone triangle erased");
+ }
+
+ #[test]
+ fn non_manifold_edges_never_move_and_cancel_is_honoured() {
+ // Two spheres sharing nothing but a fin: a third triangle on one edge.
+ let mut m = sphere(1.0, 3);
+ let t0 = m.triangles[0];
+ m.vertices.push([3.0, 3.0, 3.0]);
+ let x = (m.vertices.len() - 1) as u32;
+ m.triangles.push([t0[0], t0[1], x]);
+ let fixed = [t0[0], t0[1]].map(|i| m.vertices[i as usize]);
+ simplify(&mut m, 200, &all()).unwrap();
+ for p in fixed {
+ assert!(m.vertices.contains(&p));
+ }
+ let mut m = sphere(1.0, 5);
+ let e = simplify(&mut m, 1000, &|_, _| false).unwrap_err();
+ assert_eq!(e, AssetError::cancelled());
+ }
+}
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
index bdb7ae9..a7152b3 100644
--- a/docs/plans/specs/model-print.md
+++ b/docs/plans/specs/model-print.md
@@ -87,6 +87,22 @@ with `from_triangles`, `from_labeled`, `from_glb`, `bounds`, `soup`, `subset`,
`count_solid`; a cell is 0 (empty) or 1 + its group. `threemf::write_3mf_objects(&[Object],
Unit, Layout, path)`.
+## Simplify
+
+`simplify.rs`: quadric error metric edge collapse (Garland-Heckbert), pure Rust, no new crate
+(`meshopt` builds C++). Face quadrics are area-weighted; open edges and edges between two
+groups add a perpendicular plane (weight 10) so holes and colour borders stay put. A collapse
+is refused when it breaks the link condition, joins two boundary vertices over an inner edge,
+turns a face by more than about 78° or makes a sliver, makes two faces coincide, or would erase
+a small open piece. Vertices on non-manifold edges never move. A closed, consistently wound
+part stays closed; at or under the budget a part is unchanged; the result can stay above the
+budget when the checks refuse the rest (raw GLB soups; a voxel solid is manifold).
+
+Real data (release build, `dev print-glb --stl --simplify N`): Skylark LOD 4 (98 376
+triangles) to 20 000 in about 0.2 s, its 202 closed shells still closed; a Javelin LOD 0
+(3.66 M triangles, 420 k non-manifold edges) asked for 200 000 stops at about 725 000 in
+about 18 s.
+
## Testing on real GLBs
`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
From 5ae28f1dfb6de74cf098865c3a15d4714f13bea1 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:26:17 -0600
Subject: [PATCH 06/12] feat(print): experimental voxel solid, thicken, hollow
and pegs
- voxelize: conservative triangle/box rasterisation per z-slab (rayon),
outside flood fill on bitsets after a 2-voxel closing, then ray-stabbing
votes (seen along >= 3 of 6 axis directions) so hulls with openings fill
instead of leaking into a thin shell; per-cell group labels (closest
triangle); grids above 2^29 cells coarsen with a note.
- extract / extract_where: well-composed fix-up (no edge/corner-only
contacts), voxel faces on shared corners, clamped Laplacian smoothing
that never flips a triangle: closed, outward, 2-manifold by construction.
- thicken: opening residue away from rounded edges, dilated by t/2.
- hollow: erosion by the wall, cavities under 1 mm3 kept solid, drain holes
from each cavity's lowest point down through the bottom wall.
- peg: holes across each cut at the most solid point of the cut face and a
stand hole in the underside near the centre of mass, clamped so they
never break through, with notes.
- Bits helpers (dilate/erode/flood/components) for the split and colour
steps; pipeline notes the coarsened voxel size (one line in mod.rs).
---
crates/starorg-data/src/assets/print/mod.rs | 1 +
crates/starorg-data/src/assets/print/voxel.rs | 1978 ++++++++++++++++-
.../src/assets/print/voxel_tests.rs | 454 ++++
docs/plans/specs/model-print.md | 41 +
4 files changed, 2444 insertions(+), 30 deletions(-)
create mode 100644 crates/starorg-data/src/assets/print/voxel_tests.rs
diff --git a/crates/starorg-data/src/assets/print/mod.rs b/crates/starorg-data/src/assets/print/mod.rs
index 773a2b5..6cdc103 100644
--- a/crates/starorg-data/src/assets/print/mod.rs
+++ b/crates/starorg-data/src/assets/print/mod.rs
@@ -590,6 +590,7 @@ pub fn apply(mut mesh: Mesh, o: &PrintOptions, progress: Progress<'_>) -> AssetR
if o.solid {
step(progress, 0.05, "Building the solid")?;
let mut grid = voxel::voxelize(&mesh, o.solid_res_mm * per_mm, &sub(progress, 0.05, 0.4))?;
+ notes.extend(voxel::coarsened(&grid, o.solid_res_mm * per_mm));
drop(mesh);
if let Some(t) = o.thicken_mm {
step(progress, 0.4, "Thickening thin parts")?;
diff --git a/crates/starorg-data/src/assets/print/voxel.rs b/crates/starorg-data/src/assets/print/voxel.rs
index 360cb2a..cf3df28 100644
--- a/crates/starorg-data/src/assets/print/voxel.rs
+++ b/crates/starorg-data/src/assets/print/voxel.rs
@@ -1,16 +1,61 @@
//! Voxel solid (experimental): the model rebuilt as one closed, printable solid from voxels,
-//! then thickened, hollowed (with a drain hole) and given peg holes across the split cuts;
-//! [`extract`] turns a grid back into a mesh. Pipeline steps 6-9 and 11 of [`super::apply`].
+//! then thickened, hollowed (with drain holes) and given peg holes; [`extract`] turns a grid
+//! back into a closed, consistently outward-oriented 2-manifold mesh. Pipeline steps 6-9 and
+//! 11 of [`super::apply`].
//!
-//! Owner: the voxel agent. [`VoxelGrid`] is the shared API (split and peg code use it; keep
-//! its methods, change the storage if needed). [`voxelize`] and [`extract`] are stubs that
-//! refuse; [`thicken`], [`hollow`] and [`peg`] are pass-through stubs.
+//! Owner: the voxel agent. [`VoxelGrid`] is the shared API (split and colour code use it).
+//!
+//! How it works (robust over pretty):
+//!
+//! - [`voxelize`]: every triangle marks the cells its (slightly enlarged) box overlaps
+//! (Akenine-Moller separating-axis test), so the marked surface has no 6-connected gaps.
+//! The outside is flood-filled from the padded border through unmarked cells after a
+//! closing of [`SEAL_CELLS`] (gaps in the mesh up to about twice that are sealed). Game hulls
+//! have openings wider than that (cockpits, intakes, missing panels), so a cell the flood
+//! reaches is only outside when it is also in plain view (no surface cell between it and the
+//! border) along at least [`OUTSIDE_VOTES`] of the six axis directions (ray stabbing,
+//! Nooruddin and Turk); the inside of a hull with holes is seen through one or two of them.
+//! Whatever is not outside is solid. Open, self-intersecting and unwelded meshes therefore
+//! still give a closed solid. Trade-off: deep exterior pockets seen from fewer than three
+//! directions (under a belly between landing gear legs, a bore) fill in. The solid is about
+//! half a voxel larger on each side than the mesh. Each cell keeps the group of its closest triangle (surface cells) or
+//! of the surface cell before it along x (inside).
+//! - [`extract`]: the solid is made well-composed (Latecki: no two cells meeting only at an
+//! edge or a corner, for the solid or the empty space; fixed by adding cells), then every
+//! solid/empty cell face becomes a quad sharing grid-corner vertices: a closed 2-manifold by
+//! construction, outward by construction. The staircase is then smoothed (Laplacian, each
+//! vertex clamped to [`SMOOTH_CLAMP`] voxels of its corner, undone where a triangle would
+//! turn over), which keeps the topology. Simplifying is the simplify step's job.
+//! - [`thicken`], [`hollow`]: morphology on bitsets ([`Bits::erode`], [`Bits::dilate`] with a
+//! discrete ball, chained for large radii).
+//! - [`peg`]: peg holes across each cut and a stand hole from the underside.
use super::{Cut, Mesh, Progress};
use crate::assets::{AssetError, AssetResult};
+use rayon::prelude::*;
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// The most cells a grid may have (dense `u8`: about 1 GB).
pub const MAX_CELLS: u64 = 1 << 30;
+/// [`voxelize`] coarsens the resolution until the grid has at most this many cells (half of
+/// [`MAX_CELLS`]: the morphology needs a few bitsets on top of the cells).
+pub const CELL_BUDGET: u64 = MAX_CELLS / 2;
+/// Gaps in the mesh up to about twice this many voxels are sealed before the outside is found.
+pub const SEAL_CELLS: f32 = 2.0;
+/// A cell the flood reaches is outside only when it is in plain view along at least this
+/// many of the six axis directions (else it is inside a hull with holes).
+pub const OUTSIDE_VOTES: u32 = 3;
+/// How far (voxels) smoothing may move a vertex from its grid corner, per axis.
+pub const SMOOTH_CLAMP: f32 = 0.4;
+/// Smoothing passes over the extracted surface.
+pub const SMOOTH_ITERS: usize = 4;
+/// The least material kept around a peg or stand hole, millimetres (warned below).
+pub const PEG_WALL_MM: f32 = 0.8;
+/// The least material left at the end of a peg or stand hole, millimetres.
+pub const PEG_CAP_MM: f32 = 0.6;
+/// Cavities smaller than this (cubic millimetres) are left solid when hollowing.
+pub const MIN_CAVITY_MM3: f32 = 1.0;
/// A dense grid of cubic cells. A cell holds 0 (empty) or `1 + group` (solid, of the group
/// `labels[group]`; 1 when the mesh had no groups).
@@ -133,27 +178,944 @@ impl VoxelGrid {
}
Ok(g)
}
+
+ /// The solid cells (`keep(cell)`) as a bitset of the same dims.
+ pub fn bits(&self, keep: &(dyn Fn(u8) -> bool + Sync)) -> Bits {
+ let mut b = Bits::new(self.dims);
+ let d0 = self.dims[0] as usize;
+ if d0 == 0 {
+ return b;
+ }
+ let wpr = b.wpr;
+ b.data
+ .par_chunks_mut(wpr)
+ .zip(self.cells.par_chunks(d0))
+ .for_each(|(o, row)| {
+ for (x, c) in row.iter().enumerate() {
+ if keep(*c) {
+ o[x / 64] |= 1 << (x % 64);
+ }
+ }
+ });
+ b
+ }
+
+ /// The bounds of the solid cells (`min..max`, exclusive), `None` when empty.
+ pub fn solid_bounds(&self) -> Option<([u32; 3], [u32; 3])> {
+ let d0 = self.dims[0] as usize;
+ let d1 = self.dims[1] as usize;
+ if d0 == 0 {
+ return None;
+ }
+ self.cells
+ .par_chunks(d0)
+ .enumerate()
+ .filter_map(|(row, cs)| {
+ let first = cs.iter().position(|c| *c != 0)?;
+ let last = cs.iter().rposition(|c| *c != 0)?;
+ let (y, z) = ((row % d1) as u32, (row / d1) as u32);
+ Some(([first as u32, y, z], [last as u32 + 1, y + 1, z + 1]))
+ })
+ .reduce_with(|a, b| {
+ (
+ [0, 1, 2].map(|i| a.0[i].min(b.0[i])),
+ [0, 1, 2].map(|i| a.1[i].max(b.1[i])),
+ )
+ })
+ }
+
+ /// This grid with `m` more empty cells on every side (same cells, same world positions).
+ pub fn grown(&self, m: u32) -> AssetResult {
+ let dims = self.dims.map(|d| d + 2 * m);
+ let origin = self.origin.map(|o| o - m as f32 * self.voxel);
+ let mut g = VoxelGrid::new(origin, self.voxel, dims)?;
+ g.labels = self.labels.clone();
+ let d0 = self.dims[0] as usize;
+ if d0 == 0 {
+ return Ok(g);
+ }
+ for z in 0..self.dims[2] {
+ for y in 0..self.dims[1] {
+ let s = self.index(0, y, z);
+ let t = g.index(m, y + m, z + m);
+ g.cells[t..t + d0].copy_from_slice(&self.cells[s..s + d0]);
+ }
+ }
+ Ok(g)
+ }
+
+ /// Turn on the cells of `add` that are empty, each with the group of a solid neighbour
+ /// (1 without labels).
+ fn add_bits(&mut self, add: &Bits) {
+ let labeled = !self.labels.is_empty();
+ let mut todo: Vec<[u32; 3]> = add
+ .ones()
+ .filter(|&[x, y, z]| self.get(x, y, z) == 0)
+ .collect();
+ if !labeled {
+ for [x, y, z] in todo {
+ self.set(x, y, z, 1);
+ }
+ return;
+ }
+ // Grow labels into the new cells, a layer per pass.
+ while !todo.is_empty() {
+ let mut set = Vec::new();
+ let mut rest = Vec::new();
+ for c in todo {
+ match neighbour_label(self, c) {
+ Some(v) => set.push((c, v)),
+ None => rest.push(c),
+ }
+ }
+ if set.is_empty() {
+ for [x, y, z] in rest {
+ self.set(x, y, z, 1);
+ }
+ return;
+ }
+ for ([x, y, z], v) in set {
+ self.set(x, y, z, v);
+ }
+ todo = rest;
+ }
+ }
+}
+
+/// The value of a solid 6-neighbour of `c`.
+fn neighbour_label(g: &VoxelGrid, [x, y, z]: [u32; 3]) -> Option {
+ let n = [
+ (x.wrapping_sub(1), y, z),
+ (x + 1, y, z),
+ (x, y.wrapping_sub(1), z),
+ (x, y + 1, z),
+ (x, y, z.wrapping_sub(1)),
+ (x, y, z + 1),
+ ];
+ n.into_iter()
+ .map(|(a, b, c)| g.get(a, b, c))
+ .find(|v| *v != 0)
}
-/// TODO(voxel agent): fill the inside of `mesh` (mesh units, millimetres) with cells of edge
-/// `res`, labelled by the mesh's groups (most covering triangle); open and self-intersecting
-/// ship meshes must still give a closed solid. Stub: refused.
+// ---------------------------------------------------------------------------------------------
+// Bitsets
+
+/// A bit per cell, rows along x (each row padded to whole 64-bit words; the padding stays 0).
+#[derive(Debug, Clone, PartialEq)]
+pub struct Bits {
+ dims: [u32; 3],
+ wpr: usize,
+ data: Vec,
+}
+
+/// Bits of `src` moved `k` cells up: `out[x] = src[x - k]` (word `i`).
+fn up(src: &[u64], k: usize, i: usize) -> u64 {
+ let (q, b) = (k / 64, k % 64);
+ if i < q {
+ return 0;
+ }
+ let j = i - q;
+ let lo = src[j] << b;
+ let hi = if b > 0 && j > 0 {
+ src[j - 1] >> (64 - b)
+ } else {
+ 0
+ };
+ lo | hi
+}
+
+/// Bits of `src` moved `k` cells down: `out[x] = src[x + k]` (word `i`).
+fn down(src: &[u64], k: usize, i: usize) -> u64 {
+ let (q, b) = (k / 64, k % 64);
+ let j = i + q;
+ if j >= src.len() {
+ return 0;
+ }
+ let lo = src[j] >> b;
+ let hi = if b > 0 && j + 1 < src.len() {
+ src[j + 1] << (64 - b)
+ } else {
+ 0
+ };
+ lo | hi
+}
+
+/// The (dy, dz, half-width along x) rows of a discrete ball of radius `r` cells.
+fn ball(r: f32) -> Vec<(i32, i32, usize)> {
+ let r2 = r * r + 1e-4;
+ let ri = r.floor() as i32;
+ let mut v = Vec::new();
+ for dz in -ri..=ri {
+ for dy in -ri..=ri {
+ let s = r2 - (dy * dy + dz * dz) as f32;
+ if s >= 0.0 {
+ v.push((dy, dz, s.sqrt().floor() as usize));
+ }
+ }
+ }
+ v
+}
+
+/// The (dx, dy) cells of a disc of radius `r` cells.
+fn disc(r: f32) -> Vec<(i32, i32)> {
+ let r2 = r * r + 1e-4;
+ let ri = r.floor() as i32;
+ let mut v = Vec::new();
+ for dy in -ri..=ri {
+ for dx in -ri..=ri {
+ if ((dx * dx + dy * dy) as f32) <= r2 {
+ v.push((dx, dy));
+ }
+ }
+ }
+ v
+}
+
+/// The largest ball radius (cells) done in one pass; larger ones are chained.
+const BALL_STEP: f32 = 4.0;
+
+impl Bits {
+ /// All clear.
+ pub fn new(dims: [u32; 3]) -> Self {
+ let wpr = (dims[0] as usize).div_ceil(64);
+ Self {
+ dims,
+ wpr,
+ data: vec![0; wpr * dims[1] as usize * dims[2] as usize],
+ }
+ }
+
+ pub fn dims(&self) -> [u32; 3] {
+ self.dims
+ }
+
+ fn rows(&self) -> usize {
+ self.dims[1] as usize * self.dims[2] as usize
+ }
+
+ fn row_of(&self, y: u32, z: u32) -> usize {
+ (y as usize + self.dims[1] as usize * z as usize) * self.wpr
+ }
+
+ fn row(&self, y: i64, z: i64) -> Option<&[u64]> {
+ if y < 0 || z < 0 || y >= self.dims[1] as i64 || z >= self.dims[2] as i64 {
+ return None;
+ }
+ let r = self.row_of(y as u32, z as u32);
+ Some(&self.data[r..r + self.wpr])
+ }
+
+ fn tail(&self) -> u64 {
+ match self.dims[0] % 64 {
+ 0 => !0,
+ b => (1u64 << b) - 1,
+ }
+ }
+
+ fn mask_tails(&mut self) {
+ let (t, w) = (self.tail(), self.wpr);
+ if w > 0 {
+ self.data.par_chunks_mut(w).for_each(|r| r[w - 1] &= t);
+ }
+ }
+
+ pub fn get(&self, x: u32, y: u32, z: u32) -> bool {
+ if x >= self.dims[0] || y >= self.dims[1] || z >= self.dims[2] {
+ return false;
+ }
+ let r = self.row_of(y, z) + x as usize / 64;
+ (self.data[r] >> (x % 64)) & 1 == 1
+ }
+
+ pub fn set(&mut self, x: u32, y: u32, z: u32, on: bool) {
+ if x >= self.dims[0] || y >= self.dims[1] || z >= self.dims[2] {
+ return;
+ }
+ let r = self.row_of(y, z) + x as usize / 64;
+ let m = 1u64 << (x % 64);
+ if on {
+ self.data[r] |= m;
+ } else {
+ self.data[r] &= !m;
+ }
+ }
+
+ /// Set bits `x0..x1` of row (y, z).
+ fn set_run(&mut self, y: u32, z: u32, x0: u32, x1: u32) {
+ let r = self.row_of(y, z);
+ for x in x0..x1 {
+ self.data[r + x as usize / 64] |= 1u64 << (x % 64);
+ }
+ }
+
+ pub fn count(&self) -> u64 {
+ self.data.par_iter().map(|w| w.count_ones() as u64).sum()
+ }
+
+ pub fn any(&self) -> bool {
+ self.data.par_iter().any(|w| *w != 0)
+ }
+
+ /// The set cells, x fastest.
+ pub fn ones(&self) -> impl Iterator + '_ {
+ let (wpr, d1) = (self.wpr, self.dims[1] as usize);
+ self.data.iter().enumerate().flat_map(move |(i, w)| {
+ let mut w = *w;
+ let row = i / wpr.max(1);
+ let base = (i % wpr.max(1)) * 64;
+ std::iter::from_fn(move || {
+ if w == 0 {
+ return None;
+ }
+ let b = w.trailing_zeros() as usize;
+ w &= w - 1;
+ Some([(base + b) as u32, (row % d1) as u32, (row / d1) as u32])
+ })
+ })
+ }
+
+ /// The complement (within the dims).
+ pub fn not(&self) -> Bits {
+ let mut b = self.clone();
+ b.data.par_iter_mut().for_each(|w| *w = !*w);
+ b.mask_tails();
+ b
+ }
+
+ pub fn or_with(&mut self, o: &Bits) {
+ self.data
+ .par_iter_mut()
+ .zip(o.data.par_iter())
+ .for_each(|(a, b)| *a |= *b);
+ }
+
+ pub fn and_with(&mut self, o: &Bits) {
+ self.data
+ .par_iter_mut()
+ .zip(o.data.par_iter())
+ .for_each(|(a, b)| *a &= *b);
+ }
+
+ pub fn and_not(&mut self, o: &Bits) {
+ self.data
+ .par_iter_mut()
+ .zip(o.data.par_iter())
+ .for_each(|(a, b)| *a &= !*b);
+ }
+
+ /// Dilation by a ball of radius `r` cells (nothing below 1). Outside the dims is empty.
+ pub fn dilate(&self, r: f32) -> Bits {
+ self.chain(r, true)
+ }
+
+ /// Erosion by a ball of radius `r` cells (nothing below 1). Outside the dims is empty, so
+ /// the border erodes.
+ pub fn erode(&self, r: f32) -> Bits {
+ self.chain(r, false)
+ }
+
+ fn chain(&self, r: f32, grow: bool) -> Bits {
+ if r.is_nan() || r < 1.0 || self.wpr == 0 {
+ return self.clone();
+ }
+ // Whole steps of BALL_STEP and the rest (balls add up along the axes).
+ let mut b = self.morph(r.min(BALL_STEP), grow);
+ let mut left = r - r.min(BALL_STEP);
+ while left >= 1.0 {
+ let s = left.min(BALL_STEP);
+ b = b.morph(s, grow);
+ left -= s;
+ }
+ b
+ }
+
+ fn morph(&self, r: f32, grow: bool) -> Bits {
+ let offs = ball(r);
+ let mut out = Bits::new(self.dims);
+ let (wpr, d1, tail) = (self.wpr, self.dims[1] as usize, self.tail());
+ out.data
+ .par_chunks_mut(wpr)
+ .enumerate()
+ .for_each(|(row, o)| {
+ let (y, z) = ((row % d1) as i64, (row / d1) as i64);
+ if !grow {
+ o.fill(!0);
+ }
+ for &(dy, dz, w) in &offs {
+ let Some(s) = self.row(y + dy as i64, z + dz as i64) else {
+ if !grow {
+ o.fill(0);
+ break;
+ }
+ continue;
+ };
+ for i in 0..wpr {
+ let mut v = s[i];
+ if grow {
+ for k in 1..=w {
+ v |= up(s, k, i) | down(s, k, i);
+ }
+ o[i] |= v;
+ } else {
+ for k in 1..=w {
+ v &= up(s, k, i) & down(s, k, i);
+ }
+ o[i] &= v;
+ }
+ }
+ }
+ o[wpr - 1] &= tail;
+ });
+ out
+ }
+
+ /// The end (exclusive) of the run of `free` cells holding `x` in row `r`.
+ fn run_end(&self, free: &impl Fn(usize) -> u64, x: u32) -> u32 {
+ let mut i = x as usize / 64;
+ let mut m = !free(i) & (!0u64 << (x % 64));
+ loop {
+ if m != 0 {
+ return ((i * 64) as u32 + m.trailing_zeros()).min(self.dims[0]);
+ }
+ i += 1;
+ if i >= self.wpr {
+ return self.dims[0];
+ }
+ m = !free(i);
+ }
+ }
+
+ /// The start of the run of `free` cells holding `x`.
+ fn run_start(&self, free: &impl Fn(usize) -> u64, x: u32) -> u32 {
+ let mut i = x as usize / 64;
+ let b = x % 64;
+ let keep = if b == 63 { !0 } else { (1u64 << (b + 1)) - 1 };
+ let mut m = !free(i) & keep;
+ loop {
+ if m != 0 {
+ return (i * 64) as u32 + 64 - m.leading_zeros();
+ }
+ if i == 0 {
+ return 0;
+ }
+ i -= 1;
+ m = !free(i);
+ }
+ }
+
+ /// Mark in `seen` the cells of `self` 6-connected to `seed` (not yet seen), calling
+ /// `on_run(y, z, x0, x1)` for each run of cells filled. Returns the cells filled.
+ pub fn flood(
+ &self,
+ seen: &mut Bits,
+ seed: [u32; 3],
+ mut on_run: impl FnMut(u32, u32, u32, u32),
+ ) -> u64 {
+ let mut stack = vec![seed];
+ let mut n = 0u64;
+ let (d1, d2) = (self.dims[1], self.dims[2]);
+ while let Some([x, y, z]) = stack.pop() {
+ if !self.get(x, y, z) || seen.get(x, y, z) {
+ continue;
+ }
+ let r = self.row_of(y, z);
+ let (x0, x1) = {
+ let free = |i: usize| self.data[r + i] & !seen.data[r + i];
+ (self.run_start(&free, x), self.run_end(&free, x))
+ };
+ seen.set_run(y, z, x0, x1);
+ n += (x1 - x0) as u64;
+ on_run(y, z, x0, x1);
+ let mut near = Vec::with_capacity(4);
+ if y > 0 {
+ near.push((y - 1, z));
+ }
+ if y + 1 < d1 {
+ near.push((y + 1, z));
+ }
+ if z > 0 {
+ near.push((y, z - 1));
+ }
+ if z + 1 < d2 {
+ near.push((y, z + 1));
+ }
+ for (ny, nz) in near {
+ let nr = self.row_of(ny, nz);
+ let (w0, w1) = (x0 as usize / 64, (x1 as usize - 1) / 64);
+ let mut carry = 0u64;
+ for i in w0..=w1 {
+ let lo = if i == w0 { !0u64 << (x0 % 64) } else { !0 };
+ let hi = if i == w1 && x1 % 64 != 0 {
+ (1u64 << (x1 % 64)) - 1
+ } else {
+ !0
+ };
+ let m = self.data[nr + i] & !seen.data[nr + i] & lo & hi;
+ let mut starts = m & !((m << 1) | carry);
+ carry = m >> 63;
+ while starts != 0 {
+ let b = starts.trailing_zeros();
+ starts &= starts - 1;
+ stack.push([(i * 64) as u32 + b, ny, nz]);
+ }
+ }
+ }
+ }
+ n
+ }
+
+ /// Each 6-connected component of the set cells, as `f(cells, runs)` with its runs
+ /// `(y, z, x0, x1)`.
+ pub fn components(&self, mut f: impl FnMut(u64, Vec<[u32; 4]>)) {
+ let mut seen = Bits::new(self.dims);
+ for wi in 0..self.data.len() {
+ loop {
+ let m = self.data[wi] & !seen.data[wi];
+ if m == 0 {
+ break;
+ }
+ let row = wi / self.wpr;
+ let x = ((wi % self.wpr) * 64) as u32 + m.trailing_zeros();
+ let d1 = self.dims[1] as usize;
+ let seed = [x, (row % d1) as u32, (row / d1) as u32];
+ let mut runs = Vec::new();
+ let n = self.flood(&mut seen, seed, |y, z, a, b| runs.push([y, z, a, b]));
+ f(n, runs);
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Voxelising
+
+fn tick(p: Progress<'_>, f: f32, s: &str) -> AssetResult<()> {
+ if p(f, s) {
+ Ok(())
+ } else {
+ Err(AssetError::cancelled())
+ }
+}
+
+fn sub3(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
+ [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
+}
+
+fn cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
+ [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+ ]
+}
+
+fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+
+/// Does triangle `t` overlap the cube of centre `c` and half edge `h`? (Akenine-Moller.)
+fn tri_box(c: [f32; 3], h: f32, t: &[[f32; 3]; 3]) -> bool {
+ let v = [sub3(t[0], c), sub3(t[1], c), sub3(t[2], c)];
+ let (lo, hi) = (
+ [0, 1, 2].map(|i| v[0][i].min(v[1][i]).min(v[2][i])),
+ [0, 1, 2].map(|i| v[0][i].max(v[1][i]).max(v[2][i])),
+ );
+ if (0..3).any(|i| lo[i] > h || hi[i] < -h) {
+ return false;
+ }
+ let e = [sub3(v[1], v[0]), sub3(v[2], v[1]), sub3(v[0], v[2])];
+ let n = cross(e[0], e[1]);
+ let d = dot(n, v[0]);
+ if d.abs() > h * (n[0].abs() + n[1].abs() + n[2].abs()) {
+ return false;
+ }
+ for ej in e {
+ for i in 0..3 {
+ let mut u = [0.0; 3];
+ u[i] = 1.0;
+ let a = cross(u, ej);
+ let p = [dot(a, v[0]), dot(a, v[1]), dot(a, v[2])];
+ let r = h * (a[0].abs() + a[1].abs() + a[2].abs());
+ if p[0].min(p[1]).min(p[2]) > r || p[0].max(p[1]).max(p[2]) < -r {
+ return false;
+ }
+ }
+ }
+ true
+}
+
+/// The resolution and grid a mesh of `size` gets at `res`, coarsened to [`CELL_BUDGET`].
+fn plan_grid(size: [f32; 3], res: f32, pad: u32) -> ([u32; 3], f32) {
+ let mut res = res;
+ loop {
+ let dims = size.map(|s| ((s / res).ceil().max(1.0) as u32) + 2 * pad);
+ let n: u64 = dims.iter().map(|d| *d as u64).product();
+ if n <= CELL_BUDGET {
+ return (dims, res);
+ }
+ res *= ((n as f64 / CELL_BUDGET as f64).cbrt() as f32).max(1.01) * 1.001;
+ }
+}
+
+/// A note when [`voxelize`] used a coarser voxel than `asked` (to stay in [`CELL_BUDGET`]).
+pub fn coarsened(grid: &VoxelGrid, asked: f32) -> Option {
+ (grid.voxel > asked * 1.0001).then(|| {
+ format!(
+ "The solid uses {:.3} mm voxels instead of {:.3} mm (the model is too large for the finer grid).",
+ grid.voxel, asked
+ )
+ })
+}
+
+/// Fill the inside of `mesh` (mesh units, millimetres) with cells of edge `res` (coarsened to
+/// [`CELL_BUDGET`], see [`coarsened`]), labelled by the mesh's groups (the closest triangle
+/// for surface cells); open and self-intersecting meshes still give a closed solid (see the
+/// module doc).
pub fn voxelize(mesh: &Mesh, res: f32, progress: Progress<'_>) -> AssetResult {
- let _ = (mesh, res, progress);
- Err(AssetError::invalid(
- "the solid (experimental) is not available in this build yet",
- ))
+ if !(res.is_finite() && res > 0.0) {
+ return Err(AssetError::invalid("the voxel size must be more than 0"));
+ }
+ let b = mesh
+ .bounds()
+ .ok_or_else(|| AssetError::invalid("the model has no triangles"))?;
+ tick(progress, 0.0, "Building the solid")?;
+ let seal = SEAL_CELLS;
+ let pad = seal.ceil() as u32 + 2;
+ let (dims, res) = plan_grid(b.size(), res, pad);
+ // Half a cell off so axis-aligned faces at round sizes fall inside cells, not on borders.
+ let origin = [0, 1, 2].map(|i| b.min[i] - (pad as f32 + 0.5) * res);
+ let mut grid = VoxelGrid::new(origin, res, dims)?;
+ let labeled = mesh.groups.is_some() && !mesh.labels.is_empty();
+ if labeled {
+ grid.labels = mesh.labels.clone();
+ }
+ rasterize(mesh, &mut grid, labeled, progress)?;
+ tick(progress, 0.5, "Finding the inside")?;
+ // Outside: flood from the corner through cells away from the (dilated) surface, keep what
+ // is in plain view from enough directions (a hull with holes stays inside), then grow it
+ // back by the same ball as the dilation (a closing of the surface).
+ let surface = grid.bits(&|c| c != 0);
+ let sealed = surface.dilate(seal);
+ let open = sealed.not();
+ let mut outside = Bits::new(dims);
+ open.flood(&mut outside, [0, 0, 0], |_, _, _, _| {});
+ drop(open);
+ drop(sealed);
+ tick(progress, 0.65, "Finding the inside")?;
+ outside.and_with(&seen_from(&surface, OUTSIDE_VOTES));
+ tick(progress, 0.75, "Finding the inside")?;
+ let solid = outside.dilate(seal).not();
+ drop(outside);
+ drop(surface);
+ tick(progress, 0.9, "Finding the inside")?;
+ fill_inside(&mut grid, &solid, labeled);
+ tick(progress, 1.0, "Building the solid")?;
+ Ok(grid)
}
-/// TODO(voxel agent): grow the solid so no part is thinner than `min` (mesh units). Stub: no-op.
-pub fn thicken(grid: &mut VoxelGrid, min: f32, progress: Progress<'_>) -> AssetResult<()> {
- let _ = (grid, min, progress);
+/// `a + b + c` per bit: (sum, carry).
+fn full_add(a: u64, b: u64, c: u64) -> (u64, u64) {
+ (a ^ b ^ c, (a & b) | (c & (a ^ b)))
+}
+
+/// The cells with no `surface` cell between them and the grid's border along at least `k`
+/// (1..=6) of the six axis directions.
+fn seen_from(surface: &Bits, k: u32) -> Bits {
+ let [d0, d1, d2] = surface.dims.map(|d| d as usize);
+ let wpr = surface.wpr;
+ let tail = surface.tail();
+ let full = {
+ let mut r = vec![!0u64; wpr];
+ if wpr > 0 {
+ r[wpr - 1] = tail;
+ }
+ r
+ };
+ // Along z (both ways) and y (both ways): sweep keeping what is still clear.
+ let sweep = |outer: usize, inner: usize, row: &dyn Fn(usize, usize) -> usize, rev: bool| {
+ let mut out = Bits::new(surface.dims);
+ for o in 0..outer {
+ let mut clear = full.clone();
+ for s in 0..inner {
+ let s = if rev { inner - 1 - s } else { s };
+ let r = row(o, s) * wpr;
+ for (c, w) in clear.iter_mut().zip(&surface.data[r..r + wpr]) {
+ *c &= !*w;
+ }
+ out.data[r..r + wpr].copy_from_slice(&clear);
+ }
+ }
+ out
+ };
+ let zrow = |y: usize, z: usize| y + d1 * z;
+ let mz = sweep(d1, d2, &zrow, false);
+ let pz = sweep(d1, d2, &zrow, true);
+ let yrow = |z: usize, y: usize| y + d1 * z;
+ let my = sweep(d2, d1, &yrow, false);
+ let py = sweep(d2, d1, &yrow, true);
+ let mut out = Bits::new(surface.dims);
+ if wpr == 0 {
+ return out;
+ }
+ out.data
+ .par_chunks_mut(wpr)
+ .enumerate()
+ .for_each(|(row, o)| {
+ let s = &surface.data[row * wpr..(row + 1) * wpr];
+ // Along x: before the first and after the last surface cell of the row.
+ let first = s
+ .iter()
+ .position(|w| *w != 0)
+ .map(|i| i * 64 + s[i].trailing_zeros() as usize)
+ .unwrap_or(d0);
+ let last = s
+ .iter()
+ .rposition(|w| *w != 0)
+ .map(|i| i * 64 + 63 - s[i].leading_zeros() as usize);
+ for (i, oi) in o.iter_mut().enumerate() {
+ let bit_range = |lo: usize, hi: usize| -> u64 {
+ // Bits lo..hi of word i.
+ let (a, b) = (lo.max(i * 64), hi.min(i * 64 + 64));
+ if a >= b {
+ return 0;
+ }
+ let n = b - a;
+ let m = if n == 64 { !0 } else { (1u64 << n) - 1 };
+ m << (a - i * 64)
+ };
+ let mx = bit_range(0, first);
+ let px = match last {
+ Some(l) => bit_range(l + 1, d0),
+ None => bit_range(0, d0),
+ };
+ let r = row * wpr + i;
+ let (s1, c1) = full_add(mx, px, mz.data[r]);
+ let (s2, c2) = full_add(pz.data[r], my.data[r], py.data[r]);
+ let (low, c3) = (s1 ^ s2, s1 & s2);
+ // total = low + 2 * (c1 + c2 + c3)
+ let twos_ge1 = c1 | c2 | c3;
+ let twos_ge2 = (c1 & c2) | (c1 & c3) | (c2 & c3);
+ let twos_3 = c1 & c2 & c3;
+ *oi = match k {
+ 0 | 1 => mx | px | mz.data[r] | pz.data[r] | my.data[r] | py.data[r],
+ 2 => twos_ge1,
+ 3 => twos_ge2 | (twos_ge1 & low),
+ 4 => twos_ge2,
+ 5 => twos_3 | (twos_ge2 & low),
+ _ => twos_3,
+ };
+ }
+ o[wpr - 1] &= tail;
+ });
+ out
+}
+
+/// Mark the cells each triangle overlaps (1 + group; the closest triangle wins).
+fn rasterize(
+ mesh: &Mesh,
+ grid: &mut VoxelGrid,
+ labeled: bool,
+ progress: Progress<'_>,
+) -> AssetResult<()> {
+ let (origin, res, dims) = (grid.origin, grid.voxel, grid.dims);
+ let tris: Vec<[[f32; 3]; 3]> = (0..mesh.triangles.len())
+ .map(|t| {
+ mesh.triangle(t)
+ .map(|p| [0, 1, 2].map(|i| (p[i] - origin[i]) / res))
+ })
+ .collect();
+ let plane = dims[0] as usize * dims[1] as usize;
+ let threads = rayon::current_num_threads().max(1) as u32;
+ let layers = dims[2].div_ceil(threads * 8).max(1);
+ let nslabs = dims[2].div_ceil(layers) as usize;
+ const EPS: f32 = 1e-3;
+ let cell_range = |lo: f32, hi: f32, n: u32| -> (u32, u32) {
+ let a = (lo - EPS).floor().max(0.0) as u32;
+ let b = ((hi + EPS).floor().max(0.0) as u32).min(n.saturating_sub(1));
+ (a, b)
+ };
+ let mut bins: Vec> = vec![Vec::new(); nslabs];
+ for (t, tri) in tris.iter().enumerate() {
+ let (lo, hi) = (
+ tri[0][2].min(tri[1][2]).min(tri[2][2]),
+ tri[0][2].max(tri[1][2]).max(tri[2][2]),
+ );
+ let (z0, z1) = cell_range(lo, hi, dims[2]);
+ for s in (z0 / layers)..=(z1 / layers) {
+ bins[s as usize].push(t as u32);
+ }
+ }
+ let done = AtomicUsize::new(0);
+ let stop = AtomicBool::new(false);
+ let h = 0.5 + EPS;
+ grid.cells
+ .par_chunks_mut(plane * layers as usize)
+ .enumerate()
+ .for_each(|(s, chunk)| {
+ if stop.load(Ordering::Relaxed) {
+ return;
+ }
+ let zs = s as u32 * layers;
+ let ze = (zs + layers).min(dims[2]);
+ let mut best: HashMap = HashMap::new();
+ for &t in &bins[s] {
+ let tri = &tris[t as usize];
+ let v = if labeled {
+ 1 + mesh.group(t as usize).min(254) as u8
+ } else {
+ 1
+ };
+ let lo = [0, 1, 2].map(|i| tri[0][i].min(tri[1][i]).min(tri[2][i]));
+ let hi = [0, 1, 2].map(|i| tri[0][i].max(tri[1][i]).max(tri[2][i]));
+ let (x0, x1) = cell_range(lo[0], hi[0], dims[0]);
+ let (y0, y1) = cell_range(lo[1], hi[1], dims[1]);
+ let (mut z0, mut z1) = cell_range(lo[2], hi[2], dims[2]);
+ z0 = z0.max(zs);
+ z1 = z1.min(ze - 1);
+ let n = cross(sub3(tri[1], tri[0]), sub3(tri[2], tri[0]));
+ let nl1 = n[0].abs() + n[1].abs() + n[2].abs();
+ let nlen = dot(n, n).sqrt();
+ let d = dot(n, tri[0]);
+ let r = h * nl1;
+ for z in z0..=z1.max(z0) {
+ if z > z1 {
+ break;
+ }
+ for y in y0..=y1 {
+ let (cy, cz) = (y as f32 + 0.5, z as f32 + 0.5);
+ // The cells along x the triangle's plane can reach in this row.
+ let (mut a, mut b) = (x0, x1);
+ if n[0].abs() > 1e-6 * nl1 {
+ let m = d - n[1] * cy - n[2] * cz;
+ let (p, q) = ((m - r) / n[0], (m + r) / n[0]);
+ let (p, q) = (p.min(q) - 0.5, p.max(q) - 0.5);
+ a = a.max(p.floor().max(0.0) as u32);
+ b = b.min(q.ceil().max(0.0) as u32);
+ }
+ for x in a..=b.max(a) {
+ if x > b {
+ break;
+ }
+ let c = [x as f32 + 0.5, cy, cz];
+ if !tri_box(c, h, tri) {
+ continue;
+ }
+ let i = x as usize
+ + dims[0] as usize
+ * (y as usize + dims[1] as usize * (z - zs) as usize);
+ if labeled {
+ let dist = if nlen > 0.0 {
+ (dot(n, c) - d).abs() / nlen
+ } else {
+ 0.0
+ };
+ let e = best.entry(i).or_insert(f32::INFINITY);
+ if dist < *e {
+ *e = dist;
+ chunk[i] = v;
+ }
+ } else {
+ chunk[i] = 1;
+ }
+ }
+ }
+ }
+ }
+ let k = done.fetch_add(1, Ordering::Relaxed) + 1;
+ if !progress(0.5 * k as f32 / nslabs as f32, "Building the solid") {
+ stop.store(true, Ordering::Relaxed);
+ }
+ });
+ if stop.load(Ordering::Relaxed) {
+ return Err(AssetError::cancelled());
+ }
Ok(())
}
-/// TODO(voxel agent): hollow the solid, keeping walls `wall` thick, with a drain hole of
-/// diameter `drain` (0 = none) through the bottom of each cavity (say where in `notes`).
-/// Stub: no-op.
+/// Keep only `solid`, labelling solid cells not on the surface: the label of the surface cell
+/// before (or else after) them along x; 1 without labels.
+fn fill_inside(grid: &mut VoxelGrid, solid: &Bits, labeled: bool) {
+ let d0 = grid.dims[0] as usize;
+ if d0 == 0 {
+ return;
+ }
+ let wpr = solid.wpr;
+ grid.cells
+ .par_chunks_mut(d0)
+ .zip(solid.data.par_chunks(wpr))
+ .for_each(|(row, s)| {
+ let on = |x: usize| (s[x / 64] >> (x % 64)) & 1 == 1;
+ let mut last = 0u8;
+ for (x, c) in row.iter_mut().enumerate() {
+ if !on(x) {
+ *c = 0;
+ } else if *c != 0 {
+ last = *c;
+ } else if !labeled {
+ *c = 1;
+ } else {
+ *c = last;
+ }
+ }
+ if labeled {
+ let mut next = 0u8;
+ for x in (0..d0).rev() {
+ if row[x] != 0 {
+ next = row[x];
+ } else if on(x) {
+ row[x] = if next != 0 { next } else { 1 };
+ }
+ }
+ }
+ });
+}
+
+// ---------------------------------------------------------------------------------------------
+// Thicken, hollow
+
+/// Grow the solid so no part is thinner than `min` (mesh units): the parts an opening of
+/// radius `min / 2` removes are dilated by `min / 2` (so a sheet becomes at least `min`
+/// thick). Trade-off: thin parts grow outwards on both sides (their outline moves by up to
+/// `min / 2`) and gaps narrower than `min` between them fill in; thick parts are untouched.
+/// The grid grows when the solid is too close to its border.
+pub fn thicken(grid: &mut VoxelGrid, min: f32, progress: Progress<'_>) -> AssetResult<()> {
+ let r = 0.5 * min / grid.voxel;
+ if r.is_nan() || r < 1.0 {
+ return Ok(());
+ }
+ tick(progress, 0.0, "Thickening thin parts")?;
+ let margin = r.ceil() as u32 + 1;
+ if let Some((lo, hi)) = grid.solid_bounds()
+ && (0..3).any(|i| lo[i] < margin || hi[i] + margin > grid.dims[i])
+ {
+ *grid = grid.grown(margin)?;
+ }
+ let solid = grid.bits(&|c| c != 0);
+ let open = solid.erode(r);
+ tick(progress, 0.3, "Thickening thin parts")?;
+ let open = open.dilate(r);
+ tick(progress, 0.5, "Thickening thin parts")?;
+ // What the opening removes next to what it keeps is a rounded edge or corner of a thick
+ // part (at most (sqrt 3 - 1) r away), not a thin part.
+ let near = open.dilate(0.75 * r + 1.0);
+ drop(open);
+ tick(progress, 0.7, "Thickening thin parts")?;
+ let mut thin = solid;
+ thin.and_not(&near);
+ drop(near);
+ if !thin.any() {
+ return Ok(());
+ }
+ let add = thin.dilate(r);
+ tick(progress, 0.9, "Thickening thin parts")?;
+ grid.add_bits(&add);
+ tick(progress, 1.0, "Thickening thin parts")
+}
+
+/// Hollow the solid, keeping walls `wall` thick (mesh units), with drain holes of diameter
+/// `drain` (0 = none) from the lowest point of each cavity straight down through the bottom
+/// wall (a second one for a large cavity); says where in `notes`. Cavities under
+/// [`MIN_CAVITY_MM3`] stay solid.
pub fn hollow(
grid: &mut VoxelGrid,
wall: f32,
@@ -161,13 +1123,244 @@ pub fn hollow(
notes: &mut Vec,
progress: Progress<'_>,
) -> AssetResult<()> {
- let _ = (grid, wall, drain, notes, progress);
- Ok(())
+ tick(progress, 0.0, "Hollowing")?;
+ let v = grid.voxel;
+ let solid = grid.bits(&|c| c != 0);
+ let inner = solid.erode(wall / v);
+ drop(solid);
+ tick(progress, 0.5, "Hollowing")?;
+ let min_cells = (MIN_CAVITY_MM3 / (v * v * v)).ceil() as u64;
+ let mut cavities = Vec::new();
+ inner.components(|n, runs| {
+ if n >= min_cells.max(1) {
+ cavities.push(runs);
+ }
+ });
+ drop(inner);
+ if cavities.is_empty() {
+ notes.push(format!(
+ "Not hollowed: the model is too thin for {wall} mm walls."
+ ));
+ return Ok(());
+ }
+ tick(progress, 0.7, "Hollowing")?;
+ for runs in &cavities {
+ for &[y, z, x0, x1] in runs {
+ let i = grid.index(x0, y, z);
+ grid.cells[i..i + (x1 - x0) as usize].fill(0);
+ }
+ }
+ let mut holes = Vec::new();
+ if drain > 0.0 {
+ let r = (0.5 * drain / v).max(0.5);
+ for runs in &cavities {
+ for [x, y, z] in drain_points(runs, drain / v) {
+ if drill_down(grid, x, y, z, r) {
+ let c = grid.center(x, y, 0);
+ holes.push(format!("x {:.1} y {:.1}", c[0] + 0.0, c[1] + 0.0));
+ }
+ }
+ }
+ }
+ let mut note = format!(
+ "Hollowed with {wall} mm walls: {} cavit{}",
+ cavities.len(),
+ if cavities.len() == 1 { "y" } else { "ies" }
+ );
+ if drain > 0.0 {
+ if holes.is_empty() {
+ note.push_str(", no drain hole (no way down)");
+ } else {
+ note.push_str(&format!(
+ ", {} drain hole{} of {drain} mm at {}",
+ holes.len(),
+ if holes.len() == 1 { "" } else { "s" },
+ holes.join(", ")
+ ));
+ }
+ } else {
+ note.push_str(", no drain hole");
+ }
+ note.push('.');
+ notes.push(note);
+ tick(progress, 1.0, "Hollowing")
+}
+
+/// Where a cavity drains: its lowest cell (closest to its centre), and for a cavity wider than
+/// eight holes the lowest cell at least half its width away from that.
+fn drain_points(runs: &[[u32; 4]], hole: f32) -> Vec<[u32; 3]> {
+ let (mut sx, mut sy, mut n) = (0f64, 0f64, 0f64);
+ let mut lo = [u32::MAX; 2];
+ let mut hi = [0u32; 2];
+ let mut zmin = u32::MAX;
+ for &[y, z, x0, x1] in runs {
+ let k = (x1 - x0) as f64;
+ sx += (x0 + x1 - 1) as f64 * 0.5 * k;
+ sy += y as f64 * k;
+ n += k;
+ lo = [lo[0].min(x0), lo[1].min(y)];
+ hi = [hi[0].max(x1), hi[1].max(y + 1)];
+ zmin = zmin.min(z);
+ }
+ if n == 0.0 {
+ return Vec::new();
+ }
+ let (cx, cy) = ((sx / n) as f32, (sy / n) as f32);
+ let near = |x: u32, y: u32, px: f32, py: f32| {
+ let (dx, dy) = (x as f32 - px, y as f32 - py);
+ dx * dx + dy * dy
+ };
+ // The cell of run `r` closest to (px, py).
+ let at = |r: &[u32; 4], px: f32| -> u32 { (px.round().max(0.0) as u32).clamp(r[2], r[3] - 1) };
+ let first = runs
+ .iter()
+ .filter(|r| r[1] == zmin)
+ .map(|r| [at(r, cx), r[0], r[1]])
+ .min_by(|a, b| near(a[0], a[1], cx, cy).total_cmp(&near(b[0], b[1], cx, cy)))
+ .unwrap_or([0, 0, 0]);
+ let mut out = vec![first];
+ let width = (hi[0] - lo[0]).max(hi[1] - lo[1]) as f32;
+ if width >= 8.0 * hole {
+ let far = 0.5 * width;
+ let (fx, fy) = (first[0] as f32, first[1] as f32);
+ let second = runs
+ .iter()
+ .flat_map(|r| [[r[2], r[0], r[1]], [r[3] - 1, r[0], r[1]]])
+ .filter(|c| near(c[0], c[1], fx, fy) >= far * far)
+ .min_by_key(|c| c[2]);
+ if let Some(s) = second {
+ out.push(s);
+ }
+ }
+ out
}
-/// TODO(voxel agent): peg holes of diameter `diameter`, `depth` deep into each side, across
-/// every cut of `cuts` (from [`super::split::plan`]), where the cut face is solid enough (a
-/// note per cut without room). Stub: no-op.
+/// Drill a vertical hole of radius `r` cells down from just under cavity cell (x, y, z)
+/// until it comes out (an empty layer below it, or the bottom of the grid). False when the
+/// column was already open.
+fn drill_down(grid: &mut VoxelGrid, x: u32, y: u32, z: u32, r: f32) -> bool {
+ let d = disc(r);
+ let cells = |zz: u32| {
+ d.iter().filter_map(move |&(dx, dy)| {
+ let (a, b) = (x as i64 + dx as i64, y as i64 + dy as i64);
+ (a >= 0 && b >= 0).then_some((a as u32, b as u32, zz))
+ })
+ };
+ let mut cleared = false;
+ let mut zz = z;
+ while zz > 0 {
+ zz -= 1;
+ for (a, b, c) in cells(zz) {
+ if grid.get(a, b, c) != 0 {
+ grid.set(a, b, c, 0);
+ cleared = true;
+ }
+ }
+ if zz == 0 || cells(zz - 1).all(|(a, b, c)| grid.get(a, b, c) == 0) {
+ break;
+ }
+ }
+ cleared
+}
+
+// ---------------------------------------------------------------------------------------------
+// Pegs
+
+/// Squared Euclidean distance transform along one line (Felzenszwalb-Huttenlocher).
+fn edt_1d(f: &[f64], out: &mut [f64], v: &mut [usize], z: &mut [f64]) {
+ let n = f.len();
+ if n == 0 {
+ return;
+ }
+ let mut k = 0usize;
+ v[0] = 0;
+ z[0] = f64::NEG_INFINITY;
+ z[1] = f64::INFINITY;
+ for q in 1..n {
+ let fq = f[q] + (q * q) as f64;
+ let mut s;
+ loop {
+ let p = v[k];
+ s = (fq - (f[p] + (p * p) as f64)) / (2.0 * (q - p) as f64);
+ if s <= z[k] && k > 0 {
+ k -= 1;
+ } else {
+ break;
+ }
+ }
+ k += 1;
+ v[k] = q;
+ z[k] = s;
+ z[k + 1] = f64::INFINITY;
+ }
+ k = 0;
+ for (q, o) in out.iter_mut().enumerate() {
+ while z[k + 1] < q as f64 {
+ k += 1;
+ }
+ let p = v[k];
+ let d = q as f64 - p as f64;
+ *o = d * d + f[p];
+ }
+}
+
+/// The distance (cells) from each cell of the `w` x `h` mask to the nearest cell outside it
+/// (outside the mask's bounds counts as outside).
+fn edt_2d(mask: &[bool], w: usize, h: usize) -> Vec {
+ // Padded by one cell of background on every side; "far" is above any squared distance.
+ let (pw, ph) = (w + 2, h + 2);
+ let far = 1e10f64;
+ let mut g = vec![0f64; pw * ph];
+ for y in 0..h {
+ for x in 0..w {
+ if mask[x + w * y] {
+ g[(x + 1) + pw * (y + 1)] = far;
+ }
+ }
+ }
+ let m = pw.max(ph);
+ let (mut v, mut z) = (vec![0usize; m], vec![0f64; m + 1]);
+ let mut line = vec![0f64; m];
+ let mut out = vec![0f64; m];
+ for x in 0..pw {
+ for y in 0..ph {
+ line[y] = g[x + pw * y];
+ }
+ edt_1d(&line[..ph], &mut out[..ph], &mut v, &mut z);
+ for y in 0..ph {
+ g[x + pw * y] = out[y];
+ }
+ }
+ for y in 0..ph {
+ line[..pw].copy_from_slice(&g[pw * y..pw * (y + 1)]);
+ edt_1d(&line[..pw], &mut out[..pw], &mut v, &mut z);
+ g[pw * y..pw * (y + 1)].copy_from_slice(&out[..pw]);
+ }
+ let mut d = vec![0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ d[x + w * y] = g[(x + 1) + pw * (y + 1)].sqrt() as f32;
+ }
+ }
+ d
+}
+
+/// The cell (u, v) along axes `ua`, `va` and `a = k` as grid coordinates.
+fn cell3(a: usize, ua: usize, va: usize, k: u32, u: u32, v: u32) -> [u32; 3] {
+ let mut c = [0u32; 3];
+ c[a] = k;
+ c[ua] = u;
+ c[va] = v;
+ c
+}
+
+/// Peg holes of diameter `diameter` (mesh units), `depth` deep into each side, across every
+/// cut of `cuts` (from [`super::split::plan`]): one at the most solid point of each piece of
+/// the cut face (a second for a large face), so the split pieces can be pinned together; and a
+/// stand hole `depth` deep into the underside, as near the centre of mass (x/y) as there is
+/// room. Holes are clamped so they never break through (at least [`PEG_CAP_MM`] left), with a
+/// note when clamped, when the wall around them is under [`PEG_WALL_MM`], or when there is
+/// no room.
pub fn peg(
grid: &mut VoxelGrid,
cuts: &[Cut],
@@ -175,15 +1368,740 @@ pub fn peg(
depth: f32,
notes: &mut Vec,
) -> AssetResult<()> {
- let _ = (grid, cuts, diameter, depth, notes);
+ if !(diameter > 0.0 && depth > 0.0) {
+ return Ok(());
+ }
+ let v = grid.voxel;
+ let r = 0.5 * diameter / v;
+ let wall = PEG_WALL_MM / v;
+ let cap = (PEG_CAP_MM / v).ceil().max(1.0) as u32;
+ let depth_cells = (depth / v).round().max(1.0) as u32;
+ for (n, cut) in cuts.iter().enumerate() {
+ cut_pegs(grid, n + 1, cut, r, wall, cap, depth_cells, diameter, notes);
+ }
+ stand_hole(grid, r, wall, cap, depth_cells, diameter, depth, notes);
Ok(())
}
-/// TODO(voxel agent): the surface of the solid cells as a closed, manifold mesh (mesh units),
-/// with `groups`/`labels` from the cells' groups. Stub: refused.
+#[allow(clippy::too_many_arguments)]
+fn cut_pegs(
+ grid: &mut VoxelGrid,
+ n: usize,
+ cut: &Cut,
+ r: f32,
+ wall: f32,
+ cap: u32,
+ depth: u32,
+ diameter: f32,
+ notes: &mut Vec,
+) {
+ let a = cut.axis.min(2);
+ let (ua, va) = ((a + 1) % 3, (a + 2) % 3);
+ let v = grid.voxel;
+ let k = ((cut.at - grid.origin[a]) / v - 0.5).ceil();
+ if !(k >= 1.0 && k < grid.dims[a] as f32) {
+ return;
+ }
+ let k = k as u32;
+ let (w, h) = (grid.dims[ua] as usize, grid.dims[va] as usize);
+ let mut mask = vec![false; w * h];
+ for vv in 0..h {
+ for uu in 0..w {
+ let lo = cell3(a, ua, va, k - 1, uu as u32, vv as u32);
+ let hi = cell3(a, ua, va, k, uu as u32, vv as u32);
+ mask[uu + w * vv] =
+ grid.is_solid(lo[0], lo[1], lo[2]) && grid.is_solid(hi[0], hi[1], hi[2]);
+ }
+ }
+ let dist = edt_2d(&mask, w, h);
+ // 4-connected pieces of the cut face, largest first.
+ let mut comp = vec![u32::MAX; w * h];
+ let mut pieces: Vec> = Vec::new();
+ for s in 0..w * h {
+ if !mask[s] || comp[s] != u32::MAX {
+ continue;
+ }
+ let id = pieces.len() as u32;
+ let mut stack = vec![s];
+ comp[s] = id;
+ let mut cells = Vec::new();
+ while let Some(c) = stack.pop() {
+ cells.push(c);
+ let (x, y) = (c % w, c / w);
+ let mut push = |q: usize| {
+ if mask[q] && comp[q] == u32::MAX {
+ comp[q] = id;
+ stack.push(q);
+ }
+ };
+ if x > 0 {
+ push(c - 1);
+ }
+ if x + 1 < w {
+ push(c + 1);
+ }
+ if y > 0 {
+ push(c - w);
+ }
+ if y + 1 < h {
+ push(c + w);
+ }
+ }
+ pieces.push(cells);
+ }
+ pieces.sort_by_key(|p| std::cmp::Reverse(p.len()));
+ let axis = ["x", "y", "z"][a];
+ let mut placed = Vec::new();
+ let mut thin = false;
+ let mut clamped = false;
+ for piece in pieces.iter().take(4) {
+ let best = piece
+ .iter()
+ .copied()
+ .max_by(|p, q| dist[*p].total_cmp(&dist[*q]));
+ let Some(best) = best else { continue };
+ if dist[best] < r + 1.0 {
+ continue;
+ }
+ let mut spots = vec![best];
+ // A second peg on a large face, so the pieces cannot turn.
+ let apart = 6.0 * r;
+ let (bx, by) = ((best % w) as f32, (best / w) as f32);
+ let second = piece
+ .iter()
+ .copied()
+ .filter(|p| {
+ let (dx, dy) = ((p % w) as f32 - bx, (p / w) as f32 - by);
+ dx * dx + dy * dy >= apart * apart
+ })
+ .max_by(|p, q| dist[*p].total_cmp(&dist[*q]));
+ if let Some(s) = second
+ && dist[s] >= 2.0 * r + wall
+ {
+ spots.push(s);
+ }
+ for s in spots {
+ thin |= dist[s] < r + wall;
+ let (u0, v0) = ((s % w) as u32, (s / w) as u32);
+ let d = disc(r);
+ let cells: Vec<(u32, u32)> = d
+ .iter()
+ .filter_map(|&(du, dv)| {
+ let (uu, vv) = (u0 as i64 + du as i64, v0 as i64 + dv as i64);
+ (uu >= 0 && vv >= 0 && (uu as usize) < w && (vv as usize) < h)
+ .then_some((uu as u32, vv as u32))
+ })
+ .collect();
+ // Solid run from the cut face, each side.
+ let run = |g: &VoxelGrid, up: bool| -> u32 {
+ cells
+ .iter()
+ .map(|&(uu, vv)| {
+ let mut n = 0u32;
+ loop {
+ let kk = if up {
+ k as i64 + n as i64
+ } else {
+ k as i64 - 1 - n as i64
+ };
+ if kk < 0 || kk >= g.dims[a] as i64 {
+ break;
+ }
+ let c = cell3(a, ua, va, kk as u32, uu, vv);
+ if !g.is_solid(c[0], c[1], c[2]) {
+ break;
+ }
+ n += 1;
+ }
+ n
+ })
+ .min()
+ .unwrap_or(0)
+ };
+ let mut made = false;
+ for up in [false, true] {
+ let room = run(grid, up).saturating_sub(cap);
+ let dd = depth.min(room);
+ clamped |= dd < depth;
+ if dd == 0 {
+ continue;
+ }
+ made = true;
+ for &(uu, vv) in &cells {
+ for i in 0..dd {
+ let kk = if up { k + i } else { k - 1 - i };
+ let c = cell3(a, ua, va, kk, uu, vv);
+ grid.set(c[0], c[1], c[2], 0);
+ }
+ }
+ }
+ if made {
+ let [cx, cy, cz] = cell3(a, ua, va, k, u0, v0);
+ let c = grid.center(cx, cy, cz);
+ let names = ["x", "y", "z"];
+ placed.push(format!(
+ "{} {:.1} {} {:.1}",
+ names[ua],
+ c[ua] + 0.0,
+ names[va],
+ c[va] + 0.0
+ ));
+ }
+ }
+ }
+ if placed.is_empty() {
+ notes.push(format!(
+ "Cut {n} ({axis} {:.1}): no room for a {diameter} mm peg hole.",
+ cut.at
+ ));
+ return;
+ }
+ let mut note = format!(
+ "Cut {n} ({axis} {:.1}): {} peg hole{} of {diameter} mm at {}",
+ cut.at,
+ placed.len(),
+ if placed.len() == 1 { "" } else { "s" },
+ placed.join(", ")
+ );
+ if clamped {
+ note.push_str(" (shallower where the part is thin)");
+ }
+ if thin {
+ note.push_str(&format!(
+ " (warning: under {PEG_WALL_MM} mm of wall around)"
+ ));
+ }
+ note.push('.');
+ notes.push(note);
+}
+
+#[allow(clippy::too_many_arguments)]
+fn stand_hole(
+ grid: &mut VoxelGrid,
+ r: f32,
+ wall: f32,
+ cap: u32,
+ depth: u32,
+ diameter: f32,
+ depth_mm: f32,
+ notes: &mut Vec,
+) {
+ let [d0, d1, d2] = grid.dims.map(|d| d as usize);
+ // Per column: the lowest solid cell and the top (exclusive) of the run above it.
+ let mut bottom = vec![u32::MAX; d0 * d1];
+ let mut top = vec![0u32; d0 * d1];
+ let (mut sx, mut sy, mut n) = (0f64, 0f64, 0f64);
+ for z in 0..d2 {
+ let layer = &grid.cells[d0 * d1 * z..d0 * d1 * (z + 1)];
+ for (c, v) in layer.iter().enumerate() {
+ if *v == 0 {
+ continue;
+ }
+ if bottom[c] == u32::MAX {
+ bottom[c] = z as u32;
+ top[c] = z as u32 + 1;
+ } else if top[c] == z as u32 {
+ top[c] += 1;
+ }
+ sx += (c % d0) as f64;
+ sy += (c / d0) as f64;
+ n += 1.0;
+ }
+ }
+ if n == 0.0 {
+ return;
+ }
+ let (cx, cy) = ((sx / n) as f32, (sy / n) as f32);
+ let foot: Vec = bottom.iter().map(|b| *b != u32::MAX).collect();
+ let dist = edt_2d(&foot, d0, d1);
+ let mut order: Vec = (0..d0 * d1).filter(|c| dist[*c] >= r + 1.0).collect();
+ let far = |c: usize| {
+ let (dx, dy) = ((c % d0) as f32 - cx, (c / d0) as f32 - cy);
+ dx * dx + dy * dy
+ };
+ order.sort_by(|a, b| far(*a).total_cmp(&far(*b)));
+ let d = disc(r);
+ let slope = depth.div_ceil(2);
+ // The first spot with room, nearest the centre of mass; a full-depth one a little
+ // further (up to two diameters) is preferred.
+ let mut pick: Option<(usize, Vec, u32, u32)> = None;
+ for c in order {
+ if let Some((f, _, _, _)) = &pick
+ && far(c).sqrt() > far(*f).sqrt() + 4.0 * r
+ {
+ break;
+ }
+ let (x0, y0) = ((c % d0) as i64, (c / d0) as i64);
+ let cols: Vec = d
+ .iter()
+ .filter_map(|&(dx, dy)| {
+ let (x, y) = (x0 + dx as i64, y0 + dy as i64);
+ (x >= 0 && y >= 0 && (x as usize) < d0 && (y as usize) < d1)
+ .then_some(x as usize + d0 * y as usize)
+ })
+ .collect();
+ if cols.iter().any(|c| !foot[*c]) {
+ continue;
+ }
+ let z0 = cols.iter().map(|c| bottom[*c]).min().unwrap_or(0);
+ let zb = cols.iter().map(|c| bottom[*c]).max().unwrap_or(0);
+ if zb - z0 > slope {
+ continue;
+ }
+ let room = cols
+ .iter()
+ .map(|c| top[*c].saturating_sub(z0 + cap))
+ .min()
+ .unwrap_or(0);
+ let dd = depth.min(room);
+ if dd < 2 {
+ continue;
+ }
+ let full = dd == depth;
+ if pick.is_none() || full {
+ pick = Some((c, cols, z0, dd));
+ }
+ if full {
+ break;
+ }
+ }
+ if let Some((c, cols, z0, dd)) = pick {
+ for &col in &cols {
+ let (x, y) = ((col % d0) as u32, (col / d0) as u32);
+ for z in z0..z0 + dd {
+ grid.set(x, y, z, 0);
+ }
+ }
+ let p = grid.center((c % d0) as u32, (c / d0) as u32, z0);
+ let mut note = format!(
+ "Stand hole of {diameter} mm, {:.1} mm deep, in the underside at x {:.1} y {:.1}",
+ dd as f32 * grid.voxel,
+ p[0] + 0.0,
+ p[1] + 0.0
+ );
+ if dd < depth {
+ note.push_str(&format!(" (not {depth_mm} mm: the part is thin there)"));
+ }
+ if dist[c] < r + wall {
+ note.push_str(&format!(
+ " (warning: under {PEG_WALL_MM} mm of wall around)"
+ ));
+ }
+ note.push('.');
+ notes.push(note);
+ return;
+ }
+ notes.push(format!(
+ "No room for a {diameter} mm stand hole in the underside."
+ ));
+}
+
+// ---------------------------------------------------------------------------------------------
+// Extracting
+
+/// Padding (cells) around the grid while extracting.
+const XPAD: u32 = 3;
+
+/// The surface of the solid cells as a closed, consistently outward-oriented 2-manifold mesh
+/// (mesh units), with `groups`/`labels` from the cells' groups (each triangle: its solid
+/// cell's group). The groups' patches are open where groups meet; [`extract_where`] gives one
+/// closed mesh per group.
pub fn extract(grid: &VoxelGrid, progress: Progress<'_>) -> AssetResult {
- let _ = (grid, progress);
- Err(AssetError::invalid(
- "the solid (experimental) is not available in this build yet",
- ))
+ extract_where(grid, &|c| c != 0, progress)
+}
+
+/// [`extract`] of the cells `keep(cell)` says only (e.g. `|c| c == 1 + group`: a closed mesh
+/// of one group).
+pub fn extract_where(
+ grid: &VoxelGrid,
+ keep: &(dyn Fn(u8) -> bool + Sync),
+ progress: Progress<'_>,
+) -> AssetResult {
+ tick(progress, 0.0, "Building the surface")?;
+ let pd = grid.dims.map(|d| d + 2 * XPAD);
+ let mut p = Bits::new(pd);
+ let (gd0, gd1) = (grid.dims[0] as usize, grid.dims[1] as usize);
+ if gd0 > 0 {
+ let (wpr, pd1) = (p.wpr, pd[1] as usize);
+ p.data.par_chunks_mut(wpr).enumerate().for_each(|(row, o)| {
+ let (y, z) = ((row % pd1) as u32, (row / pd1) as u32);
+ if y < XPAD || z < XPAD || y >= grid.dims[1] + XPAD || z >= grid.dims[2] + XPAD {
+ return;
+ }
+ let s = (y - XPAD) as usize * gd0 + (z - XPAD) as usize * gd0 * gd1;
+ for (x, c) in grid.cells[s..s + gd0].iter().enumerate() {
+ if keep(*c) {
+ let xx = x + XPAD as usize;
+ o[xx / 64] |= 1 << (xx % 64);
+ }
+ }
+ });
+ }
+ // Well-composed: add cells until no critical edge or corner is left.
+ let mut rounds = 0;
+ loop {
+ let f = criticals(&p);
+ if !f.any() {
+ break;
+ }
+ p.or_with(&f);
+ rounds += 1;
+ if rounds > 10_000 {
+ return Err(AssetError::internal("could not close the solid's surface"));
+ }
+ tick(progress, 0.1, "Building the surface")?;
+ }
+ // Nothing may reach the outer layer (blocks past it are not checked).
+ let edge = (0..pd[2]).any(|z| {
+ (0..pd[1]).any(|y| {
+ let border = z == 0 || y == 0 || z == pd[2] - 1 || y == pd[1] - 1;
+ let row = p.row(y as i64, z as i64).unwrap_or(&[]);
+ if border {
+ row.iter().any(|w| *w != 0)
+ } else {
+ row.first().is_some_and(|w| w & 1 != 0)
+ || (p.dims[0] > 0 && {
+ let x = p.dims[0] - 1;
+ (row[x as usize / 64] >> (x % 64)) & 1 != 0
+ })
+ }
+ })
+ });
+ if edge {
+ return Err(AssetError::internal("could not close the solid's surface"));
+ }
+ tick(progress, 0.3, "Building the surface")?;
+ let faces = boundary_faces(&p);
+ tick(progress, 0.5, "Building the surface")?;
+ let labeled = !grid.labels.is_empty();
+ build_mesh(grid, &faces, labeled, progress)
+}
+
+/// The cells to add so `p` (and its complement) has no critical configuration: two solid (or
+/// two empty) cells meeting only at an edge (C1) or a corner (C2), the rest of the block the
+/// other kind.
+fn criticals(p: &Bits) -> Bits {
+ let (wpr, d1) = (p.wpr, p.dims[1] as usize);
+ let zero = vec![0u64; wpr];
+ let rows: Vec<(usize, Vec, Vec)> = (0..p.rows())
+ .into_par_iter()
+ .filter_map(|row| {
+ let (y, z) = ((row % d1) as i64, (row / d1) as i64);
+ let ra = p.row(y, z)?;
+ let rb = p.row(y + 1, z).unwrap_or(&zero);
+ let rc = p.row(y, z + 1).unwrap_or(&zero);
+ let rd = p.row(y + 1, z + 1).unwrap_or(&zero);
+ let mut fa = vec![0u64; wpr];
+ let mut fa1 = vec![0u64; wpr];
+ let mut fb = vec![0u64; wpr];
+ let mut fb1 = vec![0u64; wpr];
+ let mut any = false;
+ for i in 0..wpr {
+ let (a, b, c, d) = (ra[i], rb[i], rc[i], rd[i]);
+ let (a1, b1, c1, d1) = (
+ down(ra, 1, i),
+ down(rb, 1, i),
+ down(rc, 1, i),
+ down(rd, 1, i),
+ );
+ if (a | b | c | d | a1 | b1 | c1 | d1) == 0 {
+ continue;
+ }
+ let mut wa = 0u64;
+ let mut wa1 = 0u64;
+ let mut wb = 0u64;
+ let mut wb1 = 0u64;
+ // C1, edges along x, y, z.
+ wb |= a & d & !b & !c;
+ wa |= b & c & !a & !d;
+ wa1 |= a & c1 & !a1 & !c;
+ wa |= a1 & c & !a & !c1;
+ wa1 |= a & b1 & !a1 & !b;
+ wa |= a1 & b & !a & !b1;
+ // C2: antipodal pairs of the 2x2x2 block.
+ let cs = [a, a1, b, b1, c, c1, d, d1];
+ let pairs = [(0, 7), (1, 6), (2, 5), (3, 4)];
+ for (pi, (s, t)) in pairs.into_iter().enumerate() {
+ let mut or = 0u64;
+ let mut and = !0u64;
+ for (j, w) in cs.iter().enumerate() {
+ if j != s && j != t {
+ or |= w;
+ and &= w;
+ }
+ }
+ let solid_pair = cs[s] & cs[t] & !or;
+ let empty_pair = !cs[s] & !cs[t] & and;
+ match pi {
+ 0 => wa1 |= solid_pair,
+ _ => wa |= solid_pair,
+ }
+ match s {
+ 0 => wa |= empty_pair,
+ 1 => wa1 |= empty_pair,
+ 2 => wb |= empty_pair,
+ _ => wb1 |= empty_pair,
+ }
+ }
+ if (wa | wa1 | wb | wb1) != 0 {
+ any = true;
+ fa[i] |= wa;
+ fa1[i] |= wa1;
+ fb[i] |= wb;
+ fb1[i] |= wb1;
+ }
+ }
+ if !any {
+ return None;
+ }
+ for (i, (a, b)) in fa.iter_mut().zip(fb.iter_mut()).enumerate() {
+ *a |= up(&fa1, 1, i);
+ *b |= up(&fb1, 1, i);
+ }
+ Some((row, fa, fb))
+ })
+ .collect();
+ let mut f = Bits::new(p.dims);
+ for (row, fa, fb) in rows {
+ let r = row * wpr;
+ for (o, a) in f.data[r..r + wpr].iter_mut().zip(&fa) {
+ *o |= a;
+ }
+ let (y, z) = (row % d1, row / d1);
+ if y + 1 < d1 {
+ let r = f.row_of(y as u32 + 1, z as u32);
+ for (o, b) in f.data[r..r + wpr].iter_mut().zip(&fb) {
+ *o |= b;
+ }
+ }
+ }
+ f.mask_tails();
+ // Only add empty cells.
+ f.and_not(p);
+ f
+}
+
+/// One solid cell face against an empty cell: (x, y, z, direction 0..6 = +x -x +y -y +z -z).
+type Face = [u32; 4];
+
+fn boundary_faces(p: &Bits) -> Vec {
+ let (wpr, d1) = (p.wpr, p.dims[1] as usize);
+ let zero = vec![0u64; wpr];
+ let per_row: Vec> = (0..p.rows())
+ .into_par_iter()
+ .map(|row| {
+ let (y, z) = ((row % d1) as i64, (row / d1) as i64);
+ let mut out = Vec::new();
+ let Some(a) = p.row(y, z) else { return out };
+ if a.iter().all(|w| *w == 0) {
+ return out;
+ }
+ let n = [
+ p.row(y + 1, z).unwrap_or(&zero),
+ p.row(y - 1, z).unwrap_or(&zero),
+ p.row(y, z + 1).unwrap_or(&zero),
+ p.row(y, z - 1).unwrap_or(&zero),
+ ];
+ for i in 0..wpr {
+ let m = [
+ a[i] & !down(a, 1, i),
+ a[i] & !up(a, 1, i),
+ a[i] & !n[0][i],
+ a[i] & !n[1][i],
+ a[i] & !n[2][i],
+ a[i] & !n[3][i],
+ ];
+ for (dir, mut w) in m.into_iter().enumerate() {
+ while w != 0 {
+ let b = w.trailing_zeros();
+ w &= w - 1;
+ out.push([(i * 64) as u32 + b, y as u32, z as u32, dir as u32]);
+ }
+ }
+ }
+ out
+ })
+ .collect();
+ per_row.into_iter().flatten().collect()
+}
+
+/// The corners of a face, counter-clockwise seen from outside (offsets from the cell).
+const CORNERS: [[[u32; 3]; 4]; 6] = [
+ [[1, 0, 0], [1, 1, 0], [1, 1, 1], [1, 0, 1]],
+ [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]],
+ [[0, 1, 0], [0, 1, 1], [1, 1, 1], [1, 1, 0]],
+ [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]],
+ [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]],
+ [[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0]],
+];
+
+const NORMALS: [[f32; 3]; 6] = [
+ [1.0, 0.0, 0.0],
+ [-1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, -1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [0.0, 0.0, -1.0],
+];
+
+fn build_mesh(
+ grid: &VoxelGrid,
+ faces: &[Face],
+ labeled: bool,
+ progress: Progress<'_>,
+) -> AssetResult {
+ let pd = grid.dims.map(|d| d + 2 * XPAD);
+ let (kx, ky) = (pd[0] as u64 + 1, pd[1] as u64 + 1);
+ let mut ids: HashMap = HashMap::with_capacity(faces.len());
+ let mut corner: Vec<[u32; 3]> = Vec::with_capacity(faces.len());
+ let mut quads: Vec<[u32; 4]> = Vec::with_capacity(faces.len());
+ for f in faces {
+ let q = CORNERS[f[3] as usize].map(|o| {
+ let c = [f[0] + o[0], f[1] + o[1], f[2] + o[2]];
+ let key = c[0] as u64 + kx * (c[1] as u64 + ky * c[2] as u64);
+ *ids.entry(key).or_insert_with(|| {
+ corner.push(c);
+ (corner.len() - 1) as u32
+ })
+ });
+ quads.push(q);
+ }
+ drop(ids);
+ tick(progress, 0.6, "Smoothing the surface")?;
+ let (o, v) = (grid.origin, grid.voxel);
+ let base: Vec<[f32; 3]> = corner
+ .iter()
+ .map(|c| [0, 1, 2].map(|i| o[i] + (c[i] as f32 - XPAD as f32) * v))
+ .collect();
+ let mut pos = smooth(&base, &quads, v);
+ tick(progress, 0.8, "Smoothing the surface")?;
+ // Triangulate (shorter diagonal); undo smoothing where a triangle would turn over.
+ let tri_ok = |pos: &[[f32; 3]], t: [u32; 3], n: [f32; 3]| {
+ let [a, b, c] = t.map(|i| pos[i as usize]);
+ let cr = cross(sub3(b, a), sub3(c, a));
+ dot(cr, n) > 1e-4 * v * v
+ };
+ let split = |pos: &[[f32; 3]], q: [u32; 4], n: [f32; 3]| -> Option<[[u32; 3]; 2]> {
+ let d2 = |i: u32, j: u32| {
+ let e = sub3(pos[i as usize], pos[j as usize]);
+ dot(e, e)
+ };
+ let ac = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]];
+ let bd = [[q[0], q[1], q[3]], [q[1], q[2], q[3]]];
+ let (first, second) = if d2(q[0], q[2]) <= d2(q[1], q[3]) {
+ (ac, bd)
+ } else {
+ (bd, ac)
+ };
+ [first, second]
+ .into_iter()
+ .find(|ts| ts.iter().all(|t| tri_ok(pos, *t, n)))
+ };
+ let mut rounds = 0;
+ loop {
+ let bad: Vec = (0..quads.len())
+ .into_par_iter()
+ .filter(|&i| split(&pos, quads[i], NORMALS[faces[i][3] as usize]).is_none())
+ .collect();
+ if bad.is_empty() {
+ break;
+ }
+ rounds += 1;
+ for i in bad {
+ for k in quads[i] {
+ pos[k as usize] = base[k as usize];
+ }
+ }
+ if rounds > 64 {
+ pos.clone_from(&base);
+ }
+ }
+ let mut triangles = Vec::with_capacity(quads.len() * 2);
+ let mut groups = labeled.then(|| Vec::with_capacity(quads.len() * 2));
+ for (i, q) in quads.iter().enumerate() {
+ let n = NORMALS[faces[i][3] as usize];
+ let ts = split(&pos, *q, n).unwrap_or([[q[0], q[1], q[2]], [q[0], q[2], q[3]]]);
+ triangles.extend_from_slice(&ts);
+ if let Some(g) = &mut groups {
+ let f = faces[i];
+ let c = [f[0], f[1], f[2]].map(|c| c.wrapping_sub(XPAD));
+ let mut val = grid.get(c[0], c[1], c[2]);
+ if val == 0 {
+ val = neighbour_label(grid, c).unwrap_or(1);
+ }
+ let gi = val.saturating_sub(1) as u32;
+ g.extend_from_slice(&[gi, gi]);
+ }
+ }
+ tick(progress, 1.0, "Building the surface")?;
+ Ok(Mesh {
+ vertices: pos,
+ triangles,
+ groups,
+ labels: if labeled {
+ grid.labels.clone()
+ } else {
+ Vec::new()
+ },
+ })
}
+
+/// Laplacian smoothing along the quads' edges, each vertex kept within [`SMOOTH_CLAMP`]
+/// voxels of its corner.
+fn smooth(base: &[[f32; 3]], quads: &[[u32; 4]], voxel: f32) -> Vec<[f32; 3]> {
+ let n = base.len();
+ let mut deg = vec![0u32; n + 1];
+ for q in quads {
+ for k in 0..4 {
+ deg[q[k] as usize] += 1;
+ deg[q[(k + 1) % 4] as usize] += 1;
+ }
+ }
+ let mut start = vec![0usize; n + 1];
+ for i in 0..n {
+ start[i + 1] = start[i] + deg[i] as usize;
+ }
+ let mut fill = start.clone();
+ let mut adj = vec![0u32; start[n]];
+ for q in quads {
+ for k in 0..4 {
+ let (a, b) = (q[k], q[(k + 1) % 4]);
+ adj[fill[a as usize]] = b;
+ fill[a as usize] += 1;
+ adj[fill[b as usize]] = a;
+ fill[b as usize] += 1;
+ }
+ }
+ // Each edge is listed twice per vertex (two quads); averaging over duplicates is the same.
+ let clamp = SMOOTH_CLAMP * voxel;
+ let mut pos = base.to_vec();
+ for _ in 0..SMOOTH_ITERS {
+ let next: Vec<[f32; 3]> = (0..n)
+ .into_par_iter()
+ .map(|i| {
+ let nb = &adj[start[i]..start[i + 1]];
+ if nb.is_empty() {
+ return pos[i];
+ }
+ let mut s = [0f32; 3];
+ for &j in nb {
+ for k in 0..3 {
+ s[k] += pos[j as usize][k];
+ }
+ }
+ let m = nb.len() as f32;
+ [0, 1, 2].map(|k| {
+ let avg = s[k] / m;
+ let p = pos[i][k] + 0.5 * (avg - pos[i][k]);
+ p.clamp(base[i][k] - clamp, base[i][k] + clamp)
+ })
+ })
+ .collect();
+ pos = next;
+ }
+ pos
+}
+
+#[cfg(test)]
+#[path = "voxel_tests.rs"]
+mod tests;
diff --git a/crates/starorg-data/src/assets/print/voxel_tests.rs b/crates/starorg-data/src/assets/print/voxel_tests.rs
new file mode 100644
index 0000000..4c174a5
--- /dev/null
+++ b/crates/starorg-data/src/assets/print/voxel_tests.rs
@@ -0,0 +1,454 @@
+//! The voxel solid: closed, outward, manifold surfaces from messy input; thicken, hollow and
+//! pegs keep them so.
+
+use super::*;
+use std::collections::HashMap;
+
+fn all() -> impl Fn(f32, &str) -> bool + Sync {
+ |_, _| true
+}
+
+/// Two triangles per quad `a b c d` (counter-clockwise seen from outside).
+fn quad(t: &mut Vec<[[f32; 3]; 3]>, a: [f32; 3], b: [f32; 3], c: [f32; 3], d: [f32; 3]) {
+ t.push([a, b, c]);
+ t.push([a, c, d]);
+}
+
+/// A box from `lo` to `hi` as six separate quads, each `grow` larger than its face (so no
+/// edge is shared: an unwelded, overlapping soup).
+fn loose_box(t: &mut Vec<[[f32; 3]; 3]>, lo: [f32; 3], hi: [f32; 3], grow: f32) {
+ let (l, h) = (lo.map(|v| v - grow), hi.map(|v| v + grow));
+ // -z, +z, -y, +y, -x, +x
+ quad(
+ t,
+ [l[0], l[1], lo[2]],
+ [l[0], h[1], lo[2]],
+ [h[0], h[1], lo[2]],
+ [h[0], l[1], lo[2]],
+ );
+ quad(
+ t,
+ [l[0], l[1], hi[2]],
+ [h[0], l[1], hi[2]],
+ [h[0], h[1], hi[2]],
+ [l[0], h[1], hi[2]],
+ );
+ quad(
+ t,
+ [l[0], lo[1], l[2]],
+ [h[0], lo[1], l[2]],
+ [h[0], lo[1], h[2]],
+ [l[0], lo[1], h[2]],
+ );
+ quad(
+ t,
+ [l[0], hi[1], l[2]],
+ [l[0], hi[1], h[2]],
+ [h[0], hi[1], h[2]],
+ [h[0], hi[1], l[2]],
+ );
+ quad(
+ t,
+ [lo[0], l[1], l[2]],
+ [lo[0], l[1], h[2]],
+ [lo[0], h[1], h[2]],
+ [lo[0], h[1], l[2]],
+ );
+ quad(
+ t,
+ [hi[0], l[1], l[2]],
+ [hi[0], h[1], l[2]],
+ [hi[0], h[1], h[2]],
+ [hi[0], l[1], h[2]],
+ );
+}
+
+/// Every directed edge once and its reverse once: closed, 2-manifold at edges, consistently
+/// oriented. Also no degenerate triangle.
+fn assert_closed(m: &Mesh) {
+ assert!(!m.triangles.is_empty());
+ let mut e: HashMap<(u32, u32), u32> = HashMap::new();
+ for t in &m.triangles {
+ assert!(t[0] != t[1] && t[1] != t[2] && t[0] != t[2], "{t:?}");
+ for k in 0..3 {
+ *e.entry((t[k], t[(k + 1) % 3])).or_default() += 1;
+ }
+ }
+ for (&(a, b), &n) in &e {
+ assert_eq!(n, 1, "edge {a}-{b} used {n} times the same way");
+ assert_eq!(e.get(&(b, a)), Some(&1), "edge {a}-{b} has no twin");
+ }
+ // Manifold vertices: the triangles around each vertex form one fan.
+ let mut around: HashMap> = HashMap::new();
+ for t in &m.triangles {
+ for k in 0..3 {
+ around
+ .entry(t[k])
+ .or_default()
+ .push((t[(k + 1) % 3], t[(k + 2) % 3]));
+ }
+ }
+ for (v, fan) in around {
+ let next: HashMap = fan.iter().copied().collect();
+ let mut at = fan[0].0;
+ let mut steps = 0;
+ loop {
+ at = next[&at];
+ steps += 1;
+ if at == fan[0].0 {
+ break;
+ }
+ assert!(steps <= fan.len(), "vertex {v} is not a manifold fan");
+ }
+ assert_eq!(steps, fan.len(), "vertex {v}: more than one fan");
+ }
+}
+
+fn volume(m: &Mesh) -> f32 {
+ (0..m.triangles.len())
+ .map(|t| {
+ let [a, b, c] = m.triangle(t);
+ dot(a, cross(b, c)) / 6.0
+ })
+ .sum()
+}
+
+/// Empty cells all reach the border (no sealed cavity).
+fn empty_is_connected(g: &VoxelGrid) -> bool {
+ let grown = g.grown(1).unwrap();
+ let empty = grown.bits(&|c| c == 0);
+ let mut seen = Bits::new(empty.dims());
+ let n = empty.flood(&mut seen, [0, 0, 0], |_, _, _, _| {});
+ n == empty.count()
+}
+
+#[test]
+fn a_loose_box_with_an_overlapping_box_becomes_one_closed_outward_solid() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [20.0; 3], 0.05);
+ loose_box(&mut t, [5.0; 3], [25.0; 3], 0.05);
+ let mesh = Mesh::from_triangles(&t);
+ let g = voxelize(&mesh, 0.2, &all()).unwrap();
+ assert!(g.labels.is_empty());
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+ assert!(m.groups.is_none());
+ // Union: 8000 + 8000 - 15^3 = 12625 mm^3; about half a voxel larger on every side.
+ let v = volume(&m);
+ assert!((v - 12625.0).abs() / 12625.0 < 0.04, "volume {v}");
+ let b = m.bounds().unwrap();
+ for i in 0..3 {
+ assert!(
+ (b.min[i] - 0.0).abs() < 0.3 && (b.max[i] - 25.0).abs() < 0.3,
+ "{b:?}"
+ );
+ }
+}
+
+#[test]
+fn open_and_single_sided_surfaces_still_give_a_closed_shell() {
+ // A box missing its top face (a hole wider than the seal) and a lone plate.
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [10.0; 3], 0.0);
+ t.drain(2..4);
+ quad(
+ &mut t,
+ [20.0, 0.0, 0.0],
+ [30.0, 0.0, 0.0],
+ [30.0, 10.0, 0.0],
+ [20.0, 10.0, 0.0],
+ );
+ let g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+ // The open box is filled (its inside is seen from above only), the plate is a thin slab.
+ let v = volume(&m);
+ assert!(v > 1000.0 && v < 1000.0 * 1.15 + 100.0 * 0.8, "{v}");
+ let c = g.cell_at([5.0, 5.0, 5.0]).unwrap();
+ assert!(g.is_solid(c[0], c[1], c[2]));
+}
+
+#[test]
+fn a_cell_is_outside_when_seen_from_enough_directions() {
+ // A cup open at +z: its inside is seen from one direction, the space beside it from five.
+ let mut s = Bits::new([9, 9, 9]);
+ for z in 2..7 {
+ for y in 2..7 {
+ for x in 2..7 {
+ let wall = x == 2 || x == 6 || y == 2 || y == 6 || z == 2;
+ s.set(x, y, z, wall);
+ }
+ }
+ }
+ let seen = seen_from(&s, 3);
+ assert!(!seen.get(4, 4, 4), "inside the cup");
+ assert!(seen.get(0, 4, 4) && seen.get(4, 4, 8) && seen.get(4, 4, 0));
+ assert!(seen_from(&s, 1).get(4, 4, 4));
+ assert!(!seen_from(&s, 2).get(4, 4, 4));
+ // Beside the cup, at its height: blocked along x only.
+ assert!(seen_from(&s, 5).get(0, 4, 4) && !seen_from(&s, 6).get(0, 4, 4));
+}
+
+#[test]
+fn cells_touching_only_at_an_edge_or_corner_still_extract_manifold() {
+ let mut g = VoxelGrid::new([0.0; 3], 1.0, [4, 4, 4]).unwrap();
+ g.set(1, 1, 1, 1);
+ g.set(2, 2, 1, 1); // edge
+ g.set(2, 1, 2, 0);
+ g.set(1, 2, 2, 0);
+ g.set(3, 3, 2, 1); // corner of (2, 2, 1)
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+ // The complement case: a solid block with two empty cells meeting at a corner.
+ let mut g = VoxelGrid::new([0.0; 3], 1.0, [4, 4, 4]).unwrap();
+ for z in 0..4 {
+ for y in 0..4 {
+ for x in 0..4 {
+ g.set(x, y, z, 1);
+ }
+ }
+ }
+ g.set(1, 1, 1, 0);
+ g.set(2, 2, 2, 0);
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+}
+
+#[test]
+fn groups_label_cells_and_extract_one_closed_mesh_per_group() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [10.0; 3], 0.0);
+ let n = t.len();
+ loose_box(&mut t, [12.0, 0.0, 0.0], [20.0, 10.0, 10.0], 0.0);
+ let labeled = crate::assets::stl::LabeledTriangles {
+ triangles: t.clone(),
+ node: (0..t.len()).map(|i| (i >= n) as u32).collect(),
+ nodes: vec!["hull".into(), "glass".into()],
+ };
+ let mesh = Mesh::from_labeled(&labeled);
+ let g = voxelize(&mesh, 0.4, &all()).unwrap();
+ assert_eq!(g.labels, ["hull", "glass"]);
+ assert_eq!(g.get(5, 12, 12), 1, "inside the first box");
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+ let groups = m.groups.as_ref().unwrap();
+ assert!(groups.contains(&0) && groups.contains(&1));
+ for v in [1u8, 2] {
+ let one = extract_where(&g, &move |c| c == v, &all()).unwrap();
+ assert_closed(&one);
+ }
+}
+
+#[test]
+fn bits_dilate_erode_flood_and_components() {
+ let mut b = Bits::new([20, 20, 20]);
+ b.set(10, 10, 10, true);
+ let d = b.dilate(2.0);
+ assert!(d.get(12, 10, 10) && d.get(10, 8, 10) && !d.get(12, 12, 10));
+ assert_eq!(d.erode(2.0).count(), 1);
+ // A ball radius 6 (two chained passes) and back.
+ let big = b.dilate(6.0);
+ assert!(big.get(16, 10, 10) && !big.get(17, 10, 10));
+ let mut two = Bits::new([130, 3, 3]);
+ two.set(1, 1, 1, true);
+ two.set(2, 1, 1, true);
+ two.set(100, 1, 1, true);
+ let mut n = Vec::new();
+ two.components(|c, runs| n.push((c, runs.len())));
+ assert_eq!(n, [(2, 1), (1, 1)]);
+ assert_eq!(two.not().count(), 130 * 9 - 3);
+}
+
+#[test]
+fn thicken_grows_a_thin_plate_to_the_minimum() {
+ let mut t = Vec::new();
+ quad(
+ &mut t,
+ [0.0, 0.0, 0.0],
+ [20.0, 0.0, 0.0],
+ [20.0, 20.0, 0.0],
+ [0.0, 20.0, 0.0],
+ );
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.1, &all()).unwrap();
+ let thick = |g: &VoxelGrid| {
+ let (lo, hi) = g.solid_bounds().unwrap();
+ (hi[2] - lo[2]) as f32 * g.voxel
+ };
+ assert!(thick(&g) < 0.35, "{}", thick(&g));
+ thicken(&mut g, 0.8, &all()).unwrap();
+ assert!(thick(&g) >= 0.79, "{}", thick(&g));
+ assert_closed(&extract(&g, &all()).unwrap());
+ // A thick block is left alone.
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [10.0; 3], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let before = g.count_solid();
+ thicken(&mut g, 0.8, &all()).unwrap();
+ assert_eq!(g.count_solid(), before);
+}
+
+#[test]
+fn hollow_keeps_the_walls_and_drains_through_the_bottom() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [30.0, 30.0, 20.0], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let full = g.count_solid();
+ let mut notes = Vec::new();
+ hollow(&mut g, 2.0, 3.0, &mut notes, &all()).unwrap();
+ assert!(g.count_solid() < full / 2, "{} of {full}", g.count_solid());
+ assert!(
+ notes[0].contains("1 cavity") && notes[0].contains("drain hole"),
+ "{notes:?}"
+ );
+ assert!(empty_is_connected(&g), "the cavity drains");
+ let m = extract(&g, &all()).unwrap();
+ assert_closed(&m);
+ let v = volume(&m);
+ assert!(v > 0.0 && v < 0.5 * 30.0 * 30.0 * 20.0, "{v}");
+ // Walls stay: a cell 1 mm inside the side is solid, the centre is not.
+ let c = g.cell_at([1.0, 15.0, 10.0]).unwrap();
+ assert!(g.is_solid(c[0], c[1], c[2]));
+ let c = g.cell_at([15.0, 15.0, 10.0]).unwrap();
+ assert!(!g.is_solid(c[0], c[1], c[2]));
+ // No drain: a sealed cavity, still a closed (two-shell) mesh.
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let mut notes = Vec::new();
+ hollow(&mut g, 2.0, 0.0, &mut notes, &all()).unwrap();
+ assert!(!empty_is_connected(&g));
+ assert_closed(&extract(&g, &all()).unwrap());
+ // Too thin to hollow.
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [3.0, 30.0, 30.0], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let mut notes = Vec::new();
+ hollow(&mut g, 2.0, 3.0, &mut notes, &all()).unwrap();
+ assert!(notes[0].starts_with("Not hollowed"), "{notes:?}");
+}
+
+#[test]
+fn pegs_go_across_cuts_and_into_the_underside_without_breaking_through() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [40.0, 20.0, 20.0], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let full = g.count_solid();
+ let mut notes = Vec::new();
+ let cuts = [Cut { axis: 0, at: 20.0 }];
+ peg(&mut g, &cuts, 5.0, 8.0, &mut notes).unwrap();
+ assert!(g.count_solid() < full);
+ assert!(
+ notes[0].starts_with("Cut 1 (x 20.0): 1 peg hole of 5 mm at y 10.0 z 10.0."),
+ "{notes:?}"
+ );
+ // Beside the peg hole (full depth, off the centre of mass).
+ assert!(
+ notes[1].starts_with("Stand hole of 5 mm, 8.0 mm deep"),
+ "{notes:?}"
+ );
+ // The peg hole is at the middle of the cut face, 8 mm into both sides.
+ for x in [12.5, 17.0, 23.0, 27.5] {
+ let c = g.cell_at([x, 10.0, 10.0]).unwrap();
+ assert!(!g.is_solid(c[0], c[1], c[2]), "x {x}");
+ }
+ for x in [10.0, 30.0] {
+ let c = g.cell_at([x, 10.0, 10.0]).unwrap();
+ assert!(g.is_solid(c[0], c[1], c[2]), "x {x}");
+ }
+ // (The peg hole is sealed inside until the split opens it.)
+ assert!(!empty_is_connected(&g));
+ assert_closed(&extract(&g, &all()).unwrap());
+ // Without cuts: the stand hole at the centre of mass, open at the bottom only.
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let mut notes = Vec::new();
+ peg(&mut g, &[], 5.0, 8.0, &mut notes).unwrap();
+ assert!(
+ notes[0].starts_with("Stand hole of 5 mm, 8.0 mm deep, in the underside at x 20.0 y 10.0"),
+ "{notes:?}"
+ );
+ for z in [0.1, 7.0] {
+ let c = g.cell_at([20.0, 10.0, z]).unwrap();
+ assert!(!g.is_solid(c[0], c[1], c[2]), "z {z}");
+ }
+ for z in [9.0, 19.8] {
+ let c = g.cell_at([20.0, 10.0, z]).unwrap();
+ assert!(g.is_solid(c[0], c[1], c[2]), "z {z}");
+ }
+ assert_closed(&extract(&g, &all()).unwrap());
+ // A thin part: clamped, never through.
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [20.0, 20.0, 4.0], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let mut notes = Vec::new();
+ peg(&mut g, &[], 5.0, 8.0, &mut notes).unwrap();
+ assert!(notes[0].contains("the part is thin there"), "{notes:?}");
+ let c = g.cell_at([10.0, 10.0, 3.9]).unwrap();
+ assert!(g.is_solid(c[0], c[1], c[2]), "the top is kept");
+ assert!(empty_is_connected(&g));
+ assert_closed(&extract(&g, &all()).unwrap());
+ // No room on a cut face narrower than the peg.
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [20.0, 3.0, 3.0], 0.0);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ let mut notes = Vec::new();
+ peg(&mut g, &[Cut { axis: 0, at: 10.0 }], 5.0, 8.0, &mut notes).unwrap();
+ assert!(
+ notes.iter().any(|n| n.contains("no room for a 5 mm peg")),
+ "{notes:?}"
+ );
+}
+
+#[test]
+fn hollow_and_pegs_together_stay_manifold() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [40.0, 30.0, 25.0], 0.02);
+ loose_box(&mut t, [10.0, 10.0, 20.0], [30.0, 20.0, 30.0], 0.02);
+ let mut g = voxelize(&Mesh::from_triangles(&t), 0.4, &all()).unwrap();
+ thicken(&mut g, 0.8, &all()).unwrap();
+ let mut notes = Vec::new();
+ hollow(&mut g, 2.0, 3.0, &mut notes, &all()).unwrap();
+ peg(&mut g, &[Cut { axis: 0, at: 20.0 }], 3.0, 8.0, &mut notes).unwrap();
+ assert_closed(&extract(&g, &all()).unwrap());
+}
+
+#[test]
+fn the_grid_is_coarsened_to_the_budget_and_cancelling_stops() {
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [100.0, 100.0, 100.0], 0.0);
+ let mesh = Mesh::from_triangles(&t);
+ // 1000^3 / 0.1 mm would be 10^12 cells.
+ let ([a, b, c], res) = plan_grid([100.0; 3], 0.1, 4);
+ assert!(a as u64 * b as u64 * c as u64 <= CELL_BUDGET && res > 0.1);
+ let g = VoxelGrid::new([0.0; 3], res, [1, 1, 1]).unwrap();
+ assert!(coarsened(&g, 0.1).unwrap().contains("instead of 0.100 mm"));
+ assert_eq!(coarsened(&g, res), None);
+ let e = voxelize(&mesh, 0.4, &|_, _| false).unwrap_err();
+ assert_eq!(e.code, "cancelled");
+}
+
+#[test]
+fn the_pipeline_builds_a_closed_solid() {
+ use super::super::{PrintOptions, ScaleMode, apply};
+ let mut t = Vec::new();
+ loose_box(&mut t, [0.0; 3], [2.0, 1.0, 0.5], 0.0); // metres
+ let out = apply(
+ Mesh::from_triangles(&t),
+ &PrintOptions {
+ scale: ScaleMode::FitMm(40.0),
+ solid: true,
+ solid_res_mm: 0.4,
+ thicken_mm: Some(0.8),
+ hollow: Some(Default::default()),
+ ..Default::default()
+ },
+ &all(),
+ )
+ .unwrap();
+ assert_eq!(out.parts.len(), 1);
+ let m = &out.parts[0].mesh;
+ assert_closed(m);
+ assert!(m.bounds().unwrap().min[2].abs() < 1e-4, "sits on the bed");
+ assert!(
+ out.notes.iter().any(|n| n.starts_with("Hollowed")),
+ "{:?}",
+ out.notes
+ );
+}
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
index bdb7ae9..6768703 100644
--- a/docs/plans/specs/model-print.md
+++ b/docs/plans/specs/model-print.md
@@ -87,6 +87,47 @@ with `from_triangles`, `from_labeled`, `from_glb`, `bounds`, `soup`, `subset`,
`count_solid`; a cell is 0 (empty) or 1 + its group. `threemf::write_3mf_objects(&[Object],
Unit, Layout, path)`.
+## Voxel solid (`voxel.rs`)
+
+Robust over pretty: the output is always a closed, consistently outward 2-manifold.
+
+- **Voxelize** (`voxelize`): every triangle marks the cells its slightly enlarged box overlaps
+ (Akenine-Möller separating axes; per z-slab in parallel), so the surface has no 6-connected
+ gaps. The outside is flood-filled (span fill on bitsets) from the padded border after a
+ closing of `SEAL_CELLS` (2 voxels: sub-millimetre cracks between panels are sealed). Game
+ hulls have larger openings, so a flood-reached cell stays outside only when it is in plain
+ view along at least `OUTSIDE_VOTES` (3) of the six axis directions (ray stabbing); the inside
+ of a hull with holes is seen through one or two. Trade-off: deep exterior pockets seen from
+ fewer than three directions (between landing gear legs, bores) fill in. The solid is about
+ half a voxel larger on each side. Grids above `CELL_BUDGET` (2^29 cells) are coarsened, with
+ a note (`coarsened`). Each cell keeps its closest triangle's group (`1 + group`, at most 255).
+- **Extract** (`extract`, `extract_where` for one group as its own closed mesh): the cells are
+ made well-composed (no two solid or two empty cells meeting only at an edge or corner; fixed
+ by adding cells), then each solid/empty face is a quad on shared grid corners; a clamped
+ Laplacian smoothing (each vertex within 0.4 voxel of its corner, undone where a triangle would
+ turn over) softens the staircase without changing topology. Triangle counts are high
+ (millions at 0.2 mm); simplify is a separate step.
+- **Thicken** (`thicken`): what an opening of radius t/2 removes, away from the rounded edges
+ of thick parts, is dilated by t/2, so sheets become at least t thick; thin parts grow outwards
+ on both sides and gaps narrower than t between them fill in.
+- **Hollow** (`hollow`): cavities are the solid eroded by the wall (a discrete ball, chained in
+ 4-voxel steps); cavities under 1 mm³ stay solid; each cavity drains through a vertical hole
+ from its lowest point (nearest its centre) down through the bottom wall, plus a second for a
+ cavity wider than eight holes. The note lists cavities and hole positions.
+- **Pegs** (`peg`): per cut, a hole at the most solid point (2D distance transform) of each piece
+ of the cut face (up to 4; a second on a large face), `depth` into each side; plus a stand
+ hole into the underside nearest the x/y centre of mass with room. Every hole is clamped to
+ leave `PEG_CAP_MM` (0.6) of material, with a note when clamped, when the wall around is
+ under `PEG_WALL_MM` (0.8), or when there is no room.
+- Helpers for the split and colour steps: `Bits` (bitset with `dilate`/`erode`/`flood`/
+ `components`), `VoxelGrid::bits`, `solid_bounds`, `grown`.
+
+Real data (release, 32 threads; `--fit-mm 150`): Skylark LOD 4 (98 376 triangles in) at 0.2 mm:
+0.56 s, 407 MB peak, 3.09 M triangles, watertight (every edge once each way), 223 cm³; 0.1 mm is
+coarsened to 0.13 mm: 1.6 s, 1.15 GB, 7.6 M triangles; with `--thicken 0.8 --hollow 2,3`:
+0.94 s, 9 cavities, 10 drain holes, 69 cm³, watertight. Gladius LOD 2 at 0.2 mm: 0.52 s,
+278 MB, 1.83 M triangles, watertight.
+
## Testing on real GLBs
`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
From 608b05b3e0becd2980403e8cdf3ad9d4d1981132 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:36:43 -0600
Subject: [PATCH 07/12] feat(print): experimental split for the bed with
alignment pin holes
Cut the voxel solid with whole-grid axis-aligned planes into the fewest
pieces that each fit the bed (fewest pieces, then fewest slivers, then
least cut area; every plan scored when few, else per axis order), add
2 mm alignment pin holes 4 mm into each side of every cut when --peg is
not given, name the pieces part1, part2, ... and lay them out side by
side for the 3MF's separate build items.
---
crates/starorg-data/src/assets/print/mod.rs | 7 +-
crates/starorg-data/src/assets/print/split.rs | 723 +++++++++++++++++-
.../src/assets/print/split_tests.rs | 255 ++++++
docs/plans/specs/model-print.md | 30 +
4 files changed, 1000 insertions(+), 15 deletions(-)
create mode 100644 crates/starorg-data/src/assets/print/split_tests.rs
diff --git a/crates/starorg-data/src/assets/print/mod.rs b/crates/starorg-data/src/assets/print/mod.rs
index 6cdc103..6eb01a0 100644
--- a/crates/starorg-data/src/assets/print/mod.rs
+++ b/crates/starorg-data/src/assets/print/mod.rs
@@ -620,10 +620,15 @@ pub fn apply(mut mesh: Mesh, o: &PrintOptions, progress: Progress<'_>) -> AssetR
PEG_DEPTH_MM * per_mm,
&mut notes,
)?;
+ } else if o.split {
+ let (d, depth) = (split::PIN_MM * per_mm, split::PIN_DEPTH_MM * per_mm);
+ split::pins(&mut grid, &cuts, d, depth, &mut notes);
}
let pieces = if o.split {
step(progress, 0.62, "Splitting")?;
- split::split(grid, &cuts)
+ let pieces = split::split(grid, &cuts);
+ notes.push(split::summary(&cuts, &pieces));
+ pieces
} else {
vec![split::Piece {
name: String::new(),
diff --git a/crates/starorg-data/src/assets/print/split.rs b/crates/starorg-data/src/assets/print/split.rs
index 62f2ad6..8b5e494 100644
--- a/crates/starorg-data/src/assets/print/split.rs
+++ b/crates/starorg-data/src/assets/print/split.rs
@@ -1,32 +1,727 @@
//! Split (experimental): cut the voxel solid into pieces that each fit the bed. Pipeline
//! steps 9 (the cuts, planned before the pegs) and 10 of [`super::apply`].
//!
-//! Owner: the split agent. [`plan`] and [`split`] are pass-through stubs (no cuts, one piece).
+//! Owner: the split agent.
+//!
+//! - [`plan`]: the fewest axis-aligned planes (whole-grid cuts, so the pieces are the cells of
+//! a lattice) that make every piece fit the bed. Each axis gets the fewest cuts its extent
+//! needs; where the cuts go is searched (positions through thin sections, and slid from the
+//! low end to the high end), every combination when there are few, else axis by axis in
+//! every axis order, keeping the plan with the fewest non-empty pieces, then the fewest
+//! slivers (under 2 % of the solid), then the least cut area.
+//! - [`pins`]: alignment pin holes ([`PIN_MM`], [`PIN_DEPTH_MM`] into each side) across each
+//! cut, when no `--peg` is asked for (the pegs then do this job).
+//! - [`split`]: the pieces, each cropped to its cells, named `part1`, `part2`, ... and laid out
+//! side by side along x ([`LAYOUT_GAP`] apart), so the 3MF's separate build items do not
+//! overlap.
use super::Cut;
-use super::voxel::VoxelGrid;
+use super::voxel::{PEG_CAP_MM, PEG_WALL_MM, VoxelGrid};
+use rayon::prelude::*;
+use std::collections::HashMap;
+
+/// Alignment pin holes across a cut: diameter, millimetres.
+pub const PIN_MM: f32 = 2.0;
+/// How deep a pin hole goes into each side of a cut, millimetres.
+pub const PIN_DEPTH_MM: f32 = 4.0;
+/// The gap between pieces laid out side by side, mesh units (millimetres: a solid is always
+/// scaled).
+pub const LAYOUT_GAP: f32 = 5.0;
+/// Pin holes per cut face: two in its largest piece, one in each of the next ones.
+const MAX_FACE_PIECES: usize = 3;
/// One piece of the split solid.
#[derive(Debug, Clone, PartialEq)]
pub struct Piece {
- /// `piece-1`, `piece-2`, ... (empty for an unsplit solid).
+ /// `part1`, `part2`, ... (empty for an unsplit solid).
pub name: String,
pub grid: VoxelGrid,
}
-/// TODO(split agent): the cuts that make every piece fit `bed` (mesh units, x/y/z), preferring
-/// few cuts through thin sections. Stub: none.
+/// The cell planes (cell index `k`: cells below `k` go to the low side) of `cuts` along each
+/// axis, sorted, inside the grid.
+fn planes(grid: &VoxelGrid, cuts: &[Cut]) -> [Vec; 3] {
+ let mut p: [Vec; 3] = Default::default();
+ for c in cuts {
+ if let Some(k) = plane(grid, c) {
+ p[c.axis.min(2)].push(k);
+ }
+ }
+ for v in &mut p {
+ v.sort_unstable();
+ v.dedup();
+ }
+ p
+}
+
+/// The cell plane of `cut` (the same rounding as [`super::voxel::peg`]), `None` outside.
+fn plane(grid: &VoxelGrid, cut: &Cut) -> Option {
+ let a = cut.axis.min(2);
+ let k = ((cut.at - grid.origin[a]) / grid.voxel - 0.5).ceil();
+ (k >= 1.0 && k < grid.dims[a] as f32).then_some(k as u32)
+}
+
+/// Solid cells meeting across each plane `k` (cells `k - 1` and `k`) of each axis.
+fn cut_areas(grid: &VoxelGrid) -> [Vec; 3] {
+ let [d0, d1, d2] = grid.dims.map(|d| d as usize);
+ let layer = d0 * d1;
+ let cells = grid.cells();
+ let zero = || [vec![0u64; d0 + 1], vec![0u64; d1 + 1], vec![0u64; d2 + 1]];
+ if layer == 0 || d2 == 0 {
+ return zero();
+ }
+ (0..d2)
+ .into_par_iter()
+ .fold(zero, |mut acc, z| {
+ let l = &cells[layer * z..layer * (z + 1)];
+ let below = (z > 0).then(|| &cells[layer * (z - 1)..layer * z]);
+ for y in 0..d1 {
+ let row = &l[d0 * y..d0 * (y + 1)];
+ let prev = (y > 0).then(|| &l[d0 * (y - 1)..d0 * y]);
+ for x in 0..d0 {
+ if row[x] == 0 {
+ continue;
+ }
+ if x > 0 && row[x - 1] != 0 {
+ acc[0][x] += 1;
+ }
+ if let Some(p) = prev
+ && p[x] != 0
+ {
+ acc[1][y] += 1;
+ }
+ if let Some(b) = below
+ && b[d0 * y + x] != 0
+ {
+ acc[2][z] += 1;
+ }
+ }
+ }
+ acc
+ })
+ .reduce(zero, |mut a, b| {
+ for i in 0..3 {
+ for (x, y) in a[i].iter_mut().zip(&b[i]) {
+ *x += y;
+ }
+ }
+ a
+ })
+}
+
+/// The solid runs (`x0..x1`) of every row `(y, z)`, for counting the pieces of a plan quickly.
+struct Runs {
+ /// `(y, z, first run, end run)`.
+ rows: Vec<(u32, u32, u32, u32)>,
+ runs: Vec<(u32, u32)>,
+}
+
+impl Runs {
+ fn new(grid: &VoxelGrid) -> Runs {
+ let [d0, d1, _] = grid.dims.map(|d| d as usize);
+ let mut rows = Vec::new();
+ let mut runs = Vec::new();
+ if d0 == 0 {
+ return Runs { rows, runs };
+ }
+ let per_row: Vec<(usize, Vec<(u32, u32)>)> = grid
+ .cells()
+ .par_chunks(d0)
+ .enumerate()
+ .filter_map(|(r, row)| {
+ let mut v = Vec::new();
+ let mut x = 0;
+ while x < d0 {
+ if row[x] == 0 {
+ x += 1;
+ continue;
+ }
+ let s = x;
+ while x < d0 && row[x] != 0 {
+ x += 1;
+ }
+ v.push((s as u32, x as u32));
+ }
+ (!v.is_empty()).then_some((r, v))
+ })
+ .collect();
+ for (r, v) in per_row {
+ let s = runs.len() as u32;
+ runs.extend(v);
+ rows.push(((r % d1) as u32, (r / d1) as u32, s, runs.len() as u32));
+ }
+ Runs { rows, runs }
+ }
+
+ /// Solid cells in each lattice cell cut by `planes`.
+ fn pieces(&self, planes: &[Vec; 3]) -> Vec {
+ let n = [0, 1, 2].map(|a| planes[a].len() + 1);
+ let slab = |a: usize, c: u32| planes[a].partition_point(|k| *k <= c);
+ let mut cells = vec![0u64; n[0] * n[1] * n[2]];
+ for &(y, z, s, e) in &self.rows {
+ let base = n[0] * (slab(1, y) + n[1] * slab(2, z));
+ for &(x0, x1) in &self.runs[s as usize..e as usize] {
+ let mut x = x0;
+ for sx in slab(0, x0)..=slab(0, x1 - 1) {
+ let end = planes[0].get(sx).copied().unwrap_or(x1).min(x1);
+ cells[base + sx] += (end - x) as u64;
+ x = end;
+ }
+ }
+ }
+ cells
+ }
+}
+
+/// Plane positions (`lo < k < hi`, sorted) giving `n` slabs of at most `cap` cells of
+/// `lo..hi` worth trying: the least total cut area, and the slabs packed from the low end
+/// shifting to the high end.
+fn candidates(lo: u32, hi: u32, n: u32, cap: u32, area: &[u64]) -> Vec> {
+ if n <= 1 {
+ return vec![Vec::new()];
+ }
+ let valid = |b: &[u32]| {
+ let mut prev = lo;
+ for &k in b.iter().chain(std::iter::once(&hi)) {
+ if k <= prev || k - prev > cap {
+ return false;
+ }
+ prev = k;
+ }
+ true
+ };
+ let mut out = Vec::new();
+ if let Some(b) = least_area(lo, hi, n, cap, area) {
+ out.push(b);
+ }
+ let low: Vec = (1..n).map(|i| lo + i * cap).collect();
+ let high: Vec = (1..n).map(|i| hi - (n - i) * cap).collect();
+ const STEPS: u32 = 32;
+ for t in 0..=STEPS {
+ let b: Vec = low
+ .iter()
+ .zip(&high)
+ .map(|(&l, &h)| {
+ (l as f64 + (h as f64 - l as f64) * t as f64 / STEPS as f64).round() as u32
+ })
+ .collect();
+ if valid(&b) && !out.contains(&b) {
+ out.push(b);
+ }
+ }
+ out
+}
+
+/// The plane positions of the least total cut area (`area[k]`) for `n` slabs of at most `cap`
+/// cells of `lo..hi`; `None` when the search would be too long (absurdly many slabs).
+fn least_area(lo: u32, hi: u32, n: u32, cap: u32, area: &[u64]) -> Option> {
+ let (lo, hi, n, cap) = (lo as usize, hi as usize, n as usize, cap as usize);
+ let ext = hi - lo;
+ if (n as u64) * (ext as u64) * (cap as u64) > 200_000_000 {
+ return None;
+ }
+ let at = |k: usize| area.get(k).copied().unwrap_or(0);
+ // cost[i][k - lo]: the least area of i + 1 planes, the last at k; from[i][k - lo]: the
+ // plane before it.
+ let mut cost = vec![vec![u64::MAX; ext + 1]; n - 1];
+ let mut from = vec![vec![0usize; ext + 1]; n - 1];
+ for k in lo + 1..=(lo + cap).min(hi - 1) {
+ cost[0][k - lo] = at(k);
+ }
+ for i in 1..n - 1 {
+ for k in lo + 1..hi {
+ let mut best = (u64::MAX, 0);
+ for j in k.saturating_sub(cap).max(lo + 1)..k {
+ let c = cost[i - 1][j - lo];
+ if c < best.0 {
+ best = (c, j);
+ }
+ }
+ if best.0 != u64::MAX {
+ cost[i][k - lo] = best.0 + at(k);
+ from[i][k - lo] = best.1;
+ }
+ }
+ }
+ let last = (hi.saturating_sub(cap).max(lo + 1)..hi)
+ .filter(|k| cost[n - 2][k - lo] != u64::MAX)
+ .min_by_key(|k| (cost[n - 2][k - lo], k.abs_diff((lo + hi) / 2)))?;
+ let mut b = vec![last];
+ let mut k = last;
+ for i in (1..n - 1).rev() {
+ k = from[i][k - lo];
+ b.push(k);
+ }
+ b.reverse();
+ Some(b.into_iter().map(|k| k as u32).collect())
+}
+
+/// (pieces, slivers, cut area): lower is better.
+type Score = (u64, u64, u64);
+/// A piece under 1 / SLIVER of the solid counts as a sliver.
+const SLIVER: u64 = 50;
+/// Up to this many plans, every one is scored; else axis by axis in each order.
+const EXHAUSTIVE: usize = 4096;
+
+/// The axis orders tried (when there are too many plans to score them all).
+const ORDERS: [[usize; 3]; 6] = [
+ [0, 1, 2],
+ [0, 2, 1],
+ [1, 0, 2],
+ [1, 2, 0],
+ [2, 0, 1],
+ [2, 1, 0],
+];
+
+/// The cuts that make every piece fit `bed` (mesh units, x/y/z, as the pieces lie: they are
+/// not turned): on each axis the fewest planes its extent needs, placed (searching each axis
+/// order) for the fewest non-empty pieces, then the fewest slivers, then the least cut area
+/// (thin sections). None when
+/// the solid fits already.
pub fn plan(grid: &VoxelGrid, bed: [f32; 3]) -> Vec {
- let _ = (grid, bed);
- Vec::new()
+ let Some((lo, hi)) = grid.solid_bounds() else {
+ return Vec::new();
+ };
+ let v = grid.voxel;
+ // Half a voxel to spare, against rounding (the surface never leaves its cells' box).
+ let cap = bed.map(|b| {
+ let c = (b / v - 0.5).floor();
+ if c.is_finite() && c >= 1.0 {
+ c.min(u32::MAX as f32) as u32
+ } else {
+ 1
+ }
+ });
+ let n: [u32; 3] = [0, 1, 2].map(|a| (hi[a] - lo[a]).div_ceil(cap[a]).max(1));
+ if n == [1, 1, 1] {
+ return Vec::new();
+ }
+ let area = cut_areas(grid);
+ let cands: [Vec>; 3] =
+ [0, 1, 2].map(|a| candidates(lo[a], hi[a], n[a], cap[a], &area[a]));
+ let runs = Runs::new(grid);
+ let total = grid.count_solid().max(1);
+ let mut seen: HashMap<[usize; 3], Score> = HashMap::new();
+ // Fewest pieces, then fewest slivers, then the least cut area.
+ let mut score = |c: [usize; 3]| -> Score {
+ *seen.entry(c).or_insert_with(|| {
+ let p = [0, 1, 2].map(|a| cands[a][c[a]].clone());
+ let a: u64 = (0..3)
+ .map(|ax| p[ax].iter().map(|k| area[ax][*k as usize]).sum::())
+ .sum();
+ let cells = runs.pieces(&p);
+ let pieces = cells.iter().filter(|n| **n > 0).count() as u64;
+ let slivers = cells
+ .iter()
+ .filter(|n| **n > 0 && **n * SLIVER < total)
+ .count() as u64;
+ (pieces, slivers, a)
+ })
+ };
+ let mut best = ([0usize; 3], score([0; 3]));
+ let combos: usize = cands.iter().map(|c| c.len()).product();
+ if combos <= EXHAUSTIVE {
+ for i in 0..cands[0].len() {
+ for j in 0..cands[1].len() {
+ for k in 0..cands[2].len() {
+ let s = score([i, j, k]);
+ if s < best.1 {
+ best = ([i, j, k], s);
+ }
+ }
+ }
+ }
+ }
+ for order in ORDERS.iter().filter(|_| combos > EXHAUSTIVE) {
+ let mut c = [0usize; 3];
+ let mut s = score(c);
+ loop {
+ let mut better = false;
+ for &a in order {
+ for i in 0..cands[a].len() {
+ let mut t = c;
+ t[a] = i;
+ let st = score(t);
+ if st < s {
+ (c, s, better) = (t, st, true);
+ }
+ }
+ }
+ if !better {
+ break;
+ }
+ }
+ if s < best.1 {
+ best = (c, s);
+ }
+ }
+ let mut cuts = Vec::new();
+ for a in 0..3 {
+ for &k in &cands[a][best.0[a]] {
+ cuts.push(Cut {
+ axis: a,
+ at: grid.origin[a] + k as f32 * v,
+ });
+ }
+ }
+ cuts
}
-/// TODO(split agent): `grid` cut at `cuts` into named pieces (each cropped to its cells; empty
-/// pieces left out). Stub: the whole grid as one unnamed piece.
+/// `grid` cut at `cuts` into pieces (each cropped to its solid cells; empty ones left out),
+/// named `part1`, `part2`, ... (in order of x, then y, then z) and laid out side by side
+/// along x, [`LAYOUT_GAP`] apart, their low y lined up (z is left for sitting on the bed).
+/// Without cuts (or a single piece): the whole grid, unnamed and in place.
pub fn split(grid: VoxelGrid, cuts: &[Cut]) -> Vec {
- let _ = cuts;
- vec![Piece {
- name: String::new(),
- grid,
- }]
+ let p = planes(&grid, cuts);
+ if p.iter().all(|v| v.is_empty()) {
+ return vec![Piece {
+ name: String::new(),
+ grid,
+ }];
+ }
+ let edges = [0, 1, 2].map(|a| {
+ let mut e = vec![0u32];
+ e.extend(&p[a]);
+ e.push(grid.dims[a]);
+ e
+ });
+ let mut grids = Vec::new();
+ for sx in edges[0].windows(2) {
+ for sy in edges[1].windows(2) {
+ for sz in edges[2].windows(2) {
+ let (min, max) = ([sx[0], sy[0], sz[0]], [sx[1], sy[1], sz[1]]);
+ let Ok(cell) = grid.crop(min, max) else {
+ continue;
+ };
+ let Some((a, b)) = cell.solid_bounds() else {
+ continue;
+ };
+ if let Ok(g) = cell.crop(a, b) {
+ grids.push(g);
+ }
+ }
+ }
+ }
+ drop(grid);
+ if grids.len() == 1 {
+ return vec![Piece {
+ name: String::new(),
+ grid: grids.remove(0),
+ }];
+ }
+ let low_y = grids
+ .iter()
+ .map(|g| g.origin[1])
+ .fold(f32::INFINITY, f32::min);
+ let mut x = grids
+ .iter()
+ .map(|g| g.origin[0])
+ .fold(f32::INFINITY, f32::min);
+ grids
+ .into_iter()
+ .enumerate()
+ .map(|(i, mut g)| {
+ g.origin[0] = x;
+ g.origin[1] = low_y;
+ x += g.dims[0] as f32 * g.voxel + LAYOUT_GAP;
+ Piece {
+ name: format!("part{}", i + 1),
+ grid: g,
+ }
+ })
+ .collect()
+}
+
+/// A note on the split: how many parts and where the cuts are, or that none was needed.
+pub fn summary(cuts: &[Cut], pieces: &[Piece]) -> String {
+ if cuts.is_empty() || pieces.len() < 2 {
+ return "Split: the model fits the bed, no cut needed.".into();
+ }
+ let at: Vec = cuts
+ .iter()
+ .map(|c| format!("{} {:.1}", ["x", "y", "z"][c.axis.min(2)], c.at + 0.0))
+ .collect();
+ format!(
+ "Split into {} parts to fit the bed (cut{} at {}); each is its own file and build item.",
+ pieces.len(),
+ if cuts.len() == 1 { "" } else { "s" },
+ at.join(", ")
+ )
+}
+
+/// Distance (cells, 8-neighbour chamfer) from each `mask` cell to the nearest cell outside it
+/// (the border counts as outside); 0 outside.
+fn chamfer(mask: &[bool], w: usize, h: usize) -> Vec {
+ const D: f32 = std::f32::consts::SQRT_2;
+ let (pw, ph) = (w + 2, h + 2);
+ let mut d = vec![0f32; pw * ph];
+ for y in 0..h {
+ for x in 0..w {
+ if mask[x + w * y] {
+ d[(x + 1) + pw * (y + 1)] = f32::INFINITY;
+ }
+ }
+ }
+ for y in 1..ph - 1 {
+ for x in 1..pw - 1 {
+ let i = x + pw * y;
+ let m = d[i]
+ .min(d[i - 1] + 1.0)
+ .min(d[i - pw] + 1.0)
+ .min(d[i - pw - 1] + D)
+ .min(d[i - pw + 1] + D);
+ d[i] = m;
+ }
+ }
+ for y in (1..ph - 1).rev() {
+ for x in (1..pw - 1).rev() {
+ let i = x + pw * y;
+ let m = d[i]
+ .min(d[i + 1] + 1.0)
+ .min(d[i + pw] + 1.0)
+ .min(d[i + pw + 1] + D)
+ .min(d[i + pw - 1] + D);
+ d[i] = m;
+ }
+ }
+ let mut out = vec![0f32; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ out[x + w * y] = d[(x + 1) + pw * (y + 1)];
+ }
+ }
+ out
}
+
+/// 4-connected pieces of `mask`, largest first.
+fn face_pieces(mask: &[bool], w: usize, h: usize) -> Vec> {
+ let mut seen = vec![false; w * h];
+ let mut out = Vec::new();
+ for s in 0..w * h {
+ if !mask[s] || seen[s] {
+ continue;
+ }
+ seen[s] = true;
+ let mut stack = vec![s];
+ let mut cells = Vec::new();
+ while let Some(c) = stack.pop() {
+ cells.push(c);
+ let (x, y) = (c % w, c / w);
+ let mut near = [None; 4];
+ if x > 0 {
+ near[0] = Some(c - 1);
+ }
+ if x + 1 < w {
+ near[1] = Some(c + 1);
+ }
+ if y > 0 {
+ near[2] = Some(c - w);
+ }
+ if y + 1 < h {
+ near[3] = Some(c + w);
+ }
+ for q in near.into_iter().flatten() {
+ if mask[q] && !seen[q] {
+ seen[q] = true;
+ stack.push(q);
+ }
+ }
+ }
+ out.push(cells);
+ }
+ out.sort_by_key(|p| std::cmp::Reverse(p.len()));
+ out
+}
+
+/// The cell at plane index `k` of axis `a`, (u, v) along the other two.
+fn cell3(a: usize, k: u32, u: u32, v: u32) -> [u32; 3] {
+ let mut c = [0u32; 3];
+ c[a] = k;
+ c[(a + 1) % 3] = u;
+ c[(a + 2) % 3] = v;
+ c
+}
+
+/// Alignment pin holes of `diameter` (mesh units), `depth` deep into each side, across every
+/// cut: two in the largest piece of the cut face (as far apart as there is room for, so the
+/// parts cannot turn), one in each of the next pieces. A hole goes only where the face has
+/// room for it, and never through (at least [`PEG_CAP_MM`] left). One note per cut.
+pub fn pins(
+ grid: &mut VoxelGrid,
+ cuts: &[Cut],
+ diameter: f32,
+ depth: f32,
+ notes: &mut Vec,
+) {
+ if !(diameter > 0.0 && depth > 0.0) {
+ return;
+ }
+ let v = grid.voxel;
+ let r = 0.5 * diameter / v;
+ let wall = PEG_WALL_MM / v;
+ let cap = (PEG_CAP_MM / v).ceil().max(1.0) as u32;
+ let depth_cells = (depth / v).round().max(1.0) as u32;
+ let disc: Vec<(i64, i64)> = {
+ let ri = r.ceil() as i64;
+ let mut d = Vec::new();
+ for dv in -ri..=ri {
+ for du in -ri..=ri {
+ let (fu, fv) = (du as f32, dv as f32);
+ if fu * fu + fv * fv <= r * r {
+ d.push((du, dv));
+ }
+ }
+ }
+ if d.is_empty() {
+ d.push((0, 0));
+ }
+ d
+ };
+ for (n, cut) in cuts.iter().enumerate() {
+ let a = cut.axis.min(2);
+ let (ua, va) = ((a + 1) % 3, (a + 2) % 3);
+ let names = ["x", "y", "z"];
+ let head = format!("Cut {} ({} {:.1})", n + 1, names[a], cut.at + 0.0);
+ let Some(k) = plane(grid, cut) else {
+ continue;
+ };
+ let (w, h) = (grid.dims[ua] as usize, grid.dims[va] as usize);
+ let mut mask = vec![false; w * h];
+ for vv in 0..h {
+ for uu in 0..w {
+ let lo = cell3(a, k - 1, uu as u32, vv as u32);
+ let hi = cell3(a, k, uu as u32, vv as u32);
+ mask[uu + w * vv] =
+ grid.is_solid(lo[0], lo[1], lo[2]) && grid.is_solid(hi[0], hi[1], hi[2]);
+ }
+ }
+ let dist = chamfer(&mask, w, h);
+ let room = r + 1.0;
+ let mut spots = Vec::new();
+ for (i, piece) in face_pieces(&mask, w, h)
+ .iter()
+ .take(MAX_FACE_PIECES)
+ .enumerate()
+ {
+ let Some(best) = piece
+ .iter()
+ .copied()
+ .filter(|p| dist[*p] >= room)
+ .max_by(|p, q| dist[*p].total_cmp(&dist[*q]))
+ else {
+ continue;
+ };
+ spots.push(best);
+ if i > 0 {
+ continue;
+ }
+ // The second as far from the first as the face allows, a good wall preferred.
+ let (bx, by) = ((best % w) as f32, (best / w) as f32);
+ let apart = |p: usize| {
+ let (dx, dy) = ((p % w) as f32 - bx, (p / w) as f32 - by);
+ dx * dx + dy * dy
+ };
+ let min_apart = (6.0 * r).max(4.0);
+ let far = |need: f32| {
+ piece
+ .iter()
+ .copied()
+ .filter(|p| dist[*p] >= need && apart(*p) >= min_apart * min_apart)
+ .max_by(|p, q| apart(*p).total_cmp(&apart(*q)))
+ };
+ if let Some(s) = far(r + wall.max(1.0)).or_else(|| far(room)) {
+ spots.push(s);
+ }
+ }
+ let mut placed = Vec::new();
+ let mut clamped = false;
+ for s in spots {
+ let (u0, v0) = ((s % w) as i64, (s / w) as i64);
+ let cells: Vec<(u32, u32)> = disc
+ .iter()
+ .filter_map(|&(du, dv)| {
+ let (uu, vv) = (u0 + du, v0 + dv);
+ (uu >= 0 && vv >= 0 && (uu as usize) < w && (vv as usize) < h)
+ .then_some((uu as u32, vv as u32))
+ })
+ .collect();
+ let run = |g: &VoxelGrid, up: bool| -> u32 {
+ cells
+ .iter()
+ .map(|&(uu, vv)| {
+ let mut n = 0u32;
+ loop {
+ let kk = if up {
+ k as i64 + n as i64
+ } else {
+ k as i64 - 1 - n as i64
+ };
+ if kk < 0 || kk >= g.dims[a] as i64 {
+ break;
+ }
+ let c = cell3(a, kk as u32, uu, vv);
+ if !g.is_solid(c[0], c[1], c[2]) {
+ break;
+ }
+ n += 1;
+ }
+ n
+ })
+ .min()
+ .unwrap_or(0)
+ };
+ let mut made = false;
+ for up in [false, true] {
+ let dd = depth_cells.min(run(grid, up).saturating_sub(cap));
+ clamped |= dd < depth_cells;
+ if dd == 0 {
+ continue;
+ }
+ made = true;
+ for &(uu, vv) in &cells {
+ for i in 0..dd {
+ let kk = if up { k + i } else { k - 1 - i };
+ let c = cell3(a, kk, uu, vv);
+ grid.set(c[0], c[1], c[2], 0);
+ }
+ }
+ }
+ if made {
+ let c = grid.center(
+ cell3(a, k, u0 as u32, v0 as u32)[0],
+ cell3(a, k, u0 as u32, v0 as u32)[1],
+ cell3(a, k, u0 as u32, v0 as u32)[2],
+ );
+ placed.push(format!(
+ "{} {:.1} {} {:.1}",
+ names[ua],
+ c[ua] + 0.0,
+ names[va],
+ c[va] + 0.0
+ ));
+ }
+ }
+ if placed.is_empty() {
+ notes.push(format!(
+ "{head}: no room for a {diameter} mm alignment pin hole."
+ ));
+ continue;
+ }
+ notes.push(format!(
+ "{head}: {} alignment pin hole{} of {diameter} mm, {depth} mm into each side{}, at {} \
+ (a {diameter} mm pin or a piece of filament lines the parts up).",
+ placed.len(),
+ if placed.len() == 1 { "" } else { "s" },
+ if clamped {
+ " (shallower where the part is thin)"
+ } else {
+ ""
+ },
+ placed.join(", ")
+ ));
+ }
+}
+
+#[cfg(test)]
+#[path = "split_tests.rs"]
+mod tests;
diff --git a/crates/starorg-data/src/assets/print/split_tests.rs b/crates/starorg-data/src/assets/print/split_tests.rs
new file mode 100644
index 0000000..d06e06c
--- /dev/null
+++ b/crates/starorg-data/src/assets/print/split_tests.rs
@@ -0,0 +1,255 @@
+//! Split for the bed: the fewest pieces that each fit, cut through thin sections, pin holes
+//! across the cuts, every piece a closed mesh.
+
+use super::super::voxel::extract;
+use super::super::{Mesh, PrintOptions, ScaleMode, apply, write_output};
+use super::*;
+use std::collections::HashMap;
+
+fn all() -> impl Fn(f32, &str) -> bool + Sync {
+ |_, _| true
+}
+
+/// A grid of `dims` cells of `voxel`, solid where `solid(x, y, z)`.
+fn grid(voxel: f32, dims: [u32; 3], solid: impl Fn(u32, u32, u32) -> bool) -> VoxelGrid {
+ let mut g = VoxelGrid::new([0.0; 3], voxel, dims).unwrap();
+ for z in 0..dims[2] {
+ for y in 0..dims[1] {
+ for x in 0..dims[0] {
+ if solid(x, y, z) {
+ g.set(x, y, z, 1);
+ }
+ }
+ }
+ }
+ g
+}
+
+/// A closed box, outward.
+fn cube(min: [f32; 3], max: [f32; 3]) -> Mesh {
+ let c = |i: usize| {
+ [
+ if i & 1 == 0 { min[0] } else { max[0] },
+ if i & 2 == 0 { min[1] } else { max[1] },
+ if i & 4 == 0 { min[2] } else { max[2] },
+ ]
+ };
+ let faces = [
+ [0, 2, 3, 1],
+ [4, 5, 7, 6],
+ [0, 1, 5, 4],
+ [2, 6, 7, 3],
+ [0, 4, 6, 2],
+ [1, 3, 7, 5],
+ ];
+ let mut tris = Vec::new();
+ for [a, b, cc, d] in faces {
+ tris.push([c(a), c(b), c(cc)]);
+ tris.push([c(a), c(cc), c(d)]);
+ }
+ Mesh::from_triangles(&tris)
+}
+
+/// Every edge used once each way (closed, consistently oriented).
+fn assert_closed(m: &Mesh) {
+ assert!(!m.triangles.is_empty());
+ let mut e: HashMap<(u32, u32), u32> = HashMap::new();
+ for t in &m.triangles {
+ for k in 0..3 {
+ *e.entry((t[k], t[(k + 1) % 3])).or_default() += 1;
+ }
+ }
+ for (&(a, b), &n) in &e {
+ assert_eq!(n, 1, "edge {a}-{b} used {n} times the same way");
+ assert_eq!(e.get(&(b, a)), Some(&1), "edge {a}-{b} has no twin");
+ }
+}
+
+#[test]
+fn a_solid_that_fits_is_left_whole() {
+ let g = grid(1.0, [50, 20, 20], |_, _, _| true);
+ assert!(plan(&g, [100.0; 3]).is_empty());
+ let p = split(g.clone(), &[]);
+ assert_eq!(p.len(), 1);
+ assert_eq!(p[0].name, "");
+ assert_eq!(p[0].grid, g);
+ assert!(summary(&[], &p).contains("no cut needed"));
+}
+
+#[test]
+fn a_long_box_is_cut_into_the_fewest_pieces_that_fit() {
+ let g = grid(1.0, [250, 30, 20], |_, _, _| true);
+ let bed = [100.0, 100.0, 100.0];
+ let cuts = plan(&g, bed);
+ assert_eq!(cuts.len(), 2, "{cuts:?}");
+ assert!(cuts.iter().all(|c| c.axis == 0), "{cuts:?}");
+ let pieces = split(g, &cuts);
+ let names: Vec<&str> = pieces.iter().map(|p| p.name.as_str()).collect();
+ assert_eq!(names, ["part1", "part2", "part3"]);
+ let total: u64 = pieces.iter().map(|p| p.grid.count_solid()).sum();
+ assert_eq!(total, 250 * 30 * 20, "no cell lost or doubled");
+ let mut right = f32::NEG_INFINITY;
+ for p in &pieces {
+ let size = p.grid.dims.map(|d| d as f32 * p.grid.voxel);
+ assert!((0..3).all(|a| size[a] <= bed[a]), "{size:?}");
+ // Side by side, apart, low y lined up.
+ assert!(p.grid.origin[0] >= right + LAYOUT_GAP - 1e-3);
+ assert_eq!(p.grid.origin[1], 0.0);
+ right = p.grid.origin[0] + size[0];
+ assert_closed(&extract(&p.grid, &all()).unwrap());
+ }
+ assert!(summary(&cuts, &pieces).starts_with("Split into 3 parts"));
+}
+
+#[test]
+fn a_tall_or_wide_solid_is_cut_on_the_axes_that_need_it() {
+ let g = grid(1.0, [40, 150, 130], |_, _, _| true);
+ let cuts = plan(&g, [100.0, 100.0, 100.0]);
+ let mut axes: Vec = cuts.iter().map(|c| c.axis).collect();
+ axes.sort();
+ assert_eq!(axes, [1, 2]);
+ assert_eq!(split(g, &cuts).len(), 4);
+}
+
+#[test]
+fn the_cut_goes_through_the_thin_neck() {
+ // Two blocks joined by a 2 x 2 neck from x 40 to 60.
+ let g = grid(1.0, [100, 20, 20], |x, y, z| {
+ !(40..60).contains(&x) || ((9..11).contains(&y) && (9..11).contains(&z))
+ });
+ let cuts = plan(&g, [80.0, 100.0, 100.0]);
+ assert_eq!(cuts.len(), 1);
+ assert!(
+ cuts[0].axis == 0 && cuts[0].at > 40.0 && cuts[0].at < 60.0,
+ "{cuts:?}"
+ );
+}
+
+#[test]
+fn empty_lattice_cells_are_left_out() {
+ // An L: a bar along x and one along y; a 2 x 2 lattice leaves one corner empty.
+ let g = grid(1.0, [100, 100, 10], |x, y, _| x < 20 || y < 20);
+ let cuts = plan(&g, [60.0, 60.0, 60.0]);
+ assert_eq!(cuts.len(), 2);
+ let pieces = split(g, &cuts);
+ assert_eq!(pieces.len(), 3);
+ for p in &pieces {
+ assert!(p.grid.dims.iter().all(|d| *d as f32 * p.grid.voxel <= 60.0));
+ }
+}
+
+#[test]
+fn pin_holes_go_across_the_cut_into_both_sides() {
+ // 40 x 30 x 20 mm at 0.5 mm, cut at x 20: room for two 2 mm pins, 4 mm each side.
+ let mut g = grid(0.5, [80, 60, 40], |_, _, _| true);
+ let cut = Cut { axis: 0, at: 20.0 };
+ let mut notes = Vec::new();
+ pins(&mut g, &[cut], PIN_MM, PIN_DEPTH_MM, &mut notes);
+ assert_eq!(notes.len(), 1);
+ assert!(
+ notes[0].starts_with("Cut 1 (x 20.0): 2 alignment pin holes of 2 mm, 4 mm into each side"),
+ "{notes:?}"
+ );
+ // 2 holes, about pi * 2^2 cells each, 8 cells deep on each side.
+ let gone = 80 * 60 * 40 - g.count_solid();
+ assert!((2 * 2 * 8 * 9..2 * 2 * 8 * 16).contains(&gone), "{gone}");
+ let pieces = split(g, &[cut]);
+ assert_eq!(pieces.len(), 2);
+ for p in &pieces {
+ assert_eq!(p.grid.dims[0], 40);
+ assert_closed(&extract(&p.grid, &all()).unwrap());
+ }
+ // A face too small for a pin: a note, nothing drilled.
+ let mut g = grid(0.5, [80, 4, 4], |_, _, _| true);
+ let mut notes = Vec::new();
+ pins(&mut g, &[cut], PIN_MM, PIN_DEPTH_MM, &mut notes);
+ assert!(notes[0].contains("no room"), "{notes:?}");
+ assert_eq!(g.count_solid(), 80 * 4 * 4);
+}
+
+#[test]
+fn the_pipeline_splits_a_long_ship_into_closed_parts_that_fit() {
+ let t = tempfile::tempdir().unwrap();
+ // 2.5 m x 0.3 m x 0.2 m, printed 250 mm long on a 100 mm bed.
+ let o = PrintOptions {
+ scale: ScaleMode::FitMm(250.0),
+ bed_mm: [100.0; 3],
+ solid: true,
+ solid_res_mm: 0.4,
+ split: true,
+ ..Default::default()
+ };
+ let out = apply(cube([0.0; 3], [2.5, 0.3, 0.2]), &o, &all()).unwrap();
+ let names: Vec<&str> = out.parts.iter().map(|p| p.name.as_str()).collect();
+ assert_eq!(names, ["part1", "part2", "part3"]);
+ let mut right = f32::NEG_INFINITY;
+ for p in &out.parts {
+ assert_closed(&p.mesh);
+ let b = p.mesh.bounds().unwrap();
+ assert!(b.size().iter().all(|s| *s <= 100.0), "{b:?}");
+ assert!(b.min[2].abs() < 1e-4, "sits on the bed: {b:?}");
+ assert!(b.min[0] > right, "side by side");
+ right = b.max[0];
+ }
+ let pins = out
+ .notes
+ .iter()
+ .filter(|n| n.contains("2 alignment pin holes"))
+ .count();
+ assert_eq!(pins, 2, "{:?}", out.notes);
+ assert!(
+ out.notes
+ .iter()
+ .any(|n| n.starts_with("Split into 3 parts")),
+ "{:?}",
+ out.notes
+ );
+ let files = write_output(&out, &t.path().join("ship.glb"), true, true).unwrap();
+ let names: Vec = files
+ .iter()
+ .map(|f| {
+ std::path::Path::new(&f.path)
+ .file_name()
+ .unwrap()
+ .to_string_lossy()
+ .into_owned()
+ })
+ .collect();
+ assert_eq!(
+ names,
+ [
+ "ship-part1.stl",
+ "ship-part2.stl",
+ "ship-part3.stl",
+ "ship.3mf"
+ ]
+ );
+ let model = {
+ use std::io::Read;
+ let mut z = zip::ZipArchive::new(std::fs::File::open(&files[3].path).unwrap()).unwrap();
+ let mut s = String::new();
+ z.by_name("3D/3dmodel.model")
+ .unwrap()
+ .read_to_string(&mut s)
+ .unwrap();
+ s
+ };
+ assert_eq!(
+ model.matches("-part1.stl`, ... (one `MeshFile` each), the 3MF one object and build item per part.
+ Without a needed cut: one unnamed piece, unchanged output. `summary` gives the note.
+
+Real data (release, 32 threads): Gladius Print shell LOD 2 at 1:100, `--bed 120x120x120
+--solid 0.2 --split`: 4.9 s in all for `dev print-glb` (STL + 3MF), 552 MB peak; cuts at
+x -16.6 and y 24.2, 4 parts (70 x 109 x 51, 20 x 70 x 26, 103 x 109 x 57, 53 x 104 x 42 mm),
+each watertight and within the bed, 2 pin holes per cut; with `--peg 5` the same cuts with
+5 mm pegs and a stand hole; the 3MF has 4 build items.
+
## Testing on real GLBs
`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
From 5dbe9fcec25d986095cd5e0607b41b735d8a9ba1 Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Tue, 17 Nov 2026 22:37:50 -0600
Subject: [PATCH 08/12] feat(print): experimental multicolor groups and one
closed mesh per colour
Classify Print shell triangles into hull, engine and glass from their GLB
node paths (materials are only material_NN with MaterialMode::None). Without
Make solid each group is its own 3MF part; with it, outer-surface voxels keep
their group, glass and engine reach 1.2 mm in (glass > engine > hull) and
each group is extracted as its own closed mesh. The 3MF stays one object of
components with basematerials colours; the STL stays one mesh.
---
crates/starorg-data/src/assets/print/color.rs | 328 ++++++++++++++++-
.../src/assets/print/color_tests.rs | 335 ++++++++++++++++++
crates/starorg-data/src/assets/print/mod.rs | 16 +-
docs/plans/specs/model-print.md | 48 +++
4 files changed, 709 insertions(+), 18 deletions(-)
create mode 100644 crates/starorg-data/src/assets/print/color_tests.rs
diff --git a/crates/starorg-data/src/assets/print/color.rs b/crates/starorg-data/src/assets/print/color.rs
index 965c082..859b798 100644
--- a/crates/starorg-data/src/assets/print/color.rs
+++ b/crates/starorg-data/src/assets/print/color.rs
@@ -1,30 +1,126 @@
-//! Multicolor (experimental): the triangles grouped by what they are (hull, glass, engines,
-//! ...) from their GLB node paths, one 3MF object per group with a display colour, and how the
-//! 3MF places the objects. Pipeline steps 1, 11 and 14 of [`super::apply`].
+//! Multicolor (experimental): the triangles grouped by what they are (hull, glass, engines)
+//! from their GLB node paths, one 3MF part per group with a display colour, and how the 3MF
+//! places the parts. Pipeline steps 1, 11 and 14 of [`super::apply`].
//!
-//! Owner: the color agent. [`layout`] is done; [`classify`], [`by_group`] and [`color_of`]
-//! are pass-through stubs.
+//! Owner: the color agent.
+//!
+//! What the names can tell. A Print shell GLB is exported with `MaterialMode::None`, so its
+//! materials are only `material_NN` and say nothing; the node names survive (the full path from
+//! the scene root, e.g. `rsi_skylark/geo_body/lower_cockpit_frame/geo_cockpit_glass_lower_ext`,
+//! `AEGS_Gladius/Body/Nose/Canopy`, `.../hardpoint_thruster_main_left/.../geo_thruster_main_left`).
+//! So [`classify`] works per node, not per material: a node named for glass (`glass`,
+//! `canopy`, `windshield`, `window`) is glass, with its frame when the artist put both in one
+//! node (the Gladius `Canopy` node is about a quarter glass and three quarters frame in the
+//! Full export's materials); glass modelled inside the body node stays hull. Main and VTOL
+//! thrusters (any node under a `thruster` or `engine` node, not a manoeuvring one: `mav`,
+//! `retro`, `rcs`) are the engine group, whole (the nozzle glow is not a node of its own).
+//! Everything else is hull.
+//!
+//! With Make solid, [`extract_groups`] gives one closed mesh per group: outer-surface cells keep
+//! their group, glass and engine grow [`COLOR_DEPTH_MM`] into the solid (glass wins over
+//! engine, engine over hull where they meet), every other cell is hull.
+//!
+//! Slicers ([`layout`]): one object made of one component per group, each with a colour of
+//! one `basematerials` group. Bambu Studio loads it as one object with a part per group and
+//! maps the `basematerials` colours to filaments (its importer reads an object's
+//! `pid`/`pindex`). PrusaSlicer's current loader (master, after 2.9) makes each component a
+//! part of one object; PrusaSlicer 2.9 places each component as an object of its own, in
+//! place (its "load as a single object with multiple parts?" question, or select all and
+//! Assemble, joins them). PrusaSlicer reads no colours, so the parts are named after the
+//! groups (`hull`, `glass`, `engine`) and a filament is picked per part.
-use super::{Mesh, PrintOptions};
+use super::voxel::{Bits, VoxelGrid};
+use super::{Mesh, PrintOptions, Progress};
use crate::assets::threemf::Layout;
+use crate::assets::{AssetError, AssetResult};
+use rayon::prelude::*;
+
+/// The hull group (everything not glass or engine).
+pub const HULL: &str = "hull";
+/// Canopies and windows.
+pub const GLASS: &str = "glass";
+/// Main and VTOL thrusters.
+pub const ENGINE: &str = "engine";
+/// The groups [`classify`] gives, in this order (lowest priority first: the 3MF lists the
+/// parts in this order, so where two overlap a slicer that lets the later part win keeps the
+/// glass).
+pub const GROUPS: [&str; 3] = [HULL, ENGINE, GLASS];
+/// How deep (millimetres) glass and engine reach into a solid from its outer surface.
+pub const COLOR_DEPTH_MM: f32 = 1.2;
+/// Groups with fewer cells than this become hull (specks too small to print in a colour).
+pub const MIN_GROUP_CELLS: u64 = 27;
+
+/// Which group a node path belongs to (see the module doc).
+pub fn group_of(path: &str) -> &'static str {
+ let lower = path.to_ascii_lowercase();
+ let segs: Vec<&str> = lower.split('/').filter(|s| !s.is_empty()).collect();
+ let own = segs.last().copied().unwrap_or("");
+ let glassy = ["glass", "canopy", "windshield", "window"]
+ .iter()
+ .any(|k| own.contains(k));
+ if glassy && !own.contains("frame") {
+ return GLASS;
+ }
+ let engine_seg = |s: &str| {
+ s.contains("thruster")
+ || (s.contains("engine") && !s.contains("cryengine"))
+ || s.contains("exhaust")
+ };
+ if segs.iter().any(|s| engine_seg(s)) {
+ let manoeuvring = segs.iter().any(|s| {
+ ["mav", "retro", "rcs", "maneuver", "manoeuvre"]
+ .iter()
+ .any(|k| s.contains(k))
+ });
+ if !manoeuvring {
+ return ENGINE;
+ }
+ }
+ HULL
+}
-/// TODO(color agent): replace the mesh's groups (node paths from the GLB, e.g.
-/// `geo_body`, `geo_cockpit_glass_upper_ext`) with colour groups and their labels (`hull`,
-/// `glass`, ...). Stub: keeps the node groups.
+/// Replace the mesh's groups (node paths from the GLB) with the colour groups of [`GROUPS`]
+/// ([`group_of`] each node path). A mesh without groups becomes all hull.
pub fn classify(mesh: &mut Mesh) {
- let _ = mesh;
+ let index = |g: &str| GROUPS.iter().position(|x| *x == g).unwrap_or(0) as u32;
+ let map: Vec = mesh.labels.iter().map(|l| index(group_of(l))).collect();
+ let groups = match &mesh.groups {
+ Some(g) => g
+ .iter()
+ .map(|&i| map.get(i as usize).copied().unwrap_or(0))
+ .collect(),
+ None => vec![0; mesh.triangles.len()],
+ };
+ mesh.groups = Some(groups);
+ mesh.labels = GROUPS.iter().map(|s| s.to_string()).collect();
}
-/// TODO(color agent): the mesh split by group, `(label, mesh)` per non-empty group (use
-/// [`Mesh::subset`]). Stub: the whole mesh as one unlabelled part.
+/// The mesh split by group, `(label, mesh)` per non-empty group, in label order. Without
+/// groups, the whole mesh as one unlabelled part.
pub fn by_group(mesh: &Mesh) -> Vec<(String, Mesh)> {
- vec![(String::new(), mesh.clone())]
+ let Some(groups) = &mesh.groups else {
+ return vec![(String::new(), mesh.clone())];
+ };
+ let n = mesh.labels.len().max(1);
+ let mut tris: Vec> = vec![Vec::new(); n];
+ for (t, &g) in groups.iter().enumerate() {
+ tris[(g as usize).min(n - 1)].push(t);
+ }
+ tris.into_iter()
+ .enumerate()
+ .filter(|(_, t)| !t.is_empty())
+ .map(|(g, t)| (mesh.label(g as u32).to_string(), mesh.subset(t)))
+ .collect()
}
-/// TODO(color agent): the display colour (RGBA) of a group label. Stub: none.
+/// The display colour (RGBA) of a group label: light grey hull, blue glass, orange engine.
pub fn color_of(label: &str) -> Option<[u8; 4]> {
- let _ = label;
- None
+ match label {
+ HULL => Some([0xB8, 0xBC, 0xC2, 0xFF]),
+ GLASS => Some([0x3A, 0x6E, 0xA5, 0xFF]),
+ ENGINE => Some([0xFF, 0x7A, 0x1A, 0xFF]),
+ _ => None,
+ }
}
/// How the 3MF places the parts: one assembly (one object with a part per colour) for
@@ -36,3 +132,203 @@ pub fn layout(o: &PrintOptions) -> Layout {
Layout::Separate
}
}
+
+/// How strongly a group holds a cell where groups meet (glass > engine > the rest).
+fn priority(label: &str) -> u8 {
+ match label {
+ GLASS => 2,
+ ENGINE => 1,
+ _ => 0,
+ }
+}
+
+/// The 6 neighbours of a cell (wrapping below 0, which [`VoxelGrid::get`] reads as empty).
+fn near([x, y, z]: [u32; 3]) -> [[u32; 3]; 6] {
+ [
+ [x.wrapping_sub(1), y, z],
+ [x + 1, y, z],
+ [x, y.wrapping_sub(1), z],
+ [x, y + 1, z],
+ [x, y, z.wrapping_sub(1)],
+ [x, y, z + 1],
+ ]
+}
+
+/// Relabel a labelled solid for printing in colours: outer-surface cells keep their group,
+/// glass and engine grow `depth` (mesh units) into the solid, everything else is hull (the
+/// [`HULL`] label, else the first label without priority). Groups under [`MIN_GROUP_CELLS`]
+/// become hull. Returns the cell value of the hull.
+pub fn paint(grid: &mut VoxelGrid, depth: f32, progress: Progress<'_>) -> AssetResult {
+ let tick = |f: f32| {
+ if progress(f, "Colouring the solid") {
+ Ok(())
+ } else {
+ Err(AssetError::cancelled())
+ }
+ };
+ tick(0.0)?;
+ let pr: Vec = std::iter::once(0)
+ .chain(grid.labels.iter().map(|l| priority(l)))
+ .collect();
+ let prio = |v: u8| pr.get(v as usize).copied().unwrap_or(0);
+ let hull = grid
+ .labels
+ .iter()
+ .position(|l| l == HULL)
+ .or_else(|| grid.labels.iter().position(|l| priority(l) == 0))
+ .map_or(1, |i| (i + 1).min(255) as u8);
+ let dims = grid.dims;
+ // The outside: the empty cells connected to the grid's corner (voxelize pads the grid).
+ let empty = grid.bits(&|c| c == 0);
+ let mut outside = Bits::new(dims);
+ if empty.get(0, 0, 0) {
+ empty.flood(&mut outside, [0, 0, 0], |_, _, _, _| {});
+ }
+ tick(0.2)?;
+ let (d0, d1) = (dims[0] as usize, dims[1] as usize);
+ let plane = d0 * d1;
+ let at = |i: usize| [(i % d0) as u32, ((i / d0) % d1) as u32, (i / plane) as u32];
+ // Outer-surface cells (a face on the outside) keep their group; every other solid cell is
+ // hull for now.
+ let mut surface = outside.dilate(1.0);
+ surface.and_not(&empty);
+ drop(outside);
+ drop(empty);
+ let mut seeds_lo = [u32::MAX; 3];
+ let mut seeds_hi = [0u32; 3];
+ {
+ let out = grid.cells_mut();
+ for (i, c) in out.iter_mut().enumerate() {
+ if *c == 0 {
+ continue;
+ }
+ let p = at(i);
+ if !surface.get(p[0], p[1], p[2]) {
+ *c = hull;
+ } else if prio(*c) > 0 {
+ for k in 0..3 {
+ seeds_lo[k] = seeds_lo[k].min(p[k]);
+ seeds_hi[k] = seeds_hi[k].max(p[k] + 1);
+ }
+ } else {
+ *c = hull;
+ }
+ }
+ }
+ tick(0.4)?;
+ // Grow glass and engine inwards a layer at a time (the strongest neighbour wins).
+ let layers = (depth / grid.voxel).ceil().max(1.0) as u32;
+ if seeds_hi[0] > 0 {
+ let lo = seeds_lo.map(|v| v.saturating_sub(layers));
+ let hi = [0, 1, 2].map(|k| (seeds_hi[k] + layers).min(dims[k]));
+ for layer in 0..layers {
+ let g = &*grid;
+ let set: Vec<(usize, u8)> = (lo[2]..hi[2])
+ .into_par_iter()
+ .flat_map_iter(|z| {
+ let mut v = Vec::new();
+ for y in lo[1]..hi[1] {
+ for x in lo[0]..hi[0] {
+ let i = g.index(x, y, z);
+ if surface.get(x, y, z) || g.cells()[i] != hull {
+ continue;
+ }
+ let best = near([x, y, z])
+ .iter()
+ .map(|&[a, b, c]| g.get(a, b, c))
+ .filter(|&n| prio(n) > 0)
+ .max_by_key(|&n| prio(n));
+ if let Some(b) = best {
+ v.push((i, b));
+ }
+ }
+ }
+ v
+ })
+ .collect();
+ let out = grid.cells_mut();
+ for (i, b) in set {
+ out[i] = b;
+ }
+ tick(0.4 + 0.5 * (layer + 1) as f32 / layers as f32)?;
+ }
+ }
+ // Specks become hull.
+ let mut count = [0u64; 256];
+ for &c in grid.cells() {
+ count[c as usize] += 1;
+ }
+ for c in grid.cells_mut() {
+ if *c != 0 && *c != hull && count[*c as usize] < MIN_GROUP_CELLS {
+ *c = hull;
+ }
+ }
+ tick(1.0)?;
+ Ok(hull)
+}
+
+/// With Make solid: one closed mesh per group of a labelled solid ([`paint`] with `depth` in
+/// mesh units, then [`super::voxel::extract_where`] per group on the group's own crop), in the
+/// order of increasing priority (hull, engine, glass). Neighbouring groups' meshes touch (and
+/// may overlap by up to a voxel where extracting closes a corner). An unlabelled grid gives one
+/// unlabelled mesh.
+pub fn extract_groups(
+ grid: &VoxelGrid,
+ depth: f32,
+ progress: Progress<'_>,
+) -> AssetResult> {
+ if grid.labels.is_empty() {
+ return Ok(vec![(
+ String::new(),
+ super::voxel::extract(grid, progress)?,
+ )]);
+ }
+ let mut g = grid.clone();
+ paint(&mut g, depth, &|f, s| progress(0.2 * f, s))?;
+ // Each group's cells and bounds.
+ let dims = g.dims;
+ let (d0, d1) = (dims[0] as usize, dims[1] as usize);
+ let mut lo = [[u32::MAX; 3]; 256];
+ let mut hi = [[0u32; 3]; 256];
+ for (i, &c) in g.cells().iter().enumerate() {
+ if c == 0 {
+ continue;
+ }
+ let p = [
+ (i % d0) as u32,
+ ((i / d0) % d1) as u32,
+ (i / (d0 * d1)) as u32,
+ ];
+ let (l, h) = (&mut lo[c as usize], &mut hi[c as usize]);
+ for k in 0..3 {
+ l[k] = l[k].min(p[k]);
+ h[k] = h[k].max(p[k] + 1);
+ }
+ }
+ let mut values: Vec = (1..=255u8).filter(|&v| hi[v as usize][0] > 0).collect();
+ values.sort_by_key(|&v| {
+ let label = g.labels.get(v as usize - 1).map_or("", String::as_str);
+ (priority(label), v)
+ });
+ let n = values.len().max(1) as f32;
+ let mut out = Vec::new();
+ for (k, v) in values.into_iter().enumerate() {
+ let (a, b) = (0.2 + 0.8 * k as f32 / n, 0.2 + 0.8 * (k + 1) as f32 / n);
+ let (l, h) = (lo[v as usize], hi[v as usize]);
+ let cells: u64 = (0..3).map(|k| (h[k] - l[k]) as u64).product();
+ let sub = |f: f32, s: &str| progress(a + (b - a) * f.clamp(0.0, 1.0), s);
+ // A crop only pays when it is much smaller than the grid (the hull rarely is).
+ let mesh = if cells * 2 < g.len() as u64 {
+ super::voxel::extract_where(&g.crop(l, h)?, &move |c| c == v, &sub)?
+ } else {
+ super::voxel::extract_where(&g, &move |c| c == v, &sub)?
+ };
+ let label = g.labels.get(v as usize - 1).cloned().unwrap_or_default();
+ out.push((label, mesh));
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+#[path = "color_tests.rs"]
+mod tests;
diff --git a/crates/starorg-data/src/assets/print/color_tests.rs b/crates/starorg-data/src/assets/print/color_tests.rs
new file mode 100644
index 0000000..e15d963
--- /dev/null
+++ b/crates/starorg-data/src/assets/print/color_tests.rs
@@ -0,0 +1,335 @@
+//! Multicolor: node paths to groups, parts per group, and one closed mesh per group of a solid.
+
+use super::*;
+use crate::assets::print::{PrintOptions, ScaleMode, apply, write_output};
+use crate::assets::stl::LabeledTriangles;
+use std::collections::HashMap;
+
+fn all() -> impl Fn(f32, &str) -> bool + Sync {
+ |_, _| true
+}
+
+/// A closed box from `min` to `max`, 12 triangles, outward.
+fn box_tris(min: [f32; 3], max: [f32; 3]) -> Vec<[[f32; 3]; 3]> {
+ let c = |i: usize| {
+ [
+ if i & 1 == 0 { min[0] } else { max[0] },
+ if i & 2 == 0 { min[1] } else { max[1] },
+ if i & 4 == 0 { min[2] } else { max[2] },
+ ]
+ };
+ let faces = [
+ [0, 2, 3, 1],
+ [4, 5, 7, 6],
+ [0, 1, 5, 4],
+ [2, 6, 7, 3],
+ [0, 4, 6, 2],
+ [1, 3, 7, 5],
+ ];
+ let mut t = Vec::new();
+ for [a, b, cc, d] in faces {
+ t.push([c(a), c(b), c(cc)]);
+ t.push([c(a), c(cc), c(d)]);
+ }
+ t
+}
+
+/// Boxes labelled with node paths.
+fn ship(parts: &[(&str, [f32; 3], [f32; 3])]) -> Mesh {
+ let mut l = LabeledTriangles::default();
+ for (i, (path, lo, hi)) in parts.iter().enumerate() {
+ l.nodes.push(path.to_string());
+ for t in box_tris(*lo, *hi) {
+ l.triangles.push(t);
+ l.node.push(i as u32);
+ }
+ }
+ Mesh::from_labeled(&l)
+}
+
+/// Every directed edge once and its reverse once (closed, consistently oriented).
+fn assert_closed(m: &Mesh) {
+ assert!(!m.triangles.is_empty());
+ let mut e: HashMap<(u32, u32), u32> = HashMap::new();
+ for t in &m.triangles {
+ for k in 0..3 {
+ *e.entry((t[k], t[(k + 1) % 3])).or_default() += 1;
+ }
+ }
+ for (&(a, b), &n) in &e {
+ assert_eq!(n, 1, "edge {a}-{b} used {n} times the same way");
+ assert_eq!(e.get(&(b, a)), Some(&1), "edge {a}-{b} has no twin");
+ }
+}
+
+fn volume(m: &Mesh) -> f32 {
+ (0..m.triangles.len())
+ .map(|t| {
+ let [a, b, c] = m.triangle(t);
+ let cr = [
+ b[1] * c[2] - b[2] * c[1],
+ b[2] * c[0] - b[0] * c[2],
+ b[0] * c[1] - b[1] * c[0],
+ ];
+ (a[0] * cr[0] + a[1] * cr[1] + a[2] * cr[2]) / 6.0
+ })
+ .sum()
+}
+
+#[test]
+fn node_paths_from_real_ships_name_their_group() {
+ let cases = [
+ // Skylark (Print shell, LOD 4)
+ ("CryEngine_Z_up/rsi_skylark/geo_body", HULL),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/lower_cockpit_frame/geo_cockpit_glass_lower_ext",
+ GLASS,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/anim_cockpit_frame/anim_cockpit_glass_upper_hinge/geo_cockpit_glass_upper_ext",
+ GLASS,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/anim_cockpit_frame",
+ HULL,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/hardpoint_thruster_main_left/RSI_Skylark_Thruster_Main_Left/rsi_skylark_thruster_main_left/geo_thruster_main_left",
+ ENGINE,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/hardpoint_thruster_retro_left/RSI_Skylark_Thruster_Retro_Left/rsi_skylark_thruster_retro_left/geo_skylark_thruster_retro_left",
+ HULL,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/hardpoint_thruster_mav_top_front_left/RSI_Skylark_Thruster_Mav_Top/rsi_skylark_thruster_mav/geo_thruster_mav",
+ HULL,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/anim_component_racking/hardpoint_relay/RELAY_2slot_slim/relay_demo_2fuse_s01/mesh_relay01/LinkedGlow_Fuse",
+ HULL,
+ ),
+ (
+ "CryEngine_Z_up/rsi_skylark/geo_body/hardpoint_fuelport_ground/RSI_Skylark_Ground_Refueling/rsi_skylark_fuelport_ground/anim_fuelport_ground_housing/anim_fuelport_ground_nozzle",
+ HULL,
+ ),
+ // Gladius
+ ("CryEngine_Z_up/AEGS_Gladius/Body/Nose/Canopy", GLASS),
+ (
+ "CryEngine_Z_up/AEGS_Gladius/Body/hardpoint_thruster_main_left/AEGS_Gladius_Thruster_Main/AEGS_Gladius_Thruster_Main/Gladius_Thruster_Main",
+ ENGINE,
+ ),
+ (
+ "CryEngine_Z_up/AEGS_Gladius/Body/Nose/MAYA_thruster_front_left_top_CTRL/hardpoint_thruster_front_left_top/AEGS_Gladius_Thruster_Mav_Joint_01/AEGS_Gladius_Thruster_Mav_Joint_01/YAW_CONTROL/PITCH_CONTROL/Gladius_Thruster_Mav_Joint_01",
+ HULL,
+ ),
+ // Made up: a canopy frame, a VTOL, an engine without "thruster".
+ ("ship/body/canopy_frame", HULL),
+ ("ship/body/hardpoint_thruster_vtol_left/geo", ENGINE),
+ ("ship/body/engine_left/geo_exhaust", ENGINE),
+ ("", HULL),
+ ];
+ for (path, want) in cases {
+ assert_eq!(group_of(path), want, "{path}");
+ }
+}
+
+#[test]
+fn classify_groups_by_node_and_by_group_gives_one_part_per_group_with_its_colour() {
+ let mut m = ship(&[
+ ("ship/geo_body", [0.0; 3], [10.0, 4.0, 2.0]),
+ ("ship/geo_body/geo_canopy", [2.0, 1.0, 2.0], [4.0, 3.0, 3.0]),
+ (
+ "ship/geo_body/hardpoint_thruster_main/geo",
+ [10.0, 1.0, 0.5],
+ [11.0, 3.0, 1.5],
+ ),
+ (
+ "ship/geo_body/hardpoint_thruster_mav/geo",
+ [5.0, 4.0, 1.0],
+ [6.0, 5.0, 2.0],
+ ),
+ ]);
+ classify(&mut m);
+ assert_eq!(m.labels, GROUPS);
+ let parts = by_group(&m);
+ let names: Vec<&str> = parts.iter().map(|(n, _)| n.as_str()).collect();
+ assert_eq!(names, [HULL, ENGINE, GLASS]);
+ let tris: Vec = parts.iter().map(|(_, p)| p.triangles.len()).collect();
+ assert_eq!(tris, [24, 12, 12], "the mav thruster is hull");
+ let colors: Vec<[u8; 4]> = names.iter().map(|n| color_of(n).unwrap()).collect();
+ assert!(colors[0] != colors[1] && colors[1] != colors[2] && colors[0] != colors[2]);
+ assert_eq!(color_of("piece-1"), None);
+ // No groups at all: everything is hull.
+ let mut plain = Mesh::from_triangles(&box_tris([0.0; 3], [1.0; 3]));
+ classify(&mut plain);
+ let p = by_group(&plain);
+ assert_eq!((p.len(), p[0].0.as_str()), (1, HULL));
+ assert_eq!(
+ by_group(&Mesh::from_triangles(&box_tris([0.0; 3], [1.0; 3])))[0].0,
+ ""
+ );
+}
+
+/// A solid block of hull with the given outer faces painted (labels `GROUPS`).
+fn block(n: u32) -> VoxelGrid {
+ let mut g = VoxelGrid::new([0.0; 3], 1.0, [n + 4, n + 4, n + 4]).unwrap();
+ g.labels = GROUPS.iter().map(|s| s.to_string()).collect();
+ for z in 2..n + 2 {
+ for y in 2..n + 2 {
+ for x in 2..n + 2 {
+ g.set(x, y, z, 1);
+ }
+ }
+ }
+ g
+}
+
+#[test]
+fn paint_grows_glass_and_engine_inwards_and_glass_wins_where_they_meet() {
+ let n = 10;
+ let mut g = block(n);
+ let (top, side) = (n + 1, n + 1);
+ // +x face engine (value 2), then the top face glass (value 3), edge included.
+ for z in 2..n + 2 {
+ for y in 2..n + 2 {
+ g.set(side, y, z, 2);
+ }
+ }
+ for y in 2..n + 2 {
+ for x in 2..n + 2 {
+ g.set(x, y, top, 3);
+ }
+ }
+ // Inside cells start with arbitrary labels (voxelize fills along x): they become hull.
+ g.set(5, 5, 5, 3);
+ let hull = paint(&mut g, 2.0, &all()).unwrap();
+ assert_eq!(hull, 1);
+ assert_eq!(g.get(5, 6, top), 3, "the glass surface stays");
+ assert_eq!(g.get(5, 6, top - 1), 3, "one layer in");
+ assert_eq!(g.get(5, 6, top - 2), 3, "two layers in");
+ assert_eq!(g.get(5, 6, top - 3), 1, "past the depth: hull");
+ assert_eq!(g.get(side - 2, 6, 5), 2, "engine two layers in");
+ assert_eq!(g.get(5, 5, 5), 1, "the inside is hull");
+ assert_eq!(g.get(side - 1, 6, top - 1), 3, "glass wins over engine");
+ assert_eq!(g.get(2, 6, 5), 1, "the -x surface is hull");
+ // A speck of glass under MIN_GROUP_CELLS becomes hull.
+ let mut s = block(6);
+ s.set(4, 4, 7, 3);
+ paint(&mut s, 1.0, &all()).unwrap();
+ assert_eq!(s.get(4, 4, 7), 1);
+ // Cancelling stops.
+ assert_eq!(
+ paint(&mut block(4), 1.0, &|_, _| false).unwrap_err().code,
+ "cancelled"
+ );
+}
+
+#[test]
+fn extract_groups_gives_one_closed_mesh_per_group_in_priority_order() {
+ let mesh = {
+ let mut m = ship(&[
+ ("ship/geo_body", [0.0; 3], [20.0, 10.0, 6.0]),
+ ("ship/geo_canopy", [4.0, 3.0, 6.0], [10.0, 7.0, 9.0]),
+ (
+ "ship/hardpoint_thruster_main/geo",
+ [20.0, 3.0, 1.0],
+ [24.0, 7.0, 5.0],
+ ),
+ ]);
+ classify(&mut m);
+ m
+ };
+ let grid = super::super::voxel::voxelize(&mesh, 0.5, &all()).unwrap();
+ let parts = extract_groups(&grid, 1.0, &all()).unwrap();
+ let names: Vec<&str> = parts.iter().map(|(n, _)| n.as_str()).collect();
+ assert_eq!(names, [HULL, ENGINE, GLASS]);
+ let mut total = 0.0;
+ for (name, m) in &parts {
+ assert_closed(m);
+ let v = volume(m);
+ assert!(v > 0.0, "{name} is outward");
+ total += v;
+ }
+ let whole = volume(&super::super::voxel::extract(&grid, &all()).unwrap());
+ assert!(
+ (total - whole).abs() < 0.1 * whole,
+ "the groups add up to the solid: {total} vs {whole}"
+ );
+ // An unlabelled grid: one unlabelled mesh.
+ let plain = super::super::voxel::voxelize(
+ &Mesh::from_triangles(&box_tris([0.0; 3], [4.0; 3])),
+ 0.5,
+ &all(),
+ )
+ .unwrap();
+ let one = extract_groups(&plain, 1.0, &all()).unwrap();
+ assert_eq!((one.len(), one[0].0.as_str()), (1, ""));
+}
+
+fn model_xml(p: &std::path::Path) -> String {
+ use std::io::Read;
+ let mut z = zip::ZipArchive::new(std::fs::File::open(p).unwrap()).unwrap();
+ let mut s = String::new();
+ z.by_name("3D/3dmodel.model")
+ .unwrap()
+ .read_to_string(&mut s)
+ .unwrap();
+ s
+}
+
+fn little_ship() -> Mesh {
+ // Metres, as from the GLB.
+ ship(&[
+ ("ship/geo_body", [0.0; 3], [2.0, 1.0, 0.6]),
+ (
+ "ship/geo_body/geo_cockpit_glass",
+ [0.4, 0.3, 0.6],
+ [1.0, 0.7, 0.9],
+ ),
+ (
+ "ship/hardpoint_thruster_main/geo",
+ [2.0, 0.3, 0.1],
+ [2.4, 0.7, 0.5],
+ ),
+ ])
+}
+
+#[test]
+fn multicolor_writes_one_3mf_assembly_with_coloured_parts_and_one_stl() {
+ let t = tempfile::tempdir().unwrap();
+ let glb = t.path().join("ship.glb");
+ for solid in [false, true] {
+ let o = PrintOptions {
+ multicolor: true,
+ solid,
+ scale: if solid {
+ ScaleMode::FitMm(30.0)
+ } else {
+ ScaleMode::None
+ },
+ solid_res_mm: 0.4,
+ ..Default::default()
+ };
+ let out = apply(little_ship(), &o, &all()).unwrap();
+ assert_eq!(out.layout, Layout::Assembly);
+ let names: Vec<&str> = out.parts.iter().map(|p| p.name.as_str()).collect();
+ assert_eq!(names, [HULL, ENGINE, GLASS], "solid {solid}");
+ for p in &out.parts {
+ assert_eq!(p.color, color_of(&p.name));
+ if solid {
+ assert_closed(&p.mesh);
+ }
+ }
+ let files = write_output(&out, &glb, true, true).unwrap();
+ let kinds: Vec<&str> = files.iter().map(|f| f.kind.as_str()).collect();
+ assert_eq!(kinds, ["stl", "3mf"], "one STL (a single mesh) and one 3MF");
+ let m = model_xml(&glb.with_extension("3mf"));
+ assert!(m.contains(r#""#), "{solid}");
+ assert!(m.contains(r##""##));
+ assert!(m.contains(r#"name="engine" pid="5" pindex="1""#));
+ assert_eq!(m.matches(""#]);
+ }
+}
diff --git a/crates/starorg-data/src/assets/print/mod.rs b/crates/starorg-data/src/assets/print/mod.rs
index 6cdc103..e93752d 100644
--- a/crates/starorg-data/src/assets/print/mod.rs
+++ b/crates/starorg-data/src/assets/print/mod.rs
@@ -633,8 +633,20 @@ pub fn apply(mut mesh: Mesh, o: &PrintOptions, progress: Progress<'_>) -> AssetR
let n = pieces.len().max(1) as f32;
for (i, piece) in pieces.into_iter().enumerate() {
let (a, b) = (0.65 + 0.2 * i as f32 / n, 0.65 + 0.2 * (i + 1) as f32 / n);
- let m = voxel::extract(&piece.grid, &sub(progress, a, b))?;
- parts.extend(per_group(&piece.name, m, o));
+ if o.multicolor {
+ // One closed mesh per colour group (not the open patches of one mesh).
+ let depth = color::COLOR_DEPTH_MM * per_mm;
+ for (label, m) in color::extract_groups(&piece.grid, depth, &sub(progress, a, b))? {
+ parts.push(Part {
+ name: part_name(&piece.name, &label),
+ color: color::color_of(&label),
+ mesh: m,
+ });
+ }
+ } else {
+ let m = voxel::extract(&piece.grid, &sub(progress, a, b))?;
+ parts.extend(per_group(&piece.name, m, o));
+ }
}
} else {
parts = per_group("", mesh, o);
diff --git a/docs/plans/specs/model-print.md b/docs/plans/specs/model-print.md
index 6768703..70dfedf 100644
--- a/docs/plans/specs/model-print.md
+++ b/docs/plans/specs/model-print.md
@@ -128,6 +128,54 @@ coarsened to 0.13 mm: 1.6 s, 1.15 GB, 7.6 M triangles; with `--thicken 0.8 --hol
0.94 s, 9 cavities, 10 drain holes, 69 cm³, watertight. Gladius LOD 2 at 0.2 mm: 0.52 s,
278 MB, 1.83 M triangles, watertight.
+## Multicolor (`color.rs`)
+
+- What is reliable. A Print shell GLB is exported with `MaterialMode::None`, so its materials
+ are only `material_NN`; the node names survive as full paths (Skylark:
+ `geo_body/lower_cockpit_frame/geo_cockpit_glass_lower_ext`,
+ `hardpoint_thruster_main_left/.../geo_thruster_main_left`; Gladius: `Body/Nose/Canopy`,
+ `hardpoint_thruster_main_left/.../Gladius_Thruster_Main`). So grouping is per node:
+ - `glass`: the node's own name has `glass`, `canopy`, `windshield` or `window` (not
+ `frame`). A canopy node holds its frame too when the artist modelled both in it (the
+ Gladius `Canopy` is about a quarter glass in the Full export's materials); glass inside the
+ body node stays hull.
+ - `engine`: any path segment has `thruster`, `engine` (not `CryEngine`) or `exhaust`, and
+ none has `mav`, `retro`, `rcs` or `maneuver` (manoeuvring thrusters stay hull). The whole
+ thruster, not just its glow (there is no glow node).
+ - `hull`: everything else.
+ - Exact glass would need material names: StarBreaker's `MaterialMode::Colors` keeps them
+ (`..._mtl_glass_ext_04`) without textures, but it changes the Print shell GLB (and its
+ cache key), so it is not used; a follow-up could export it for `--multicolor` only and
+ carry the material per triangle through `stl::walk_glb`.
+- Parts: `classify` sets the groups `hull`, `engine`, `glass` (in that order, the lowest
+ priority first); without Make solid, `by_group` gives one part per non-empty group (open
+ game surfaces, as before). Colours (`color_of`): hull `#B8BCC2`, engine `#FF7A1A`, glass
+ `#3A6EA5`.
+- With Make solid, `color::extract_groups(grid, COLOR_DEPTH_MM, progress)` (called by the
+ pipeline instead of `voxel::extract` + `by_group` when multicolor; one change in `mod.rs`):
+ `paint` keeps the group of outer-surface cells (a face on the outside flood), grows glass
+ and engine `COLOR_DEPTH_MM` (1.2 mm) inwards a layer at a time (glass > engine > hull where
+ they meet), makes every other cell hull and specks under `MIN_GROUP_CELLS` (27) hull; then
+ `voxel::extract_where` per group (on the group's crop when that is under half the grid):
+ one closed mesh per group. Neighbouring parts touch and may overlap by up to a voxel where
+ extracting closes a corner. The walls of a hollowed cavity count as outside (it drains), so
+ they may carry a colour inside; that costs filament, not looks.
+- Slicers (one object made of one component per group, `Layout::Assembly`, object-level
+ `pid`/`pindex` into one `basematerials`). From their 3MF importers' source: Bambu Studio
+ makes each component a part of one object and maps the distinct `displaycolor`s to filament
+ slots (non-Bambu 3MF path, object `pid`/`pindex`); PrusaSlicer's current loader (master,
+ after 2.9) makes each component a part of one object; PrusaSlicer 2.9 places each component
+ as an object of its own in place (join them with its "single object with multiple parts?"
+ question or Assemble). PrusaSlicer reads no colours: pick a filament per part (named `hull`,
+ `glass`, `engine`). Not yet checked in the slicers' GUIs.
+- STL: one file with every part (a single mesh), as without multicolor.
+- Real data (release, `--multicolor --fit-mm 150 --solid`): Skylark LOD 4: 3.7 s (2.7 s
+ without multicolor), 628 MB peak, hull 3.16 M / engine 83 k / glass 277 k triangles, each
+ closed (every edge once each way), 219.7 + 0.5 + 2.3 cm³ = 222.5 cm³ (one-colour solid
+ 222.5 cm³). Gladius LOD 2: 2.3 s, 387 MB, hull 1.89 M / engine 128 k / glass 53 k
+ triangles, each closed. Without solid, the Skylark gives hull 96 028, engine 2 018 and glass
+ 330 triangles in 0.13 s.
+
## Testing on real GLBs
`starorg-codex dev print-glb --out [print flags] [--stl] [--3mf]` runs the
From f0a4eea7e83cb616974e77e095387c7a2093c33a Mon Sep 17 00:00:00 2001
From: Nyle Garcia
Date: Thu, 19 Nov 2026 09:11:56 -0600
Subject: [PATCH 09/12] fix(print): integrate the experimental print steps
- Split pieces keep their side-by-side layout: after scale's x/y centring
each piece was centred alone (stacked at the origin). Each piece, with
its colour parts, is now lowered on its own and the layout centred.
- --peg without --split is accepted (stand hole only), in Rust, TS, UI
and CLI help.
- A note when simplify cannot reach its triangle budget.
- Drop-small and split wording: bounding-box diagonal, alignment pins.
- User guide model export section and spec status with real-data runs.
---
app/src/components/assets/PrintSection.svelte | 7 +--
app/src/lib/printoptions.ts | 1 -
app/tests/printoptions.test.ts | 3 +-
crates/starorg-cli/src/lib.rs | 9 ++-
crates/starorg-cli/tests/dev_assets.rs | 4 --
crates/starorg-data/src/assets/print/mod.rs | 56 ++++++++++++++-----
.../src/assets/print/split_tests.rs | 47 ++++++++++++++++
crates/starorg-data/src/assets/print/tests.rs | 9 ---
docs/plans/specs/model-print.md | 33 ++++++++---
docs/user-guide.md | 22 ++++++--
10 files changed, 143 insertions(+), 48 deletions(-)
diff --git a/app/src/components/assets/PrintSection.svelte b/app/src/components/assets/PrintSection.svelte
index 939208a..5b04310 100644
--- a/app/src/components/assets/PrintSection.svelte
+++ b/app/src/components/assets/PrintSection.svelte
@@ -56,7 +56,6 @@
}
function setSplit(on: boolean) {
value.split = on;
- if (!on) value.peg_mm = null;
}
const on = $derived(
[value.scale.mode !== 'none', value.shrink_to_bed, value.drop_small_mm !== null, value.solid, value.multicolor, value.simplify_tris !== null, value.no_weapons].filter(Boolean).length,
@@ -100,7 +99,7 @@
(value.shrink_to_bed = v)}>
{@render experimental()}
- (value.drop_small_mm = v ? dropMm : null)}>
+ (value.drop_small_mm = v ? dropMm : null)}>
{#if value.drop_small_mm !== null} (value.drop_small_mm = dropMm = num(e))} />{/if}
{@render experimental()}
@@ -123,10 +122,10 @@
{/if}
{@render experimental()}
-
+
{@render experimental()}
- (value.peg_mm = v ? pegMm : null)}>
+ (value.peg_mm = v ? pegMm : null)}>
{#if value.peg_mm !== null}