diff --git a/Cargo.lock b/Cargo.lock index 2bc6d5b..5584aa3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4822,6 +4822,7 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "ww2ogg", + "zip", ] [[package]] @@ -6983,6 +6984,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..b58f221 100644 --- a/app/src-tauri/src/contract/assets.rs +++ b/app/src-tauri/src/contract/assets.rs @@ -26,6 +26,7 @@ pub use starorg_data::assets::audio::{ }; pub use starorg_data::assets::files::{DirPage, FileEntry, FileSearch, PreviewKind}; pub use starorg_data::assets::model::{ModelPaint, ModelPaints, ModelPreset}; +pub use starorg_data::assets::print::{Hollow, PrintOptions, ScaleMode}; /// Shown next to every export button (and in the CLI help). pub const PERSONAL_USE: &str = @@ -175,7 +176,7 @@ pub struct AssetExportSoundsRequest { pub wem: bool, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AssetExportModelRequest { pub target: ChannelRef, pub what: String, @@ -185,6 +186,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` @@ -194,6 +198,11 @@ pub struct AssetExportModelRequest { /// Full only: StarBreaker's experimental layer materials too. #[serde(default)] pub layers: bool, + /// Print shell only: the experimental 3D print processing of the STL/3MF (every option + /// off by default; `no_weapons` changes the GLB too). Refused (`invalid`) when its options + /// do not go together ([`PrintOptions::validate`]). + #[serde(default)] + pub print: PrintOptions, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/app/src-tauri/src/contract/dev.rs b/app/src-tauri/src/contract/dev.rs index a617f5b..dfd6d5e 100644 --- a/app/src-tauri/src/contract/dev.rs +++ b/app/src-tauri/src/contract/dev.rs @@ -28,7 +28,7 @@ pub use starorg_core::dev::readable::{LabelKind, Readable}; pub use starorg_core::dev::record::{LocText, RecordHeader, RecordView}; pub use starorg_core::dev::sections::{ Change, FacetCounts, FacetValue, Filters, GroupHead, ListGroup, ListItem, ListPage, ListQuery, - Matching, SectionStats, SortKey, Stat, + Matching, SectionStats, SortKey, Stat, TreeOpts, VariantRef, }; /// Records above this count get a size warning in the export dialog (7.4). @@ -79,6 +79,10 @@ pub struct DevTreeRequest { /// Sections view: hide AI, NPC, test and template variants (7.17). #[serde(default)] pub player_only: bool, + /// Sections view: one record leaf per readable name, its `count` the records it + /// stands for (0 when only itself). + #[serde(default)] + pub fold_variants: bool, } /// The item finder's list (7.17): a node of the Sections view (or every record), search diff --git a/app/src-tauri/src/contract/mock_assets.rs b/app/src-tauri/src/contract/mock_assets.rs index 191108c..eb3f778 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,9 +1006,16 @@ 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, + print: req.print.clone(), }; + if req.preset == ModelPreset::PrintShell + && let Err(m) = o.print.validate() + { + return Err(AppError::new(ErrorCode::Invalid, m)); + } let key = format!("model:{}", o.cache_key(&req.what)); let held = self.cache_size(&key); let bytes = held.unwrap_or(match req.preset { @@ -1032,11 +1043,13 @@ 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, + note: print_note(&req), }) } @@ -1230,3 +1243,9 @@ impl AssetBackend for MockBackend { Ok(self.cache_view()) } } + +/// The mock's note for an export with print processing (as the real one's notes would read). +fn print_note(req: &AssetExportModelRequest) -> Option { + (req.preset == ModelPreset::PrintShell && (req.stl || req.three_mf) && !req.print.is_default()) + .then(|| "3D print processing (experimental) applied to the STL/3MF.".to_string()) +} diff --git a/app/src-tauri/src/contract/mock_dev.rs b/app/src-tauri/src/contract/mock_dev.rs index 5c7c513..9bacf41 100644 --- a/app/src-tauri/src/contract/mock_dev.rs +++ b/app/src-tauri/src/contract/mock_dev.rs @@ -945,6 +945,12 @@ pub fn catalogue_geometry(n: usize) -> Option { }) } +/// What catalogue row `r` reads as in game: an AI copy reads as the ship it copies (`Alpha +/// Kestrel`; the ` PU AI CIV` suffix is the record name's only), so the finder folds them. +fn catalogue_display(r: &CatRow) -> &'static str { + r.5.strip_suffix(" PU AI CIV").unwrap_or(r.5) +} + fn catalogue_facts(r: &CatRow) -> Option { let some = |s: &str| (!s.is_empty()).then(|| s.to_string()); (r.0 == E).then(|| Facts { @@ -952,7 +958,7 @@ fn catalogue_facts(r: &CatRow) -> Option { sub_type: some(r.2), size: (r.3 > 0).then_some(r.3), manufacturer: some(r.4), - display: some(r.5), + display: some(catalogue_display(r)), grade: some(r.7), class: some(r.8), model: r.9, @@ -1098,12 +1104,12 @@ fn build_core() -> MockCore { "_Type_": "SItemDefinition", "Type": r.1, "SubType": r.2, "Size": r.3, "Grade": r.7, "Manufacturer": r.4, - "Localization": { "Name": r.5 }, + "Localization": { "Name": catalogue_display(r) }, }, }], }) } else { - json!({ "_Type_": r.0, "displayName": r.5 }) + json!({ "_Type_": r.0, "displayName": catalogue_display(r) }) }; values.push(json!({ "_RecordName_": format!("{}.{name}", r.0), @@ -1651,13 +1657,16 @@ impl DevBackend for MockBackend { fn dev_tree(&self, req: DevTreeRequest) -> CmdResult { let c = self.explorer(&req.target)?; if req.root == TreeRoot::Section { - return Ok(c.sections.tree( + return Ok(c.sections.tree_with( &c.index, &req.node, req.offset as usize, (req.limit as usize).min(MAX_PAGE), - req.main_only, - req.player_only, + TreeOpts { + main_only: req.main_only, + player_only: req.player_only, + fold_variants: req.fold_variants, + }, )); } Ok(c.index.tree( diff --git a/app/src-tauri/src/contract/real/assets.rs b/app/src-tauri/src/contract/real/assets.rs index 3092c1a..9ce4fb4 100644 --- a/app/src-tauri/src/contract/real/assets.rs +++ b/app/src-tauri/src/contract/real/assets.rs @@ -10,7 +10,7 @@ //! the archive index, while a model exports, and while the first sounds request reads the //! DataCore and the Wwise index, so none of these peaks overlap an extraction. -use super::dev::{Worker, WorkerKey, lock_or}; +use super::dev::{Worker, WorkerKey, lock_or, worker_error}; use super::dialogs::FileFilter; use super::{RealBackend, err, internal, io}; use crate::contract::Progress; @@ -134,6 +134,11 @@ fn export_result(path: Option, files: u32, bytes: u64, cached: bool) -> } } +/// The print processing's notes as one line (`None` without any). +fn print_note(notes: &[String]) -> Option { + (!notes.is_empty()).then(|| notes.join(" ")) +} + fn preview_key(path: &str) -> String { starorg_data::assets::norm_path(path).to_ascii_lowercase() } @@ -332,7 +337,11 @@ impl RealBackend { let mut j = lock_or(&cell); j.steps = p.total.max(1); let label = if unit == "%" { - format!("{label} {} %", p.done * 100 / p.total.max(1)) + let pct = p.done * 100 / p.total.max(1); + match p.stage.as_deref() { + Some(s) => format!("{label} {pct} % · {s}"), + None => format!("{label} {pct} %"), + } } else { format!("{} of {} {unit}", p.done, p.total) }; @@ -919,9 +928,14 @@ 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, + print: req.print.clone(), }; + if o.preset == model::ModelPreset::PrintShell { + o.print.validate().map_err(|m| err(ErrorCode::Invalid, m))?; + } let name = if req.name.is_empty() { &req.what } else { @@ -972,20 +986,54 @@ 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 { + let mut notes = Vec::new(); + if (o.stl || o.three_mf) && model::print_memory(&o) == 0 { + // A plain conversion (no voxel solid): cheap enough to do here. 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 m = starorg_data::assets::print::write_meshes(&glb, &out, &o) + .map_err(|e| worker_error(&e.into()))?; + let (n, len) = m.files_bytes(); + files += n; bytes += len; + notes = m.notes; + } else if o.stl || o.three_mf { + // The voxel steps take seconds to minutes and GBs: a fresh worker under the + // memory cap, with progress and cancel, on the copy just made. + let _x = wait_lock(&self.dirs().extract_lock())?; + let w = self.spawn_asset(&ch, &key)?; + let r = self.asset_stream( + &w, + &ch.name, + &format!("Processing model {name} for printing"), + &AssetRequest::PrintModel { + glb: out.clone(), + options: o.clone(), + out: out.clone(), + }, + "%", + progress, + ); + w.stop(); + drop(_x); + let d: model::PrintDone = serde_json::from_value(r?).map_err(internal)?; + let (n, len) = starorg_data::assets::print::files_bytes(&d.meshes); + files += n; + bytes += len; + notes = d.notes; + self.log( + LogLevel::Info, + Some(JobKind::Dev), + Some(&ch.name), + &format!( + "Processed cached model {name} for printing ({} ms, peak memory {} MB)", + d.ms, + d.peak_rss.map(|b| b / 1_048_576).unwrap_or(0) + ), + ); } - return Ok(export_result( - Some(out.display().to_string()), - files, - bytes, - true, - )); + let mut r = export_result(Some(out.display().to_string()), files, bytes, true); + r.note = print_note(¬es); + return Ok(r); } // A fresh worker: the export's memory goes back to the OS when it stops. let _x = wait_lock(&self.dirs().extract_lock())?; @@ -1024,9 +1072,11 @@ 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); - Ok(export_result(Some(d.path), files, bytes, false)) + let (n, len) = starorg_data::assets::print::files_bytes(&d.meshes); + let (files, bytes) = (1 + n, d.bytes + len); + let mut r = export_result(Some(d.path), files, bytes, false); + r.note = print_note(&d.notes); + Ok(r) } fn asset_model_info(&self, req: AssetModelInfoRequest) -> CmdResult { diff --git a/app/src-tauri/src/contract/real/dev.rs b/app/src-tauri/src/contract/real/dev.rs index f5d9b3b..6da7e4a 100644 --- a/app/src-tauri/src/contract/real/dev.rs +++ b/app/src-tauri/src/contract/real/dev.rs @@ -130,7 +130,7 @@ pub(super) fn lock_or(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|p| p.into_inner()) } -fn worker_error(e: &starorg_data::devworker::ReplyError) -> AppError { +pub(super) fn worker_error(e: &starorg_data::devworker::ReplyError) -> AppError { let code = match e.code.as_str() { "not-found" => ErrorCode::NotFound, "invalid" => ErrorCode::Invalid, @@ -1217,6 +1217,7 @@ impl DevBackend for RealBackend { limit: req.limit.min(MAX_PAGE as u32), main_only: req.main_only, player_only: req.player_only, + fold_variants: req.fold_variants, }) } diff --git a/app/src-tauri/src/contract/tests_assets.rs b/app/src-tauri/src/contract/tests_assets.rs index 06e7d5c..569dc8a 100644 --- a/app/src-tauri/src/contract/tests_assets.rs +++ b/app/src-tauri/src/contract/tests_assets.rs @@ -20,6 +20,28 @@ fn live() -> ChannelRef { fn noop(_: JobProgress) {} +/// Every print option on (a valid combination). +fn print_example() -> PrintOptions { + PrintOptions { + scale: ScaleMode::FitMm(150.0), + bed_mm: [256.0, 256.0, 256.0], + shrink_to_bed: true, + drop_small_mm: Some(1.0), + solid: true, + solid_res_mm: 0.2, + thicken_mm: Some(0.8), + hollow: Some(Hollow { + wall_mm: 2.0, + drain_mm: 3.0, + }), + peg_mm: Some(5.0), + split: true, + multicolor: true, + simplify_tris: Some(200_000), + no_weapons: true, + } +} + fn dev_mock() -> MockBackend { let b = MockBackend::default(); let mut s = b.get_settings().unwrap(); @@ -215,9 +237,11 @@ pub(super) fn asset_samples() -> Vec<(&'static str, Value)> { preset, lod, stl, + three_mf: stl, force: false, paint: None, layers: false, + print: PrintOptions::default(), }; put( "asset_export_model", @@ -264,6 +288,30 @@ pub(super) fn asset_samples() -> Vec<(&'static str, Value)> { .unwrap() ), ); + put( + "asset_export_model_print", + json!( + b.asset_export_model( + AssetExportModelRequest { + three_mf: true, + print: print_example(), + ..model(ModelPreset::PrintShell, 0, false) + }, + &noop + ) + .unwrap() + ), + ); + put("print_options_default", json!(PrintOptions::default())); + put("print_options_example", json!(print_example())); + put( + "print_scale_modes", + json!([ + ScaleMode::None, + ScaleMode::FitMm(150.0), + ScaleMode::Ratio(100) + ]), + ); let info = |what: String| AssetModelInfoRequest { target: live(), what, @@ -451,9 +499,11 @@ 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, + print: PrintOptions::default(), }, &noop, ) @@ -539,9 +589,11 @@ 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, + print: PrintOptions::default(), }, &noop, ) @@ -663,9 +715,11 @@ 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, + print: PrintOptions::default(), }, &noop, ) @@ -796,9 +850,11 @@ 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, + print: PrintOptions::default(), }; let r = b .asset_export_model(req(ModelPreset::Full, "syn_ship_002blackgold"), &noop) @@ -828,3 +884,90 @@ fn a_full_export_wears_a_paint_and_refuses_one_the_ship_lacks() { .is_empty() ); } + +#[test] +fn a_model_export_takes_print_options_and_refuses_ones_that_do_not_go_together() { + let b = dev_mock(); + let req = |print: PrintOptions| AssetExportModelRequest { + target: live(), + what: ship_guid(2), + name: "SYN_Ship_002".into(), + preset: ModelPreset::PrintShell, + lod: 0, + stl: true, + three_mf: true, + force: false, + paint: None, + layers: false, + print, + }; + // No weapons changes the GLB, so its file name and cache key. + let r = b + .asset_export_model( + req(PrintOptions { + no_weapons: true, + ..Default::default() + }), + &noop, + ) + .unwrap(); + assert!( + r.path + .unwrap() + .ends_with("SYN_Ship_002-print-lod0-noweapons.glb") + ); + assert!(r.note.unwrap().contains("experimental")); + // The other options change only the STL/3MF: same GLB name, no note without them. + let plain = b + .asset_export_model(req(PrintOptions::default()), &noop) + .unwrap(); + assert!(plain.path.unwrap().ends_with("SYN_Ship_002-print-lod0.glb")); + assert_eq!(plain.note, None); + let e = b + .asset_export_model( + req(PrintOptions { + split: true, + ..Default::default() + }), + &noop, + ) + .unwrap_err(); + assert_eq!(e.code, ErrorCode::Invalid); + assert!(e.message.contains("--split needs --solid"), "{}", e.message); + // A Full export ignores them (as a Print shell ignores paints). + let full = b + .asset_export_model( + AssetExportModelRequest { + preset: ModelPreset::Full, + lod: 1, + stl: false, + three_mf: false, + ..req(PrintOptions { + split: true, + no_weapons: true, + ..Default::default() + }) + }, + &noop, + ) + .unwrap(); + assert!(full.path.unwrap().ends_with("SYN_Ship_002-full-lod1.glb")); +} + +#[test] +fn a_model_request_without_print_or_with_part_of_it_takes_the_defaults() { + let base = json!({ + "target": { "install": "inst-7f3a", "channel": "LIVE" }, + "what": "x", "name": "", "preset": "print-shell", "lod": 0, "stl": true, "force": false + }); + let r: AssetExportModelRequest = serde_json::from_value(base.clone()).unwrap(); + assert_eq!(r.print, PrintOptions::default()); + let mut part = base; + part["print"] = json!({ "solid": true, "scale": { "mode": "fit-mm", "value": 120 } }); + let r: AssetExportModelRequest = serde_json::from_value(part).unwrap(); + assert!(r.print.solid); + assert_eq!(r.print.scale, ScaleMode::FitMm(120.0)); + assert_eq!(r.print.bed_mm, [256.0; 3]); + assert_eq!(r.print.solid_res_mm, 0.2); + assert_eq!(r.print.validate(), Ok(())); +} diff --git a/app/src-tauri/src/contract/tests_dev.rs b/app/src-tauri/src/contract/tests_dev.rs index 1fe94ef..09a02f0 100644 --- a/app/src-tauri/src/contract/tests_dev.rs +++ b/app/src-tauri/src/contract/tests_dev.rs @@ -29,6 +29,7 @@ fn dev_mock() -> MockBackend { fn tree(root: TreeRoot, node: &str, limit: u32) -> DevTreeRequest { DevTreeRequest { + fold_variants: false, player_only: false, target: live(), root, @@ -282,6 +283,34 @@ pub(super) fn dev_samples() -> Vec<(&'static str, Value)> { let models = b .dev_tree(tree(TreeRoot::Section, "m:models:[]", 50)) .unwrap(); + // The Spaceships leaf: `Alpha Kestrel` folds its AI copy. + let mut node = ships_id.clone(); + let leaves = loop { + let page = b.dev_tree(tree(TreeRoot::Section, &node, 50)).unwrap(); + // The biggest group at each level (Vehicles, Spaceships, Alpha). + let biggest = page + .nodes + .iter() + .filter(|n| n.kind == NodeKind::Folder) + .max_by_key(|n| n.count); + match biggest { + Some(n) => node = n.id.clone(), + None => break node.clone(), + } + }; + let tree_folded = b + .dev_tree(DevTreeRequest { + fold_variants: true, + ..tree(TreeRoot::Section, &leaves, 50) + }) + .unwrap(); + let list_folded = list(ListQuery { + node: ships_id.clone(), + limit: 10, + main_only: true, + fold_variants: true, + ..Default::default() + }); let list_all = list(ListQuery { limit: 5, main_only: true, @@ -368,6 +397,8 @@ pub(super) fn dev_samples() -> Vec<(&'static str, Value)> { ("dev_tree_sections", json!(sections)), ("dev_tree_section", json!(ships)), ("dev_tree_models", json!(models)), + ("dev_tree_folded", json!(tree_folded)), + ("dev_list_folded", json!(list_folded)), ("dev_list", json!(list_all)), ("dev_list_node", json!(list_node)), ("dev_list_query", json!(list_query)), diff --git a/app/src-tauri/tests/real_assets.rs b/app/src-tauri/tests/real_assets.rs index 0de825c..68b2626 100644 --- a/app/src-tauri/tests/real_assets.rs +++ b/app/src-tauri/tests/real_assets.rs @@ -391,9 +391,11 @@ 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, + print: PrintOptions::default(), } }; let e = f diff --git a/app/src-tauri/tests/real_dev.rs b/app/src-tauri/tests/real_dev.rs index 3f2839d..d9a2801 100644 --- a/app/src-tauri/tests/real_dev.rs +++ b/app/src-tauri/tests/real_dev.rs @@ -322,6 +322,7 @@ fn the_worker_starts_answers_exports_and_stops() { let types = f .backend .dev_tree(DevTreeRequest { + fold_variants: false, player_only: false, target: live.clone(), root: TreeRoot::Type, @@ -335,6 +336,7 @@ fn the_worker_starts_answers_exports_and_stops() { let items = f .backend .dev_tree(DevTreeRequest { + fold_variants: false, player_only: false, target: live.clone(), root: TreeRoot::Type, @@ -579,6 +581,7 @@ fn the_worker_serves_sections_list_owner_and_compare() { let root = f .backend .dev_tree(DevTreeRequest { + fold_variants: false, player_only: true, target: live.clone(), root: TreeRoot::Section, diff --git a/app/src/components/assets/AssetPanel.svelte b/app/src/components/assets/AssetPanel.svelte index a1c6bf2..00d3d0a 100644 --- a/app/src/components/assets/AssetPanel.svelte +++ b/app/src/components/assets/AssetPanel.svelte @@ -12,12 +12,16 @@ 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'; import ErrorState from '@/components/common/ErrorState.svelte'; import JobProgress from '@/components/common/JobProgress.svelte'; + import PrintSection from '@/components/assets/PrintSection.svelte'; + import { defaultPrintOptions, isDefaultPrint, loadBed, printProblem } from '@/lib/printoptions'; import { assetApi, bytesText, DEFAULT_LOD, hasModel, MAX_LOD, paintLabel, PERSONAL_USE, soundId, type ModelPaints, type ModelPreset, type RecordSounds, type SoundInfo } from '@/lib/contract/assets'; import { toContractError, type ContractError } from '@/lib/contract/client'; import type { ChannelRef } from '@/lib/contract/types'; @@ -87,6 +91,11 @@ let preset = $state('print-shell'); let lod = $state(0); let stl = $state(false); + let threeMf = $state(false); + /** Print shell with an STL or 3MF: the experimental 3D print options (bed size remembered). */ + let print = $state({ ...defaultPrintOptions(), bed_mm: loadBed() }); + const printShown = $derived(preset === 'print-shell' && (stl || threeMf)); + const printBlock = $derived(printShown ? printProblem(print) : null); /** Full only: the paint ('' = the fitted one) and StarBreaker's layer materials. */ let paint = $state(''); let layers = $state(false); @@ -97,7 +106,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 +144,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 +154,9 @@ 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 p = $state.snapshot(print); + const withPrint = printShown && !isDefaultPrint(p) ? { print: p } : {}; + 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, ...withPrint }); 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 +255,10 @@ (stl = v)} disabled={preset === 'full'} /> + (threeMf = v)} disabled={preset === 'full'}> + + + {#if printShown}{/if} {#if preset === 'full'}