Render: save wood images with physical grain controls (#1599)

* Render: save wood images with physical grain controls

* Render: prepare plain glass before marking the GPU host ready
This commit is contained in:
selune
2026-11-05 04:49:46 +00:00
committed by GitHub
parent 6d2465b52d
commit 8691cefbbf
60 changed files with 5776 additions and 238 deletions
+17 -1
View File
@@ -26,10 +26,26 @@ mod shots;
mod staging;
mod studio_presets;
mod surface_bindings;
mod surface_resources;
mod textures;
mod transmission;
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("render.surface.import", "Import Surface Maps", crate::checked!("render.surface.import", surface_resources::import))
.icon("appearance")
.contract(&surface_resources::IMPORT_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_surface_resources::ImportResult>)
.params("name; set?: typed CPU raytrace or GPU path setup patch; body_index and body_name from render.scene; frame: world-mm origin/u/v physical repeat vectors; maps: explicit base_color_srgb/normal_opengl/roughness_linear/metallic_linear {path,expected_sha256?}; provenance:{author,source,license}; normal_strength?:1; flip_v?:false; replace?:false. Captures exact PNG/JPEG bytes and saves definition-local binding in one undo. CPU maps require noninterlaced 8-bit PNG. Saved designs reopen without the source files."),
CommandSpec::new("render.texture.list", "List Embedded Surface Images", crate::checked!("render.texture.list", surface_resources::list))
.icon("list").noundo().doc_only()
.contract(&surface_resources::LIST_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_surface_resources::ListResult>)
.params("No parameters. Lists bounded design-owned texture digests, byte counts, dimensions, declared provenance and referencing setups; never returns image bytes or source filesystem paths."),
CommandSpec::new("render.texture.remove", "Remove Embedded Surface Image", crate::checked!("render.texture.remove", surface_resources::remove))
.icon("delete").doc_only()
.contract(&surface_resources::REMOVE_CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render_surface_resources::RemoveResult>)
.params("sha256: exact embedded image digest. Refuses while any saved setup uses the image, listing its users. Removing an unused image is one undo step."),
CommandSpec::new("render.environment.set", "Set Render Environment", crate::checked!("render.environment.set", environment::set)).icon("settings").doc_only()
.contract(&environment::CONTRACT)
.output(crate::schema::output_schema_for::<crate::schema::render::EnvironmentResult>)
@@ -134,7 +150,7 @@ CommandSpec::new("render.library.appearance.apply", "Apply Library Opaque Appear
CommandSpec::new("render.library.environment.apply", "Apply Built-in HDR Environment", library::apply_environment).icon("settings").doc_only()
.params("id: HDR-*; name: saved setup; set?: typed CPU/GPU setup patch; rotation_rad?: authored rotation (native origin offset is explicit in the reply); intensity?:1; samples?:16 for CPU; replace_environment?:false. Hash-verifies and embeds original bytes, saves one atomic undo without external files or a render device. An HDR-owned sun cannot duplicate an analytic sun."),
CommandSpec::new("render.library.surface.prepare", "Prepare Authored Surface Maps", library::prepare_surface).icon("appearance").noundo()
.params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1. Returns an explicit GPU planar map binding with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."),
.params("id: SURF-*; body_index and body_name from render.scene; origin?:[0,0,0]; plane?:xy/yz/zx; scale?:1; rotation_rad?:0 (positive around the plane normal). Returns an explicit GPU planar map binding with source hashes, original millimetre scale, image-up normal orientation and absolute base-color semantics. No document change; height/displacement and true anisotropy are not included."),
CommandSpec::new("render.library.studio.prepare", "Prepare Authored Studio Lights", library::prepare_studio).icon("inspect").noundo().doc_only()
.params("id: RIG-*; variant: complete for emitter-only rigs, emitters_only for rigs with passive cards; center_mm and subject_extent_mm required. Converts exact rectangular half-edges and solar direction/radius to GPU lighting. Blocked calibration and external-sun rigs refuse. Returns a geometry-clearance review requirement; does not create cards or modify the scene."),
CommandSpec::new("render.library.studio.apply", "Apply Authored Studio Lights", library::apply_studio).icon("settings")
+11 -2
View File
@@ -336,6 +336,15 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
None
};
let mut scene = crate::product_scene::extract(s)?;
let textures = if let Some(bindings) = normalized.as_ref().map(|saved| &saved.surfaces).filter(|bindings| !bindings.is_empty()) {
if input.integrator != Integrator::Raytrace {
return Err(bad(command, "saved surface maps require a raytrace executor"));
}
let overrides = super::surface_bindings::resolve(s, &scene, bindings, command)?;
super::textures::capture_with_resources(&scene, &overrides, Some(&s.doc.render.texture_resources), command)?
} else {
None
};
if environment.is_some() {
input.raytrace.as_ref().unwrap_or(&RaytraceOptions::default()).validate_environment_reflections(&scene).map_err(job_error)?;
}
@@ -410,7 +419,7 @@ fn prepare(s: &Session, params: &Value, command: &str) -> Result<Prepared> {
let request = ImageRequest {
studio_weights: validate_studio_weights(input.studio_weights, command)?,
environment: None,
textures: None,
textures,
integrator: input.integrator,
raytrace: input.raytrace.take(),
camera: settings.camera,
@@ -624,7 +633,7 @@ fn prepare_progressive(
height: settings.height,
background: settings.background,
transparent_background: input.transparent_background,
textures: super::textures::capture(&scene, &input.raytrace.textures, command)?,
textures: super::textures::capture_with_resources(&scene, &input.raytrace.textures, Some(&s.doc.render.texture_resources), command)?,
};
let mut admission = host.admit(&scene, &request, options).map_err(job_error)?;
admission.estimated_total_bytes = admission
+11 -3
View File
@@ -505,6 +505,8 @@ struct SurfacePrepare {
scale: f64,
#[serde(default)]
plane: Plane,
#[serde(default)]
rotation_rad: f64,
}
#[derive(Default, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -522,12 +524,18 @@ pub(super) fn prepare_surface(s: &mut Session, params: &Value) -> Result<Value>
if !input.scale.is_finite() || !(0.001..=1000.0).contains(&input.scale) {
return Err(bad(command, "surface repeat scale must be finite in 0.001..1000"));
}
if !input.rotation_rad.is_finite() || input.rotation_rad.abs() > 1e6 {
return Err(bad(command, "surface grain rotation must be finite and within one million radians"));
}
let tile: [f64; 2] = serde_json::from_value(value["tile_mm"].clone()).map_err(|e| bad(command, e.to_string()))?;
let (u, v) = (tile[0] * input.scale, tile[1] * input.scale);
let (sin, cos) = input.rotation_rad.sin_cos();
// Rotate the unit directions before applying the two physical repeat lengths.
// Mixing the already-scaled vectors would skew non-square wood tiles.
let (u, v) = match input.plane {
Plane::Xy => ([u, 0.0, 0.0], [0.0, v, 0.0]),
Plane::Yz => ([0.0, u, 0.0], [0.0, 0.0, v]),
Plane::Zx => ([0.0, 0.0, u], [v, 0.0, 0.0]),
Plane::Xy => ([cos * u, sin * u, 0.0], [-sin * v, cos * v, 0.0]),
Plane::Yz => ([0.0, cos * u, sin * u], [0.0, -sin * v, cos * v]),
Plane::Zx => ([sin * u, 0.0, cos * u], [cos * v, 0.0, -sin * v]),
};
let scene = crate::product_scene::extract(s)?;
let body = scene
+236 -2
View File
@@ -1,4 +1,6 @@
use super::*;
#[cfg(not(target_arch = "wasm32"))]
use image::ImageEncoder;
#[cfg(feature = "bundled-render-library")]
use solidcraft_render::job::textures::{BaseColorMode, TextureMap};
@@ -37,6 +39,139 @@ fn authored_library_search_is_bounded_and_concepts_are_not_runtime_presets() {
assert_eq!(s.execute("render.library.list", &json!({"kind":"surfaces","query":"SURF-001"})).unwrap()["total"], 1);
}
#[cfg(not(target_arch = "wasm32"))]
fn custom_surface_fixture() -> (Session, std::path::PathBuf, Vec<u8>, Value) {
let mut s = Session::default();
s.execute("solid.box", &json!({"length":100,"width":40,"height":10,"body_name":"Board"})).unwrap();
let mut bytes = Vec::new();
image::codecs::png::PngEncoder::new(&mut bytes)
.write_image(&[128, 64, 32, 255, 192, 96, 48, 255, 64, 32, 16, 255, 224, 160, 96, 255], 2, 2, image::ExtendedColorType::Rgba8)
.unwrap();
let nonce = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let path = std::env::temp_dir().join(format!("solidcraft-wood-owned-{}-{nonce}.png", std::process::id()));
std::fs::write(&path, &bytes).unwrap();
let input = json!({"name":"Wood","set":{"width":64,"height":64,"job":{"method":"gpu_path","options":{}}},
"body_index":0,"body_name":"Board","frame":{"origin":[0,0,0],"u":[20,0,0],"v":[0,40,0]},
"maps":{"base_color_srgb":{"path":path,"expected_sha256":HdrId::of(&bytes)}},
"provenance":{"author":"Original test","source":"synthetic diagnostic","license":"CC0-1.0"}});
(s, path, bytes, input)
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn imported_wood_maps_reopen_without_source_and_keep_geometry_history_and_resource_users() {
let (mut s, path, bytes, mut input) = custom_surface_fixture();
// The exact same source in two explicitly different roles occupies one bank entry.
input["maps"]["roughness_linear"] = input["maps"]["base_color_srgb"].clone();
let before = s.doc.to_json();
let physical = (s.doc.materials.clone(), s.doc.features.clone());
let undo = s.undo.len();
let result = s.execute("render.surface.import", &input).unwrap();
assert_eq!(result["self_contained"], true);
assert_eq!(s.undo.len(), undo + 1);
assert_eq!((s.doc.materials.clone(), s.doc.features.clone()), physical);
assert_eq!(s.doc.render.texture_resources.len(), 1);
let digest = HdrId::of(&bytes);
assert_eq!(s.doc.render.texture_resources.required(&digest).unwrap().bytes(), bytes);
let temporary: super::super::textures::Override = serde_json::from_value(json!({
"body_index":0,"body_name":"Board","frame":{"origin":[0,0,0],"u":[20,0,0],"v":[0,40,0]},"base_color_srgb":path
}))
.unwrap();
let temporary = super::super::textures::capture(&crate::product_scene::extract(&s).unwrap(), &[temporary], "test").unwrap().unwrap();
assert!(!temporary.bindings()[0].base_color.as_ref().unwrap().gpu_mip_filtering(), "temporary paths retain legacy GPU sampling");
std::fs::remove_file(&path).unwrap();
let saved = s.doc.to_json();
assert!(!saved.contains(path.to_str().unwrap()));
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
reopened.execute("render.scene", &json!({})).unwrap();
let scene = crate::product_scene::extract(&reopened).unwrap();
let bindings = &reopened.doc.render.setups["Wood"].surfaces;
let lowered = super::super::surface_bindings::resolve(&reopened, &scene, bindings, "test").unwrap();
let captured =
super::super::textures::capture_with_resources(&scene, &lowered, Some(&reopened.doc.render.texture_resources), "test").unwrap().unwrap();
let map = captured.bindings()[0].base_color.as_ref().unwrap();
assert!(map.gpu_mip_filtering(), "reopened imported images retain their new filtering policy");
assert!(captured.bindings()[0].roughness.as_ref().unwrap().gpu_mip_filtering());
assert_eq!(map.dimensions(), [2, 2]);
let pixels = map.decode(&solidcraft_render::job::CancelToken::default()).unwrap();
let expected = ((128.0_f64 / 255.0 + 0.055) / 1.055).powf(2.4);
assert!((f64::from(pixels[0]) - expected).abs() < 1e-7);
assert_eq!(captured.bindings()[0].frame.u, [20.0, 0.0, 0.0]);
assert_eq!(captured.bindings()[0].frame.v, [0.0, 40.0, 0.0]);
let list = reopened.execute("render.texture.list", &json!({})).unwrap();
assert_eq!(list["resources"][0]["sha256"], digest.to_string());
assert_eq!(list["resources"][0]["users"], json!(["Wood"]));
assert!(reopened.execute("render.texture.remove", &json!({"sha256":digest})).unwrap_err().to_string().contains("Wood"));
let target = reopened.doc.render.setups["Wood"].surfaces.iter().next().unwrap().target.clone();
reopened.execute("render.library.surface.unbind", &json!({"name":"Wood","target":target})).unwrap();
reopened.execute("render.texture.remove", &json!({"sha256":digest})).unwrap();
assert!(reopened.doc.render.texture_resources.is_empty());
reopened.execute("edit.undo", &json!({})).unwrap();
assert_eq!(reopened.doc.render.texture_resources.required(&digest).unwrap().bytes(), bytes);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc.to_json(), before);
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.doc.to_json(), saved);
assert!(Session::default().doc.render.texture_resources.is_empty());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn imported_surface_refusals_are_atomic_and_validate_identity_before_source_access() {
let (mut s, path, _, input) = custom_surface_fixture();
let before = s.doc.to_json();
let history = (s.revision, s.undo.len());
for patch in [
json!({"body_name":"Wrong", "maps":{"base_color_srgb":{"path":"missing-file.png"}}}),
json!({"normal_strength":2.0}),
json!({"frame":{"origin":[0,0,0],"u":[20,0,0],"v":[20,0,0]}}),
json!({"maps":{}}),
json!({"maps":{"base_color_srgb":{"path":path,"expected_sha256":"0".repeat(64)}}}),
json!({"set":{"job":{"method":"raster"}}}),
json!({"provenance":{"author":"bad\ntext","source":"synthetic","license":"CC0"}}),
] {
let mut request = input.clone();
for (field, value) in patch.as_object().unwrap() {
request[field] = value.clone();
}
assert!(s.execute("render.surface.import", &request).is_err(), "{request}");
assert_eq!(s.doc.to_json(), before);
assert_eq!((s.revision, s.undo.len()), history);
}
let mut request = input.clone();
request["maps"]["normal_opengl"] = json!({"path":"missing-later-map.png"});
assert!(s.execute("render.surface.import", &request).is_err());
assert_eq!(s.doc.to_json(), before, "a later failed map cannot leak an earlier imported resource");
std::fs::remove_file(path).unwrap();
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn cpu_surface_import_and_method_switch_reject_unsupported_encoding_without_losing_the_gpu_binding() {
let (mut s, path, _, mut input) = custom_surface_fixture();
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new(&mut jpeg).write_image(&[128_u8; 12], 2, 2, image::ExtendedColorType::Rgb8).unwrap();
std::fs::write(&path, &jpeg).unwrap();
input["maps"]["base_color_srgb"]["expected_sha256"] = json!(HdrId::of(&jpeg));
input["set"]["job"]["method"] = json!("cpu_raytrace");
let before = s.doc.to_json();
let history = (s.revision, s.undo.len());
assert!(s.execute("render.surface.import", &input).unwrap_err().to_string().contains("noninterlaced 8-bit PNG"));
assert_eq!(s.doc.to_json(), before);
assert_eq!((s.revision, s.undo.len()), history);
input["set"]["job"]["method"] = json!("gpu_path");
s.execute("render.surface.import", &input).unwrap();
let saved = s.doc.to_json();
assert!(
s.execute("render.settings.set", &json!({"name":"Wood","set":{"job":{"method":"cpu_raytrace","options":{}}}}))
.unwrap_err()
.to_string()
.contains("noninterlaced 8-bit PNG")
);
assert_eq!(s.doc.to_json(), saved);
std::fs::remove_file(path).unwrap();
}
#[cfg(feature = "bundled-render-library")]
#[test]
fn built_in_maps_keep_exact_published_bytes_and_explicit_channel_roles() {
@@ -128,12 +263,104 @@ fn explicit_surface_prepare_has_physical_scale_and_does_not_assign_materials() {
let textures = super::super::textures::capture(&scene, &[input], "test").unwrap().unwrap();
let binding = &textures.bindings()[0];
assert!(binding.flip_v && binding.roughness.is_some() && binding.metallic.is_some());
for map in [&binding.base_color, &binding.normal, &binding.roughness, &binding.metallic].into_iter().flatten() {
assert!(!map.gpu_mip_filtering(), "built-in preparation retains legacy GPU sampling");
}
assert_eq!(binding.base_color_mode, BaseColorMode::Replace);
assert_eq!(s.doc.to_json(), before);
assert_eq!(s.undo.len(), undo);
assert!(s.execute("render.library.surface.prepare", &json!({"id":"SURF-001","body_index":0,"body_name":"Old name"})).is_err());
}
#[cfg(feature = "bundled-render-library")]
#[test]
fn wood_grain_rotation_preserves_non_square_repeats_in_each_plane() {
use solidcraft_render::job::textures::PlanarFrame;
let mut s = Session::default();
s.execute("solid.box", &json!({"length":100,"width":100,"height":20,"body_name":"Board"})).unwrap();
let before = s.doc.to_json();
let history = (s.undo.len(), s.redo.len());
for (plane, expected_u, expected_v) in
[("xy", [0.0, 60.0, 0.0], [-120.0, 0.0, 0.0]), ("yz", [0.0, 0.0, 60.0], [0.0, -120.0, 0.0]), ("zx", [60.0, 0.0, 0.0], [0.0, 0.0, -120.0])]
{
let reply = s
.execute(
"render.library.surface.prepare",
&json!({"id":"SURF-027","body_index":0,"body_name":"Board","plane":plane,"scale":0.25,
"rotation_rad":std::f64::consts::FRAC_PI_2}),
)
.unwrap();
let frame: PlanarFrame = serde_json::from_value(reply["texture"]["frame"].clone()).unwrap();
for ((u, expected_u), (v, expected_v)) in frame.u.into_iter().zip(expected_u).zip(frame.v.into_iter().zip(expected_v)) {
assert!((u - expected_u).abs() < 1e-10);
assert!((v - expected_v).abs() < 1e-10);
}
let reply = s
.execute(
"render.library.surface.prepare",
&json!({"id":"SURF-027","body_index":0,"body_name":"Board","plane":plane,"scale":0.25,
"rotation_rad":std::f64::consts::FRAC_PI_4}),
)
.unwrap();
let frame: PlanarFrame = serde_json::from_value(reply["texture"]["frame"].clone()).unwrap();
let len2 = |v: [f64; 3]| v.into_iter().map(|x| x * x).sum::<f64>();
assert!((len2(frame.u) - 60.0 * 60.0).abs() < 1e-9);
assert!((len2(frame.v) - 120.0 * 120.0).abs() < 1e-9);
assert!(frame.u.into_iter().zip(frame.v).map(|(u, v)| u * v).sum::<f64>().abs() < 1e-9);
}
for angle in [json!(1_000_001.0), json!(-1_000_001.0), Value::Null, json!("90 deg"), json!([])] {
assert!(
s.execute("render.library.surface.prepare", &json!({"id":"SURF-027","body_index":0,"body_name":"Board","rotation_rad":angle})).is_err()
);
}
assert_eq!(s.doc.to_json(), before);
assert_eq!((s.undo.len(), s.redo.len()), history);
}
#[cfg(feature = "bundled-render-library")]
#[test]
fn saved_wood_grain_angle_reopens_and_rotates_with_only_its_occurrence() {
let mut s = Session::default();
let component = s.execute("component.create", &json!({"name":"Board part","grounded":false})).unwrap();
s.execute("solid.box", &json!({"length":100,"width":40,"height":10,"body_name":"Board"})).unwrap();
s.execute("component.activate", &json!({"component":0})).unwrap();
s.execute("occurrence.copy", &json!({"component":component["component"],"translate":[150,0,0]})).unwrap();
let physical = (s.doc.materials.clone(), s.doc.features.clone());
s.execute(
"render.library.surface.bind",
&json!({"name":"Grain","set":{"job":{"method":"gpu_path","options":{}}},
"surface":{"id":"SURF-027","body_index":0,"body_name":"Board","scale":0.25,
"rotation_rad":std::f64::consts::FRAC_PI_4}}),
)
.unwrap();
assert_eq!((s.doc.materials.clone(), s.doc.features.clone()), physical);
let saved = s.doc.to_json();
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());
reopened.execute("render.scene", &json!({})).unwrap();
let bindings = reopened.doc.render.setups["Grain"].surfaces.clone();
let lower = |session: &Session| {
let scene = crate::product_scene::extract(session).unwrap();
let lowered = super::super::surface_bindings::resolve(session, &scene, &bindings, "test").unwrap();
super::super::textures::capture(&scene, &lowered, "test").unwrap().unwrap().bindings().iter().map(|binding| binding.frame).collect::<Vec<_>>()
};
let first = lower(&reopened);
assert_eq!(first.len(), 1);
let frame = first[0];
reopened.execute("occurrence.move", &json!({"occurrence":component["occurrence"],"axis":[0,0,1],"angle":std::f64::consts::FRAC_PI_2})).unwrap();
let rotated = lower(&reopened);
assert_eq!(rotated.len(), 1);
for (actual, old) in [(rotated[0].u, frame.u), (rotated[0].v, frame.v)] {
assert!((actual[0] + old[1]).abs() < 1e-10);
assert!((actual[1] - old[0]).abs() < 1e-10);
assert!((actual[2] - old[2]).abs() < 1e-10);
}
assert_eq!(reopened.doc.render.setups["Grain"].surfaces, bindings);
assert_eq!(reopened.doc.materials, physical.0);
assert_eq!(reopened.doc.features, physical.1);
reopened.execute("edit.undo", &json!({})).unwrap();
assert_eq!(lower(&reopened)[0], frame);
}
#[test]
fn uniform_appearance_requires_acknowledged_projection_and_preserves_physical_data() {
let mut s = Session::default();
@@ -211,9 +438,16 @@ fn saved_authored_maps_roundtrip_and_resolve_without_paths_or_captured_ordinals(
assert_eq!(maps.bindings()[0].body_name, "Coupon");
assert_eq!(maps.bindings()[0].base_color_mode, BaseColorMode::Replace);
assert!(maps.bindings()[0].flip_v);
for map in [&maps.bindings()[0].base_color, &maps.bindings()[0].normal, &maps.bindings()[0].roughness, &maps.bindings()[0].metallic]
.into_iter()
.flatten()
{
assert!(!map.gpu_mip_filtering(), "existing saved built-in surfaces retain legacy GPU sampling");
}
let mut changed = s.doc.render.setups["Portable"].clone();
let mut binding = changed.surfaces.iter().next().unwrap().clone();
binding.source.base_color_sha256 = HdrId::of(b"changed");
let solidcraft_doc::render_surface::SurfaceSource::Builtin(source) = &mut binding.source else { panic!("built-in fixture") };
source.base_color_sha256 = HdrId::of(b"changed");
changed.surfaces.set(binding, true).unwrap();
assert!(super::super::surface_bindings::resolve(&s, &crate::product_scene::extract(&s).unwrap(), &changed.surfaces, "test").is_err());
s.execute("edit.undo", &json!({})).unwrap();
@@ -290,7 +524,7 @@ fn saved_surface_rejects_changed_feature_and_hidden_target_and_can_be_removed_of
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc, previous);
let before = s.doc.to_json();
assert!(s.execute("render.settings.set", &json!({"name":"P","set":{"job":{"method":"cpu_raytrace","options":{}}}})).is_err());
assert!(s.execute("render.settings.set", &json!({"name":"P","set":{"job":{"method":"raster"}}})).is_err());
assert_eq!(s.doc.to_json(), before);
}
@@ -7,7 +7,7 @@ use solidcore_record::Vec3;
use solidcraft_doc::{
render_resources::HdrId,
render_settings::{RenderJob, RenderSetup},
render_surface::{BuiltinSurfaceSource, RenderBodyTarget, SavedSurface, SurfaceBindings},
render_surface::{BuiltinSurfaceSource, RenderBodyTarget, SavedSurface, SurfaceBindings, SurfaceSource},
};
use solidcraft_render::{ProductScene, job::textures::PlanarFrame};
use std::{collections::BTreeMap, sync::Arc};
@@ -18,7 +18,7 @@ fn vec(a: [f64; 3]) -> Vec3 {
fn array(v: Vec3) -> [f64; 3] {
[v.x, v.y, v.z]
}
fn transform(frame: PlanarFrame, m: &solidcraft_doc::Mat, command: &str) -> Result<PlanarFrame> {
pub(super) fn transform(frame: PlanarFrame, m: &solidcraft_doc::Mat, command: &str) -> Result<PlanarFrame> {
let result = PlanarFrame {
origin: array(solidcraft_doc::apply_point(m, vec(frame.origin))),
u: array(solidcraft_doc::apply_vector(m, vec(frame.u))),
@@ -85,7 +85,9 @@ pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &SurfaceBindi
let mut result = Vec::new();
result.try_reserve_exact(bindings.len()).map_err(|_| bad(command, "could not reserve saved surface lowering"))?;
for binding in bindings.iter() {
if binding.source != source(&binding.source.id, command)? {
if let SurfaceSource::Builtin(builtin) = &binding.source
&& *builtin != source(&builtin.id, command)?
{
return Err(bad(command, "saved surface version or SHA-256 differs from installed source; explicit rebinding required"));
}
let name =
@@ -96,10 +98,36 @@ pub(super) fn resolve(s: &Session, scene: &ProductScene, bindings: &SurfaceBindi
return Err(bad(command, "surface definition/world mapping disagrees"));
}
let frame = transform(binding.local_frame, &body.source_transform, command)?;
let id = &binding.source.id;
let wire = json!({"body_index":ordinal,"body_name":name,"frame":frame,"normal_strength":binding.normal_strength,
"flip_v":true,"base_color_mode":"replace","base_color_srgb":format!("builtin://{id}/base_color"),
"normal_opengl":format!("builtin://{id}/normal_open_gl"),"roughness_linear":format!("builtin://{id}/roughness"),"metallic_linear":format!("builtin://{id}/metallic")});
let mut wire = json!({"body_index":ordinal,"body_name":name,"frame":frame,"normal_strength":binding.normal_strength,
"base_color_mode":"replace"});
match &binding.source {
SurfaceSource::Builtin(source) => {
let id = &source.id;
wire["flip_v"] = json!(true);
for (field, role) in [
("base_color_srgb", "base_color"),
("normal_opengl", "normal_open_gl"),
("roughness_linear", "roughness"),
("metallic_linear", "metallic"),
] {
wire[field] = json!(format!("builtin://{id}/{role}"));
}
}
SurfaceSource::Embedded(source) => {
wire["flip_v"] = json!(source.flip_v);
for (field, id) in [
("base_color_srgb", source.base_color),
("normal_opengl", source.normal_open_gl),
("roughness_linear", source.roughness),
("metallic_linear", source.metallic),
] {
if let Some(id) = id {
s.doc.render.texture_resources.required(&id).map_err(|e| bad(command, e.to_string()))?;
wire[field] = json!(format!("embedded://{id}"));
}
}
}
}
result.push(serde_json::from_value(wire).map_err(|e| bad(command, e.to_string()))?);
}
Ok(result)
@@ -135,8 +163,8 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(command, "setup patch cannot erase or replace saved surface bindings; use explicit bind/unbind commands"));
}
if !matches!(setup.job, Some(RenderJob::GpuPath { .. })) {
return Err(bad(command, "persistent authored maps require an explicit GPU setup"));
if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) {
return Err(bad(command, "persistent authored maps require an explicit CPU raytrace or GPU path setup"));
}
let prepared = super::library::prepare_surface(s, &input.surface)?;
let id = prepared["id"].as_str().ok_or_else(|| bad(command, "missing prepared surface identifier"))?;
@@ -154,7 +182,7 @@ pub(super) fn bind(s: &mut Session, params: &Value) -> Result<Value> {
setup
.surfaces
.set(
SavedSurface { target, source: source(id, command)?, local_frame: transform(frame, &inverse, command)?, normal_strength: 1.0 },
SavedSurface { target, source: source(id, command)?.into(), local_frame: transform(frame, &inverse, command)?, normal_strength: 1.0 },
input.replace,
)
.map_err(|e| bad(command, e.to_string()))?;
@@ -0,0 +1,189 @@
//! Capture source maps atomically, retain exact bytes, and bind a local physical frame.
use crate::schema::render_surface_resources::{
ImportParams, ImportResult, ListParams, ListResult, RemoveParams, RemoveResult, ResourceInfo, TextureFile,
};
use crate::{Result, Session, params::bad, schema::TypedContract};
use serde_json::{Value, json};
use solidcraft_doc::{
render_resources::HdrId,
render_settings::RenderJob,
render_surface::{EmbeddedSurfaceKind, EmbeddedSurfaceSource, SavedSurface, SurfaceSource},
render_texture_resources::{MAX_TEXTURE_RESOURCE_BYTES, TextureProvenance, TextureResource, TextureResources},
};
use solidcraft_render::job::textures::PlanarFrame;
use solidcraft_render::texture_input::MapRole;
use std::sync::Arc;
pub(super) const IMPORT_CONTRACT: TypedContract<ImportParams> = TypedContract::new();
pub(super) const LIST_CONTRACT: TypedContract<ListParams> = TypedContract::new();
pub(super) const REMOVE_CONTRACT: TypedContract<RemoveParams> = TypedContract::new();
fn id(value: &str, command: &str) -> Result<HdrId> {
serde_json::from_value(json!(value)).map_err(|e| bad(command, e.to_string()))
}
fn capture(
input: Option<&TextureFile>,
role: MapRole,
resources: &mut TextureResources,
provenance: &TextureProvenance,
command: &str,
) -> Result<Option<HdrId>> {
let Some(input) = input else { return Ok(None) };
if input.path.is_empty() || input.path.len() > 4096 || input.path.chars().any(char::is_control) {
return Err(bad(command, "texture import requires a bounded scoped local path"));
}
let expected = input.expected_sha256.as_deref().map(|value| id(value, command)).transpose()?;
let bytes = solidcraft_io::vfs::read(&input.path, solidcraft_render::texture_input::MAX_TEXTURE_BYTES)
.map_err(|e| bad(command, format!("could not capture texture: {e}")))?;
if expected.is_some_and(|expected| expected != HdrId::of(&bytes)) {
return Err(bad(command, "texture file changed since selection; inspect and select it again"));
}
// Validation and all resource inserts affect the private settings copy only.
let resource = TextureResource::new(bytes, provenance.clone()).map_err(|e| bad(command, e.to_string()))?;
resource.validate_role(role).map_err(|e| bad(command, e.to_string()))?;
resources.insert(resource).map(Some).map_err(|e| bad(command, e.to_string()))
}
pub(super) fn import(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.surface.import";
let input: ImportParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
let mut setup = super::patched_settings(s, &input.name, &input.set, command)?;
if !matches!(setup.job, Some(RenderJob::CpuRaytrace { .. } | RenderJob::GpuPath { .. })) {
return Err(bad(command, "imported surface maps require an explicit CPU raytrace or GPU path setup"));
}
if s.doc.render.setups.get(&input.name).is_some_and(|previous| previous.surfaces != setup.surfaces) {
return Err(bad(command, "setup patch cannot erase saved surface bindings; use explicit unbind"));
}
let frame = PlanarFrame { origin: input.frame.origin, u: input.frame.u, v: input.frame.v };
frame.validate().map_err(|e| bad(command, e.to_string()))?;
if !input.normal_strength.is_finite() || !(0.0..=1.0).contains(&input.normal_strength) {
return Err(bad(command, "normal strength must be finite in 0..1"));
}
if input.maps.base_color_srgb.is_none()
&& input.maps.normal_opengl.is_none()
&& input.maps.roughness_linear.is_none()
&& input.maps.metallic_linear.is_none()
{
return Err(bad(command, "import at least one explicitly typed surface map"));
}
let scene = crate::product_scene::extract(s)?;
let body = scene
.meshes
.get(input.body_index)
.filter(|body| body.name == input.body_name)
.ok_or_else(|| bad(command, "body ordinal and name must both match render.scene"))?;
if body.opacity != 1.0 || body.transmission.is_some() || body.faces.iter().any(|face| face.opacity != 1.0 || face.transmission.is_some()) {
return Err(bad(command, "imported maps support opaque bodies only"));
}
let bounds = body.mesh.bounds();
for x in [bounds.min.x, bounds.max.x] {
for y in [bounds.min.y, bounds.max.y] {
for z in [bounds.min.z, bounds.max.z] {
frame.uv(solidcore_record::Vec3::new(x, y, z)).map_err(|e| bad(command, e.to_string()))?;
}
}
}
let targets = super::surface_bindings::targets(s, command)?;
let mut matching = targets.iter().filter(|(_, name)| **name == input.body_name);
let target = matching.next().map(|(target, _)| target.clone()).ok_or_else(|| bad(command, "surface target has no stable identity"))?;
if matching.next().is_some() {
return Err(bad(command, "surface target has ambiguous identity"));
}
if !input.replace && setup.surfaces.iter().any(|binding| binding.target == target) {
return Err(bad(command, "surface target already has a binding; explicit replacement required"));
}
let world = s.world_state()?;
let computed = world.bodies.iter().find(|body| body.name == input.body_name).ok_or_else(|| bad(command, "surface world body disappeared"))?;
let inverse = solidcraft_doc::mat_inverse(&computed.source_transform).ok_or_else(|| bad(command, "surface placement is not invertible"))?;
let local_frame = super::surface_bindings::transform(frame, &inverse, command)?;
let provenance = TextureProvenance { author: input.provenance.author, source: input.provenance.source, license: input.provenance.license };
let mut settings = (*s.doc.render).clone();
let source = EmbeddedSurfaceSource {
kind: EmbeddedSurfaceKind::Embedded,
base_color: capture(input.maps.base_color_srgb.as_ref(), MapRole::BaseColor, &mut settings.texture_resources, &provenance, command)?,
normal_open_gl: capture(input.maps.normal_opengl.as_ref(), MapRole::NormalOpenGl, &mut settings.texture_resources, &provenance, command)?,
roughness: capture(input.maps.roughness_linear.as_ref(), MapRole::Roughness, &mut settings.texture_resources, &provenance, command)?,
metallic: capture(input.maps.metallic_linear.as_ref(), MapRole::Metallic, &mut settings.texture_resources, &provenance, command)?,
flip_v: input.flip_v,
};
setup
.surfaces
.set(
SavedSurface { target, source: SurfaceSource::Embedded(source.clone()), local_frame, normal_strength: input.normal_strength },
input.replace,
)
.map_err(|e| bad(command, e.to_string()))?;
settings.setups.insert(input.name.clone(), setup.clone());
settings.validate().map_err(|e| bad(command, e.to_string()))?;
if settings.texture_resources.total_bytes() > MAX_TEXTURE_RESOURCE_BYTES {
return Err(bad(command, "encoded texture resources exceed the design budget"));
}
let resources = [source.base_color, source.normal_open_gl, source.roughness, source.metallic]
.into_iter()
.flatten()
.map(|digest| digest.to_string())
.collect();
let result = ImportResult {
name: input.name,
setup: serde_json::to_value(setup).map_err(|e| bad(command, e.to_string()))?,
resources,
self_contained: true,
mapping_space: "definition_local_mm".into(),
};
if settings != *s.doc.render {
s.doc_mut().render = Arc::new(settings);
}
serde_json::to_value(result).map_err(|e| bad(command, e.to_string()))
}
fn users(s: &Session, id: HdrId) -> Vec<String> {
s.doc
.render
.setups
.iter()
.filter(|(_, setup)| {
setup.surfaces.iter().any(|binding| match &binding.source {
SurfaceSource::Embedded(source) => [source.base_color, source.normal_open_gl, source.roughness, source.metallic].contains(&Some(id)),
SurfaceSource::Builtin(_) => false,
})
})
.map(|(name, _)| name.clone())
.collect()
}
pub(super) fn list(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.texture.list";
let _: ListParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
let resources = s
.doc
.render
.texture_resources
.iter()
.map(|(id, resource)| {
Ok(ResourceInfo {
sha256: id.to_string(),
encoded_bytes: resource.bytes().len(),
dimensions: resource.dimensions(),
provenance: serde_json::to_value(resource.provenance()).map_err(|e| bad(command, e.to_string()))?,
users: users(s, *id),
})
})
.collect::<Result<_>>()?;
let encoded_bytes = s.doc.render.texture_resources.iter().map(|(_, resource)| resource.bytes().len()).sum();
serde_json::to_value(ListResult { resources, encoded_bytes }).map_err(|e| bad(command, e.to_string()))
}
pub(super) fn remove(s: &mut Session, params: &Value) -> Result<Value> {
let command = "render.texture.remove";
let input: RemoveParams = serde_json::from_value(params.clone()).map_err(|e| bad(command, e.to_string()))?;
let id = id(&input.sha256, command)?;
let users = users(s, id);
if !users.is_empty() {
return Err(bad(command, format!("texture is referenced by render setups: {}; unbind it first", users.join(", "))));
}
let mut settings = (*s.doc.render).clone();
let removed = settings.texture_resources.remove(&id).is_some();
settings.validate().map_err(|e| bad(command, e.to_string()))?;
if removed {
s.doc_mut().render = Arc::new(settings);
}
serde_json::to_value(RemoveResult { sha256: input.sha256, removed }).map_err(|e| bad(command, e.to_string()))
}
+34 -6
View File
@@ -38,6 +38,7 @@ fn load(
remaining: &mut u64,
command: &str,
captured: &mut std::collections::BTreeMap<(String, u8), TextureMap>,
resources: Option<&solidcraft_doc::render_texture_resources::TextureResources>,
) -> Result<TextureMap> {
if path.is_empty() || path.len() > 4096 || path.chars().any(char::is_control) {
return Err(bad(command, "texture path must be a bounded local path"));
@@ -54,7 +55,20 @@ fn load(
return Ok(map.clone());
}
let maximum = (*remaining).min(solidcraft_render::texture_input::MAX_TEXTURE_BYTES as u64);
let bytes = if let Some(key) = path.strip_prefix("builtin://") {
let bytes = if let Some(key) = path.strip_prefix("embedded://") {
let id: solidcraft_doc::render_resources::HdrId = serde_json::from_value(serde_json::json!(key)).map_err(|e| bad(command, e.to_string()))?;
let resource = resources
.ok_or_else(|| bad(command, "embedded texture resources are unavailable"))?
.required(&id)
.map_err(|e| bad(command, e.to_string()))?;
if resource.retained_bytes() as u64 > maximum {
return Err(bad(command, "embedded texture exceeds captured source budget"));
}
let mut bytes = Vec::new();
bytes.try_reserve_exact(resource.bytes().len()).map_err(|_| bad(command, "could not reserve captured texture"))?;
bytes.extend_from_slice(resource.bytes());
bytes
} else if let Some(key) = path.strip_prefix("builtin://") {
super::library::texture_bytes(key, role, maximum, command)?
} else {
solidcraft_io::vfs::read(path, maximum as usize).map_err(|e| bad(command, format!("could not capture texture: {e}")))?
@@ -62,7 +76,8 @@ fn load(
if bytes.is_empty() {
return Err(bad(command, "texture file must not be empty"));
}
let map = TextureMap::new(bytes, role).map_err(|e| bad(command, e.to_string()))?;
let map = if path.starts_with("embedded://") { TextureMap::new_portable(bytes, role) } else { TextureMap::new(bytes, role) }
.map_err(|e| bad(command, e.to_string()))?;
*remaining = remaining.checked_sub(map.retained_bytes() as u64).ok_or_else(|| bad(command, "encoded texture capacity exceeds budget"))?;
captured.insert(key, map.clone());
Ok(map)
@@ -96,7 +111,16 @@ pub(super) fn validate_targets(scene: &ProductScene, overrides: &[Override], com
}
Ok(())
}
#[cfg(test)]
pub(super) fn capture(scene: &ProductScene, overrides: &[Override], command: &str) -> Result<Option<Arc<RuntimeTextures>>> {
capture_with_resources(scene, overrides, None, command)
}
pub(super) fn capture_with_resources(
scene: &ProductScene,
overrides: &[Override],
resources: Option<&solidcraft_doc::render_texture_resources::TextureResources>,
command: &str,
) -> Result<Option<Arc<RuntimeTextures>>> {
if overrides.is_empty() {
return Ok(None);
}
@@ -119,10 +143,14 @@ pub(super) fn capture(scene: &ProductScene, overrides: &[Override], command: &st
if body.transmission.is_some() || body.opacity != 1.0 || body.faces.iter().any(|f| f.transmission.is_some() || f.opacity != 1.0) {
return Err(bad(command, "runtime maps support opaque bodies only"));
}
let base_color = input.base_color_srgb.as_ref().map(|p| load(p, MapRole::BaseColor, &mut remaining, command, &mut captured)).transpose()?;
let normal = input.normal_opengl.as_ref().map(|p| load(p, MapRole::NormalOpenGl, &mut remaining, command, &mut captured)).transpose()?;
let roughness = input.roughness_linear.as_ref().map(|p| load(p, MapRole::Roughness, &mut remaining, command, &mut captured)).transpose()?;
let metallic = input.metallic_linear.as_ref().map(|p| load(p, MapRole::Metallic, &mut remaining, command, &mut captured)).transpose()?;
let base_color =
input.base_color_srgb.as_ref().map(|p| load(p, MapRole::BaseColor, &mut remaining, command, &mut captured, resources)).transpose()?;
let normal =
input.normal_opengl.as_ref().map(|p| load(p, MapRole::NormalOpenGl, &mut remaining, command, &mut captured, resources)).transpose()?;
let roughness =
input.roughness_linear.as_ref().map(|p| load(p, MapRole::Roughness, &mut remaining, command, &mut captured, resources)).transpose()?;
let metallic =
input.metallic_linear.as_ref().map(|p| load(p, MapRole::Metallic, &mut remaining, command, &mut captured, resources)).transpose()?;
bindings.push(TextureBinding {
body_index: input.body_index,
body_name: input.body_name.clone(),