diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 150734229..c519a07d2 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -87,7 +87,9 @@ CommandSpec::new("render.shot.rename", "Rename Render Shot", shots::rename).icon .params("name, new_name, expected_revision:u64. Renames exact saved setup in one undo; an existing destination or stale review refuses."), CommandSpec::new("render.shot.remove", "Remove Render Shot", shots::remove).icon("delete").doc_only() .params("name, expected_revision:u64. Removes only that saved setup in one undo; retains resources, geometry and captured results."), -CommandSpec::new("render.library.preview", "Inspect Original Surface Map", library::preview).icon("appearance").noundo().doc_only() +CommandSpec::new("render.library.preview", "Inspect Original Surface Map", crate::checked!("render.library.preview", library::preview)).icon("appearance").noundo().doc_only() + .contract(&library::PREVIEW_CONTRACT) + .output(crate::schema::output_schema_for::) .params("id: SURF-*. Returns bounded hash-verified original base-color PNG bytes and source-map fidelity label, not a rendered material thumbnail. No external paths, rendering or document edits."), CommandSpec::new("render.library.physical.prepare", "Prepare Physical Reference", physical_library::prepare).icon("inspect").noundo().doc_only() .params("id: named built-in physical profile, name: proposed new material label, acknowledge_reference:true. Read-only loss-aware creation plan using native ValidatedCard admission and one point density; returns source receipts, extended fields and omissions. Does not execute material.create, assign bodies or infer effective-part physics."), @@ -109,11 +111,17 @@ CommandSpec::new("render.library.surface.unbind", "Remove Surface Binding", surf .params("name: setup, target: saved definition/feature/component/occurrence_path, set?: setup patch. Removes only that explicit binding in one undo; no device or current geometry required."), CommandSpec::new("render.result.pin", "Retain Displayed Render Result", jobs::pin).icon("inspect").noundo().doc_only() .params("job?: completed JobId (default selected result), or null to clear selection. Selects within the eight retained completed results; oldest is evicted first. Preserves exact export bytes and original host memory accounting. No design/undo change; preview or foreign jobs refuse."), -CommandSpec::new("render.library.targets", "Find Render Library Targets", library::targets).icon("list").noundo() +CommandSpec::new("render.library.targets", "Find Render Library Targets", crate::checked!("render.library.targets", library::targets)).icon("list").noundo() + .contract(&library::TARGETS_CONTRACT) + .output(crate::schema::output_schema_for::) .params("query?: exact-name substring; offset?:0; limit?:128 (1..128). Returns a bounded page of captured body ordinals/names, revision and scene bounds. Settles the model through ordinary command handling; never returns a large mesh payload."), -CommandSpec::new("render.library.list", "Browse Render Library", library::list).icon("list").noundo().doc_only() +CommandSpec::new("render.library.list", "Browse Render Library", crate::checked!("render.library.list", library::list)).icon("list").noundo().doc_only() + .contract(&library::LIST_CONTRACT) + .output(crate::schema::output_schema_for::) .params("kind?: surfaces, selene_appearances, hdr, rigs, scenes, materials, lighting, environments, quality, native_scenes, selene_shots or capabilities; query?: bounded search; availability?: all/usable/specification/blocked; offset?:0; limit?:48 (1..128). Returns source status and explicit implemented projections separately. No device, file IO or design change."), -CommandSpec::new("render.library.describe", "Inspect Render Library Resource", library::describe).icon("inspect").noundo().doc_only() +CommandSpec::new("render.library.describe", "Inspect Render Library Resource", crate::checked!("render.library.describe", library::describe)).icon("inspect").noundo().doc_only() + .contract(&library::DESCRIBE_CONTRACT) + .output(crate::schema::output_schema_for::) .params("kind, id: exact authored resource. Returns original specification, runtime projection variants and explicit omissions. A concept is not an executable preset."), CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appearance", library::apply_appearance).icon("appearance") .params("id: SURF-* or SELENE-AP-*; variant: uniform_opaque (required); bodies: 1..256 exact body names. Applies the original scalar baseline through ordinary appearance assignment in one undo, preserving physical properties. Spatial maps and advanced target effects are explicitly excluded."), diff --git a/crates/engine/src/cmd/render/library.rs b/crates/engine/src/cmd/render/library.rs index cb74adeae..681565128 100644 --- a/crates/engine/src/cmd/render/library.rs +++ b/crates/engine/src/cmd/render/library.rs @@ -16,8 +16,22 @@ use solidcraft_render::{ texture_input::MapRole, }; +use crate::schema::TypedContract; +use crate::schema::render_library::{ + LibraryDescribeParams, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryResource, LibraryTargets, + LibraryTargetsParams, Pbr, RenderTarget, ResourceSummary, SceneBounds, +}; use crate::{Result, Session, params::bad}; +pub(super) const LIST_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const DESCRIBE_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const TARGETS_CONTRACT: TypedContract = TypedContract::new(); +pub(super) const PREVIEW_CONTRACT: TypedContract = TypedContract::new(); + +fn reply(command: &str, reply: impl serde::Serialize) -> Result { + serde_json::to_value(reply).map_err(|e| bad(command, e.to_string())) +} + const KINDS: &[&str] = &[ "materials", "lighting", @@ -162,28 +176,47 @@ pub(super) fn list(_s: &mut Session, params: &Value) -> Result { }; let values = catalog(&input.kind, command)?; let count = values.iter().filter(matches).count(); - let items: Vec<_> = values.iter().filter(matches).skip(input.offset).take(input.limit).map(|v| { - json!({"id":v["id"],"name":v["name"],"domains":v["domains"],"family":v["family"],"source_status":v.get("status").or_else(|| v.get("state")),"projection":projection(&input.kind,v)}) - }).collect(); + let items = values + .iter() + .filter(matches) + .skip(input.offset) + .take(input.limit) + .map(|v| { + let listed = Listed::deserialize(v).map_err(|e| bad(command, format!("built-in catalog {}: {e}", input.kind)))?; + Ok(ResourceSummary { + id: listed.id, + name: listed.name, + domains: listed.domains, + family: listed.family, + source_status: listed.status.or(listed.state), + projection: projection(&input.kind, v), + }) + }) + .collect::>>()?; let end = input.offset.saturating_add(items.len()); - Ok(json!({"kind":input.kind,"total":count,"offset":input.offset,"next_offset":(end < count).then_some(end),"items":items})) + let next_offset = (end < count).then_some(end); + reply(command, LibraryPage { kind: input.kind, total: count, offset: input.offset, next_offset, items, param_warnings: Vec::new() }) } +/// The fields of a catalog's resource a page lists. Every catalog gives an id and a name; the +/// source's status is `status`, or a rig's `state`. #[derive(Deserialize)] -#[serde(default, deny_unknown_fields)] -struct TargetQuery { - query: String, - offset: usize, - limit: usize, -} -impl Default for TargetQuery { - fn default() -> Self { - Self { query: String::new(), offset: 0, limit: 128 } - } +struct Listed { + id: String, + name: String, + #[serde(default)] + domains: Option>, + #[serde(default)] + family: Option, + #[serde(default)] + status: Option, + #[serde(default)] + state: Option, } + pub(super) fn targets(s: &mut Session, params: &Value) -> Result { let command = "render.library.targets"; - let input: TargetQuery = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: LibraryTargetsParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.query.len() > 256 || input.query.chars().any(char::is_control) || input.limit == 0 @@ -202,49 +235,70 @@ pub(super) fn targets(s: &mut Session, params: &Value) -> Result { .filter(|(_, body)| body.name.to_lowercase().contains(&query)) .skip(input.offset) .take(input.limit) - .map(|(ordinal, body)| { - json!({"ordinal":ordinal,"name":body.name,"color":body.color,"opacity":body.opacity, - "pbr":body.surface.map(|v|json!({"metallic":v.metallic(),"roughness":v.roughness(),"dielectric_ior":v.dielectric_ior()}))}) + .map(|(ordinal, body)| RenderTarget { + ordinal, + name: body.name.clone(), + color: body.color, + opacity: body.opacity, + pbr: body.surface.map(|v| Pbr { metallic: v.metallic(), roughness: v.roughness(), dielectric_ior: v.dielectric_ior() }), }) .collect(); let end = input.offset.saturating_add(items.len()); - Ok(json!({"items":items,"total":count,"offset":input.offset,"next_offset":(end Result { let command = "render.library.describe"; - let input: Identify = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: LibraryDescribeParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; if input.kind == "physical_profiles" { return super::physical_library::describe(&input.id); } let value = item(&input.kind, &input.id, command)?; - let mut reply = json!({"kind":input.kind,"resource":value,"projection":projection(&input.kind,value),"source_manifest_unchanged":true}); - if matches!(input.kind.as_str(), "materials" | "surfaces") { - reply["physical_references"] = super::physical_library::associations(&input.id)?; - } - Ok(reply) + let physical_references = + if matches!(input.kind.as_str(), "materials" | "surfaces") { Some(super::physical_library::associations(&input.id)?) } else { None }; + let projection = projection(&input.kind, value); + reply( + command, + LibraryResource { + kind: input.kind, + resource: value.as_object().cloned().unwrap_or_default(), + projection, + source_manifest_unchanged: true, + physical_references, + param_warnings: Vec::new(), + }, + ) } -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct Preview { - id: String, -} pub(super) fn preview(_s: &mut Session, params: &Value) -> Result { let command = "render.library.preview"; - let input: Preview = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; + let input: LibraryPreviewParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?; item("surfaces", &input.id, command)?; let bytes = asset_bytes(&format!("{}/base_color", input.id), 2 * 1024 * 1024, command)?; - Ok(json!({"id":input.id,"mime":"image/png","sha256":HdrId::of(&bytes),"bytes":bytes, - "fidelity":"authored_base_color_source_map_not_a_render","document_changed":false})) + reply( + command, + LibraryPreview { + id: input.id, + mime: "image/png".into(), + sha256: HdrId::of(&bytes).to_string(), + bytes, + fidelity: "authored_base_color_source_map_not_a_render".into(), + document_changed: false, + param_warnings: Vec::new(), + }, + ) } /// The key is matched against generated constants, never joined to a filesystem path. diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs index 0e212f8f8..3e3a37f30 100644 --- a/crates/engine/src/schema/mod.rs +++ b/crates/engine/src/schema/mod.rs @@ -76,6 +76,7 @@ pub mod motion; pub mod panels; pub mod print_face; pub mod render; +pub mod render_library; pub mod render_lights; pub mod render_stage; pub mod render_ui; diff --git a/crates/engine/src/schema/render_library.rs b/crates/engine/src/schema/render_library.rs new file mode 100644 index 000000000..da76f0c16 --- /dev/null +++ b/crates/engine/src/schema/render_library.rs @@ -0,0 +1,370 @@ +//! Contracts and result types for the commands that browse the built-in render library, in +//! `cmd/render/library.rs` (#11443). `render.library.describe`, `.targets` and `.preview` read +//! these same parameter types, so the contract is exactly what they take. `render.library.list` +//! keeps the two readers it has: the physical profiles' takes `availability: null`, the other +//! catalogs' doesn't. Its type takes what either takes, and its schema says which `kind` takes +//! which (`availability_by_kind`). Like the handlers, a contract refuses unknown keys. + +use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema}; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +/// Every catalog `render.library.list` and `render.library.describe` read. +const KINDS: &[&str] = &[ + "capabilities", + "environments", + "hdr", + "lighting", + "materials", + "native_scenes", + "physical_profiles", + "quality", + "rigs", + "scenes", + "selene_appearances", + "selene_shots", + "surface_manifest", + "surfaces", +]; + +/// List a page of one catalog of the built-in render library: each resource's id and name, its +/// family, its source's status, and what the app can do with it. Nothing is changed, read from a +/// file or rendered. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(transform = availability_by_kind)] +pub struct LibraryListParams { + /// The catalog. Default: surfaces. + #[serde(default = "surfaces")] + #[schemars(schema_with = "list_kind_schema")] + pub kind: String, + /// Text to look for, ignoring case: in a resource's id, name, family, description, domains, + /// process, intended use and tags, or a physical profile's id, designation, family and + /// material form. At most 256 bytes, without control characters. Default: every resource. + #[serde(default)] + pub query: String, + /// Which resources: `all`, `usable` (the app can use them now), `specification` (described, + /// not usable) or `blocked`. Physical profiles take only `all`, `usable` or `null`; the other + /// catalogs don't take `null`. Default: all. + #[serde(default)] + #[schemars(schema_with = "availability_schema")] + pub availability: Option, + /// How many matching resources to skip: at most 4096. Default: 0. + #[serde(default)] + #[schemars(range(max = 4096))] + pub offset: usize, + /// The most resources on the page: 1 to 128. Default: 48. + #[serde(default = "page")] + #[schemars(range(min = 1, max = 128))] + pub limit: usize, +} + +fn surfaces() -> String { + "surfaces".into() +} + +fn page() -> usize { + 48 +} + +fn list_kind_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "enum": KINDS, "default": "surfaces"}) +} + +fn availability_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": ["string", "null"], "enum": ["all", "usable", "specification", "blocked", null]}) +} + +/// Which `availability` each of `render.library.list`'s readers takes, by `kind`: the physical +/// profiles' takes `all`, `usable` or `null`; every other catalog's (an absent `kind` is +/// `surfaces`) takes the four filters but not `null`. Only the schema says this. The type leaves +/// the refusal to the readers, which check the query and the page first, so a call with more +/// than one mistake keeps the handler's first message. +fn availability_by_kind(schema: &mut Schema) { + let others: Vec<&str> = KINDS.iter().copied().filter(|kind| *kind != "physical_profiles").collect(); + schema.insert( + "anyOf".into(), + serde_json::json!([ + {"required": ["kind"], "properties": {"kind": {"enum": ["physical_profiles"]}, "availability": {"enum": ["all", "usable", null]}}}, + {"properties": {"kind": {"enum": others}, "availability": {"enum": ["all", "usable", "specification", "blocked"]}}} + ]), + ); +} + +/// Describe one resource of a catalog of the built-in render library: the resource as its +/// source holds it, and what the app can do with it. A described concept is not a preset the +/// app can run. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryDescribeParams { + /// The catalog, as `render.library.list` takes it. + #[schemars(schema_with = "kind_schema")] + pub kind: String, + /// The resource's exact id, as `render.library.list` gives it: 1 to 128 ASCII letters, + /// digits, hyphens or underscores. + pub id: String, +} + +fn kind_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({"type": "string", "enum": KINDS}) +} + +/// List a page of the bodies a render would show, with their place in the render scene and +/// their looks, to pick the targets for the library's surfaces. The model is brought up to date +/// first, as for any command; no mesh is returned. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct LibraryTargetsParams { + /// Text to look for in a body's name, ignoring case: at most 256 bytes, without control + /// characters. Default: every body. + pub query: String, + /// How many matching bodies to skip: at most 262 144. Default: 0. + #[schemars(range(max = 262_144))] + pub offset: usize, + /// The most bodies on the page: 1 to 128. Default: 128. + #[schemars(range(min = 1, max = 128))] + pub limit: usize, +} + +impl Default for LibraryTargetsParams { + fn default() -> Self { + Self { query: String::new(), offset: 0, limit: 128 } + } +} + +/// Read a library surface's original base-colour map, as PNG bytes checked against their +/// recorded hash. This is the source picture, not a render of the material. It needs a build +/// with the bundled render library. +#[derive(Debug, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct LibraryPreviewParams { + /// The surface's id: `SURF-` and its number, as `render.library.list` gives it. + pub id: String, +} + +/// What `render.library.list` returns: a page of one catalog. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryPage { + /// The catalog listed. + pub kind: String, + /// How many resources match, on all pages together. + pub total: usize, + /// How many matching resources come before this page. + pub offset: usize, + /// The `offset` of the next page; `null` on the last page. + pub next_offset: Option, + /// The page's resources. A physical profile's has its own fields. + #[schemars(with = "Vec")] + pub items: Vec, + /// 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, +} + +/// A resource on a page: of a catalog, or a physical profile. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum LibraryItem { + Resource(ResourceSummary), + Profile(ProfileSummary), +} + +/// A resource of a catalog, as a page lists it. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ResourceSummary { + pub id: String, + pub name: String, + /// The kinds of product it suits; `null` when its catalog gives none. + pub domains: Option>, + /// Its family; `null` when its catalog gives none. + pub family: Option, + /// The status its source gives it; `null` when the source gives none. + pub source_status: Option, + #[schemars(schema_with = "projection_schema")] + pub projection: Value, +} + +/// A physical profile, as a page lists it: a reference material's measured properties to choose +/// from. It is never assigned to a body by itself. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileSummary { + pub id: String, + /// Its designation. + pub name: String, + pub family: String, + /// Always `reference_selection_required`: someone has to choose it. + pub source_status: String, + #[schemars(schema_with = "projection_schema")] + pub projection: Value, + /// How many properties it gives. + pub property_count: usize, +} + +/// What the app can do with a resource: its `status`, and the forms it can take or why it can't. +fn projection_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ + "description": "What the app can do with the resource: its `status`, and the forms it can take or why it can't.", + "type": "object", + "properties": { + "status": { + "description": "`implemented_pending_batch_validation`: the app can use it. `native_composition`: a studio scene the app builds. `blocked`: not in this build, or not usable as authored. `specification_only`: described, not usable. `reference_only`: a physical profile, read but never assigned.", + "type": "string", + "enum": ["implemented_pending_batch_validation", "native_composition", "blocked", "specification_only", "reference_only"] + }, + "variants": {"description": "The forms it can be used in.", "type": "array", "items": {"type": "string"}}, + "reason": {"description": "Why it is blocked or only a specification.", "type": "string"}, + "omitted": {"description": "What the app leaves out of it.", "type": "array", "items": {"type": "string"}} + }, + "required": ["status"] + }) +} + +/// What `render.library.describe` returns: a resource of a catalog, or a physical profile. +#[derive(Debug, Serialize, JsonSchema)] +#[serde(untagged)] +pub enum LibraryDescription { + Resource(LibraryResource), + Profile(ProfileDescription), +} + +/// A resource of a catalog, described. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryResource { + /// The catalog. + pub kind: String, + /// The resource as its catalog holds it, unchanged. + pub resource: Map, + #[schemars(schema_with = "projection_schema")] + pub projection: Value, + /// Always true: describing a resource leaves its catalog as it is. + pub source_manifest_unchanged: bool, + /// For a material or a surface: the physical profiles that may suit it, which nothing + /// assigns by itself. + #[serde(skip_serializing_if = "Option::is_none")] + #[schemars(with = "Option")] + pub physical_references: Option, + /// 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, +} + +/// The physical profiles that may suit a material or a surface. +#[derive(Debug, Serialize, JsonSchema)] +pub struct PhysicalReferences { + /// What the material or surface asks of a physical material, from the bindings catalog. + pub specifications: Vec>, + /// The profiles that meet it, as a page lists them. + pub candidate_profiles: Vec, + /// Always false: no profile is assigned by itself. + pub auto_assign: bool, + /// Always false: a property a profile doesn't give is unknown, not zero. + pub unknown_is_zero: bool, +} + +/// A physical profile, described. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileDescription { + /// Always `physical_profiles`. + pub kind: String, + /// The profile as its catalog holds it, unchanged. + pub resource: Map, + #[schemars(schema_with = "projection_schema")] + pub projection: Value, + /// The physical material card the profile becomes in the app. + pub native_projection: Map, + /// That card's check. + pub native_validation: Value, + /// The sources of the profile's properties. + pub sources: Vec>, + /// The SHA-256 digests of the profiles and cards read. + pub receipts: ProfileReceipts, + /// Always false. + pub document_changed: bool, + /// Always false: describing assigns nothing. + pub physical_assignment: bool, + /// Always true. + pub source_manifest_unchanged: 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, +} + +/// The SHA-256 digests of the physical profile data read. +#[derive(Debug, Serialize, JsonSchema)] +pub struct ProfileReceipts { + pub profiles_sha256: String, + pub native_cards_sha256: String, +} + +/// What `render.library.targets` returns: a page of the bodies a render would show. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryTargets { + pub items: Vec, + /// How many bodies match, on all pages together. + pub total: usize, + /// How many matching bodies come before this page. + pub offset: usize, + /// The `offset` of the next page; `null` on the last page. + pub next_offset: Option, + /// The design's revision the bodies were read at. + pub revision: u64, + /// The box around every body shown (mm); `null` when none is. + pub bounds: Option, + /// 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, +} + +/// A body a render would show. +#[derive(Debug, Serialize, JsonSchema)] +pub struct RenderTarget { + /// Its place in the render scene, from 0, among all bodies shown. + pub ordinal: usize, + /// Its name, with its component's path when it is in one. + pub name: String, + /// Its colour: red, green and blue, 0 to 255. + pub color: [u8; 3], + /// How opaque it is: 1 is solid. + pub opacity: f64, + /// Its PBR look; `null` when it has none. + pub pbr: Option, +} + +/// A body's PBR look. +#[derive(Debug, Serialize, JsonSchema)] +pub struct Pbr { + pub metallic: f64, + pub roughness: f64, + pub dielectric_ior: f64, +} + +/// A box, by its corners (mm). +#[derive(Debug, Serialize, JsonSchema)] +pub struct SceneBounds { + pub min: [f64; 3], + pub max: [f64; 3], +} + +/// What `render.library.preview` returns: a surface's original base-colour map. +#[derive(Debug, Serialize, JsonSchema)] +pub struct LibraryPreview { + /// The surface's id. + pub id: String, + /// Always `image/png`. + pub mime: String, + /// The picture's SHA-256, in hex. + pub sha256: String, + /// The PNG file's bytes, each 0 to 255. + pub bytes: Vec, + /// Always `authored_base_color_source_map_not_a_render`: the source picture, not a render. + pub fidelity: String, + /// Always false. + 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, +} + +#[cfg(test)] +#[path = "render_library_tests.rs"] +mod tests; diff --git a/crates/engine/src/schema/render_library_tests.rs b/crates/engine/src/schema/render_library_tests.rs new file mode 100644 index 000000000..6724ba0d1 --- /dev/null +++ b/crates/engine/src/schema/render_library_tests.rs @@ -0,0 +1,145 @@ +use serde_json::{Value, json}; + +use super::{ + LibraryDescribeParams, LibraryDescription, LibraryListParams, LibraryPage, LibraryPreview, LibraryPreviewParams, LibraryTargets, + LibraryTargetsParams, +}; +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}; + +#[test] +fn schemas_and_the_key_check_agree() { + assert_keys(input_schema_for::(), &["availability", "kind", "limit", "offset", "query"]); + assert_keys(input_schema_for::(), &["id", "kind"]); + assert_keys(input_schema_for::(), &["limit", "offset", "query"]); + assert_keys(input_schema_for::(), &["id"]); +} + +/// The list's schema takes an `availability` exactly when the reader for its `kind` does: the +/// physical profiles' takes `null` but not `specification` or `blocked`, the others' the reverse. +#[test] +fn the_list_schema_takes_each_readers_availability() { + let schema = input_schema_for::(); + let schema = schema.as_value(); + let calls = [ + json!({}), + json!({"availability": "blocked"}), + json!({"availability": null}), + json!({"kind": "hdr", "availability": "specification"}), + json!({"kind": "hdr", "availability": null}), + json!({"kind": "physical_profiles"}), + json!({"kind": "physical_profiles", "availability": "usable"}), + json!({"kind": "physical_profiles", "availability": null}), + json!({"kind": "physical_profiles", "availability": "blocked"}), + json!({"kind": "physical_profiles", "availability": "specification"}), + ]; + for p in calls { + let handled = Session::default().execute("render.library.list", &p).is_ok(); + assert_eq!(conforms(schema, schema, &p), handled, "{p}"); + } +} + +#[test] +fn strict_keeps_todays_errors() { + let long = "x".repeat(257); + assert_strict_keeps_todays_errors(&[ + ("render.library.list", json!({"kind": "not-a-kind"})), + ("render.library.list", json!({"query": long})), + ("render.library.list", json!({"query": "a\u{7}b"})), + ("render.library.list", json!({"limit": 0})), + ("render.library.list", json!({"limit": 129})), + ("render.library.list", json!({"offset": 4097})), + ("render.library.list", json!({"availability": "sometimes"})), + ("render.library.list", json!({"availability": null})), + ("render.library.list", json!({"kind": "physical_profiles", "availability": "blocked"})), + ("render.library.list", json!({"kind": "physical_profiles", "limit": 0})), + ("render.library.describe", json!({"kind": "not-a-kind", "id": "MAT-001"})), + ("render.library.describe", json!({"kind": "materials", "id": "MAT 001"})), + ("render.library.describe", json!({"kind": "materials", "id": "MAT-999"})), + ("render.library.describe", json!({"kind": "physical_profiles", "id": "no-such-profile"})), + ("render.library.targets", json!({"limit": 0})), + ("render.library.targets", json!({"limit": 129})), + ("render.library.targets", json!({"query": long})), + ("render.library.targets", json!({"offset": 262_145})), + ("render.library.preview", json!({"id": "MAT-001"})), + ("render.library.preview", json!({"id": ""})), + ]); +} + +/// #11443: the four commands reply as their output schemas say, in Warn without warnings. Every +/// resource of every catalog, physical profiles included, is listed through its pages, and the +/// first of each is described. Like the handlers, warn and strict refuse a misspelt key. +#[test] +fn render_library_commands_reply_with_their_schemas() { + let (page, described, targets, preview) = ( + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + output_schema_for::(), + ); + let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() }; + let run = |s: &mut Session, id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")); + let matches = |schema: &schemars::Schema, r: &Value| { + let schema = schema.as_value(); + assert!(conforms(schema, schema, r), "{r} doesn't match {schema}"); + assert!(r.get("param_warnings").is_none(), "{r}"); + }; + let kinds = [ + "capabilities", + "environments", + "hdr", + "lighting", + "materials", + "native_scenes", + "physical_profiles", + "quality", + "rigs", + "scenes", + "selene_appearances", + "selene_shots", + "surface_manifest", + "surfaces", + ]; + for kind in kinds { + let mut offset = Some(0); + let mut first = None; + let mut listed = 0; + while let Some(at) = offset { + let r = run(&mut s, "render.library.list", json!({"kind": kind, "offset": at, "limit": 128})); + matches(&page, &r); + let items = r["items"].as_array().cloned().unwrap_or_default(); + first = first.or_else(|| items.first().map(|i| i["id"].clone())); + listed += items.len(); + offset = r["next_offset"].as_u64(); + } + assert!(listed > 0, "{kind} lists nothing"); + let id = first.unwrap_or_else(|| panic!("no first {kind}")); + let r = run(&mut s, "render.library.describe", json!({"kind": kind, "id": id})); + matches(&described, &r); + assert_eq!(r["physical_references"].is_object(), matches!(kind, "materials" | "surfaces"), "{kind}: {r}"); + } + matches(&page, &run(&mut s, "render.library.list", json!({"query": "brushed", "availability": "usable", "offset": 0, "limit": 5}))); + matches(&page, &run(&mut s, "render.library.list", json!({"kind": "physical_profiles", "availability": null}))); + let empty = run(&mut s, "render.library.targets", json!({})); + matches(&targets, &empty); + assert!(empty["bounds"].is_null(), "{empty}"); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 5, "body_name": "Target"})); + run( + &mut s, + "appearance.assign", + json!({"bodies": ["Target"], "color": [180, 120, 70], "pbr": {"metallic": 1.0, "roughness": 0.3, "dielectric_ior": 1.5}}), + ); + let r = run(&mut s, "render.library.targets", json!({"query": "targ", "offset": 0, "limit": 1})); + matches(&targets, &r); + assert_eq!((r["total"].as_u64(), r["items"][0]["name"].as_str()), (Some(1), Some("Target")), "{r}"); + assert!(r["items"][0]["pbr"].is_object() && r["bounds"].is_object(), "{r}"); + if cfg!(feature = "bundled-render-library") { + matches(&preview, &run(&mut s, "render.library.preview", json!({"id": "SURF-001"}))); + } + for level in [ParamCheck::Warn, ParamCheck::Strict] { + let mut s = Session { param_check: level, ..Session::default() }; + let error = s.execute("render.library.list", &json!({"knd": "hdr"})).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(error.contains("knd"), "{level:?}: {error}"); + } +} diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt index 1f61739dd..c5443ed5e 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -153,17 +153,13 @@ render.effects.describe render.export render.hdr.inspect render.library.appearance.apply -render.library.describe render.library.environment.apply -render.library.list render.library.physical.prepare -render.library.preview render.library.studio.apply render.library.studio.prepare render.library.surface.bind render.library.surface.prepare render.library.surface.unbind -render.library.targets render.optics.bind render.optics.unbind render.preflight