diff --git a/.gitattributes b/.gitattributes index 12adf75e..de2d0fd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,4 @@ *.ico binary *.icns binary *.ps1 text eol=crlf +*.tcraft binary diff --git a/assets/samples/Material Ball.tcraft b/assets/samples/Material Ball.tcraft new file mode 100644 index 00000000..915697f3 Binary files /dev/null and b/assets/samples/Material Ball.tcraft differ diff --git a/assets/samples/README.md b/assets/samples/README.md new file mode 100644 index 00000000..ae44e7c8 --- /dev/null +++ b/assets/samples/README.md @@ -0,0 +1,9 @@ +# Sample projects + +Projects that ship with TextureCraft and are offered by File > Open Sample Project. + +- `Material Ball.tcraft`: the material ball with smart materials on both texture sets, generated by + TextureCraft's own `sample_session` (1024 px textures, mesh maps baked at 256 px to keep the file small). + +The app embeds these files and copies each into the `Samples` folder of the data folder the first +time the entry is used. A file that is already there is never overwritten. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 09a8a3bd..23c6b489 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -97,7 +97,7 @@ pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use log::{LogEntry, LogLevel, SessionLog}; pub use path_tool::PathState; -pub use project_cmds::{SAMPLE_BAKE_RESOLUTION_PX, SAMPLE_PROJECT_NAME, SAMPLE_RESOLUTION_PX, sample_session}; +pub use project_cmds::sample_session; pub use session::{ CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, NORMAL_HEIGHT_MESH_LABEL, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, stroke_template, diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 33d2861d..33432cda 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -57,18 +57,9 @@ fn material(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": l.0 })) } -/// Name of the sample project, which is also the stem of its project file -pub const SAMPLE_PROJECT_NAME: &str = "Material Ball"; - -/// Texture size of the sample project the Open Sample Project menu entry offers -pub const SAMPLE_RESOLUTION_PX: u32 = 2048; - -/// Bake size of the sample project the Open Sample Project menu entry offers -pub const SAMPLE_BAKE_RESOLUTION_PX: u32 = 1024; - /// A baked material ball with smart materials on both texture sets pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result { - let mut session = Session::new_project(SAMPLE_PROJECT_NAME, primitives::material_ball(), "builtin:material_ball", None, resolution)?; + let mut session = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?; for set_index in 0..session.set_count() { let set = session.doc.project.texture_set_mut(set_index)?; set.bake.common.resolution = BakeResolution::from_pixels(bake_resolution).ok_or_else(|| bad("project.sample", "invalid bake resolution"))?; @@ -100,7 +91,7 @@ pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result } fn sample(s: &mut Session, _: &Value) -> Result { - let next = sample_session(SAMPLE_RESOLUTION_PX, SAMPLE_BAKE_RESOLUTION_PX)?; + let next = sample_session(2048, 1024)?; s.switch_to(next); Ok(crate::inspect::session(s)) } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4487f7f2..48316b84 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -248,9 +248,6 @@ pub struct TextureCraftApp { /// The folder File > Open Sample Project starts in, under the data folder #[cfg(not(target_arch = "wasm32"))] pub samples_folder: std::path::PathBuf, - /// The sample project being written in the background - #[cfg(not(target_arch = "wasm32"))] - pub(crate) sample_preparation: Option, viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds, /// A smooth move to a saved camera in progress. camera_glide: Option, @@ -406,8 +403,6 @@ impl TextureCraftApp { session_log_file: None, #[cfg(not(target_arch = "wasm32"))] samples_folder: std::path::PathBuf::new(), - #[cfg(not(target_arch = "wasm32"))] - sample_preparation: None, viewport_mesh_bounds: viewport_mesh_bounds::ViewportMeshBounds::default(), ui, ui_store, @@ -1101,10 +1096,7 @@ impl eframe::App for TextureCraftApp { control::poll(self, ctx); #[cfg(not(target_arch = "wasm32"))] - { - self.run_file_dialog_answers(); - self.poll_sample_project(); - } + self.run_file_dialog_answers(); web_files::poll(self); let dropped = ctx.input(|input| input.raw.dropped_files.clone()); diff --git a/crates/ui-egui/src/sample_project.rs b/crates/ui-egui/src/sample_project.rs index 7c308732..48f8937a 100644 --- a/crates/ui-egui/src/sample_project.rs +++ b/crates/ui-egui/src/sample_project.rs @@ -1,118 +1,33 @@ -//! The sample project File > Open Sample Project offers: written once into the Samples folder. +//! The sample projects File > Open Sample Project offers: the ones shipped inside the app, copied +//! into the Samples folder of the data folder so the file picker can show them. -use std::path::{Path, PathBuf}; -use std::sync::mpsc::{Receiver, TryRecvError, channel}; - -use texturecraft_engine::core::PROJECT_EXT; -use texturecraft_engine::{SAMPLE_BAKE_RESOLUTION_PX, SAMPLE_PROJECT_NAME, SAMPLE_RESOLUTION_PX, sample_session}; - -use crate::TextureCraftApp; -use crate::file_dialogs::{Bound, FileDialog}; -use crate::i18n::{tr, trf}; +use std::path::Path; /// The folder under the data folder that holds the sample projects pub(crate) const SAMPLES_FOLDER: &str = "Samples"; -/// The error when the background thread ends without sending its result -const STOPPED_WITHOUT_ANSWER: &str = "the preparation stopped without an answer"; - -/// The background job that writes the sample project file -pub(crate) type SamplePreparation = Receiver>; - -/// The sample project's file in `folder` -fn sample_file(folder: &Path) -> PathBuf { - folder.join(format!("{SAMPLE_PROJECT_NAME}.{PROJECT_EXT}")) +/// A sample project that ships inside the app (`assets/samples`) +struct ShippedSample { + file_name: &'static str, + bytes: &'static [u8], } -/// Makes sure `folder` exists and holds the built-in sample project, and returns the file. -/// A file that is already there is kept as it is, so a sample the user edited and saved stays. -fn ensure_sample_project(folder: &Path) -> Result { +const SHIPPED_SAMPLES: &[ShippedSample] = + &[ShippedSample { file_name: "Material Ball.tcraft", bytes: include_bytes!("../../../assets/samples/Material Ball.tcraft") }]; + +/// Makes sure `folder` exists and holds every shipped sample. A file that is already there is +/// kept as it is, so a sample the user edited and saved stays. +pub(crate) fn install(folder: &Path) -> Result<(), String> { std::fs::create_dir_all(folder).map_err(|error| format!("{}: {error}", folder.display()))?; - let file = sample_file(folder); - if file.exists() { - return Ok(file); + for sample in SHIPPED_SAMPLES { + let file = folder.join(sample.file_name); + if file.exists() { + continue; + } + + texturecraft_engine::formats::write_atomic(&file, sample.bytes).map_err(|error| format!("{}: {error}", file.display()))?; } - let session = sample_session(SAMPLE_RESOLUTION_PX, SAMPLE_BAKE_RESOLUTION_PX).map_err(|error| error.to_string())?; - let bytes = session.to_project_bytes().map_err(|error| error.to_string())?; - - // Baking takes a while, so look again before writing in case the file appeared meanwhile - if file.exists() { - return Ok(file); - } - - texturecraft_engine::formats::write_atomic(&file, &bytes).map_err(|error| format!("{}: {error}", file.display()))?; - - Ok(file) -} - -impl TextureCraftApp { - /// File > Open Sample Project: the file picker, in the Samples folder. A missing sample is - /// written on a background thread first, and the picker opens when that is done. - pub(crate) fn open_sample_project(&mut self, ctx: &egui::Context) { - if self.sample_preparation.is_some() { - return; - } - - let folder = self.samples_folder.clone(); - if sample_file(&folder).exists() { - self.ask_for_sample_project(Some(folder)); - return; - } - - self.toast(tr("Preparing the sample project..."), false); - let (sender, receiver) = channel(); - let ctx = ctx.clone(); - std::thread::spawn(move || { - // The receiver is gone only when the app closed - let _ = sender.send(ensure_sample_project(&folder)); - ctx.request_repaint(); - }); - self.sample_preparation = Some(receiver); - } - - /// Whether the sample project is being written - pub fn sample_project_pending(&self) -> bool { - self.sample_preparation.is_some() - } - - /// Takes the finished sample preparation, if any, and opens the picker. Called every frame. - pub(crate) fn poll_sample_project(&mut self) { - let Some(receiver) = &self.sample_preparation else { return }; - - match receiver.try_recv() { - Ok(result) => self.finish_sample_project(result), - Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => self.finish_sample_project(Err(STOPPED_WITHOUT_ANSWER.to_string())), - } - } - - /// Waits for the sample preparation to end and opens the picker, so tests need no timing. - pub fn wait_for_sample_project(&mut self) { - let Some(receiver) = &self.sample_preparation else { return }; - - let result = receiver.recv().unwrap_or_else(|_| Err(STOPPED_WITHOUT_ANSWER.to_string())); - self.finish_sample_project(result); - } - - fn finish_sample_project(&mut self, result: Result) { - self.sample_preparation = None; - match result { - Ok(_) => self.ask_for_sample_project(Some(self.samples_folder.clone())), - Err(error) => { - self.toast(trf("Could not prepare the sample project: {error}", &[("error", &error)]), true); - self.ask_for_sample_project(None); - } - } - } - - fn ask_for_sample_project(&mut self, folder: Option) { - let dialog = FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[PROJECT_EXT]); - let dialog = match folder { - Some(folder) => dialog.directory(folder), - None => dialog, - }; - self.ask_file(dialog, Bound::App, crate::windows::open_picked); - } + Ok(()) } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 67505772..19499845 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -539,7 +539,7 @@ pub(crate) fn import_materialx(app: &mut TextureCraftApp, path: &str) -> bool { /// File menu actions that need dialogs. Returns true when handled. #[cfg(not(target_arch = "wasm32"))] -pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) -> bool { +pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> bool { match id { "file.open" => { let dialog = FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS); @@ -547,7 +547,15 @@ pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) -> true } "project.sample" => { - app.open_sample_project(ctx); + let dialog = FileDialog::open().title(tr("Open Sample Project")).filter(tr("TextureCraft project"), &[texturecraft_engine::core::PROJECT_EXT]); + let dialog = match crate::sample_project::install(&app.samples_folder) { + Ok(()) => dialog.directory(app.samples_folder.clone()), + Err(error) => { + app.toast(trf("Could not prepare the sample project: {error}", &[("error", &error)]), true); + dialog + } + }; + app.ask_file(dialog, Bound::App, open_picked); true } "file.save" if app.session.path.is_some() => { @@ -629,7 +637,7 @@ pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) -> /// Opens the project or mesh a file dialog picked #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn open_picked(app: &mut TextureCraftApp, paths: Vec) { +fn open_picked(app: &mut TextureCraftApp, paths: Vec) { if let Some(path) = paths.first() { open_path(app, &path.display().to_string()); } diff --git a/crates/ui-egui/tests/it/sample_project.rs b/crates/ui-egui/tests/it/sample_project.rs index 94af23c1..2d9bc426 100644 --- a/crates/ui-egui/tests/it/sample_project.rs +++ b/crates/ui-egui/tests/it/sample_project.rs @@ -31,41 +31,26 @@ fn answer_with(harness: &mut Harness<'static, TextureCraftApp>, pick: impl Fn(Op started_in } -fn click_open_sample_project(harness: &mut Harness<'static, TextureCraftApp>) { +fn open_sample_menu_entry(harness: &mut Harness<'static, TextureCraftApp>) { let ctx = harness.ctx.clone(); menus::invoke(harness.state_mut(), &ctx, "project.sample"); -} - -/// Clicks the menu entry and lets a background preparation end, so no test waits on a timer -fn open_sample_menu_entry(harness: &mut Harness<'static, TextureCraftApp>) { - click_open_sample_project(harness); - harness.state_mut().wait_for_sample_project(); harness.run_steps(3); } #[test] -fn the_menu_entry_writes_the_sample_and_the_dialog_starts_in_its_folder() { +fn the_menu_entry_copies_the_shipped_sample_and_the_dialog_starts_in_its_folder() { let root = super::temp_dir::TempDir::new("sample-project"); let samples_folder = root.join("Samples"); let mut harness = closed_app(&samples_folder); let started_in = answer_with(&mut harness, |folder| Answer::Paths(vec![folder.unwrap().join(SAMPLE_FILE_NAME)])); - click_open_sample_project(&mut harness); + open_sample_menu_entry(&mut harness); - assert!(harness.state().sample_project_pending(), "the sample is written in the background"); - assert!(started_in.borrow().is_empty(), "the dialog waits for the sample"); - assert!(harness.state().toasts.iter().any(|toast| !toast.error && toast.text.contains("Preparing"))); - - harness.state_mut().wait_for_sample_project(); - harness.run_steps(3); - - assert!(!harness.state().sample_project_pending()); - assert!(samples_folder.join(SAMPLE_FILE_NAME).is_file(), "the sample is written on first use"); + assert!(samples_folder.join(SAMPLE_FILE_NAME).is_file(), "the shipped sample is copied on first use"); assert_eq!(*started_in.borrow(), vec![Some(samples_folder.clone())], "the dialog starts in the Samples folder"); assert!(harness.state().session.project_open, "the picked sample opens"); assert_eq!(harness.state().session.doc.project.name, "Material Ball"); - let reference = texturecraft_engine::sample_session(128, 16).unwrap(); - assert_eq!(harness.state().session.set_count(), reference.set_count(), "the sample keeps its texture sets"); + assert_eq!(harness.state().session.set_count(), 2, "the sample keeps its texture sets"); assert!(!harness.state().session.modified, "an opened sample is a clean file"); } @@ -79,10 +64,7 @@ fn a_file_already_in_the_samples_folder_is_not_overwritten() { let mut harness = closed_app(&samples_folder); let started_in = answer_with(&mut harness, |_| Answer::Cancelled); - click_open_sample_project(&mut harness); - - assert!(!harness.state().sample_project_pending(), "nothing is written when the file is there"); - harness.run_steps(3); + open_sample_menu_entry(&mut harness); assert_eq!(std::fs::read(&existing).unwrap(), b"the user's own file"); assert_eq!(*started_in.borrow(), vec![Some(samples_folder)], "the dialog still starts in the Samples folder"); @@ -102,20 +84,3 @@ fn a_samples_folder_that_cannot_be_made_is_reported_and_the_dialog_still_opens() assert_eq!(*started_in.borrow(), vec![None], "the dialog opens without a start folder"); assert!(!harness.state().session.project_open); } - -#[test] -fn a_second_click_while_the_sample_is_written_does_not_start_another_job() { - let root = super::temp_dir::TempDir::new("sample-project-twice"); - let samples_folder = root.join("Samples"); - let mut harness = closed_app(&samples_folder); - let started_in = answer_with(&mut harness, |_| Answer::Cancelled); - - click_open_sample_project(&mut harness); - click_open_sample_project(&mut harness); - harness.state_mut().wait_for_sample_project(); - harness.run_steps(3); - - let preparing = harness.state().toasts.iter().filter(|toast| toast.text.contains("Preparing")).count(); - assert_eq!(preparing, 1, "one job was started"); - assert_eq!(started_in.borrow().len(), 1, "one dialog was asked"); -} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ea5d8235..40bfab1d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -223,7 +223,7 @@ keeps its state in a throwaway file. | `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled, checked}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window; `ui.resetUi` opens its question; `file.exportMesh` opens the Mesh Export Options prompt, whose Export asks for the file; `ui.view.export` opens the right bar's Export panel). `{"id": "ui.layout.apply", "name": ""}` switches to a legacy named panel layout (still accessible through assigned shortcuts) (panels only; mode, zoom and wireframes stay) and errors when no layout has that name. `ui.layout.save` still saves the active mode; `ui.layout.save.painting`, `ui.layout.save.rendering` and `ui.layout.save.baking` ask where to save only that mode's panels and view arrangement as a JSON file (without preferences or recent projects); loading preserves the other modes, `ui.layout.load` asks for one to load ("Load UI Layout"); `ui.toolbar.docks` and `ui.toolbar.tools` show or hide the right bar and the painting tools; the disabled Snooze Autosave and Resources Updater buttons stay visible when Tools is off; `ui.view.renderer` toggles the Renderer Settings panel (Rendering Mode only). `{"id": "ui.layout.swap"}` swaps the 3D and 2D views of the split layout (F4) | -| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. On the desktop it starts in the `Samples` folder of the data folder (the browser has none), and the first use writes the generated sample (`Material Ball.tcraft`) there; a file that is already there is kept. The direct `project.sample` engine command still creates the generated sample for automation. | +| `ui.menu.invoke` id `project.sample` | `{id}` | File > Open Sample Project opens a file picker for a `.tcraft` project. On the desktop it starts in the `Samples` folder of the data folder (the browser has none), and the first use copies the sample projects that ship with the app (`assets/samples`, `Material Ball.tcraft`) there; a file that is already there is kept. The direct `project.sample` engine command still creates the generated sample for automation. | | `ui.menu.invoke` id `ui.saveAsTemplate` | `{id}` | File > More Save Options > Save As Template opens a save dialog in the user templates folder. The choice supplies the file path and template name to `project.template.save`. `ui.saveReduced` (Save and Reduce File Size) is listed as not implemented and not enabled | | `ui.menu.invoke` ids `ui.help.releaseNotes`, `ui.help.showLog`, `ui.help.exportLog` | `{id}` | Help > Release Notes opens the releases page in the browser; Help > Show Log opens the current desktop run's rolling `log.txt` in the system text-file handler; Help > Export Log exports the session log with each entry’s recorded UTC time, severity and source (a save dialog on desktop with a `Log_TextureCraft____.txt` name, a download on the web) | | `ui.menu.invoke` id `ui.wireframe` | `{id}` | Show mesh wireframe: shows or hides the mesh wireframe in the 3D and 2D views (the Display Settings check box). It has no menu entry and no default key; bind it in Settings > Shortcuts. The key bindings `camera.next` and `camera.previous` (Select next camera `>`, Select previous camera `<`) and `ui.mode.bake` (F8) run the same commands as before | diff --git a/docs/features.md b/docs/features.md index 1ae316df..5e2e7557 100644 --- a/docs/features.md +++ b/docs/features.md @@ -115,7 +115,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**, OBJ, PLY and STL, or a built-in mesh (the `project.new` command; *File › Open sample project...* asks for a - `.tcraft` file; on the desktop it starts in the `Samples` folder of the data folder, which holds the material ball, + `.tcraft` file; on the desktop it starts in the `Samples` folder of the data folder, which holds the sample projects that ship with the app (the material ball), and the browser has no such folder); UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. The