mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-23 07:50:58 +01:00
Auto: Route displayed exports through commands and fix view handling
Use immutable shared display snapshots for PNG saving, OBJ export, and clipboard copying through engine commands and the control channel. Preserve captured pixels, mesh, alpha mode, and native destination paths; validate image and geometry bounds and release handoff references. Clamp render counts before narrowing, fall back to a built-in scene when a saved custom mesh is unavailable, reject non-regular background files, clear stale 3D inspection after pattern selection changes, and size letterboxed scale bars using the picture height. Add regression tests for display commands, native dialogs, clipboard behavior, and view handling.
This commit is contained in:
1 parent
e4b2d0a777
commit
dcb5864647
25 files changed
+562
-42
No files matched your search
Generated
+1
@@ -2861,6 +2861,7 @@ name = "materialcraft-engine"
|
||||
version = "0.4.1"
|
||||
dependencies = [
|
||||
"craft-texture 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a341e86b6d0b31ec5113a4b3e4f07f717a6cf5bf)",
|
||||
"image",
|
||||
"materialcraft-core",
|
||||
"materialcraft-eval",
|
||||
"materialcraft-formats",
|
||||
|
||||
@@ -15,6 +15,7 @@ materialcraft-nodes = { workspace = true }
|
||||
materialcraft-eval = { workspace = true }
|
||||
materialcraft-formats = { workspace = true }
|
||||
materialcraft-geom = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
|
||||
@@ -87,6 +87,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::connection_commands::specs());
|
||||
v.extend(crate::value_input_commands::specs());
|
||||
v.extend(crate::view_cmds::specs());
|
||||
v.extend(crate::display_cmds::specs());
|
||||
v.extend(crate::view3d_commands::specs());
|
||||
v.extend(crate::material_preview_commands::specs());
|
||||
v.extend(crate::wire_cmds::specs());
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Commands that consume the pixels or mesh captured from the displayed view
|
||||
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::commands::strp;
|
||||
use crate::commands::{CommandSpec, always, bad};
|
||||
use crate::{DisplaySnapshot, Result, Session, cmd};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("view.3d.saveRender", "Save displayed render", [], None, "{path} writes the captured displayed RGBA frame as PNG", always, save_render),
|
||||
cmd!("view.3d.exportGeometry", "Export displayed geometry", [], None, "{path} writes the captured displayed mesh as OBJ", always, export_geometry),
|
||||
cmd!(
|
||||
"view.2d.copyImage",
|
||||
"Copy displayed image",
|
||||
[],
|
||||
None,
|
||||
"{} returns the captured displayed RGBA image to the UI clipboard handler",
|
||||
always,
|
||||
copy_image
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
fn take(session: &mut Session, command: &str) -> Result<DisplaySnapshot> {
|
||||
session.display_snapshot.take().ok_or_else(|| bad(command, "no displayed snapshot was supplied"))
|
||||
}
|
||||
|
||||
fn copy_image(session: &mut Session, _: &J) -> Result<J> {
|
||||
const COMMAND: &str = "view.2d.copyImage";
|
||||
let snapshot = take(session, COMMAND)?;
|
||||
let DisplaySnapshot::Image { width, height, ref pixels, premultiplied } = snapshot else {
|
||||
return Err(bad(COMMAND, "a displayed 2D image is required"));
|
||||
};
|
||||
DisplaySnapshot::valid_rgba(COMMAND, width, height, pixels)?;
|
||||
|
||||
session.display_output = Some(snapshot);
|
||||
Ok(json!({"width": width, "height": height, "premultiplied": premultiplied}))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn save_render(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
use image::ImageEncoder as _;
|
||||
|
||||
const COMMAND: &str = "view.3d.saveRender";
|
||||
let snapshot = take(session, COMMAND)?;
|
||||
let DisplaySnapshot::Render { width, height, pixels, path } = snapshot else { return Err(bad(COMMAND, "a displayed 3D frame is required")) };
|
||||
let path = path
|
||||
.or_else(|| strp(parameters, "path").filter(|path| !path.is_empty()).map(std::path::PathBuf::from))
|
||||
.ok_or_else(|| bad(COMMAND, "`path` is required"))?;
|
||||
DisplaySnapshot::valid_rgba(COMMAND, width, height, &pixels)?;
|
||||
|
||||
let mut png = Vec::new();
|
||||
image::codecs::png::PngEncoder::new(&mut png)
|
||||
.write_image(&pixels, width, height, image::ExtendedColorType::Rgba8)
|
||||
.map_err(|error| bad(COMMAND, format!("the render could not be encoded: {error}")))?;
|
||||
materialcraft_formats::write_atomic(&path, &png)?;
|
||||
Ok(json!({"path": path.display().to_string(), "width": width, "height": height}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn save_render(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("view.3d.saveRender", "saving a render by path needs the desktop app"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_geometry(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
const COMMAND: &str = "view.3d.exportGeometry";
|
||||
let snapshot = take(session, COMMAND)?;
|
||||
let DisplaySnapshot::Geometry { mesh, path } = snapshot else { return Err(bad(COMMAND, "a displayed 3D mesh is required")) };
|
||||
let path = path
|
||||
.or_else(|| strp(parameters, "path").filter(|path| !path.is_empty()).map(std::path::PathBuf::from))
|
||||
.ok_or_else(|| bad(COMMAND, "`path` is required"))?;
|
||||
DisplaySnapshot::valid_geometry(COMMAND, &mesh)?;
|
||||
|
||||
let text = materialcraft_formats::mesh::obj_text(&mesh);
|
||||
materialcraft_formats::write_atomic(&path, text.as_bytes())?;
|
||||
Ok(json!({"path": path.display().to_string(), "triangles": mesh.triangle_count()}))
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn export_geometry(_: &mut Session, _: &J) -> Result<J> {
|
||||
Err(bad("view.3d.exportGeometry", "exporting geometry by path needs the desktop app"))
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//! The displayed pixels or mesh handed to one command without recooking or changing the view
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use materialcraft_geom::Mesh;
|
||||
|
||||
use crate::Result;
|
||||
use crate::commands::bad;
|
||||
|
||||
/// One immutable view snapshot, shared with the view only until its command returns
|
||||
pub enum DisplaySnapshot {
|
||||
Render { width: u32, height: u32, pixels: Arc<Vec<u8>>, path: Option<PathBuf> },
|
||||
Geometry { mesh: Arc<Mesh>, path: Option<PathBuf> },
|
||||
Image { width: u32, height: u32, pixels: Arc<Vec<u8>>, premultiplied: bool },
|
||||
}
|
||||
|
||||
impl DisplaySnapshot {
|
||||
/// The UI's retained render buffer, captured before a save dialog opens
|
||||
pub fn render(width: u32, height: u32, pixels: Arc<Vec<u8>>) -> Self {
|
||||
Self::Render { width, height, pixels, path: None }
|
||||
}
|
||||
|
||||
/// Keep the exact native destination selected by a file dialog
|
||||
pub fn render_to(width: u32, height: u32, pixels: Arc<Vec<u8>>, path: PathBuf) -> Self {
|
||||
Self::Render { width, height, pixels, path: Some(path) }
|
||||
}
|
||||
|
||||
/// The mesh belonging to the displayed frame, including any relief
|
||||
pub fn geometry(mesh: Arc<Mesh>) -> Self {
|
||||
Self::Geometry { mesh, path: None }
|
||||
}
|
||||
|
||||
/// Keep the exact native destination selected by a file dialog
|
||||
pub fn geometry_to(mesh: Arc<Mesh>, path: PathBuf) -> Self {
|
||||
Self::Geometry { mesh, path: Some(path) }
|
||||
}
|
||||
|
||||
/// The RGBA bytes already prepared for the 2D view and clipboard
|
||||
pub fn image(width: u32, height: u32, pixels: Arc<Vec<u8>>, premultiplied: bool) -> Self {
|
||||
Self::Image { width, height, pixels, premultiplied }
|
||||
}
|
||||
|
||||
pub fn into_image(self) -> Option<(u32, u32, Arc<Vec<u8>>, bool)> {
|
||||
match self {
|
||||
Self::Image { width, height, pixels, premultiplied } => Some((width, height, pixels, premultiplied)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn valid_rgba(command: &str, width: u32, height: u32, pixels: &[u8]) -> Result<()> {
|
||||
const MAX_IMAGE_SIDE: u32 = 8192;
|
||||
if width == 0 || height == 0 || width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
|
||||
return Err(bad(command, format!("displayed image dimensions must be 1..={MAX_IMAGE_SIDE}")));
|
||||
}
|
||||
|
||||
let expected = usize::try_from(u64::from(width) * u64::from(height) * 4).map_err(|_| bad(command, "displayed image is too large"))?;
|
||||
if pixels.len() != expected {
|
||||
return Err(bad(command, format!("displayed RGBA has {} bytes; expected {expected}", pixels.len())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn valid_geometry(command: &str, mesh: &Mesh) -> Result<()> {
|
||||
const MAX_EXPORT_TRIANGLES: usize = 1_000_000;
|
||||
const MAX_EXPORT_VERTICES: usize = 3_000_000;
|
||||
if mesh.positions.is_empty()
|
||||
|| mesh.indices.is_empty()
|
||||
|| mesh.indices.len() > MAX_EXPORT_TRIANGLES * 3
|
||||
|| mesh.positions.len() > MAX_EXPORT_VERTICES
|
||||
|| mesh.uvs.len() > MAX_EXPORT_VERTICES
|
||||
|| mesh.normals.len() > MAX_EXPORT_VERTICES
|
||||
|| !mesh.indices.len().is_multiple_of(3)
|
||||
|| mesh.indices.iter().any(|index| *index as usize >= mesh.positions.len())
|
||||
|| mesh.positions.iter().any(|position| !position.is_finite())
|
||||
|| mesh.uvs.iter().any(|uv| !uv.is_finite())
|
||||
|| mesh.normals.iter().any(|normal| !normal.is_finite())
|
||||
{
|
||||
return Err(bad(command, "displayed mesh is empty, invalid or exceeds the export size limit"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
extern crate self as materialcraft_engine;
|
||||
|
||||
mod decoded_images;
|
||||
mod display_snapshot;
|
||||
pub use display_snapshot::DisplaySnapshot;
|
||||
mod display_cmds;
|
||||
mod document_path;
|
||||
mod evaluation_environment_commands;
|
||||
mod explorer_clipboard;
|
||||
|
||||
@@ -9,7 +9,7 @@ use materialcraft_eval::{Cache, Cooked, Options};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::snapshot::Snapshot;
|
||||
use crate::{AnnotationSelection, Clip, EngineError, Result, View2d, View3d};
|
||||
use crate::{AnnotationSelection, Clip, DisplaySnapshot, EngineError, Result, View2d, View3d};
|
||||
|
||||
/// The 3D view's camera preferences. The app keeps them in its preferences (Edit ▸ Preferences)
|
||||
/// and pushes them in with [`Session::set_camera_prefs`]; headless sessions use the defaults.
|
||||
@@ -98,6 +98,8 @@ pub struct Session {
|
||||
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
|
||||
/// Changes on each successful mesh load, including loads under the same name
|
||||
pub custom_mesh_generation: u64,
|
||||
pub(crate) display_snapshot: Option<DisplaySnapshot>,
|
||||
pub(crate) display_output: Option<DisplaySnapshot>,
|
||||
/// The node library loaded from the SBS library folder
|
||||
pub library: Arc<crate::node_library::NodeLibrary>,
|
||||
pub(crate) history: crate::document_history::DocumentHistory,
|
||||
@@ -158,6 +160,8 @@ impl Session {
|
||||
cache: Arc::new(Mutex::new(Cache::default())),
|
||||
custom_mesh: None,
|
||||
custom_mesh_generation: 0,
|
||||
display_snapshot: None,
|
||||
display_output: None,
|
||||
library: Default::default(),
|
||||
history: Default::default(),
|
||||
group: None,
|
||||
@@ -177,6 +181,18 @@ impl Session {
|
||||
session
|
||||
}
|
||||
|
||||
/// Hand one immutable displayed snapshot to the next command
|
||||
pub fn begin_display_handoff(&mut self, snapshot: DisplaySnapshot) {
|
||||
self.display_snapshot = Some(snapshot);
|
||||
self.display_output = None;
|
||||
}
|
||||
|
||||
/// Release an unused input and return a clipboard result after the command finishes
|
||||
pub fn finish_display_handoff(&mut self) -> Option<DisplaySnapshot> {
|
||||
self.display_snapshot = None;
|
||||
self.display_output.take()
|
||||
}
|
||||
|
||||
/// The graph being edited.
|
||||
pub fn graph(&self) -> Result<&Graph> {
|
||||
self.pkg.graph(self.graph).map_err(EngineError::from)
|
||||
|
||||
@@ -120,8 +120,9 @@ pub(crate) fn updated(session: &Session, parameters: &J) -> Result<View3d> {
|
||||
view.far_clip = number("farClip", view.far_clip, View3d::CLIP).max(view.near_clip);
|
||||
view.yaw = f32p(parameters, "yaw").map_or(view.yaw, |yaw| yaw.rem_euclid(360.0));
|
||||
view.env_rotation = f32p(parameters, "envRotation").map_or(view.env_rotation, |rotation| rotation.rem_euclid(360.0));
|
||||
view.samples = u64p(parameters, "samples").map_or(view.samples, |samples| (samples as u32).clamp(1, View3d::MAX_SAMPLES));
|
||||
view.ambient_occlusion = u64p(parameters, "ambientOcclusion").map_or(view.ambient_occlusion, |rays| (rays as u32).min(View3d::MAX_AMBIENT_OCCLUSION));
|
||||
view.samples = u64p(parameters, "samples").map_or(view.samples, |samples| samples.clamp(1, u64::from(View3d::MAX_SAMPLES)) as u32);
|
||||
view.ambient_occlusion =
|
||||
u64p(parameters, "ambientOcclusion").map_or(view.ambient_occlusion, |rays| rays.min(u64::from(View3d::MAX_AMBIENT_OCCLUSION)) as u32);
|
||||
if let Some(scale) = u64p(parameters, "renderScale") {
|
||||
view.render_scale =
|
||||
View3d::RENDER_SCALES.into_iter().find(|allowed| u64::from(*allowed) == scale).ok_or_else(|| rejected("`renderScale` is 25, 50, 100 or 200"))?;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use materialcraft_core::NodeId;
|
||||
use materialcraft_geom::view::View3d;
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, has_graph, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
@@ -52,7 +53,11 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("view.3d.loadMesh", "Load mesh...", [], None, "{path} shows an OBJ, glTF or GLB mesh in the 3D view (scene \"custom\")", always, load_mesh),
|
||||
cmd!("view.3d.reset", "Reset scene", [], None, "{} back to the saved default view, or the built-in one", always, |s, _| {
|
||||
s.view3d = s.default_view3d.clone().unwrap_or_default();
|
||||
let mut view = s.default_view3d.clone().unwrap_or_default();
|
||||
if view.scene == "custom" && s.custom_mesh.is_none() {
|
||||
view.scene = View3d::default().scene;
|
||||
}
|
||||
s.view3d = view;
|
||||
Ok(J::Null)
|
||||
}),
|
||||
cmd!("view.previewSize", "Preview size", [], None, "{size: 64..8192, or 0 for full size} caps node outputs while editing", always, preview_size),
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use materialcraft_engine::{DisplaySnapshot, commands, execute, geom, new_session};
|
||||
use serde_json::json;
|
||||
|
||||
fn path(name: &str) -> std::path::PathBuf {
|
||||
std::env::temp_dir().join(format!("materialcraft-display-command-{}-{name}", std::process::id()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displayed_actions_are_registered_and_require_a_snapshot() {
|
||||
let mut session = new_session();
|
||||
for id in ["view.3d.saveRender", "view.3d.exportGeometry", "view.2d.copyImage"] {
|
||||
assert!(commands::find(id).is_some(), "{id} is missing from the shared command catalog");
|
||||
assert!(commands::list(&session, Some(id)).as_array().is_some_and(|commands| commands.iter().any(|command| command["id"] == id)));
|
||||
assert!(execute(&mut session, id, &json!({"path": path("missing")})).is_err(), "{id} accepted a missing snapshot");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_command_writes_the_captured_rgba_after_the_view_changes() {
|
||||
let mut session = new_session();
|
||||
let pixels = Arc::new(vec![3, 17, 29, 255, 200, 101, 50, 128]);
|
||||
let saved = path("frame.png");
|
||||
execute(&mut session, "view.3d", &json!({"scene": "sphere"})).unwrap();
|
||||
session.begin_display_handoff(DisplaySnapshot::render(2, 1, pixels.clone()));
|
||||
|
||||
let result = execute(&mut session, "view.3d.saveRender", &json!({"path": saved})).unwrap();
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64()), (Some(2), Some(1)));
|
||||
assert!(session.finish_display_handoff().is_none());
|
||||
assert_eq!(Arc::strong_count(&pixels), 1, "the command retained a frame after writing it");
|
||||
let written = image::load_from_memory(&std::fs::read(&saved).unwrap()).unwrap().to_rgba8();
|
||||
assert_eq!((written.width(), written.height(), written.as_raw()), (2, 1, pixels.as_ref()));
|
||||
std::fs::remove_file(saved).unwrap();
|
||||
|
||||
let invalid = path("invalid.png");
|
||||
session.begin_display_handoff(DisplaySnapshot::render(2, 1, Arc::new(vec![1, 2, 3])));
|
||||
assert!(execute(&mut session, "view.3d.saveRender", &json!({"path": invalid})).is_err());
|
||||
assert!(session.finish_display_handoff().is_none());
|
||||
assert!(!invalid.exists(), "invalid RGBA wrote a partial file");
|
||||
|
||||
session.begin_display_handoff(DisplaySnapshot::render(8193, 1, Arc::new(vec![0; 8193 * 4])));
|
||||
let error = execute(&mut session, "view.3d.saveRender", &json!({"path": invalid})).unwrap_err();
|
||||
assert!(error.to_string().contains("dimensions"), "{error}");
|
||||
assert!(!invalid.exists(), "an over-limit frame wrote a partial file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometry_command_writes_only_the_captured_mesh() {
|
||||
let mut session = new_session();
|
||||
let mesh = Arc::new(geom::primitives::cube(1.0));
|
||||
let expected = geom::primitives::sphere(1.0, 8, 4);
|
||||
let saved = path("mesh.obj");
|
||||
session.begin_display_handoff(DisplaySnapshot::geometry(mesh.clone()));
|
||||
session.custom_mesh = Some(("newer".into(), Arc::new(expected)));
|
||||
|
||||
execute(&mut session, "view.3d.exportGeometry", &json!({"path": saved})).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&saved).unwrap(), materialcraft_engine::formats::mesh::obj_text(&mesh));
|
||||
assert!(session.finish_display_handoff().is_none());
|
||||
assert_eq!(Arc::strong_count(&mesh), 1, "the command retained a mesh after writing it");
|
||||
std::fs::remove_file(saved).unwrap();
|
||||
|
||||
let mut invalid = geom::primitives::cube(1.0);
|
||||
invalid.positions[0].x = f32::INFINITY;
|
||||
session.begin_display_handoff(DisplaySnapshot::geometry(Arc::new(invalid)));
|
||||
let invalid_path = path("invalid-mesh.obj");
|
||||
assert!(execute(&mut session, "view.3d.exportGeometry", &json!({"path": invalid_path})).is_err());
|
||||
assert!(!invalid_path.exists(), "non-finite geometry wrote a partial file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_command_returns_the_same_display_buffer_and_alpha_mode() {
|
||||
let mut session = new_session();
|
||||
let pixels = Arc::new(vec![64, 0, 0, 128]);
|
||||
session.begin_display_handoff(DisplaySnapshot::image(1, 1, pixels.clone(), true));
|
||||
|
||||
let result = execute(&mut session, "view.2d.copyImage", &json!({})).unwrap();
|
||||
let output = session.finish_display_handoff().and_then(DisplaySnapshot::into_image).unwrap();
|
||||
assert_eq!((result["width"].as_u64(), result["height"].as_u64(), result["premultiplied"].as_bool()), (Some(1), Some(1), Some(true)));
|
||||
assert!(Arc::ptr_eq(&pixels, &output.2), "the command copied the displayed RGBA buffer");
|
||||
assert_eq!(output.2.as_slice(), [64, 0, 0, 128]);
|
||||
drop(output);
|
||||
assert_eq!(Arc::strong_count(&pixels), 1);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
mod annotations;
|
||||
mod atomics;
|
||||
mod delete_relink;
|
||||
mod display_commands;
|
||||
mod embedded_edit;
|
||||
mod explorer;
|
||||
mod export_names;
|
||||
|
||||
@@ -311,6 +311,30 @@ fn the_resets_put_back_their_own_part_and_a_saved_default_replaces_the_built_in_
|
||||
assert_eq!((session.view3d.scene.as_str(), session.view3d.focal_length), ("torus", 20.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_uses_a_built_in_scene_when_the_saved_custom_mesh_is_unavailable() {
|
||||
let mut session = new_session();
|
||||
let mut saved = session.view3d.clone();
|
||||
saved.scene = "custom".into();
|
||||
saved.focal_length = 42.0;
|
||||
session.default_view3d = Some(saved);
|
||||
|
||||
execute(&mut session, "view.3d.reset", &json!({})).unwrap();
|
||||
|
||||
assert_eq!(session.view3d.scene, materialcraft_engine::View3d::default().scene);
|
||||
assert_eq!(session.view3d.focal_length, 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_render_counts_clamp_before_narrowing() {
|
||||
let mut session = new_session();
|
||||
|
||||
let view = execute(&mut session, "view.3d", &json!({"samples": 4_294_967_297_u64, "ambientOcclusion": 4_294_967_296_u64})).unwrap();
|
||||
|
||||
assert_eq!(view["samples"], 4);
|
||||
assert_eq!(view["ambientOcclusion"], 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_state_file_brings_the_view_back_and_a_wrong_file_changes_nothing() {
|
||||
let directory = std::env::temp_dir().join(format!("materialcraft-view3d-state-{}", std::process::id()));
|
||||
|
||||
@@ -261,6 +261,9 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
"command.run" => {
|
||||
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
|
||||
let params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
if matches!(id, "view.3d.saveRender" | "view.3d.exportGeometry" | "view.2d.copyImage") {
|
||||
return displayed_command(app, ctx, id, ¶ms);
|
||||
}
|
||||
match crate::cook::guard("command request", || {
|
||||
Ok(materialcraft_engine::commands::execute_request(&mut app.session, id, ¶ms).map_err(|error| error.to_string()))
|
||||
}) {
|
||||
@@ -388,7 +391,7 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
}
|
||||
"view.screenshot" => {
|
||||
let shown = if p.get("view").and_then(Value::as_str) == Some("2d") { &app.view2d.shown } else { &app.view3d.shown };
|
||||
match shown.as_ref().and_then(|(w, h, px)| encode_png(*w, *h, px.clone())) {
|
||||
match shown.as_ref().and_then(|(w, h, px)| encode_png(*w, *h, px.as_ref().clone())) {
|
||||
Some((w, h, png)) => ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })),
|
||||
None => err("that view has not drawn anything yet"),
|
||||
}
|
||||
@@ -397,6 +400,50 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a programmatic command the same currently displayed bytes the toolbar or dialog uses
|
||||
fn displayed_command(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Value {
|
||||
use materialcraft_engine::DisplaySnapshot;
|
||||
|
||||
let snapshot = match id {
|
||||
"view.3d.saveRender" => app.view3d.shown.as_ref().map(|(width, height, pixels)| DisplaySnapshot::render(*width, *height, pixels.clone())),
|
||||
"view.3d.exportGeometry" => {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
crate::view3d::displayed_mesh(app).map(DisplaySnapshot::geometry)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
return err("exporting geometry by path needs the desktop app");
|
||||
}
|
||||
}
|
||||
"view.2d.copyImage" => {
|
||||
app.view2d.shown.as_ref().map(|(width, height, pixels)| DisplaySnapshot::image(*width, *height, pixels.clone(), app.view2d.shown_premultiplied))
|
||||
}
|
||||
_ => return err(format!("unknown display command `{id}`")),
|
||||
};
|
||||
let Some(snapshot) = snapshot else { return err("that view has not drawn anything yet") };
|
||||
|
||||
app.session.begin_display_handoff(snapshot);
|
||||
let result = crate::cook::guard("command request", || {
|
||||
Ok(materialcraft_engine::commands::execute_request(&mut app.session, id, params).map_err(|error| error.to_string()))
|
||||
});
|
||||
let output = app.session.finish_display_handoff();
|
||||
match result {
|
||||
Ok(Ok(value)) if id == "view.2d.copyImage" => {
|
||||
let Some((width, height, pixels, premultiplied)) = output.and_then(DisplaySnapshot::into_image) else {
|
||||
return err("the copy command returned no displayed image");
|
||||
};
|
||||
let size = [width as usize, height as usize];
|
||||
let image =
|
||||
if premultiplied { egui::ColorImage::from_rgba_premultiplied(size, &pixels) } else { egui::ColorImage::from_rgba_unmultiplied(size, &pixels) };
|
||||
ctx.copy_image(image);
|
||||
ok(value)
|
||||
}
|
||||
Ok(Ok(value)) => ok(value),
|
||||
Ok(Err(error)) | Err(error) => err(error),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -471,6 +518,29 @@ mod tests {
|
||||
assert_eq!(app.ui.windows.unsaved, Some(crate::unsaved::Guarded::Quit));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn programmatic_copy_uses_the_retained_display_pixels_and_alpha_mode() {
|
||||
let mut app = app();
|
||||
let pixels = std::sync::Arc::new(vec![64, 0, 0, 128]);
|
||||
app.view2d.shown = Some((1, 1, pixels.clone()));
|
||||
app.view2d.shown_premultiplied = true;
|
||||
app.session.view2d.premultiplied = false;
|
||||
let ctx = egui::Context::default();
|
||||
ctx.begin_pass(egui::RawInput::default());
|
||||
|
||||
let reply = handle(&mut app, &ctx, "command.run", &json!({"id": "view.2d.copyImage"}));
|
||||
let output = ctx.end_pass();
|
||||
|
||||
assert_eq!((reply["ok"].as_bool(), reply["result"]["width"].as_u64()), (Some(true), Some(1)), "{reply}");
|
||||
let copied = output.platform_output.commands.iter().find_map(|command| match command {
|
||||
egui::OutputCommand::CopyImage(image) => image.pixels.first().copied(),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(copied, Some(egui::Color32::from_rgba_premultiplied(64, 0, 0, 128)));
|
||||
assert_eq!(std::sync::Arc::strong_count(&pixels), 2, "the handoff retained an extra copy");
|
||||
assert!(app.session.finish_display_handoff().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_set_merges_nested_objects_instead_of_resetting_siblings() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -174,6 +174,19 @@ impl MaterialCraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one command with a displayed snapshot and release the handoff before returning
|
||||
pub(crate) fn run_with_display_snapshot(
|
||||
&mut self,
|
||||
id: &str,
|
||||
params: Value,
|
||||
snapshot: materialcraft_engine::DisplaySnapshot,
|
||||
) -> (Option<Value>, Option<materialcraft_engine::DisplaySnapshot>) {
|
||||
self.session.begin_display_handoff(snapshot);
|
||||
let result = self.run(id, params);
|
||||
let output = self.session.finish_display_handoff();
|
||||
(result, output)
|
||||
}
|
||||
|
||||
/// Run an engine command, reporting errors as toasts. Returns the result on success
|
||||
pub fn run(&mut self, id: &str, mut params: Value) -> Option<Value> {
|
||||
if id.starts_with("graph.annotation.")
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(crate) enum Then {
|
||||
},
|
||||
SaveImage(Box<Image>),
|
||||
/// The 3D view's frame to write as a PNG file: width, height and RGBA pixels
|
||||
SaveRender(Box<(u32, u32, Vec<u8>)>),
|
||||
SaveRender(Box<(u32, u32, std::sync::Arc<Vec<u8>>)>),
|
||||
/// The mesh the 3D view shows, to write as an OBJ file
|
||||
ExportGeometry(std::sync::Arc<materialcraft_engine::geom::Mesh>),
|
||||
SaveViewState,
|
||||
@@ -168,15 +168,16 @@ fn chosen(app: &mut MaterialCraftApp, then: Then, path: &std::path::Path) {
|
||||
Then::SaveImage(image) => save_image(app, &image, path),
|
||||
Then::SaveRender(frame) => {
|
||||
let (width, height, pixels) = *frame;
|
||||
let written = crate::control::encode_png(width, height, pixels)
|
||||
.ok_or_else(|| tr("The render could not be encoded").to_string())
|
||||
.and_then(|(_, _, png)| materialcraft_engine::formats::write_atomic(path, &png).map_err(|error| error.to_string()));
|
||||
report_saved(app, written, path);
|
||||
let snapshot = materialcraft_engine::DisplaySnapshot::render_to(width, height, pixels, path.to_path_buf());
|
||||
if app.run_with_display_snapshot("view.3d.saveRender", json!({}), snapshot).0.is_some() {
|
||||
app.toast(format!("{} {picked}", tr("Saved")), false);
|
||||
}
|
||||
}
|
||||
Then::ExportGeometry(mesh) => {
|
||||
let text = materialcraft_engine::formats::mesh::obj_text(&mesh);
|
||||
let written = materialcraft_engine::formats::write_atomic(path, text.as_bytes()).map_err(|error| error.to_string());
|
||||
report_saved(app, written, path);
|
||||
let snapshot = materialcraft_engine::DisplaySnapshot::geometry_to(mesh, path.to_path_buf());
|
||||
if app.run_with_display_snapshot("view.3d.exportGeometry", json!({}), snapshot).0.is_some() {
|
||||
app.toast(format!("{} {picked}", tr("Saved")), false);
|
||||
}
|
||||
}
|
||||
Then::SaveViewState => {
|
||||
if app.run("view.3d.saveState", json!({"path": picked})).is_some() {
|
||||
@@ -224,14 +225,6 @@ fn save_to(app: &mut MaterialCraftApp, document: u64, copy: bool, picked: &str)
|
||||
true
|
||||
}
|
||||
|
||||
/// Tell the user where a file went, or why it was not written
|
||||
fn report_saved(app: &mut MaterialCraftApp, written: Result<(), String>, path: &std::path::Path) {
|
||||
match written {
|
||||
Ok(()) => app.toast(format!("{} {}", tr("Saved"), path.display()), false),
|
||||
Err(reason) => app.toast(reason, true),
|
||||
}
|
||||
}
|
||||
|
||||
fn save_image(app: &mut MaterialCraftApp, image: &Image, path: &std::path::Path) {
|
||||
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("png").to_ascii_lowercase();
|
||||
let depth = if ext == "exr" { materialcraft_engine::formats::Depth::F32 } else { materialcraft_engine::formats::Depth::U16 };
|
||||
|
||||
@@ -311,6 +311,66 @@ fn a_picked_mesh_shows_in_the_3d_view() {
|
||||
std::fs::remove_file(path).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_dialog_exports_the_frame_captured_before_a_scene_change() {
|
||||
let mut app = app();
|
||||
let pixels = std::sync::Arc::new(vec![5, 19, 77, 255, 200, 40, 9, 128]);
|
||||
let path = temp("captured-render.png");
|
||||
ask(&mut app, FileDialog::save(), Then::SaveRender(Box::new((2, 1, pixels.clone()))));
|
||||
app.session.view3d.scene = "sphere".into();
|
||||
|
||||
let target = path.clone();
|
||||
answer_all(&mut app, move || Answer::Paths(vec![target.clone()]));
|
||||
|
||||
let written = image::load_from_memory(&std::fs::read(&path).unwrap()).unwrap().to_rgba8();
|
||||
assert_eq!((written.width(), written.height(), written.as_raw()), (2, 1, pixels.as_ref()));
|
||||
assert_eq!(std::sync::Arc::strong_count(&pixels), 1, "the answered dialog retained the frame");
|
||||
assert!(app.session.finish_display_handoff().is_none());
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn geometry_dialog_exports_the_mesh_captured_before_a_scene_change() {
|
||||
let mut app = app();
|
||||
let mesh = std::sync::Arc::new(materialcraft_engine::geom::primitives::cube(1.0));
|
||||
let path = temp("captured-mesh.obj");
|
||||
ask(&mut app, FileDialog::save(), Then::ExportGeometry(mesh.clone()));
|
||||
app.session.custom_mesh = Some(("newer".into(), std::sync::Arc::new(materialcraft_engine::geom::primitives::sphere(1.0, 8, 4))));
|
||||
|
||||
let target = path.clone();
|
||||
answer_all(&mut app, move || Answer::Paths(vec![target.clone()]));
|
||||
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), materialcraft_engine::formats::mesh::obj_text(&mesh));
|
||||
assert_eq!(std::sync::Arc::strong_count(&mesh), 1, "the answered dialog retained the mesh");
|
||||
assert!(app.session.finish_display_handoff().is_none());
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn export_dialogs_keep_native_non_utf8_destinations() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
for geometry in [false, true] {
|
||||
let mut app = app();
|
||||
let filename: Vec<u8> = format!("mc-export-{}-{geometry}-", std::process::id()).into_bytes().into_iter().chain([0xff]).collect();
|
||||
let path = std::env::temp_dir().join(std::ffi::OsString::from_vec(filename));
|
||||
if geometry {
|
||||
let mesh = std::sync::Arc::new(materialcraft_engine::geom::primitives::cube(1.0));
|
||||
ask(&mut app, FileDialog::save(), Then::ExportGeometry(mesh.clone()));
|
||||
let target = path.clone();
|
||||
answer_all(&mut app, move || Answer::Paths(vec![target.clone()]));
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), materialcraft_engine::formats::mesh::obj_text(&mesh));
|
||||
} else {
|
||||
ask(&mut app, FileDialog::save(), Then::SaveRender(Box::new((1, 1, std::sync::Arc::new(vec![5, 19, 77, 255])))));
|
||||
let target = path.clone();
|
||||
answer_all(&mut app, move || Answer::Paths(vec![target.clone()]));
|
||||
assert_eq!(image::load_from_memory(&std::fs::read(&path).unwrap()).unwrap().to_rgba8().as_raw(), &[5, 19, 77, 255]);
|
||||
}
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_2d_views_image_is_written_to_the_picked_file() {
|
||||
for ext in ["png", "exr"] {
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, shown: Option<&Shown
|
||||
super::save_image(app);
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::COPY, tr("Copy image to the clipboard"), false, BUTTON_SIDE).clicked() {
|
||||
copy_image(app, ui);
|
||||
copy_image(app, ui.ctx());
|
||||
}
|
||||
});
|
||||
output_menu(app, ui, shown);
|
||||
@@ -66,17 +66,17 @@ fn background_image(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
|
||||
/// Put the image on the clipboard as the view draws it
|
||||
fn copy_image(app: &mut MaterialCraftApp, ui: &Ui) {
|
||||
let Some((width, height, pixels)) = &app.view2d.shown else { return };
|
||||
pub(crate) fn copy_image(app: &mut MaterialCraftApp, context: &egui::Context) -> Option<serde_json::Value> {
|
||||
let Some((width, height, pixels)) = &app.view2d.shown else { return None };
|
||||
let snapshot = materialcraft_engine::DisplaySnapshot::image(*width, *height, pixels.clone(), app.view2d.shown_premultiplied);
|
||||
let (result, output) = app.run_with_display_snapshot("view.2d.copyImage", json!({}), snapshot);
|
||||
let (width, height, pixels, premultiplied) = output?.into_image()?;
|
||||
|
||||
let size = [*width as usize, *height as usize];
|
||||
let image = if app.session.view2d.premultiplied {
|
||||
egui::ColorImage::from_rgba_premultiplied(size, pixels)
|
||||
} else {
|
||||
egui::ColorImage::from_rgba_unmultiplied(size, pixels)
|
||||
};
|
||||
ui.ctx().copy_image(image);
|
||||
let size = [width as usize, height as usize];
|
||||
let image = if premultiplied { egui::ColorImage::from_rgba_premultiplied(size, &pixels) } else { egui::ColorImage::from_rgba_unmultiplied(size, &pixels) };
|
||||
context.copy_image(image);
|
||||
app.toast(tr("Image copied to the clipboard"), false);
|
||||
result
|
||||
}
|
||||
|
||||
/// Choose what the view shows: another output of the graph when an output node is shown, else another output of the shown node
|
||||
|
||||
@@ -10,7 +10,9 @@ pub struct View2dState {
|
||||
/// The texture of the shown image, keyed by everything it was made from
|
||||
pub(super) texture: Option<(u64, TextureHandle)>,
|
||||
/// The last shown image (RGBA8, for `view.screenshot`)
|
||||
pub shown: Option<(u32, u32, Vec<u8>)>,
|
||||
pub shown: Option<(u32, u32, Arc<Vec<u8>>)>,
|
||||
/// Alpha handling used when the retained pixels were last displayed
|
||||
pub shown_premultiplied: bool,
|
||||
/// The histogram of the shown image, keyed by the image and the counted channel
|
||||
pub(super) histogram: Option<(u64, Histogram)>,
|
||||
/// The background image file and its texture; no texture when the file could not be shown
|
||||
|
||||
@@ -53,6 +53,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, shown: Option<&Shown
|
||||
);
|
||||
app.view2d.texture = None;
|
||||
app.view2d.shown = None;
|
||||
app.view2d.shown_premultiplied = false;
|
||||
app.view2d.histogram = None;
|
||||
app.view2d.image_size = None;
|
||||
app.view2d.hover = None;
|
||||
@@ -252,7 +253,8 @@ fn texture(app: &mut MaterialCraftApp, context: &egui::Context, shown: &Shown) -
|
||||
let texture = context.load_texture("view2d", color_image, options);
|
||||
let id = texture.id();
|
||||
app.view2d.texture = Some((key, texture));
|
||||
app.view2d.shown = Some((image.width(), image.height(), pixels));
|
||||
app.view2d.shown = Some((image.width(), image.height(), std::sync::Arc::new(pixels)));
|
||||
app.view2d.shown_premultiplied = view.premultiplied;
|
||||
id
|
||||
}
|
||||
|
||||
@@ -351,8 +353,12 @@ fn background_texture(app: &mut MaterialCraftApp, context: &egui::Context) -> Op
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn load_background(context: &egui::Context, path: &str) -> Result<TextureHandle, String> {
|
||||
let length = std::fs::metadata(path).map_err(|error| error.to_string())?.len();
|
||||
if length > MAX_BACKGROUND_BYTES {
|
||||
let metadata = std::fs::metadata(path).map_err(|error| error.to_string())?;
|
||||
// A pipe can report zero bytes but block the draw path indefinitely on read
|
||||
if !metadata.is_file() {
|
||||
return Err(format!("{path}: not a regular file"));
|
||||
}
|
||||
if metadata.len() > MAX_BACKGROUND_BYTES {
|
||||
return Err(format!("{path} is larger than {} MB", MAX_BACKGROUND_BYTES >> 20));
|
||||
}
|
||||
|
||||
@@ -381,6 +387,14 @@ mod tests {
|
||||
use super::*;
|
||||
use materialcraft_engine::core::NodeId;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_device_file_is_rejected_before_the_background_read() {
|
||||
let error = load_background(&egui::Context::default(), "/dev/null").err().unwrap();
|
||||
|
||||
assert!(error.contains("not a regular file"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_view_releases_the_previous_image_and_screenshot() {
|
||||
let context = egui::Context::default();
|
||||
|
||||
@@ -14,6 +14,8 @@ mod frame_scene;
|
||||
mod menus;
|
||||
mod navigation;
|
||||
mod output;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use output::displayed_mesh;
|
||||
mod overlay;
|
||||
mod overlay_line;
|
||||
mod overlay_mark;
|
||||
@@ -70,6 +72,7 @@ fn panel_context(app: &MaterialCraftApp) -> u64 {
|
||||
format!("{:?} {:?}", app.inspected_graph, session.annotation_selection).hash(&mut hasher);
|
||||
(app.function_editor.is_some(), app.pattern_editor.is_some()).hash(&mut hasher);
|
||||
app.function_editor.as_ref().map(|editor| (&editor.selection, editor.inspected_node)).hash(&mut hasher);
|
||||
app.pattern_editor.as_ref().map(|editor| (&editor.selection, editor.inspected_node)).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
@@ -198,4 +201,19 @@ mod inspection_tests {
|
||||
|
||||
assert_eq!(inspected(&app), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_selection_discards_the_previous_3d_inspection() {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
|
||||
app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, NodeId(0)));
|
||||
inspect(&mut app, Subject::Camera);
|
||||
assert_eq!(inspected(&app), Some(Subject::Camera));
|
||||
|
||||
if let Some(editor) = &mut app.pattern_editor {
|
||||
editor.selection.push(1);
|
||||
editor.inspected_node = Some(1);
|
||||
}
|
||||
|
||||
assert_eq!(inspected(&app), None);
|
||||
}
|
||||
}
|
||||
@@ -437,7 +437,7 @@ fn show_frame(app: &mut MaterialCraftApp, ctx: &egui::Context, frame: Frame, key
|
||||
|
||||
state.render_ms = frame.milliseconds;
|
||||
state.renders += 1;
|
||||
state.shown = Some((frame.width, frame.height, frame.pixels));
|
||||
state.shown = Some((frame.width, frame.height, Arc::new(frame.pixels)));
|
||||
state.shown_scene = Some(frame.scene);
|
||||
state.key = Some((key, full));
|
||||
state.tex_size = Some(size);
|
||||
|
||||
@@ -31,12 +31,20 @@ pub(super) fn save_render(app: &mut MaterialCraftApp) {
|
||||
/// Ask where to save the mesh the view shows, raised by the height output when it is, as an OBJ file
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn export_geometry(app: &mut MaterialCraftApp) {
|
||||
let mesh = super::frame::shown_scene(app).mesh.clone();
|
||||
let Some(mesh) = displayed_mesh(app) else {
|
||||
app.toast(tr("The 3D view has not drawn a mesh yet"), true);
|
||||
return;
|
||||
};
|
||||
let name = format!("{}.obj", materialcraft_engine::formats::safe_file_name(&super::frame::shown_label(app)));
|
||||
let dialog = craft_dialogs::FileDialog::save().file_name(name).filter("Wavefront OBJ", &["obj"]);
|
||||
crate::native_dialogs::ask(app, dialog, crate::native_dialogs::Then::ExportGeometry(mesh));
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn displayed_mesh(app: &MaterialCraftApp) -> Option<std::sync::Arc<materialcraft_engine::geom::Mesh>> {
|
||||
app.view3d.shown_scene.as_ref().map(|frame| frame.scene.mesh.clone())
|
||||
}
|
||||
|
||||
/// Ask where to save the view's state
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(super) fn save_state(app: &mut MaterialCraftApp) {
|
||||
|
||||
@@ -65,7 +65,7 @@ pub(super) fn paint(app: &mut MaterialCraftApp, ui: &Ui, view_rect: Rect, area:
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let painter = ui.painter_at(view_rect);
|
||||
if view.show_axis {
|
||||
axes(&painter, &sight, view_rect, tokens.viewport_text);
|
||||
axes(&painter, &sight, view_rect, area.height(), tokens.viewport_text);
|
||||
}
|
||||
if view.scene_stats {
|
||||
for (row, line) in statistics(app, &scene).into_iter().enumerate() {
|
||||
@@ -123,7 +123,7 @@ fn overlay_key(app: &MaterialCraftApp, scene: &Arc<materialcraft_render::Scene>,
|
||||
|
||||
/// The world axes as the camera sees them, in the view's lower left corner, with a bar that
|
||||
/// shows how long a round length is where the camera orbits
|
||||
fn axes(painter: &egui::Painter, sight: &Sight, view_rect: Rect, text: Color32) {
|
||||
fn axes(painter: &egui::Painter, sight: &Sight, view_rect: Rect, picture_height: f32, text: Color32) {
|
||||
let center = view_rect.left_bottom() + vec2(MARGIN + AXIS_ARM + 8.0, -(MARGIN + AXIS_ARM + 8.0));
|
||||
let rotation = sight.camera.view();
|
||||
let mut arms: Vec<(Vec3, Color32, &str)> = [Vec3::X, Vec3::Y, Vec3::Z]
|
||||
@@ -141,7 +141,7 @@ fn axes(painter: &egui::Painter, sight: &Sight, view_rect: Rect, text: Color32)
|
||||
write(painter, tip + vec2(direction.x, -direction.y) * 7.0, Align2::CENTER_CENTER, name, 10.0, color);
|
||||
}
|
||||
|
||||
let points_per_meter = sight.points_per_unit(view_rect.height()) * UNITS_PER_METER / UNITS_PER_MESH_UNIT;
|
||||
let points_per_meter = sight.points_per_unit(picture_height) * UNITS_PER_METER / UNITS_PER_MESH_UNIT;
|
||||
let Some(meters) = SCALE_LENGTHS.into_iter().rev().find(|meters| meters * points_per_meter <= SCALE_BAR_LIMIT) else { return };
|
||||
|
||||
let start = pos2(center.x + AXIS_ARM + 18.0, view_rect.bottom() - MARGIN - 4.0);
|
||||
@@ -192,6 +192,28 @@ mod tests {
|
||||
use materialcraft_engine::View3d;
|
||||
use materialcraft_render::Scene;
|
||||
|
||||
#[test]
|
||||
fn scale_bar_uses_the_picture_height_in_a_letterboxed_view() {
|
||||
let context = egui::Context::default();
|
||||
let scene = Scene::builtin("cube");
|
||||
let sight = Sight::of(&scene, &View3d::default(), 400.0 / 225.0);
|
||||
let view_rect = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 400.0));
|
||||
let points_per_meter = sight.points_per_unit(225.0) * UNITS_PER_METER / UNITS_PER_MESH_UNIT;
|
||||
let meters = SCALE_LENGTHS.into_iter().rev().find(|meters| meters * points_per_meter <= SCALE_BAR_LIMIT).unwrap();
|
||||
|
||||
context.begin_pass(egui::RawInput::default());
|
||||
axes(&context.layer_painter(egui::LayerId::background()), &sight, view_rect, 225.0, Color32::WHITE);
|
||||
let output = context.end_pass();
|
||||
let bar = output.shapes.iter().find_map(|shape| match &shape.shape {
|
||||
egui::Shape::LineSegment { points, stroke } if *stroke == Stroke::new(1.5, Color32::from_black_alpha(0xc0)) && points[0].y == points[1].y => {
|
||||
Some(points[1].x - points[0].x)
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
|
||||
assert!((bar.unwrap() - meters * points_per_meter).abs() < 0.01);
|
||||
}
|
||||
|
||||
fn overlay(view: &View3d, selected: bool) -> Overlay {
|
||||
let scene = Scene::builtin("cube");
|
||||
Overlay::of(&Sight::of(&scene, view, 1.5), view, selected)
|
||||
|
||||
@@ -33,7 +33,7 @@ pub struct View3dState {
|
||||
/// Frames rendered so far (previews and full quality)
|
||||
pub renders: u64,
|
||||
/// The last frame shown (RGBA8, for `view.screenshot`)
|
||||
pub shown: Option<(u32, u32, Vec<u8>)>,
|
||||
pub shown: Option<(u32, u32, Arc<Vec<u8>>)>,
|
||||
/// The scene and camera that produced the displayed pixels
|
||||
pub(super) shown_scene: Option<FrameScene>,
|
||||
/// Index of the quality level of the last moving frame
|
||||
|
||||
@@ -62,7 +62,7 @@ fn copying_premultiplied_pixels_keeps_their_display_brightness() {
|
||||
harness.event(Event::PointerMoved(position));
|
||||
harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
harness.step();
|
||||
harness.state_mut().view2d.shown = Some((1, 1, vec![64, 0, 0, 128]));
|
||||
harness.state_mut().view2d.shown = Some((1, 1, std::sync::Arc::new(vec![64, 0, 0, 128])));
|
||||
harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.step();
|
||||
|
||||
@@ -73,6 +73,21 @@ fn copying_premultiplied_pixels_keeps_their_display_brightness() {
|
||||
assert_eq!(copied, Some(egui::Color32::from_rgba_premultiplied(64, 0, 0, 128)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copy_button_rejects_an_invalid_display_buffer_before_the_clipboard_write() {
|
||||
let mut harness = harness(app(true));
|
||||
let position = harness.get_by_role_and_label(egui::accesskit::Role::Button, "Copy image to the clipboard").rect().center();
|
||||
harness.event(Event::PointerMoved(position));
|
||||
harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
harness.step();
|
||||
harness.state_mut().view2d.shown = Some((2, 1, std::sync::Arc::new(vec![1, 2, 3])));
|
||||
harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
harness.step();
|
||||
|
||||
assert!(harness.output().platform_output.commands.iter().all(|command| !matches!(command, egui::OutputCommand::CopyImage(_))));
|
||||
assert!(harness.state().toasts.iter().any(|toast| toast.error && toast.text.contains("displayed RGBA")));
|
||||
}
|
||||
|
||||
fn click(harness: &mut Harness<'static, MaterialCraftApp>, label: &str) {
|
||||
harness.get_by_role_and_label(egui::accesskit::Role::Button, label).click();
|
||||
harness.run();
|
||||
|
||||
Reference in new issue
Block a user