diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index d602e78c7..647146702 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -8,6 +8,7 @@ use solidcraft_doc::render_settings::{RenderSettings, RenderSetup}; use super::CommandSpec; use crate::params::bad; +use crate::schema::render_camera::{CameraApplied, CameraFitted, CameraInfo, CameraSet, RenderCamera}; use crate::{Result, Session}; mod clear_coat; @@ -99,11 +100,17 @@ pub static COMMANDS: &[CommandSpec] = &[ .params("name: saved setup; target: exact saved definition/feature/component/occurrence_path; expected_revision. Removes only that optical assignment in one undo without a device or file access."), CommandSpec::new("render.result.regrade", "Regrade Linear Master", jobs::regrade).icon("render_image").noundo().doc_only() .params("job?: exact completed JobId (default selected result); presentation: {exposure_ev?,tone_map?,finishing?,backdrop?,background?,transparent_background?}. Queues cancellable nondestructive PNG presentation from that retained native FLOAT32 master, not from PNG. Captured geometry/camera/lighting and source EXR remain unchanged; no path tracing, denoising, external EXR import or automatic file writes. Returns a distinct job with source identity and original-master digest. Existing frame retention and export rules still apply."), - CommandSpec::new("render.camera.set", "Set Render Camera", set_camera).icon("camera").noundo().doc_only() + CommandSpec::new("render.camera.set", "Set Render Camera", crate::checked!("render.camera.set", set_camera)).icon("camera").noundo().doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) .params("camera: complete Render Camera snapshot (target, yaw, pitch, distance, fov; roll defaults to 0 and up to z). Validates the same finite mm/radian bounds as saved render intent, preserves explicit roll/up and changes only transient view state. No model evaluation, setup save, renderer, dirty flag or undo step. Design view.apply retains its separate up-axis policy."), - CommandSpec::new("render.camera.get", "Inspect Render Camera", get_camera).icon("camera").noundo() + CommandSpec::new("render.camera.get", "Inspect Render Camera", crate::checked!("render.camera.get", get_camera)).icon("camera").noundo() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) .params("No parameters. Returns the explicitly defined current view camera, or null if the session has no camera override. No camera is fitted, no job is started and no saved setup or engineering document is changed."), -CommandSpec::new("render.camera.fit", "Frame Render Subject", fit_camera).icon("camera").noundo() +CommandSpec::new("render.camera.fit", "Frame Render Subject", crate::checked!("render.camera.fit", fit_camera)).icon("camera").noundo() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) .params("aspect?: the picture's width over its height, 0.000001 to 1000000 (default 1). Fits the current camera to the visible product bounds through the shared Camera::fit contract, moving back for a picture taller than wide so its sides hold the product too; changes only view state, not a saved setup, rendering job, stage or engineering geometry."), CommandSpec::new("render.preset.resolve", "Review Native Studio", crate::checked!("render.preset.resolve", studio_presets::resolve)).icon("render_scene").noundo() .contract(&studio_presets::PRESET_CONTRACT) @@ -209,10 +216,18 @@ CommandSpec::new("render.settings.set", "Save Render Settings", set_settings).ic .params("name: setup name, set: object of fields to replace (backend, mode, camera, width, height, format, exposure_ev, environment_rotation, environment_intensity, background, job, surfaces, optics, coats, stage). job?: typed active raster/cpu_raytrace/gpu_path configuration with optional validated embedded HDR reference; omitted preserves, null clears, object replaces the complete job. Creates from defaults and saves without a host, validates atomically, one undo step; identical edits are no-ops. See docs/render-settings.md"), CommandSpec::new("render.scene", "Inspect Render Scene", scene).noundo().at("RENDER", "SCENE").icon("render_scene") .params("No parameters. Authoritative product-scene metadata, without modelling overlays or mesh payloads. Explicitly settles stale geometry; does not render an image. See docs/render-workspace.md"), -CommandSpec::new("render.settings.apply", "Apply Render Camera", apply_settings).icon("camera").noundo().doc_only() +CommandSpec::new("render.settings.apply", "Apply Render Camera", crate::checked!("render.settings.apply", apply_settings)).icon("camera").noundo().doc_only() + .contract(&crate::schema::TypedContract::::new()) + .output(crate::schema::output_schema_for::) .params("name: saved setup. Applies its existing Camera snapshot including roll/up as view state, without modifying the document or starting a render."), ]; +/// A reply built from its output schema's type (`schema::render_camera`), so the two can't +/// drift apart. +fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) +} + fn set_camera(s: &mut Session, params: &Value) -> Result { let cmd = "render.camera.set"; if !params.as_object().is_some_and(|p| p.len() == 1 && p.contains_key("camera")) { @@ -222,14 +237,17 @@ fn set_camera(s: &mut Session, params: &Value) -> Result { let setup: RenderSetup = serde_json::from_value(params.clone()).map_err(|e| bad(cmd, e.to_string()))?; setup.validate().map_err(|e| bad(cmd, e.to_string()))?; s.camera = Some(setup.camera); - Ok(json!({"camera":setup.camera,"document_changed":false})) + typed_reply(cmd, CameraSet { camera: RenderCamera(setup.camera), document_changed: false, param_warnings: Vec::new() }) } fn get_camera(s: &mut Session, params: &Value) -> Result { + let cmd = "render.camera.get"; if !params.as_object().is_some_and(|p| p.is_empty()) { - return Err(bad("render.camera.get", "expected an empty parameter object")); + return Err(bad(cmd, "expected an empty parameter object")); } - Ok(json!({"camera":s.camera,"explicit_view":s.camera.is_some(),"document_changed":false})) + let reply = + CameraInfo { camera: s.camera.map(RenderCamera), explicit_view: s.camera.is_some(), document_changed: false, param_warnings: Vec::new() }; + typed_reply(cmd, reply) } fn fit_camera(s: &mut Session, params: &Value) -> Result { @@ -253,7 +271,8 @@ fn fit_camera(s: &mut Session, params: &Value) -> Result { return Err(bad("render.camera.fit", "the product cannot be framed at this aspect: the fitted camera is out of range")); } s.camera = Some(camera); - Ok(json!({"camera":camera,"empty":scene.bounds.is_empty(),"document_changed":false})) + let reply = CameraFitted { camera: RenderCamera(camera), empty: scene.bounds.is_empty(), document_changed: false, param_warnings: Vec::new() }; + typed_reply("render.camera.fit", reply) } fn scene(s: &mut Session, params: &Value) -> Result { @@ -284,8 +303,9 @@ fn apply_settings(s: &mut Session, params: &Value) -> Result { RenderSettings::validate_name(&name).map_err(|e| bad("render.settings.apply", e.to_string()))?; let setup = s.doc.render.setups.get(&name).ok_or_else(|| bad("render.settings.apply", "no saved render setup with that name"))?; setup.validate().map_err(|e| bad("render.settings.apply", e.to_string()))?; - s.camera = Some(setup.camera); - Ok(json!({"name":name,"camera":setup.camera})) + let camera = setup.camera; + s.camera = Some(camera); + typed_reply("render.settings.apply", CameraApplied { name, camera: RenderCamera(camera), param_warnings: Vec::new() }) } #[derive(Deserialize)] diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 4817da305..1d5742b8c 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -85,6 +85,7 @@ pub mod point_cloud; pub mod print_face; pub mod render; pub mod render_bindings; +pub mod render_camera; pub mod render_hdr; pub mod render_library; pub mod render_lights; diff --git a/crates/engine/src/schema/render_camera.rs b/crates/engine/src/schema/render_camera.rs new file mode 100644 index 000000000..bd6eb7cc5 --- /dev/null +++ b/crates/engine/src/schema/render_camera.rs @@ -0,0 +1,265 @@ +//! Contracts and reply types for the render camera commands in `cmd/render.rs` (#12288): Set, +//! Inspect and Frame Render Camera, and Apply Render Camera. They change only the camera in the +//! view, never the design. +//! +//! The handlers read their parameters from the raw JSON, so each key here reads as its handler +//! reads it and fails with the handler's message. Whether a saved setup exists, and whether the +//! product can be framed, stay the handlers' to check. + +use std::borrow::Cow; + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::{Value, json}; +use solidcraft_doc::render_settings::{RenderSettings, RenderSetup}; + +use super::check::whole; +use super::types::not_blank_pattern; + +/// The largest size a camera's target coordinates and distance may have, in mm, as a saved +/// render setup keeps them (`RenderSetup::validate`). +const MAX_LENGTH_MM: f64 = 1e9; +/// The largest size a camera's yaw, pitch and roll may have, in radians, likewise. +const MAX_ANGLE: f64 = 1e6; +/// The picture's width over its height that Frame Render Subject takes: the range a preview +/// frame can show (`frame_rect` in the Render workspace). +const MIN_ASPECT: f64 = 1e-6; +const MAX_ASPECT: f64 = 1e6; + +/// A render camera, as a saved render setup keeps it: strict about its keys, with finite +/// lengths and angles within [`MAX_LENGTH_MM`] and [`MAX_ANGLE`], a positive distance and a +/// field of view in [0, π). +/// +/// It is not the view commands' `types::CameraParam`: those read a camera more loosely and +/// refuse an explicit `up`, while a render camera keeps both `roll` and `up`. +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(transparent)] +pub struct RenderCamera(pub solidcraft_render::Camera); + +impl JsonSchema for RenderCamera { + fn schema_name() -> Cow<'static, str> { + "RenderCamera".into() + } + /// The size bounds are for a camera given (the input schema) only. A reply gives back the + /// camera in the view, which Frame Render Subject may have moved beyond them (a picture far + /// taller than wide moves it back that much) and the view commands don't bound, so the + /// output schema has the camera's shape alone. + fn json_schema(generator: &mut SchemaGenerator) -> Schema { + let given = generator.contract().is_deserialize(); + // `schema` with a largest size of `limit` either way, in the input schema only. + let sized = |mut schema: Value, limit: f64| { + if given { + schema["minimum"] = json!(-limit); + schema["maximum"] = json!(limit); + } + schema + }; + let angle = |description: &str| sized(json!({"description": description, "type": "number"}), MAX_ANGLE); + let coordinate = sized(json!({"type": "number"}), MAX_LENGTH_MM); + let mut roll = angle("Turn about the viewing direction; 0 keeps the up axis upright. Default: 0."); + roll["default"] = json!(0.0); + let mut distance = json!({"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0}); + if given { + distance["maximum"] = json!(MAX_LENGTH_MM); + } + let bounds = if given { " Lengths are at most 1e9 mm in size, and angles at most 1e6 radians." } else { "" }; + json_schema!({ + "description": format!("A render camera orbiting a target point. Lengths are in mm and angles in radians, measured in the frame of the up axis.{bounds}"), + "type": "object", + "properties": { + "target": { + "description": "The point the camera looks at, in mm: [x, y, z].", + "type": "array", + "items": coordinate, + "minItems": 3, + "maxItems": 3 + }, + "yaw": angle("Turn about the up axis; 0 looks along +Y, from the front."), + "pitch": angle("Elevation above the ground plane: π/2 looks straight down."), + "roll": roll, + "distance": distance, + "fov": {"description": "Vertical field of view; 0 is orthographic.", "type": "number", "minimum": 0, "exclusiveMaximum": std::f64::consts::PI}, + "up": {"description": "The world's up axis. Default: z.", "enum": ["z", "y"], "default": "z"} + }, + "required": ["target", "yaw", "pitch", "distance", "fov"], + "additionalProperties": false + }) + } +} + +/// `serde(default)` makes schemars publish `"default": null` on a key; drop it from a key the +/// schema requires. +fn drop_default(schema: &mut Schema) { + schema.remove("default"); +} + +/// Adds `key` to the schema's `required` list: for a key the type has optional so that the +/// handler, not the check, refuses it with its own message when it's left out. +/// (`#[schemars(required)]` doesn't do this for a key with `serde(default)`.) +fn require(schema: &mut Schema, key: &str) { + match schema.get_mut("required") { + Some(Value::Array(required)) => { + if !required.iter().any(|k| k == key) { + required.push(key.into()); + } + } + _ => { + schema.insert("required".into(), Value::Array(vec![key.into()])); + } + } +} + +fn camera_required(schema: &mut Schema) { + require(schema, "camera"); +} + +fn name_required(schema: &mut Schema) { + require(schema, "name"); +} + +/// Set the camera in the view from a complete camera snapshot. Nothing in the design changes, +/// and there is no undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = camera_required)] +pub struct SetParams { + /// The camera: `target`, `yaw`, `pitch`, `distance` and `fov`, and optionally `roll` and + /// `up`. + // Optional in the type, required in the schema: left out, the handler refuses the call + // with its own message. + #[serde(default, deserialize_with = "render_camera")] + #[schemars(with = "RenderCamera", transform = drop_default)] + pub camera: Option, +} + +/// A camera as `render.camera.set` reads it: a render setup holding only that camera, decoded +/// and checked as a saved one is, with the same messages. +fn render_camera<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let setup: RenderSetup = serde_json::from_value(json!({"camera": Value::deserialize(d)?})).map_err(|e| D::Error::custom(whole(e)))?; + setup.validate().map_err(|e| D::Error::custom(whole(e)))?; + Ok(Some(RenderCamera(setup.camera))) +} + +/// The camera set in the view, if any. No parameters. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct GetParams {} + +/// Fit the camera in the view to the visible product, keeping its direction: for a picture +/// taller than wide it moves back, so the picture's sides hold the product too. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct FitParams { + // `skip_serializing_if` keeps schemars from publishing `"default": null`, which the reader + // refuses, over the schema's own default of 1. + #[serde(default, deserialize_with = "aspect", skip_serializing_if = "Option::is_none")] + #[schemars(schema_with = "aspect_schema")] + pub aspect: Option, +} + +/// `aspect`, with `render.camera.fit`'s message for anything outside its range, `null` +/// included. +fn aspect<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + match Value::deserialize(d)?.as_f64() { + Some(a) if (MIN_ASPECT..=MAX_ASPECT).contains(&a) => Ok(Some(a)), + _ => Err(D::Error::custom(whole("aspect must be a number from 0.000001 to 1000000: the picture's width over its height"))), + } +} + +fn aspect_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "The picture's width over its height: 0.000001 to 1000000. Default: 1.", + "type": "number", + "minimum": MIN_ASPECT, + "maximum": MAX_ASPECT, + "default": 1.0 + }) +} + +/// Put a saved render setup's camera, with its roll and up axis, in the view. Nothing in the +/// design changes, and there is no undo step. +#[derive(Debug, Deserialize, JsonSchema)] +#[schemars(deny_unknown_fields, transform = name_required)] +pub struct ApplyParams { + /// The saved render setup, by name: trimmed, at most 128 bytes, with no control characters. + // Optional in the type, required in the schema: left out (or `null`), the handler refuses + // the call with its own message. + #[serde(default, deserialize_with = "setup_name")] + #[schemars(schema_with = "setup_name_schema", transform = drop_default)] + pub name: Option, +} + +/// A setup's name as `render.settings.apply` reads it: `null` is left out, other text than a +/// string gets serde's message, and a string must be a valid setup name. +fn setup_name<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let Some(name) = Option::::deserialize(Value::deserialize(d)?).map_err(|e| D::Error::custom(whole(e)))? else { + return Ok(None); + }; + RenderSettings::validate_name(&name).map_err(|e| D::Error::custom(whole(e)))?; + Ok(Some(name)) +} + +/// The pattern says "not blank"; trimmed, at most 128 bytes and free of control characters, +/// which JSON Schema can't count or class portably, are in the field's description and +/// checked by [`setup_name`]. +fn setup_name_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": not_blank_pattern() + }) +} + +/// What `render.camera.set` returns: the camera now in the view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CameraSet { + pub camera: RenderCamera, + /// Always false: the design doesn't change. + pub document_changed: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `render.camera.get` returns. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CameraInfo { + /// The camera set in the view, or `null` when none is. + pub camera: Option, + /// Whether a camera is set in the view. + pub explicit_view: bool, + /// Always false: the design doesn't change. + pub document_changed: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `render.camera.fit` returns: the fitted camera, now in the view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CameraFitted { + pub camera: RenderCamera, + /// Whether nothing visible was there to frame. The camera then isn't moved: it stays the + /// one set in the view, or the default camera when none was. + pub empty: bool, + /// Always false: the design doesn't change. + pub document_changed: bool, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +/// What `render.settings.apply` returns: the setup and its camera, now in the view. +#[derive(Debug, Serialize, JsonSchema)] +pub struct CameraApplied { + pub name: String, + pub camera: RenderCamera, + /// In the warn parameter-check mode: what the call's parameters got wrong. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub param_warnings: Vec, +} + +#[cfg(test)] +#[path = "render_camera_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/render_camera_tests.rs b/crates/engine/src/schema/render_camera_tests.rs new file mode 100644 index 000000000..8bb0f2f77 --- /dev/null +++ b/crates/engine/src/schema/render_camera_tests.rs @@ -0,0 +1,195 @@ +use serde_json::{Value, json}; + +use super::{ApplyParams, CameraApplied, CameraFitted, CameraInfo, CameraSet, FitParams, GetParams, SetParams}; +use crate::Session; +use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms}; +use crate::schema::{ParamCheck, input_schema_for, output_schema_for}; + +/// A render camera that isn't the default one, as `render.camera.set` takes it. +fn camera() -> Value { + json!(solidcraft_render::Camera { yaw: 0.2, pitch: 0.3, roll: 0.1, ..Default::default() }) +} + +/// `camera()` with `key` set to `value`, or taken out when `value` is `None`. +fn camera_with(key: &str, value: Option) -> Value { + let mut c = camera(); + if let Some(fields) = c.as_object_mut() { + match value { + Some(v) => fields.insert(key.into(), v), + None => fields.remove(key), + }; + } + c +} + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["camera"]); + assert_keys(input_schema_for::(), &[]); + assert_keys(input_schema_for::(), &["aspect"]); + assert_keys(input_schema_for::(), &["name"]); +} + +/// #12288: calls that fail today get the same message in strict. (Inspect Render Camera fails +/// only on an unknown key, which strict refuses in the check's own words, as for every +/// converted command.) +#[test] +fn strict_keeps_todays_errors() { + let mut cases = vec![ + ("render.camera.set", json!({})), + ("render.camera.set", json!({"camera": null})), + ("render.camera.set", json!({"camera": []})), + ("render.camera.set", json!({"camera": camera_with("yaw", None)})), + ("render.camera.set", json!({"camera": camera_with("fov_degrees", Some(json!(45)))})), + ("render.camera.set", json!({"camera": camera_with("target", Some(json!([0, 0])))})), + ]; + for (key, value) in [ + ("roll", json!(null)), + ("roll", json!("invalid")), + ("roll", json!(1e7)), + ("up", json!("invalid")), + ("up", json!(null)), + ("distance", json!(0)), + ("distance", json!(1e10)), + ("fov", json!(-1)), + ("fov", json!(4)), + ("target", json!([1e10, 0, 0])), + ] { + cases.push(("render.camera.set", json!({"camera": camera_with(key, Some(value))}))); + } + for aspect in [json!(0), json!(-1), json!(1e-320), json!(1e-7), json!(1e7), json!("tall"), json!(null)] { + cases.push(("render.camera.fit", json!({"aspect": aspect}))); + } + for name in [json!(null), json!(5), json!(""), json!(" Studio"), json!("Studio\u{7}"), json!("x".repeat(129)), json!("Nope")] { + cases.push(("render.settings.apply", json!({"name": name}))); + } + cases.push(("render.settings.apply", json!({}))); + assert_strict_keeps_todays_errors(&cases); +} + +/// #12288: the camera's schema takes exactly what Set Render Camera takes (a saved setup's +/// camera, its keys and bounds), and the aspect's exactly what Frame Render Subject takes: each +/// case is checked against the handler too. +#[test] +fn the_camera_and_aspect_schemas_take_what_the_handlers_take() { + let mut s = Session::default(); + s.execute("solid.box", &json!({"length": 20, "width": 15, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + let set = input_schema_for::(); + let set = set.as_value(); + let mut calls = vec![ + json!({"camera": camera()}), + json!({}), + json!({"camera": null}), + json!({"camera": camera(), "width": 1}), + json!({"camera": camera_with("roll", None)}), + json!({"camera": camera_with("up", None)}), + json!({"camera": camera_with("yaw", None)}), + json!({"camera": camera_with("fov_degrees", Some(json!(45)))}), + ]; + for (key, value) in [ + ("roll", json!(1e6)), + ("roll", json!(1_000_001.0)), + ("roll", json!(null)), + ("yaw", json!(-1e6)), + ("pitch", json!(-2e6)), + ("up", json!("y")), + ("up", json!("x")), + ("distance", json!(1e-9)), + ("distance", json!(1e9)), + ("distance", json!(1_000_000_001.0)), + ("distance", json!(0)), + ("fov", json!(0)), + ("fov", json!(3.0)), + ("fov", json!(std::f64::consts::PI)), + ("target", json!([1e9, -1e9, 0])), + ("target", json!([1_000_000_001.0, 0, 0])), + ("target", json!([0, 0, 0, 0])), + ("target", json!("origin")), + ] { + calls.push(json!({"camera": camera_with(key, Some(value))})); + } + for p in calls { + let takes = s.execute("render.camera.set", &p).is_ok(); + assert_eq!(conforms(set, set, &p), takes, "{p}"); + } + let fit = input_schema_for::(); + let fit = fit.as_value(); + for p in [ + json!({}), + json!({"aspect": 1}), + json!({"aspect": 0.5}), + json!({"aspect": 1e-6}), + json!({"aspect": 1e6}), + json!({"aspect": 1e-7}), + json!({"aspect": 1e7}), + json!({"aspect": 0}), + json!({"aspect": "tall"}), + json!({"aspect": null}), + json!({"scale": 0}), + ] { + let takes = s.execute("render.camera.fit", &p).is_ok(); + assert_eq!(conforms(fit, fit, &p), takes, "{p}"); + } + // Whether the setup exists is the handler's to check, so these are the schema's alone. + let apply = input_schema_for::(); + let apply = apply.as_value(); + for (p, takes) in [ + (json!({"name": "Studio"}), true), + (json!({}), false), + (json!({"name": null}), false), + (json!({"name": 5}), false), + (json!({"name": ""}), false), + (json!({"name": "x".repeat(129)}), false), + (json!({"name": "Studio", "camera": camera()}), false), + ] { + assert_eq!(conforms(apply, apply, &p), takes, "{p}"); + } +} + +/// #12288: the four commands reply as their output schemas say, in Warn without warnings: +/// Inspect before and after a camera is set, Frame with nothing to frame and then a box (wide +/// and tall), Set, and Apply of a saved setup's camera. The handlers already refuse an unknown +/// key, so a misspelt one fails in every mode; strict says so in the check's words. +#[test] +fn render_camera_commands_reply_with_their_schemas() { + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value, schema: schemars::Schema| { + let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let schema = schema.as_value(); + assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + r + }; + let r = run(&mut s, "render.camera.get", json!({}), output_schema_for::()); + assert_eq!((&r["camera"], &r["explicit_view"]), (&json!(null), &json!(false)), "{r}"); + let r = run(&mut s, "render.camera.fit", json!({}), output_schema_for::()); + assert_eq!(r["empty"], true, "nothing to frame: {r}"); + s.execute("solid.box", &json!({"length": 20, "width": 15, "height": 10})).unwrap_or_else(|e| panic!("{e}")); + let r = run(&mut s, "render.camera.fit", json!({"aspect": 0.5}), output_schema_for::()); + assert_eq!(r["empty"], false, "{r}"); + let r = run(&mut s, "render.camera.set", json!({"camera": camera()}), output_schema_for::()); + assert_eq!(r["camera"], camera(), "{r}"); + let r = run(&mut s, "render.camera.get", json!({}), output_schema_for::()); + assert_eq!((&r["camera"], &r["explicit_view"]), (&camera(), &json!(true)), "{r}"); + let saved = camera_with("up", Some(json!("y"))); + s.execute("render.settings.set", &json!({"name": "Studio", "set": {"camera": saved}})).unwrap_or_else(|e| panic!("{e}")); + let r = run(&mut s, "render.settings.apply", json!({"name": "Studio"}), output_schema_for::()); + assert_eq!((&r["name"], &r["camera"]), (&json!("Studio"), &saved), "{r}"); + // A picture far taller than wide moves the camera back beyond what a given camera may be: + // the reply still matches its schema, which has no size bounds, and the input schema + // refuses that camera, as Set Render Camera does. + s.execute("solid.box", &json!({"length": 5000, "width": 5000, "height": 5000})).unwrap_or_else(|e| panic!("{e}")); + let far = run(&mut s, "render.camera.fit", json!({"aspect": 1e-6}), output_schema_for::()); + assert!(far["camera"]["distance"].as_f64().is_some_and(|d| d > 1e9), "{far}"); + let set = input_schema_for::(); + let given = json!({"camera": far["camera"]}); + assert!(!conforms(set.as_value(), set.as_value(), &given), "{given}"); + assert!(s.execute("render.camera.set", &given).is_err(), "{given}"); + let misspelt = json!({"aspekt": 2}); + for level in [ParamCheck::Off, ParamCheck::Warn, ParamCheck::Strict] { + s.param_check = level; + let error = s.execute("render.camera.fit", &misspelt).err().map(|e| e.to_string()).unwrap_or_default(); + let expected = if level == ParamCheck::Strict { "`aspekt`" } else { "expected an empty parameter object or {aspect}" }; + assert!(error.contains(expected), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 80861315b..8eea70ebc 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -91,9 +91,6 @@ plastic.rest plastic.snap_fit render.aging.describe render.backends -render.camera.fit -render.camera.get -render.camera.set render.cancel render.effects.describe render.export @@ -107,7 +104,6 @@ render.preflight render.result.pin render.result.regrade render.scene -render.settings.apply render.settings.get render.settings.set render.start